tempo-sdk 0.0.28 → 0.0.31

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../modules/iframe-projection/fiber/react-types.ts","../../../../modules/iframe-projection/fiber/serialize.ts","../../../../modules/iframe-projection/fiber/capture.ts","../../../../modules/iframe-projection/fiber/utils.ts","../../../../modules/iframe-projection/fiber/watch.ts","../../../../modules/iframe-projection/html/watch-head.ts","../../../../modules/iframe-projection/shared/capture-perf.ts","../../../../modules/iframe-projection/combined/projection-capture-perf.ts","../../../../modules/iframe-projection/html/selectors.ts","../../../../modules/iframe-projection/html/watch-dom.ts","../../../../modules/iframe-projection/html/declared-facts.ts","../../../../modules/iframe-projection/html/displayability.ts","../../../../modules/iframe-projection/html/capture.ts","../../../../modules/iframe-projection/html/watch-state.ts","../../../../modules/iframe-projection/html/watch-portal.ts","../../../../modules/iframe-projection/combined/css-escape.ts","../../../../modules/iframe-projection/combined/projection-observed-files.ts","../../../../modules/iframe-projection/combined/projection-patch.ts","../../../../modules/iframe-projection/combined/projection-dom-layers.ts","../../../../modules/iframe-projection/combined/projection-layer-snapshot.ts","../../../../modules/iframe-projection/combined/projection-full-snapshot.ts","../../../../modules/iframe-projection/combined/projection-producer.ts","../../../../modules/iframe-projection/shared/portal-tracker.ts","../../../../modules/iframe-projection/combined/projection-root-accumulator.ts","../../../../modules/iframe-projection/combined/enriched-to-serialized-fiber.ts","../../../../modules/iframe-projection/combined/projection-semantic-subtree.ts","../../../../modules/iframe-projection/combined/document-producer.ts","../../../../modules/iframe-projection/html/snapshot.ts","../../../../modules/iframe-projection/combined/render-identity.ts","../../../../modules/iframe-projection/combined/declared-facts.ts","../../../../modules/element-overlay/render/layout-kind.ts","../../../../modules/iframe-projection/combined/enriched-serialize.ts","../../../../modules/iframe-projection/combined/hide-fiber-tree.ts","../../../../modules/iframe-projection/combined/realm-epoch.ts","../../../../modules/iframe-projection/combined/watch.ts","../../../../modules/iframe-projection/combined/postmessage.ts","../../canvas/interact-projection.ts"],"sourcesContent":["/**\n * React Internal Types\n *\n * These types are copied from React's source code. They are internal to React\n * and not exported publicly, so we define them here for type safety.\n *\n * ## Sources\n *\n * - Fiber, FiberRoot: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactInternalTypes.js\n * - WorkTags: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactWorkTags.js\n * - Hooks: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactFiberHooks.js\n * - Memo/ForwardRef/Lazy: https://github.com/facebook/react/blob/main/packages/react/src/\n *\n * ## Stability\n *\n * These structures have been stable since React 16 (Fiber architecture).\n * Major changes are rare, but this file should be updated if React's\n * internals change significantly.\n */\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Fiber Tags (WorkTag)\n// From: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactWorkTags.js\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * React Fiber tag values (WorkTag).\n *\n * These identify what kind of node a fiber represents and determine:\n * - How React processes the fiber during reconciliation\n * - What `stateNode` contains (DOM node, class instance, null)\n * - How `memoizedState` is structured (hooks list, class state, etc.)\n */\nexport const FiberTag = {\n /** Function component: `function MyComponent(props) { ... }` */\n FunctionComponent: 0,\n\n /** Class component: `class MyComponent extends React.Component` */\n ClassComponent: 1,\n\n /**\n * Component not yet determined to be function or class.\n * React resolves this on first render, then updates the tag.\n */\n IndeterminateComponent: 2,\n\n /** Root of a React tree (created by createRoot/render) */\n HostRoot: 3,\n\n /** React Portal: renders children into a different DOM container */\n HostPortal: 4,\n\n /** DOM element: div, span, button, etc. */\n HostComponent: 5,\n\n /** Text node: string/number children */\n HostText: 6,\n\n /** React.Fragment or <>...</> */\n Fragment: 7,\n\n /** StrictMode, ConcurrentMode, etc. */\n Mode: 8,\n\n /** Context.Consumer (legacy pattern) */\n ContextConsumer: 9,\n\n /** Context.Provider */\n ContextProvider: 10,\n\n /** React.forwardRef wrapper */\n ForwardRef: 11,\n\n /** React.Profiler for performance measurements */\n Profiler: 12,\n\n /** React.Suspense boundary */\n SuspenseComponent: 13,\n\n /** React.memo() wrapper */\n MemoComponent: 14,\n\n /** Simplified memo (internal optimization) */\n SimpleMemoComponent: 15,\n\n /** React.lazy() wrapper for code splitting */\n LazyComponent: 16,\n\n /** Incomplete class component (errored during render) */\n IncompleteClassComponent: 17,\n\n /** Dehydrated Suspense boundary (server-rendered) */\n DehydratedFragment: 18,\n\n /** SuspenseList for coordinating reveal order */\n SuspenseListComponent: 19,\n\n /** Scope component (experimental) */\n ScopeComponent: 21,\n\n /** Offscreen component (experimental, powers Activity) */\n OffscreenComponent: 22,\n\n /** Legacy hidden component (deprecated) */\n LegacyHiddenComponent: 23,\n\n /** Cache component (experimental) */\n CacheComponent: 24,\n\n /** Tracing marker (experimental) */\n TracingMarkerComponent: 25,\n\n /** Hoistable elements like <title>, <meta> (React 18.3+) */\n HostHoistable: 26,\n\n /** Singleton elements like <html>, <head>, <body> (React 18.3+) */\n HostSingleton: 27,\n} as const;\n\nexport type FiberTagValue = (typeof FiberTag)[keyof typeof FiberTag];\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Component Types (fiber.type)\n// From: https://github.com/facebook/react/blob/main/packages/react/src/\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** A React function component */\nexport interface FunctionComponent<P = Record<string, unknown>> {\n (props: P): unknown; // Returns ReactNode\n displayName?: string;\n name?: string;\n}\n\n/** A React class component constructor */\nexport interface ClassComponent<P = Record<string, unknown>> {\n new (props: P): { render(): unknown };\n displayName?: string;\n name?: string;\n}\n\n/**\n * React.memo() wrapper.\n * From: https://github.com/facebook/react/blob/main/packages/react/src/ReactMemo.js\n */\nexport interface MemoComponent<P = Record<string, unknown>> {\n $$typeof: symbol; // Symbol.for('react.memo')\n type: FunctionComponent<P> | ClassComponent<P>;\n compare: ((prevProps: P, nextProps: P) => boolean) | null;\n}\n\n/**\n * React.forwardRef() wrapper.\n * From: https://github.com/facebook/react/blob/main/packages/react/src/ReactForwardRef.js\n */\nexport interface ForwardRefComponent<P = Record<string, unknown>> {\n $$typeof: symbol; // Symbol.for('react.forward_ref')\n render: FunctionComponent<P>;\n displayName?: string;\n}\n\n/**\n * React.lazy() wrapper.\n * From: https://github.com/facebook/react/blob/main/packages/react/src/ReactLazy.js\n */\nexport interface LazyComponent {\n $$typeof: symbol; // Symbol.for('react.lazy')\n _payload: {\n _status: -1 | 0 | 1 | 2; // Uninitialized, Pending, Resolved, Rejected\n _result: unknown;\n };\n _init: (payload: unknown) => FunctionComponent | ClassComponent;\n}\n\n/**\n * Context.Provider type.\n */\nexport interface ContextProvider<T = unknown> {\n $$typeof: symbol; // Symbol.for('react.provider') or Symbol.for('react.context')\n _context: {\n Provider: unknown;\n Consumer: unknown;\n _currentValue: T;\n displayName?: string;\n };\n}\n\n/** All possible values for fiber.type */\nexport type FiberType =\n | string // HostComponent: \"div\", \"span\", etc.\n | FunctionComponent\n | ClassComponent\n | MemoComponent\n | ForwardRefComponent\n | LazyComponent\n | ContextProvider\n | symbol // Fragment, StrictMode, Profiler, etc.\n | null; // HostText\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Hooks (fiber.memoizedState for FunctionComponent)\n// From: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactFiberHooks.js\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * React Hook object (linked list node).\n *\n * For function components, fiber.memoizedState is the head of a linked list\n * of Hook objects, one for each hook call in the component.\n */\nexport interface Hook {\n /**\n * The current value of this hook. Contents depend on hook type:\n * - useState/useReducer: the state value\n * - useRef: { current: T }\n * - useMemo: [memoizedValue, dependencies]\n * - useCallback: [callback, dependencies]\n * - useEffect/useLayoutEffect: Effect object\n * - useContext: the context value\n */\n memoizedState: unknown;\n\n /** Base state for updates (used during state transitions) */\n baseState: unknown;\n\n /** Base queue of updates */\n baseQueue: HookUpdate | null;\n\n /** Queue of pending updates. Present for useState/useReducer, null for others */\n queue: HookQueue | null;\n\n /** Next hook in the linked list */\n next: Hook | null;\n}\n\n/**\n * Update queue for useState/useReducer.\n */\nexport interface HookQueue<S = unknown, A = unknown> {\n pending: HookUpdate<S, A> | null;\n lanes: number;\n dispatch: ((action: A) => void) | null;\n lastRenderedReducer: ((state: S, action: A) => S) | null;\n lastRenderedState: S | null;\n}\n\n/**\n * A state update object (circular linked list).\n */\nexport interface HookUpdate<S = unknown, A = unknown> {\n lane: number;\n revertLane: number;\n action: A;\n hasEagerState: boolean;\n eagerState: S | null;\n next: HookUpdate<S, A>;\n}\n\n/**\n * Effect hook object (memoizedState for useEffect/useLayoutEffect).\n */\nexport interface Effect {\n /** Effect type tag (HasEffect, Passive, Layout, etc.) */\n tag: number;\n /** The effect function */\n create: () => (() => void) | void;\n /** The cleanup function returned by create */\n destroy: (() => void) | undefined;\n /** Dependencies array */\n deps: unknown[] | null;\n /** Next effect in the circular linked list */\n next: Effect;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Ref Types\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Ref object created by useRef or createRef */\nexport interface RefObject<T = unknown> {\n current: T;\n}\n\n/** Callback ref function */\nexport type RefCallback<T = unknown> = (instance: T | null) => void;\n\n/** All possible values for fiber.ref */\nexport type FiberRef<T = unknown> = RefObject<T> | RefCallback<T> | null;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Props Type\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Props object passed to components */\nexport type FiberProps = Record<string, unknown> & {\n children?: unknown;\n};\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Fiber\n// From: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactInternalTypes.js\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * React Fiber node.\n *\n * A fiber is a unit of work in React's rendering engine. It maintains\n * component identity, state, tree relationships, and scheduling information.\n *\n * ## Key Properties for Serialization\n *\n * - `tag`: What kind of fiber (use FiberTag constants)\n * - `type`: The component function/class or DOM tag string\n * - `key`: React key prop for reconciliation\n * - `stateNode`: DOM element (HostComponent) or class instance (ClassComponent)\n * - `memoizedProps`: Current props\n * - `memoizedState`: Hooks linked list (FunctionComponent) or state object (ClassComponent)\n * - `child`/`sibling`/`return`: Tree navigation\n */\nexport interface Fiber {\n // ─── Core Identity ─────────────────────────────────────────────────────────\n\n /** Fiber type tag (FunctionComponent, HostComponent, etc.) */\n tag: FiberTagValue;\n\n /** Unique key among siblings (from key prop) */\n key: string | null;\n\n /** Element type for reconciliation (usually same as type) */\n elementType: FiberType;\n\n /**\n * The resolved function/class/string for this fiber.\n * - FunctionComponent: the function\n * - ClassComponent: the class constructor\n * - HostComponent: tag string (\"div\", \"span\", etc.)\n * - HostText: null\n */\n type: FiberType;\n\n /**\n * Local state associated with this fiber.\n * - HostComponent: the DOM Element\n * - HostText: the DOM Text node\n * - ClassComponent: the class instance\n * - HostRoot: the FiberRoot\n * - FunctionComponent: null\n */\n stateNode: Element | Text | object | null;\n\n // ─── Tree Structure ────────────────────────────────────────────────────────\n\n /** Parent fiber (\"return\" because processing returns to parent) */\n return: Fiber | null;\n\n /** First child (head of children linked list) */\n child: Fiber | null;\n\n /** Next sibling */\n sibling: Fiber | null;\n\n /** Position among siblings */\n index: number;\n\n // ─── Props and State ───────────────────────────────────────────────────────\n\n /** Ref attached to this fiber */\n ref: FiberRef;\n\n /** Ref cleanup function (React 19+) */\n refCleanup: (() => void) | null;\n\n /** Input props being processed */\n pendingProps: FiberProps;\n\n /** Props from most recent completed render */\n memoizedProps: FiberProps;\n\n /** Update queue */\n updateQueue: unknown;\n\n /**\n * State from most recent completed render.\n * - FunctionComponent: Hook linked list (first hook)\n * - ClassComponent: state object\n * - HostRoot: element to render\n */\n memoizedState: Hook | object | null;\n\n /** Context and event dependencies */\n dependencies: unknown;\n\n // ─── Effects and Flags ─────────────────────────────────────────────────────\n\n /** Bitfield of effects needed on this fiber */\n flags: number;\n\n /** Aggregate flags from descendants */\n subtreeFlags: number;\n\n /** Fibers to delete */\n deletions: Fiber[] | null;\n\n // ─── Scheduling ────────────────────────────────────────────────────────────\n\n /** Update lanes for this fiber */\n lanes: number;\n\n /** Aggregate lanes from descendants */\n childLanes: number;\n\n // ─── Alternate (Double Buffering) ──────────────────────────────────────────\n\n /**\n * Link to corresponding fiber in the alternate tree.\n *\n * React maintains current (on screen) and work-in-progress trees.\n * After commit, if you're on FiberRoot.current, alternate points to OLD tree.\n */\n alternate: Fiber | null;\n\n // ─── Mode ──────────────────────────────────────────────────────────────────\n\n /** Bitfield for StrictMode, ConcurrentMode, etc. */\n mode: number;\n\n // ─── Profiling (dev/profiling builds) ──────────────────────────────────────\n\n actualDuration?: number;\n actualStartTime?: number;\n selfBaseDuration?: number;\n treeBaseDuration?: number;\n\n // ─── Debug (dev only) ──────────────────────────────────────────────────────\n\n _debugInfo?: unknown;\n _debugOwner?: Fiber | null;\n _debugStack?: Error | null;\n _debugTask?: unknown;\n _debugNeedsRemount?: boolean;\n _debugHookTypes?: string[] | null;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// FiberRoot\n// From: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactInternalTypes.js\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * FiberRoot - the root object for a React tree.\n *\n * Created by createRoot() or ReactDOM.render(). The `current` property\n * always points to the committed fiber tree (HostRoot fiber).\n */\nexport interface FiberRoot {\n /** The HostRoot fiber of the committed tree */\n current: Fiber;\n\n /** The DOM container element */\n containerInfo: Element;\n\n /** Whether this root is hydrating */\n hydrate: boolean;\n\n /** Pending work lanes */\n pendingLanes: number;\n\n /** Scheduler callback */\n callbackNode: unknown;\n callbackPriority: number;\n\n /** Suspense ping cache */\n pingCache: unknown;\n\n /** Completed work ready to commit */\n finishedWork: Fiber | null;\n\n /**\n * Development renderers retain the Fibers that scheduled the commit while\n * the DevTools commit hook is running, then clear the set immediately after\n * the hook returns. Tempo installs that hook before React, so the projection\n * producer can retain exact candidate anchors without walking the root.\n */\n memoizedUpdaters?: ReadonlySet<Fiber>;\n\n /** Legacy context */\n context: object | null;\n pendingContext: object | null;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// DevTools Hook\n// From: https://github.com/facebook/react/blob/main/packages/react-devtools-shared/src/hook.js\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * React renderer info passed to hook.inject().\n */\nexport interface ReactRenderer {\n version: string;\n rendererPackageName?: string;\n bundleType?: number; // 0 = production, 1 = development\n findFiberByHostInstance?: (instance: unknown) => Fiber | null;\n}\n\n/**\n * The React DevTools global hook.\n *\n * Must be installed on `window.__REACT_DEVTOOLS_GLOBAL_HOOK__` BEFORE\n * React loads. React checks for this exactly once at initialization.\n */\nexport interface DevToolsHook {\n /** Must be true for modern React (16+) to inject */\n supportsFiber: boolean;\n\n /** Map of renderer ID -> renderer info */\n renderers: Map<number, ReactRenderer>;\n\n /** Called by React to register itself. Returns renderer ID. */\n inject(renderer: ReactRenderer): number;\n\n /**\n * Called by React after each commit.\n * fiberRoot.current points to the freshly committed tree.\n */\n onCommitFiberRoot(\n rendererId: number,\n fiberRoot: FiberRoot,\n priority?: number,\n didError?: boolean\n ): void;\n\n /** Called when a fiber is about to unmount */\n onCommitFiberUnmount?(rendererId: number, fiber: Fiber): void;\n\n /** Dead code elimination check */\n checkDCE?(fn: Function): void;\n\n /** Called when render is scheduled */\n onScheduleFiberRoot?(): void;\n}\n\ndeclare global {\n interface Window {\n __REACT_DEVTOOLS_GLOBAL_HOOK__?: DevToolsHook;\n }\n}\n","/**\n * Fiber Serialization Helpers\n *\n * Utility functions for extracting data from React Fiber nodes.\n * Use these to build your custom serialize functions.\n *\n * @example\n * ```ts\n * import { getDisplayName, getTag, getProps, getKey } from './serialize';\n *\n * const mySerialize: SerializeFn<MyNode> = (fiber) => ({\n * name: getDisplayName(fiber),\n * tag: getTag(fiber),\n * key: getKey(fiber),\n * props: getProps(fiber),\n * });\n * ```\n */\n\nimport type { Fiber, FiberProps, Hook, FunctionComponent, ClassComponent, MemoComponent, ForwardRefComponent, FiberTagValue } from \"./react-types\";\nimport { FiberTag } from \"./react-types\";\nimport type { DefaultFiberNode, SerializeFn } from \"./types\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Name Resolution\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get the display name of a fiber.\n *\n * Resolution order:\n * 1. type.displayName (explicit name set on component)\n * 2. type.name (function/class name)\n * 3. Wrapped component name (for memo/forwardRef)\n * 4. Tag-based fallback (\"Fragment\", \"#text\", etc.)\n */\nexport function getDisplayName(fiber: Fiber): string {\n const { type, tag } = fiber;\n\n // HostComponent: DOM elements have string type\n if (typeof type === \"string\") {\n return type;\n }\n\n // HostText: text nodes\n if (tag === FiberTag.HostText) {\n return \"#text\";\n }\n\n // Function/Class components\n if (typeof type === \"function\") {\n const fn = type as FunctionComponent | ClassComponent;\n return fn.displayName || fn.name || \"Anonymous\";\n }\n\n // Object types (memo, forwardRef, lazy, context)\n if (type && typeof type === \"object\") {\n // React.memo\n if (\"type\" in type && (type as MemoComponent).type) {\n const inner = (type as MemoComponent).type;\n if (typeof inner === \"function\") {\n return (inner as FunctionComponent).displayName || (inner as FunctionComponent).name || \"Memo\";\n }\n }\n\n // React.forwardRef\n if (\"render\" in type && (type as ForwardRefComponent).render) {\n const render = (type as ForwardRefComponent).render;\n return (type as ForwardRefComponent).displayName || render.displayName || render.name || \"ForwardRef\";\n }\n\n // Context.Provider\n if (\"_context\" in type) {\n const ctx = (type as { _context: { displayName?: string } })._context;\n return ctx.displayName ? `${ctx.displayName}.Provider` : \"Context.Provider\";\n }\n }\n\n // Tag-based fallbacks\n const tagNames: Partial<Record<number, string>> = {\n [FiberTag.HostRoot]: \"HostRoot\",\n [FiberTag.Fragment]: \"Fragment\",\n [FiberTag.Mode]: \"Mode\",\n [FiberTag.ContextConsumer]: \"Context.Consumer\",\n [FiberTag.ContextProvider]: \"Context.Provider\",\n [FiberTag.Profiler]: \"Profiler\",\n [FiberTag.SuspenseComponent]: \"Suspense\",\n [FiberTag.SuspenseListComponent]: \"SuspenseList\",\n [FiberTag.OffscreenComponent]: \"Offscreen\",\n };\n\n return tagNames[tag] || `Unknown(${tag})`;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Basic Accessors\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Get the fiber's tag value */\nexport function getTag(fiber: Fiber): FiberTagValue {\n return fiber.tag as FiberTagValue;\n}\n\n/** Get the fiber's key (null if not set) */\nexport function getKey(fiber: Fiber): string | null {\n return fiber.key;\n}\n\n/** Get the fiber's index among siblings */\nexport function getIndex(fiber: Fiber): number {\n return fiber.index;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Props\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get the fiber's current props.\n *\n * Returns memoizedProps which reflect the most recent render.\n */\nexport function getProps(fiber: Fiber): FiberProps {\n return fiber.memoizedProps;\n}\n\n/**\n * Sanitize props for serialization.\n *\n * - Removes `children` (handled separately in tree)\n * - Converts functions to \"[Function]\"\n * - Converts DOM elements to \"[Element:tagName]\"\n * - Converts React elements to \"[ReactElement]\"\n * - Deep clones serializable objects\n * - Falls back to \"[Object]\" for non-serializable values\n */\nexport function sanitizeProps(props: FiberProps | null): Record<string, unknown> | undefined {\n if (!props) return undefined;\n\n const result: Record<string, unknown> = {};\n let hasProps = false;\n\n for (const [key, value] of Object.entries(props)) {\n // Skip children - handled in tree structure\n if (key === \"children\") continue;\n\n hasProps = true;\n result[key] = sanitizeValue(value);\n }\n\n return hasProps ? result : undefined;\n}\n\n/**\n * Sanitize a single value for serialization.\n */\nexport function sanitizeValue(value: unknown): unknown {\n if (value === null || value === undefined) {\n return value;\n }\n\n if (typeof value === \"function\") {\n return \"[Function]\";\n }\n\n if (typeof value === \"symbol\") {\n return `[Symbol:${value.description ?? \"\"}]`;\n }\n\n if (value instanceof Element) {\n return `[Element:${value.tagName.toLowerCase()}${value.id ? `#${value.id}` : \"\"}]`;\n }\n\n if (value instanceof Node) {\n return `[Node:${value.nodeName}]`;\n }\n\n if (Array.isArray(value)) {\n // For small arrays, serialize contents\n if (value.length <= 10) {\n return value.map(sanitizeValue);\n }\n return `[Array(${value.length})]`;\n }\n\n if (typeof value === \"object\") {\n // React element\n if (\"$$typeof\" in value) {\n return \"[ReactElement]\";\n }\n\n // Try to deep clone\n try {\n return JSON.parse(JSON.stringify(value));\n } catch {\n return \"[Object]\";\n }\n }\n\n // Primitives pass through\n return value;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// State Node (DOM Element)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get the DOM element for a HostComponent fiber.\n *\n * Returns null for non-host fibers or if stateNode isn't an Element.\n */\nexport function getDomElement(fiber: Fiber): Element | null {\n if (fiber.tag !== FiberTag.HostComponent) {\n return null;\n }\n return fiber.stateNode instanceof Element ? fiber.stateNode : null;\n}\n\n/**\n * Get the Text node for a HostText fiber.\n */\nexport function getTextNode(fiber: Fiber): Text | null {\n if (fiber.tag !== FiberTag.HostText) {\n return null;\n }\n return fiber.stateNode instanceof Text ? fiber.stateNode : null;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Hooks (Function Components)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get the hooks linked list for a function component.\n *\n * Returns null for non-function components or components without hooks.\n */\nexport function getHooks(fiber: Fiber): Hook | null {\n if (fiber.tag !== FiberTag.FunctionComponent) {\n return null;\n }\n // memoizedState is the head of the hooks linked list\n return fiber.memoizedState as Hook | null;\n}\n\n/**\n * Iterate over all hooks in a function component.\n *\n * @example\n * ```ts\n * for (const hook of iterateHooks(fiber)) {\n * console.log(hook.memoizedState);\n * }\n * ```\n */\nexport function* iterateHooks(fiber: Fiber): Generator<Hook> {\n let hook = getHooks(fiber);\n let count = 0;\n const maxHooks = 100; // Safety limit\n\n while (hook && count < maxHooks) {\n yield hook;\n hook = hook.next;\n count++;\n }\n}\n\n/**\n * Extract hook values as an array.\n *\n * Returns array of memoizedState values for each hook.\n */\nexport function getHookValues(fiber: Fiber): unknown[] {\n const values: unknown[] = [];\n for (const hook of iterateHooks(fiber)) {\n values.push(hook.memoizedState);\n }\n return values;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Tree Navigation\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Iterate over a fiber's children.\n *\n * @example\n * ```ts\n * for (const child of iterateChildren(fiber)) {\n * console.log(getDisplayName(child));\n * }\n * ```\n */\nexport function* iterateChildren(fiber: Fiber): Generator<Fiber> {\n let child = fiber.child;\n while (child) {\n yield child;\n child = child.sibling;\n }\n}\n\n/**\n * Get all children as an array.\n */\nexport function getChildren(fiber: Fiber): Fiber[] {\n return [...iterateChildren(fiber)];\n}\n\n/**\n * Walk up the tree to find the root fiber.\n *\n * Important: Uses FiberRoot.current to get the committed tree,\n * avoiding stale data from the work-in-progress tree.\n */\nexport function findRootFiber(fiber: Fiber): Fiber {\n // Walk up to HostRoot\n let current = fiber;\n while (current.return) {\n current = current.return;\n }\n\n // HostRoot's stateNode is FiberRoot, which has `.current`\n // pointing to the committed tree's root\n const stateNode = current.stateNode;\n if (\n stateNode &&\n typeof stateNode === \"object\" &&\n \"current\" in stateNode &&\n (stateNode as { current: Fiber }).current\n ) {\n return (stateNode as { current: Fiber }).current;\n }\n\n return current;\n}\n\n/**\n * Resolve a fiber to its committed-tree version.\n *\n * React double-buffers fibers: each host instance has up to two fiber\n * objects (`fiber` and `fiber.alternate`) that swap the \"current\" role on\n * every commit. The `__reactFiber$` pointer a DOM element carries is stamped\n * once at mount and never re-pointed, so after an odd number of commits it\n * refers to the NON-committed generation — its `memoizedProps` (and the\n * whole subtree walked from it) are one commit stale.\n *\n * Both generations' HostRoot fibers share one `FiberRoot` stateNode, but a\n * bailout can also make the generations share intermediate child lists. Walk\n * both return paths and use parent-child membership to preserve which original\n * endpoint each path represents, matching React's own current-fiber slow path.\n *\n * A fiber with no alternate that fails the check is kept as-is (a freshly\n * mounted node exists in only one generation; a detached fiber has no\n * better answer).\n *\n * Throws `isTransientFiberResolutionError` failures for a fiber React has\n * detached from the committed tree — an ordinary outcome for a caller holding\n * fibers React may unmount under it.\n */\nexport function resolveCommittedFiber(fiber: Fiber): Fiber {\n const alternate = fiber.alternate;\n if (!alternate) {\n return fiber;\n }\n\n let a = fiber;\n let b = alternate;\n for (;;) {\n const parentA = a.return;\n if (!parentA) break;\n const parentB = parentA.alternate;\n if (!parentB) {\n const nextParent = parentA.return;\n if (nextParent) {\n a = nextParent;\n b = nextParent;\n continue;\n }\n break;\n }\n\n if (parentA.child === parentB.child) {\n for (let child = parentA.child; child; child = child.sibling) {\n if (child === a) return fiber;\n if (child === b) return alternate;\n }\n throw new Error(\"Unable to resolve a mounted React fiber\");\n }\n\n if (a.return !== b.return) {\n a = parentA;\n b = parentB;\n } else {\n let found = false;\n for (let child = parentA.child; child; child = child.sibling) {\n if (child === a) {\n found = true;\n a = parentA;\n b = parentB;\n break;\n }\n if (child === b) {\n found = true;\n a = parentB;\n b = parentA;\n break;\n }\n }\n if (!found) {\n for (let child = parentB.child; child; child = child.sibling) {\n if (child === a) {\n found = true;\n a = parentB;\n b = parentA;\n break;\n }\n if (child === b) {\n found = true;\n a = parentA;\n b = parentB;\n break;\n }\n }\n }\n if (!found) {\n throw new Error(\"React fiber is absent from both parent generations\");\n }\n }\n\n if (a.alternate !== b) {\n throw new Error(\"React return fibers are not paired alternates\");\n }\n }\n\n if (a.tag !== FiberTag.HostRoot) {\n throw new Error(\"Unable to resolve an unmounted React fiber\");\n }\n const fiberRoot = a.stateNode as { current?: Fiber } | null;\n return fiberRoot?.current === a ? fiber : alternate;\n}\n\nconst TRANSIENT_FIBER_RESOLUTION_ERRORS = new Set([\n \"Unable to resolve a mounted React fiber\",\n \"React fiber is absent from both parent generations\",\n \"React return fibers are not paired alternates\",\n \"Unable to resolve an unmounted React fiber\",\n]);\n\n/**\n * Did `resolveCommittedFiber` fail because the fiber is no longer part of the\n * committed tree, rather than because the caller misused it?\n *\n * A fiber captured at one moment can be detached by any later commit — an\n * updater unmounted by the very commit that scheduled it, an alternate React\n * dropped between DOM enumeration and the identity read. Callers holding many\n * fibers treat this as \"this one has no answer\" and keep going; every other\n * error is a real defect and must keep propagating.\n */\nexport function isTransientFiberResolutionError(error: unknown): boolean {\n return (\n error instanceof Error &&\n TRANSIENT_FIBER_RESOLUTION_ERRORS.has(error.message)\n );\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Type Guards\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Check if fiber is a function component */\nexport function isFunctionComponent(fiber: Fiber): boolean {\n return fiber.tag === FiberTag.FunctionComponent;\n}\n\n/** Check if fiber is a class component */\nexport function isClassComponent(fiber: Fiber): boolean {\n return fiber.tag === FiberTag.ClassComponent;\n}\n\n/** Check if fiber is a React component (function or class) */\nexport function isComponent(fiber: Fiber): boolean {\n return fiber.tag === FiberTag.FunctionComponent || fiber.tag === FiberTag.ClassComponent;\n}\n\n/** Check if fiber is a DOM element */\nexport function isHostComponent(fiber: Fiber): boolean {\n return fiber.tag === FiberTag.HostComponent;\n}\n\n/** Check if fiber is a text node */\nexport function isHostText(fiber: Fiber): boolean {\n return fiber.tag === FiberTag.HostText;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Default Serializer\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Default serialize function.\n *\n * Produces nodes with just name and tag - the minimal representation.\n */\nexport const defaultSerialize: SerializeFn<DefaultFiberNode> = (fiber) => ({\n name: getDisplayName(fiber),\n tag: getTag(fiber),\n});\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Tree Serialization\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Options for serializeTree.\n */\nexport interface SerializeOptions {\n /** Maximum depth to traverse (default: unlimited) */\n maxDepth?: number;\n /** Whether to skip text nodes (default: true) */\n skipText?: boolean;\n}\n\n/**\n * Serialize a fiber tree using the provided serialize function.\n *\n * This is the core serialization function. It handles:\n * - Recursive tree traversal via child/sibling links\n * - Building children arrays\n * - Depth limiting\n * - Optional text node skipping\n *\n * @param fiber - Root fiber to serialize from\n * @param serialize - Function to serialize each fiber\n * @param options - Serialization options\n */\nexport function serializeTree<T extends { children: T[] }>(\n fiber: Fiber,\n serialize: (fiber: Fiber) => Omit<T, \"children\">,\n options: SerializeOptions = {}\n): T | null {\n const { maxDepth = Infinity, skipText = true } = options;\n\n function serializeNode(f: Fiber, depth: number): T | null {\n if (depth > maxDepth) return null;\n\n // Optionally skip text nodes\n if (skipText && f.tag === FiberTag.HostText) {\n return null;\n }\n\n // Serialize this node (without children)\n const nodeData = serialize(f);\n\n // Recursively serialize children\n const children: T[] = [];\n for (const child of iterateChildren(f)) {\n const serialized = serializeNode(child, depth + 1);\n if (serialized) {\n children.push(serialized);\n }\n }\n\n // Combine node data with children\n return { ...nodeData, children } as T;\n }\n\n return serializeNode(fiber, 0);\n}\n","/**\n * Fiber Tree Capture\n *\n * One-shot capture of a React fiber tree from a DOM element.\n *\n * @example\n * ```ts\n * // Default capture (name + tag)\n * const tree = capture(document.getElementById('root'));\n *\n * // Custom capture with more data\n * const tree = capture(rootEl, (fiber) => ({\n * name: getDisplayName(fiber),\n * tag: fiber.tag,\n * props: sanitizeProps(fiber.memoizedProps),\n * }));\n * ```\n */\n\nimport type { Fiber } from \"./react-types\";\nimport { FiberTag } from \"./react-types\";\nimport type { FiberNode, FiberNodeConstraint, DefaultFiberNode, SerializeFn } from \"./types\";\nimport { defaultSerialize, serializeTree, findRootFiber, type SerializeOptions } from \"./serialize\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Fiber Access from DOM\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Find the React fiber key on a DOM element.\n *\n * React attaches fibers to DOM elements using keys like `__reactFiber$abc123`.\n * The suffix is unique per React instance but consistent across all elements.\n */\nfunction findFiberKey(element: Element): string | null {\n return (\n Object.keys(element).find(\n (k) => k.startsWith(\"__reactFiber$\") || k.startsWith(\"__reactInternalInstance$\")\n ) ?? null\n );\n}\n\n/**\n * Find the React container key on a root element.\n *\n * Root containers (like #root) have `__reactContainer$` instead of `__reactFiber$`.\n */\nfunction findContainerKey(element: Element): string | null {\n return Object.keys(element).find((k) => k.startsWith(\"__reactContainer$\")) ?? null;\n}\n\n/**\n * Get the React fiber from a DOM element.\n *\n * Works with both regular elements (__reactFiber$) and\n * root containers (__reactContainer$).\n */\nexport function getFiberFromElement(element: Element): Fiber | null {\n // Try standard fiber key first\n const fiberKey = findFiberKey(element);\n if (fiberKey) {\n return (element as unknown as Record<string, Fiber>)[fiberKey] ?? null;\n }\n\n // For root containers, try container key\n const containerKey = findContainerKey(element);\n if (containerKey) {\n return (element as unknown as Record<string, Fiber>)[containerKey] ?? null;\n }\n\n return null;\n}\n\n/**\n * Check if React fiber data is available on this element.\n */\nexport function hasFiber(element: Element): boolean {\n return findFiberKey(element) !== null || findContainerKey(element) !== null;\n}\n\n/**\n * Check if any element in the document has React fiber data.\n *\n * Useful for detecting if React is present and has rendered.\n */\nexport function isReactAvailable(): boolean {\n const elements = document.querySelectorAll(\"*\");\n for (const el of elements) {\n if (hasFiber(el)) return true;\n }\n return false;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Capture\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Options for capture().\n */\nexport interface CaptureOptions extends SerializeOptions {\n /**\n * Whether to start from the committed root fiber.\n *\n * If true (default), walks up from the element's fiber to find the\n * root, then uses FiberRoot.current to ensure we're reading from\n * the committed tree (not the stale work-in-progress tree).\n *\n * If false, starts directly from the element's fiber.\n */\n fromRoot?: boolean;\n}\n\n/**\n * Capture the fiber tree from a DOM element.\n *\n * ## Default Behavior\n *\n * Returns nodes with `name`, `tag`, and `children`. This is the minimal\n * representation that captures the tree structure.\n *\n * ## Custom Serialization\n *\n * Pass a serialize function to control exactly what data each node has.\n * Your function receives the raw Fiber and returns everything except\n * `children` (we handle the recursion).\n *\n * @param element - DOM element to capture from\n * @param serialize - Optional custom serialize function\n * @param options - Capture options\n *\n * @example\n * ```ts\n * // Default capture\n * const tree = capture(document.getElementById('root'));\n * // tree: { name: \"App\", tag: 0, children: [...] }\n *\n * // Custom capture with props\n * interface MyNode {\n * name: string;\n * tag: number;\n * props?: Record<string, unknown>;\n * children: MyNode[];\n * }\n *\n * const tree = capture<MyNode>(rootEl, (fiber) => ({\n * name: getDisplayName(fiber),\n * tag: fiber.tag,\n * props: sanitizeProps(fiber.memoizedProps),\n * }));\n * ```\n */\nexport function capture(\n element: Element,\n options?: CaptureOptions\n): FiberNode<DefaultFiberNode> | null;\n\nexport function capture<T extends FiberNodeConstraint>(\n element: Element,\n serialize: SerializeFn<T>,\n options?: CaptureOptions\n): FiberNode<T> | null;\n\nexport function capture<T extends FiberNodeConstraint = DefaultFiberNode>(\n element: Element,\n serializeOrOptions?: SerializeFn<T> | CaptureOptions,\n maybeOptions?: CaptureOptions\n): FiberNode<T> | null {\n // Parse overloaded arguments\n let serialize: SerializeFn<T>;\n let options: CaptureOptions;\n\n if (typeof serializeOrOptions === \"function\") {\n serialize = serializeOrOptions;\n options = maybeOptions ?? {};\n } else {\n serialize = defaultSerialize as unknown as SerializeFn<T>;\n options = serializeOrOptions ?? {};\n }\n\n const { fromRoot = true, ...serializeOptions } = options;\n\n // Get fiber from element\n let fiber = getFiberFromElement(element);\n if (!fiber) {\n return null;\n }\n\n // Navigate to committed root if requested\n if (fromRoot) {\n const root = findRootFiber(fiber);\n // Start from first child of HostRoot (the app component)\n if (root.tag === FiberTag.HostRoot && root.child) {\n fiber = root.child;\n } else {\n fiber = root;\n }\n }\n\n // Serialize the tree\n return serializeTree(fiber, serialize, serializeOptions);\n}\n","/**\n * Fiber Tree Utilities\n *\n * Utility functions for working with serialized fiber trees.\n */\n\nimport type { FiberNodeConstraint, FiberTagValue } from \"./types\";\n\n/**\n * Filter a fiber tree, removing nodes with excluded tags.\n *\n * When a node is filtered out, its children are promoted to take its place\n * (recursively filtered as well). This allows hiding wrapper nodes like\n * Fragment, Mode, or ContextProvider while preserving the tree structure.\n *\n * @param tree - The root node (or null)\n * @param excludeTags - Set of tag values to exclude\n * @returns The filtered tree, or null if root was filtered and had no children\n *\n * @example\n * ```ts\n * import { FiberTag } from './types';\n *\n * // Filter out Fragment (7) and Mode (8) nodes\n * const filtered = filterTree(tree, new Set([\n * FiberTag.Fragment,\n * FiberTag.Mode,\n * ]));\n * ```\n *\n * @example\n * ```ts\n * // Hide common wrapper nodes\n * const WRAPPER_TAGS = new Set([\n * 7, // Fragment\n * 8, // Mode\n * 10, // ContextProvider\n * 11, // ForwardRef\n * 14, // MemoComponent\n * 15, // SimpleMemoComponent\n * ]);\n * const filtered = filterTree(tree, WRAPPER_TAGS);\n * ```\n */\nexport function filterTree<T extends FiberNodeConstraint & { tag: number }>(\n tree: T | null,\n excludeTags: Set<number>\n): T | null {\n if (tree === null) return null;\n\n // If root is excluded, promote its children (but there can only be one root)\n if (excludeTags.has(tree.tag)) {\n // Recursively filter children and return the first one (promoting it to root)\n const filteredChildren = filterChildren(tree.children, excludeTags);\n return filteredChildren.length > 0 ? filteredChildren[0]! : null;\n }\n\n // Root is not excluded, filter its children\n return {\n ...tree,\n children: filterChildren(tree.children, excludeTags),\n };\n}\n\n/**\n * Filter an array of children, promoting grandchildren when a child is filtered.\n */\nfunction filterChildren<T extends FiberNodeConstraint & { tag: number }>(\n children: T[],\n excludeTags: Set<number>\n): T[] {\n const result: T[] = [];\n\n for (const child of children) {\n if (excludeTags.has(child.tag)) {\n // Child is excluded - promote its filtered children\n const grandchildren = filterChildren(child.children, excludeTags);\n result.push(...grandchildren);\n } else {\n // Child is kept - recursively filter its children\n result.push({\n ...child,\n children: filterChildren(child.children, excludeTags),\n });\n }\n }\n\n return result;\n}\n\n/**\n * Common wrapper tags that can be hidden without losing semantic information.\n */\nexport const WRAPPER_TAGS = new Set([\n 7, // Fragment\n 8, // Mode (StrictMode)\n 10, // ContextProvider\n 11, // ForwardRef\n 14, // MemoComponent\n 15, // SimpleMemoComponent\n]);\n\n/**\n * Create a filter set from tag values.\n * Convenience function for creating filter sets.\n */\nexport function createTagFilter(...tags: number[]): Set<number> {\n return new Set(tags);\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Include-based Filtering\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Filter a fiber tree to only include nodes with specified tags.\n *\n * When a node is NOT in includeTags, it is removed and its children are\n * promoted to take its place (recursively filtered as well). This is the\n * inverse of filterTree which excludes tags.\n *\n * @param tree - The root node (or null)\n * @param includeTags - Set of tag values to keep\n * @returns The filtered tree, or null if root was filtered and had no children\n *\n * @example\n * ```ts\n * import { FiberTag } from './types';\n *\n * // Keep only FunctionComponent (0) and HostComponent (5) nodes\n * const filtered = filterTreeInclude(tree, new Set([\n * FiberTag.FunctionComponent,\n * FiberTag.HostComponent,\n * ]));\n * ```\n */\nexport function filterTreeInclude<T extends FiberNodeConstraint & { tag: FiberTagValue }>(\n tree: T | null,\n includeTags: Set<FiberTagValue>\n): T | null {\n if (tree === null) return null;\n\n // If root is NOT included, promote its children (but there can only be one root)\n if (!includeTags.has(tree.tag)) {\n const filteredChildren = filterChildrenInclude(tree.children, includeTags);\n return filteredChildren.length > 0 ? filteredChildren[0]! : null;\n }\n\n // Root is included, filter its children\n return {\n ...tree,\n children: filterChildrenInclude(tree.children, includeTags),\n };\n}\n\n/**\n * Filter an array of children, promoting grandchildren when a child is not included.\n */\nfunction filterChildrenInclude<T extends FiberNodeConstraint & { tag: FiberTagValue }>(\n children: T[],\n includeTags: Set<FiberTagValue>\n): T[] {\n const result: T[] = [];\n\n for (const child of children) {\n if (!includeTags.has(child.tag)) {\n // Child is NOT included - promote its filtered children\n const grandchildren = filterChildrenInclude(child.children, includeTags);\n result.push(...grandchildren);\n } else {\n // Child is included - keep it, recursively filter its children\n result.push({\n ...child,\n children: filterChildrenInclude(child.children, includeTags),\n });\n }\n }\n\n return result;\n}\n","/**\n * Fiber Tree Watching\n *\n * Stream fiber tree snapshots on React commits.\n *\n * ## Setup (Recommended)\n *\n * For guaranteed capture, call initHook() BEFORE React loads:\n *\n * ```ts\n * // At the VERY TOP of your entry file, before any React imports:\n * import { initHook } from '@modules/iframe-projection/fiber';\n *\n * initHook(); // Idempotent - safe to call multiple times\n *\n * // Now safe to import React\n * import React from 'react';\n * ```\n *\n * ## Watching\n *\n * After React mounts, call watch() to start receiving snapshots.\n * watch() will auto-initialize the hook if not already done.\n *\n * ```ts\n * const { stop } = watch((snapshot) => {\n * console.log('Tree updated:', snapshot.tree);\n * parent.postMessage(snapshot, '*');\n * });\n *\n * // Later: stop watching\n * stop();\n * ```\n *\n * ## How It Works\n *\n * - If no hook exists: creates one (works if called before React)\n * - If hook exists (e.g., DevTools extension): wraps it (works after React)\n * - If already initialized by us: reuses existing (idempotent)\n */\n\nimport { getFiberFromElement } from \"./capture\";\nimport type {\n DevToolsHook,\n Fiber,\n FiberRoot,\n ReactRenderer,\n} from \"./react-types\";\nimport { FiberTag } from \"./react-types\";\nimport {\n defaultSerialize,\n resolveCommittedFiber,\n type SerializeOptions,\n serializeTree,\n} from \"./serialize\";\nimport type {\n DefaultFiberNode,\n FiberNodeConstraint,\n FiberSnapshot,\n FiberTagValue,\n SerializeFn,\n} from \"./types\";\nimport { filterTreeInclude } from \"./utils\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// One-shot Capture (for validation)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Options for captureTree().\n */\nexport interface CaptureTreeOptions<\n T extends FiberNodeConstraint = DefaultFiberNode,\n> extends SerializeOptions {\n /**\n * CSS selector for the element to capture.\n * If not provided, captures the entire tree.\n */\n selector?: string;\n\n /**\n * Custom serialization function.\n * If not provided, uses defaultSerialize (name + tag).\n */\n serialize?: SerializeFn<T>;\n\n /**\n * Only include nodes with these tags in the tree.\n * Other nodes are filtered out and their children promoted.\n */\n tags?: FiberTagValue[];\n}\n\n/**\n * Capture the current fiber tree (one-shot).\n *\n * This uses the same logic as watch() to find the starting fiber,\n * ensuring consistency between watched deltas and captured snapshots.\n * Useful for validation that delta merging produces correct results.\n *\n * @returns The serialized tree, or null if no React root found\n *\n * @example\n * ```ts\n * // Capture full tree\n * const tree = captureTree();\n *\n * // Capture with same options as watcher\n * const tree = captureTree({ tags: [FiberTag.FunctionComponent] });\n * ```\n */\nexport function captureTree<T extends FiberNodeConstraint = DefaultFiberNode>(\n options: CaptureTreeOptions<T> = {},\n): T | null {\n const { selector, serialize, tags, ...serializeOptions } = options;\n const serializeFn =\n serialize ?? (defaultSerialize as unknown as SerializeFn<T>);\n const tagSet = tags && tags.length > 0 ? new Set(tags) : null;\n\n let startFiber: Fiber | null = null;\n\n if (selector) {\n // A selector is a self-contained root lookup: React stamps the selected\n // host element with its live fiber pointer. Do not require this bundle's\n // commit cache first. CanvasHost can contain more than one bundled copy of\n // iframe-projection; they share the marked global hook, but only the copy\n // that installed it owns the module-local `lastCommittedRoots` cache.\n const element = document.querySelector(selector);\n if (element) {\n const rawFiber = getFiberFromElement(element);\n startFiber = rawFiber ? resolveCommittedFiber(rawFiber) : null;\n }\n } else {\n const hook = getHook();\n if (!hook) return null;\n\n // Find a fiber root - try multiple approaches. Whole-document capture has\n // no DOM anchor, so it legitimately depends on the hook's root registry.\n let fiberRoot: FiberRoot | null = null;\n\n // 1. Try lastCommittedRoots (populated by our hook)\n for (const roots of lastCommittedRoots.values()) {\n for (const root of roots) {\n if (root.current) {\n fiberRoot = root;\n break;\n }\n }\n if (fiberRoot) break;\n }\n\n // 2. Try renderer.getFiberRoots() if available\n if (!fiberRoot) {\n for (const [_id, renderer] of hook.renderers) {\n const roots = (renderer as any).getFiberRoots?.();\n if (roots) {\n for (const root of roots) {\n if (root?.current) {\n fiberRoot = root;\n break;\n }\n }\n }\n if (fiberRoot) break;\n }\n }\n\n if (!fiberRoot) return null;\n\n // No selector: use first child of HostRoot (same as watch)\n const rootFiber = fiberRoot.current;\n if (rootFiber && rootFiber.tag === FiberTag.HostRoot && rootFiber.child) {\n startFiber = rootFiber.child;\n } else if (rootFiber) {\n startFiber = rootFiber;\n }\n }\n\n if (!startFiber) return null;\n\n // Serialize the tree\n let tree = serializeTree(startFiber, serializeFn, serializeOptions);\n\n // Apply tag filtering if specified\n if (tree && tagSet && \"tag\" in tree) {\n const filtered = filterTreeInclude(\n tree as unknown as FiberNodeConstraint & { tag: FiberTagValue },\n tagSet,\n );\n tree = filtered as unknown as typeof tree;\n }\n\n return tree;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Hook Initialization\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Symbol to mark hooks we've initialized */\nconst HOOK_MARKER = Symbol.for(\"iframe-projection-fiber-hook\");\n\n/** Handler types */\ntype CommitHandler = (\n fiberRoot: FiberRoot,\n rendererId: number,\n didError: boolean,\n) => void;\ntype InjectHandler = (renderer: ReactRenderer, rendererId: number) => void;\ntype UnmountHandler = (fiber: Fiber, rendererId: number) => void;\n\n/**\n * Interface returned by initHook() for registering callbacks.\n */\nexport interface HookInterface {\n /** Add a handler called on each React commit. Returns unsubscribe function. */\n onCommit: (handler: CommitHandler) => () => void;\n /** Add a handler called when React registers. Returns unsubscribe function. */\n onInject: (handler: InjectHandler) => () => void;\n /** Add a handler called when a fiber unmounts. Returns unsubscribe function. */\n onUnmount: (handler: UnmountHandler) => () => void;\n /** The underlying DevTools hook object */\n hook: DevToolsHook;\n /** Seed commits captured by a synchronous pre-module bootstrap. This updates\n * iframe-projection's cache without re-delivering them to a wrapped hook. */\n seedCommittedRoots: (roots: Iterable<readonly [number, FiberRoot]>) => void;\n}\n\n/** Extended hook type with our marker */\ninterface MarkedHook extends DevToolsHook {\n [HOOK_MARKER]: HookInterface;\n}\n\n/** Cached interface (module-level singleton) */\nlet cachedInterface: HookInterface | null = null;\n\n/** Every live committed fiber root per renderer ID. One React renderer can own\n * multiple roots in the same document (micro-frontends, portals mounted through\n * separate roots, and test harnesses all do this). */\nconst lastCommittedRoots = new Map<number, Set<FiberRoot>>();\n\nfunction rememberCommittedRoot(rendererId: number, root: FiberRoot): void {\n const roots = lastCommittedRoots.get(rendererId) ?? new Set<FiberRoot>();\n for (const previous of roots) {\n if (previous !== root && previous.containerInfo === root.containerInfo) {\n roots.delete(previous);\n }\n }\n // A HostRoot with no child is still a live, authoritative `root.render(null)`\n // result. Retain it; document-scope filtering excludes roots whose containers\n // no longer belong to the watched surface.\n roots.add(root);\n lastCommittedRoots.set(rendererId, roots);\n}\n\n/** Current roots captured by the hook, in commit-insertion order. */\nexport function getCommittedFiberRoots(): FiberRoot[] {\n return [...lastCommittedRoots.values()].flatMap((roots) => [...roots]);\n}\n\n/**\n * Reset the hook state. For testing only.\n * @internal\n */\nexport function _resetHookForTesting(): void {\n cachedInterface = null;\n lastCommittedRoots.clear();\n}\n\n/**\n * Initialize the DevTools hook for fiber watching.\n *\n * This function is idempotent - safe to call multiple times:\n * - If no hook exists: creates a new one\n * - If a hook exists (e.g., DevTools extension): wraps it\n * - If already initialized by us: returns existing interface\n *\n * For best results, call this BEFORE React loads. But if React DevTools\n * extension is installed, calling after React loads still works.\n *\n * @example\n * ```ts\n * // At top of entry file (before React):\n * initHook();\n *\n * // Or get the interface for manual handler registration:\n * const { onCommit } = initHook();\n * const unsubscribe = onCommit((root, id) => console.log('Commit!'));\n * ```\n */\nexport function initHook(): HookInterface {\n // Return cached if available\n if (cachedInterface) {\n return cachedInterface;\n }\n\n // Check for existing hook\n const existing =\n typeof window !== \"undefined\"\n ? (window as { __REACT_DEVTOOLS_GLOBAL_HOOK__?: DevToolsHook })\n .__REACT_DEVTOOLS_GLOBAL_HOOK__\n : undefined;\n\n // Already initialized by us (in case cachedInterface was cleared somehow)\n if (existing && HOOK_MARKER in existing) {\n cachedInterface = (existing as MarkedHook)[HOOK_MARKER];\n return cachedInterface;\n }\n\n // Create handler sets\n const commitHandlers = new Set<CommitHandler>();\n const injectHandlers = new Set<InjectHandler>();\n const unmountHandlers = new Set<UnmountHandler>();\n\n // Helper to create add/remove functions\n const createRegistrar =\n <T>(set: Set<T>) =>\n (handler: T): (() => void) => {\n set.add(handler);\n return () => set.delete(handler);\n };\n\n // Callbacks that dispatch to all registered handlers\n const callbacks: HookCallbacks = {\n onCommit: (root, id, didError) => {\n // Store for immediate snapshots when watch() starts\n rememberCommittedRoot(id, root);\n commitHandlers.forEach((h) => h(root, id, didError));\n },\n onInject: (renderer, id) => injectHandlers.forEach((h) => h(renderer, id)),\n onUnmount: (fiber, id) => unmountHandlers.forEach((h) => h(fiber, id)),\n };\n\n let hook: DevToolsHook;\n\n if (existing) {\n // Wrap existing hook (preserves DevTools extension functionality)\n wrapDevToolsHook(existing, callbacks);\n hook = existing;\n } else {\n // Create new hook\n hook = createDevToolsHook(callbacks);\n if (typeof window !== \"undefined\") {\n (\n window as { __REACT_DEVTOOLS_GLOBAL_HOOK__?: DevToolsHook }\n ).__REACT_DEVTOOLS_GLOBAL_HOOK__ = hook;\n }\n }\n\n // Build interface\n const hookInterface: HookInterface = {\n onCommit: createRegistrar(commitHandlers),\n onInject: createRegistrar(injectHandlers),\n onUnmount: createRegistrar(unmountHandlers),\n hook,\n seedCommittedRoots(roots) {\n for (const [rendererId, root] of roots) {\n rememberCommittedRoot(rendererId, root);\n }\n },\n };\n\n // Mark the hook so we recognize it later\n (hook as MarkedHook)[HOOK_MARKER] = hookInterface;\n cachedInterface = hookInterface;\n\n return hookInterface;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// DevTools Hook\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Callbacks for DevTools hook events.\n */\nexport interface HookCallbacks {\n /** Called when React injects a renderer */\n onInject?: (renderer: ReactRenderer, id: number) => void;\n /** Called after each React commit */\n onCommit?: (\n fiberRoot: FiberRoot,\n rendererId: number,\n didError: boolean,\n ) => void;\n /** Called when a fiber unmounts */\n onUnmount?: (fiber: Fiber, rendererId: number) => void;\n}\n\n/**\n * Create a React DevTools hook.\n *\n * Install this on `window.__REACT_DEVTOOLS_GLOBAL_HOOK__` BEFORE React loads.\n * React checks for this hook exactly once at initialization time.\n *\n * @param callbacks - Optional callbacks for hook events\n *\n * @example\n * ```ts\n * // Basic usage - just install the hook\n * window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = createDevToolsHook();\n *\n * // With callbacks\n * window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = createDevToolsHook({\n * onCommit: (root, id) => console.log('Commit!', root),\n * });\n * ```\n */\nexport function createDevToolsHook(callbacks?: HookCallbacks): DevToolsHook {\n const hook: DevToolsHook = {\n supportsFiber: true,\n renderers: new Map(),\n\n inject(renderer: ReactRenderer): number {\n const id = this.renderers.size + 1;\n this.renderers.set(id, renderer);\n callbacks?.onInject?.(renderer, id);\n return id;\n },\n\n onCommitFiberRoot(\n rendererId: number,\n fiberRoot: FiberRoot,\n _priority?: number,\n didError?: boolean,\n ): void {\n callbacks?.onCommit?.(fiberRoot, rendererId, didError === true);\n },\n\n onCommitFiberUnmount(rendererId: number, fiber: Fiber): void {\n callbacks?.onUnmount?.(fiber, rendererId);\n },\n\n // Required stubs for React compatibility\n checkDCE(_fn: Function): void {},\n onScheduleFiberRoot(): void {},\n };\n\n return hook;\n}\n\n/**\n * Wrap an existing DevTools hook to intercept events.\n *\n * Use this when React DevTools extension is already installed.\n * Preserves the original hook's functionality while adding your callbacks.\n *\n * @example\n * ```ts\n * if (window.__REACT_DEVTOOLS_GLOBAL_HOOK__) {\n * wrapDevToolsHook(window.__REACT_DEVTOOLS_GLOBAL_HOOK__, {\n * onCommit: (root) => console.log('Commit intercepted!'),\n * });\n * }\n * ```\n */\nexport function wrapDevToolsHook(\n hook: DevToolsHook,\n callbacks: HookCallbacks,\n): void {\n // Wrap inject\n if (callbacks.onInject) {\n const original = hook.inject.bind(hook);\n hook.inject = function (renderer: ReactRenderer): number {\n const id = original(renderer);\n callbacks.onInject!(renderer, id);\n return id;\n };\n }\n\n // Wrap onCommitFiberRoot\n if (callbacks.onCommit) {\n const original = hook.onCommitFiberRoot?.bind(hook);\n hook.onCommitFiberRoot = function (\n rendererId: number,\n fiberRoot: FiberRoot,\n priority?: number,\n didError?: boolean,\n ): void {\n callbacks.onCommit!(fiberRoot, rendererId, didError === true);\n original?.(rendererId, fiberRoot, priority, didError);\n };\n }\n\n // Wrap onCommitFiberUnmount\n if (callbacks.onUnmount) {\n const original = hook.onCommitFiberUnmount?.bind(hook);\n hook.onCommitFiberUnmount = function (\n rendererId: number,\n fiber: Fiber,\n ): void {\n callbacks.onUnmount!(fiber, rendererId);\n original?.(rendererId, fiber);\n };\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Hook Access\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get the installed DevTools hook, if any.\n */\nexport function getHook(): DevToolsHook | null {\n if (typeof window === \"undefined\") return null;\n return window.__REACT_DEVTOOLS_GLOBAL_HOOK__ ?? null;\n}\n\n/**\n * Check if React has connected to the hook.\n */\nexport function isReactConnected(): boolean {\n const hook = getHook();\n return hook !== null && hook.renderers.size > 0;\n}\n\n/**\n * Snapshot for diagnostics: whether {@link initHook} installed our marked hook on\n * `window.__REACT_DEVTOOLS_GLOBAL_HOOK__`, and whether React has registered a renderer.\n */\nexport function getFiberHookInjectionStatus(): {\n injected: boolean;\n reactConnected: boolean;\n} {\n const hook = getHook();\n if (!hook) {\n return { injected: false, reactConnected: false };\n }\n const injected = HOOK_MARKER in hook;\n const reactConnected = hook.renderers.size > 0;\n return { injected, reactConnected };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Watch\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Options for watch().\n */\nexport interface WatchOptions<T extends FiberNodeConstraint = DefaultFiberNode>\n extends SerializeOptions {\n /**\n * Callback receiving snapshots after each relevant commit.\n */\n onChange: (snapshot: FiberSnapshot<T>) => void;\n\n /**\n * CSS selector for the element to watch.\n * If not provided, watches the entire tree.\n *\n * When set, uses fiber flags for O(1) change detection:\n * - Checks `fiber.flags | fiber.subtreeFlags` to determine if subtree changed\n * - Only serializes when the subtree actually has changes\n * - Falls back to full serialization if element not found (may appear later)\n */\n selector?: string;\n\n /**\n * Only watch a specific renderer ID.\n * If not set, watches all renderers.\n */\n rendererId?: number;\n\n /**\n * Custom serialization function.\n * If not provided, uses defaultSerialize (name + tag).\n */\n serialize?: SerializeFn<T>;\n\n /**\n * Only include nodes with these tags in the tree.\n * Other nodes are filtered out and their children promoted.\n * @example tags: [FiberTag.FunctionComponent, FiberTag.HostComponent]\n */\n tags?: FiberTagValue[];\n}\n\n/**\n * Result of calling watch().\n */\nexport interface WatchHandle {\n /** Stop watching for updates */\n stop: () => void;\n}\n\n/**\n * Watch for fiber tree changes.\n *\n * Calls onChange with a FiberSnapshot after each React commit.\n * The snapshot contains a monotonically increasing sequence number\n * and the full serialized tree (or subtree if selector is specified).\n *\n * Automatically initializes the hook if not already done (via initHook()).\n *\n * @param options - Watch options including onChange callback\n *\n * @example\n * ```ts\n * // Default watch (name + tag)\n * const { stop } = watch({\n * onChange: (snapshot) => {\n * console.log(`Commit #${snapshot.sequence}:`, snapshot.tree);\n * }\n * });\n *\n * // Watch a specific subtree with tag filtering\n * const { stop } = watch({\n * selector: '#my-component',\n * tags: [FiberTag.FunctionComponent],\n * onChange: (snapshot) => sendToParent(snapshot),\n * });\n * ```\n */\nexport function watch<T extends FiberNodeConstraint = DefaultFiberNode>(\n options: WatchOptions<T>,\n): WatchHandle {\n const {\n onChange,\n selector,\n rendererId,\n serialize,\n tags,\n ...serializeOptions\n } = options;\n const serializeFn =\n serialize ?? (defaultSerialize as unknown as SerializeFn<T>);\n const tagSet = tags && tags.length > 0 ? new Set(tags) : null;\n\n // Initialize hook (idempotent) and get commit handler registrar\n const { onCommit } = initHook();\n\n // State\n let sequence = 0;\n let hasEmittedInitial = false;\n\n /**\n * React fiber flags that indicate actual RENDER changes (content changed).\n *\n * For delta optimization, we need to distinguish:\n * 1. RENDER flags: Indicate the component's output changed (affects DOM)\n * 2. EFFECT flags: Just mean effects need to run (don't affect DOM structure)\n * 3. STATIC flags: Always present on fibers with certain effect types\n *\n * We only care about RENDER flags when finding the minimal changed subtree,\n * because effect-only changes don't affect what gets serialized.\n *\n * RENDER flags (content changed):\n * Placement = 2 - Node needs to be inserted\n * Update = 4 - Node needs to update (state/props changed)\n * ChildDeletion = 16 - Child was deleted\n * ContentReset = 32 - Text content needs reset\n * Callback = 64 - Has callback (class components)\n * DidCapture = 128 - Error boundary captured error\n * ForceClientRender = 256 - Force client render\n * Ref = 512 - Ref changed\n * Snapshot = 1024 - Needs snapshot (getSnapshotBeforeUpdate)\n *\n * EFFECT flags (excluded - don't indicate content change):\n * Passive = 2048 - useEffect needs to run\n * Visibility = 8192 - Visibility changed (offscreen)\n * StoreConsistency = 32768 - Concurrent mode store check\n *\n * STATIC flags (excluded - always present, not work indicators):\n * RefStatic = 0x400000 (bit 22)\n * PassiveStatic = 0x800000 (bit 23)\n */\n const RENDER_CHANGE_FLAGS =\n 2 | // Placement\n 4 | // Update\n 16 | // ChildDeletion\n 32 | // ContentReset\n // 64 | // Callback - lifecycle callback, doesn't affect serialized output\n 128 | // DidCapture\n 256; // ForceClientRender\n // 512 | // Ref - ref changes don't affect serialized output\n // 1024; // Snapshot - getSnapshotBeforeUpdate, doesn't affect serialized output\n // = 2038 = 0x7F6\n\n /**\n * Check if a fiber subtree has changes using fiber flags.\n * Returns true if the subtree has any pending work (flags set).\n *\n * React's fiber.flags indicates work on this fiber.\n * React's fiber.subtreeFlags aggregates flags from all descendants.\n * If both are 0, nothing in the subtree changed.\n */\n const hasSubtreeChanges = (fiber: Fiber): boolean => {\n // flags and subtreeFlags are bitmasks indicating pending work\n // Mask out static flags (PassiveStatic, RefStatic, etc.) to get actual work flags\n const flags = ((fiber as any).flags ?? 0) & RENDER_CHANGE_FLAGS;\n const subtreeFlags =\n ((fiber as any).subtreeFlags ?? 0) & RENDER_CHANGE_FLAGS;\n return (flags | subtreeFlags) !== 0;\n };\n\n /**\n * Count how many \"filtered roots\" a fiber contributes to the filtered tree.\n * If the fiber is included, it contributes 1.\n * If filtered out, its children's contributions are summed (they get promoted).\n */\n const countFilteredRoots = (\n fiber: Fiber,\n includeTags: Set<FiberTagValue>,\n ): number => {\n if (includeTags.has(fiber.tag)) {\n return 1;\n }\n // Fiber is filtered out, count children's contributions\n let count = 0;\n let child = fiber.child;\n while (child) {\n count += countFilteredRoots(child, includeTags);\n child = child.sibling;\n }\n return count;\n };\n\n /**\n * Find all first-level changed subtrees.\n * Stops at the first changed node in each branch (doesn't descend further).\n * Returns array of { fiber, path } - may be multiple if siblings changed.\n *\n * \"First-level\" means we stop at the first changed node in each branch.\n * This emits a delta for EACH first-level changed node instead of finding\n * a common ancestor. The benefit is smaller payloads and naturally correct\n * paths even with tag filtering.\n *\n * Key properties:\n * 1. Never returns filtered-out nodes (only returns where isIncluded === true)\n * 2. Multiple deltas per commit possible, but never overlapping subtrees\n * 3. Path is built as we descend with proper offset tracking\n * 4. When a filtered-out node has direct changes, all its included\n * descendants are emitted (since we don't know exactly what changed)\n */\n const findChangedSubtrees = (\n startFiber: Fiber,\n includeTags: Set<FiberTagValue> | null,\n ): Array<{ fiber: Fiber; path: number[] }> => {\n const results: Array<{ fiber: Fiber; path: number[] }> = [];\n\n /**\n * @param currentPath Path to the nearest included ancestor\n * @param pendingOffset When inside a filtered-out node, the offset from\n * preceding siblings that needs to be added to path.\n * undefined means \"no pending offset\" (path is complete).\n * @param forceEmit When true, emit this node if included (used when a\n * filtered-out ancestor has direct changes)\n */\n const collect = (\n fiber: Fiber,\n currentPath: number[],\n pendingOffset: number | undefined,\n forceEmit: boolean,\n ): void => {\n const flags = ((fiber as any).flags ?? 0) & RENDER_CHANGE_FLAGS;\n const subtreeFlags =\n ((fiber as any).subtreeFlags ?? 0) & RENDER_CHANGE_FLAGS;\n const isIncluded = !includeTags || includeTags.has(fiber.tag);\n\n // If this node is included AND either:\n // - has direct changes, OR\n // - we're forced to emit (filtered ancestor had changes)\n // → collect it with the accumulated path\n if (isIncluded && (flags !== 0 || forceEmit)) {\n // Add pendingOffset to path if we have one (meaning we traversed\n // through filtered ancestors). undefined means path is already complete.\n const finalPath =\n pendingOffset !== undefined\n ? [...currentPath, pendingOffset]\n : currentPath;\n results.push({ fiber, path: finalPath });\n return;\n }\n\n // If this node is filtered out but has direct changes,\n // we need to emit all its included descendants\n const shouldForceChildren = !isIncluded && flags !== 0;\n\n // If no changes anywhere in subtree and not forcing → done\n if ((flags | subtreeFlags) === 0 && !forceEmit) {\n return;\n }\n\n // Descend into children\n let child = fiber.child;\n let filteredIndex = 0;\n\n while (child) {\n const childIsIncluded = !includeTags || includeTags.has(child.tag);\n // Compute child's index: add any pending offset to current filtered index\n const childIndex = (pendingOffset ?? 0) + filteredIndex;\n\n if (childIsIncluded) {\n // Child is included: if parent is included, add index to path and clear\n // pending. If parent is filtered, pass index as pending offset.\n collect(\n child,\n isIncluded ? [...currentPath, childIndex] : currentPath,\n isIncluded ? undefined : childIndex,\n shouldForceChildren || forceEmit,\n );\n } else {\n // Child is filtered out: pass accumulated offset to its descendants\n collect(\n child,\n currentPath,\n childIndex,\n shouldForceChildren || forceEmit,\n );\n }\n\n // Advance filtered index (account for promotion when filtering)\n filteredIndex += includeTags\n ? countFilteredRoots(child, includeTags)\n : 1;\n\n child = child.sibling;\n }\n };\n\n collect(startFiber, [], undefined, false);\n return results;\n };\n\n /**\n * Find the starting fiber for serialization.\n * If selector is specified, finds that element's fiber.\n * Otherwise returns the app component (first child of HostRoot).\n */\n const findStartFiber = (\n fiberRoot: FiberRoot,\n ): { fiber: Fiber | null; fromSelector: boolean } => {\n if (selector) {\n const element = document.querySelector(selector);\n if (element) {\n const fiber = getFiberFromElement(element);\n if (fiber) {\n // The element's raw fiber pointer is stamped once at mount and\n // alternates between the two double-buffered generations as\n // commits land; resolve to the committed one so serialized props\n // are never one commit stale.\n return { fiber: resolveCommittedFiber(fiber), fromSelector: true };\n }\n }\n // Selector specified but element not found - return null\n return { fiber: null, fromSelector: true };\n }\n\n // No selector - use full tree starting from app component\n const rootFiber = fiberRoot.current;\n if (rootFiber.tag === FiberTag.HostRoot && rootFiber.child) {\n return { fiber: rootFiber.child, fromSelector: false };\n }\n return { fiber: rootFiber, fromSelector: false };\n };\n\n // Handler for commits\n const handleCommit = (fiberRoot: FiberRoot, id: number): void => {\n if (rendererId !== undefined && id !== rendererId) return;\n\n // Find starting fiber (full tree or selector subtree)\n const { fiber: startFiber, fromSelector } = findStartFiber(fiberRoot);\n\n // Skip if no render changes in the tree (effect-only commits don't need re-serialization)\n // But always allow the first emission (for immediate snapshot on watch() start)\n if (hasEmittedInitial && startFiber && !hasSubtreeChanges(startFiber)) {\n return;\n }\n\n // Find all changed subtrees (may be multiple if siblings changed)\n // Falls back to full tree if no flags set or first emission\n const changedSubtrees =\n startFiber && hasSubtreeChanges(startFiber)\n ? findChangedSubtrees(startFiber, tagSet)\n : [{ fiber: startFiber, path: [] as number[] }];\n\n // If no changed subtrees found (can happen with filtering), emit full tree\n const subtreesToEmit =\n changedSubtrees.length > 0\n ? changedSubtrees\n : [{ fiber: startFiber, path: [] as number[] }];\n\n // Emit a delta for each changed subtree\n for (const { fiber, path } of subtreesToEmit) {\n if (!fiber) continue;\n\n let tree = serializeTree(fiber, serializeFn, serializeOptions);\n\n // Apply tag filtering if specified\n if (tree && tagSet && \"tag\" in tree) {\n const filtered = filterTreeInclude(\n tree as unknown as FiberNodeConstraint & { tag: FiberTagValue },\n tagSet,\n );\n tree = filtered as unknown as typeof tree;\n }\n\n if (!tree) continue; // Skip if filtering removed everything\n\n const snapshot: FiberSnapshot<T> = {\n sequence: sequence++,\n tree,\n path,\n };\n\n hasEmittedInitial = true;\n onChange(snapshot);\n }\n };\n\n // Register handler and get unsubscribe function\n const unsubscribe = onCommit(handleCommit);\n\n // Emit immediate snapshot if we have a last committed root\n if (rendererId !== undefined) {\n for (const root of lastCommittedRoots.get(rendererId) ?? []) {\n handleCommit(root, rendererId);\n }\n } else {\n // Emit for all renderers\n for (const [id, roots] of lastCommittedRoots) {\n for (const root of roots) {\n handleCommit(root, id);\n }\n }\n }\n\n return {\n stop: unsubscribe,\n };\n}\n","/**\n * Head Capture Utility\n *\n * Captures relevant <head> content from a document, excluding scripts\n * and resolving relative URLs to absolute.\n *\n * ## Shared Observer Pattern\n *\n * Uses a singleton HeadTracker that maintains one MutationObserver per document,\n * shared across all subscriptions. This avoids creating 50+ observers when there\n * are many watchers on the same page.\n */\n\n/** Elements to include from <head> */\nconst INCLUDE_TAGS = new Set([\"STYLE\", \"META\", \"BASE\", \"LINK\"]);\n\n/** Link rel values to include (stylesheet-related) */\nconst INCLUDE_LINK_RELS = new Set([\"stylesheet\"]);\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Head Tracker (Shared Observer)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * A subscription to head changes for a specific document.\n * Each subscription maintains its own hasMutations flag since they flush independently.\n */\nexport interface HeadSubscription {\n /** Whether there have been mutations since last flush */\n hasMutations: boolean;\n /** Flush and get head content. Returns content if isInitial or if mutations occurred. */\n flush(isInitial: boolean): string | undefined;\n /** Unsubscribe from head changes */\n unsubscribe(): void;\n}\n\nexport interface HeadMutationDetails {\n /** Vite stylesheet module ids whose style/link nodes changed in this batch. */\n stylesheetPaths: string[];\n}\n\n/**\n * Singleton tracker that manages shared MutationObservers for head watching.\n * One observer per document, shared across all subscriptions.\n */\nexport interface HeadTracker {\n /** Subscribe to head changes for a document */\n subscribe(\n doc: Document,\n onMutation: (details: HeadMutationDetails) => void,\n ): HeadSubscription;\n /** Clean up all observers */\n destroy(): void;\n /** Cardinality only; reads maintained collection sizes and performs no DOM\n * work. Used by the performance trace attached to an emitted capture. */\n readPerfSnapshot(): { observers: number; subscriptions: number };\n}\n\n/** Module-level singleton */\nlet instance: HeadTrackerImpl | null = null;\n\n/**\n * Get the singleton HeadTracker instance.\n */\nexport function getHeadTracker(): HeadTracker {\n if (!instance) {\n instance = new HeadTrackerImpl();\n }\n return instance;\n}\n\n/**\n * Reset the singleton. For testing only.\n * @internal\n */\nexport function _resetHeadTrackerForTesting(): void {\n instance?.destroy();\n instance = null;\n}\n\n/** Internal subscription implementation */\nclass HeadSubscriptionImpl implements HeadSubscription {\n hasMutations = false;\n private doc: Document;\n private callback: (details: HeadMutationDetails) => void;\n private onUnsubscribe: () => void;\n\n constructor(\n doc: Document,\n callback: (details: HeadMutationDetails) => void,\n onUnsubscribe: () => void,\n ) {\n this.doc = doc;\n this.callback = callback;\n this.onUnsubscribe = onUnsubscribe;\n }\n\n flush(isInitial: boolean): string | undefined {\n if (!isInitial && !this.hasMutations) {\n return undefined;\n }\n this.hasMutations = false;\n return captureHead(this.doc);\n }\n\n unsubscribe(): void {\n this.onUnsubscribe();\n }\n\n /** Called by tracker when relevant mutation detected */\n notifyMutation(details: HeadMutationDetails): void {\n this.hasMutations = true;\n this.callback(details);\n }\n}\n\n/** Per-document observer state */\ninterface DocObserverState {\n observer: MutationObserver;\n subscriptions: Set<HeadSubscriptionImpl>;\n}\n\nclass HeadTrackerImpl implements HeadTracker {\n private docObservers = new Map<Document, DocObserverState>();\n private activeSubscriptions = 0;\n\n subscribe(\n doc: Document,\n onMutation: (details: HeadMutationDetails) => void,\n ): HeadSubscription {\n let docState = this.docObservers.get(doc);\n\n // Create observer for this document if first subscription\n if (!docState) {\n docState = this.createDocObserver(doc);\n this.docObservers.set(doc, docState);\n }\n\n const subscription = new HeadSubscriptionImpl(doc, onMutation, () => {\n this.unsubscribe(doc, subscription);\n });\n docState.subscriptions.add(subscription);\n this.activeSubscriptions += 1;\n\n return subscription;\n }\n\n private createDocObserver(doc: Document): DocObserverState {\n const subscriptions = new Set<HeadSubscriptionImpl>();\n\n const notify = (details: HeadMutationDetails): void => {\n for (const sub of subscriptions) {\n sub.notifyMutation(details);\n }\n };\n\n const observeHead = (head: HTMLHeadElement): MutationObserver => {\n const observer = new MutationObserver((mutations) => {\n const details = this.readRelevantMutations(mutations, head);\n if (!details) return;\n notify(details);\n });\n observer.observe(head, {\n childList: true,\n subtree: true,\n attributes: true,\n characterData: true,\n });\n return observer;\n };\n\n if (doc.head) {\n return { observer: observeHead(doc.head), subscriptions };\n }\n\n // The document has no <head> yet — subscribers can attach before parsing\n // (e.g. a producer created from a frame preload). Watch for the head to\n // appear, then swap in the real observer and report one synthetic\n // mutation so subscribers capture the head they never saw arrive.\n const bootstrap = new MutationObserver(() => {\n const head = doc.head;\n if (!head) return;\n bootstrap.disconnect();\n state.observer = observeHead(head);\n notify({ stylesheetPaths: [] });\n });\n bootstrap.observe(doc, { childList: true, subtree: true });\n const state: DocObserverState = { observer: bootstrap, subscriptions };\n return state;\n }\n\n private unsubscribe(doc: Document, sub: HeadSubscriptionImpl): void {\n const docState = this.docObservers.get(doc);\n if (!docState) return;\n\n if (!docState.subscriptions.delete(sub)) return;\n this.activeSubscriptions = Math.max(0, this.activeSubscriptions - 1);\n\n // Disconnect observer if no more subscriptions for this document\n if (docState.subscriptions.size === 0) {\n docState.observer.disconnect();\n this.docObservers.delete(doc);\n }\n }\n\n /**\n * Check if mutations contain changes to elements we care about.\n * This filtering runs once per mutation batch (not once per subscription).\n */\n private readRelevantMutations(\n mutations: MutationRecord[],\n head: HTMLHeadElement,\n ): HeadMutationDetails | null {\n let relevant = false;\n const stylesheetPaths = new Set<string>();\n const collectStylesheetPath = (node: Node | null): void => {\n const element =\n node instanceof Element ? node : (node?.parentElement ?? null);\n if (!element) return;\n const candidates = [\n element,\n ...element.querySelectorAll(\n \"style[data-vite-dev-id], link[rel~='stylesheet']\",\n ),\n ];\n for (const candidate of candidates) {\n if (candidate instanceof HTMLStyleElement) {\n const id = candidate.getAttribute(\"data-vite-dev-id\")?.trim();\n if (id) stylesheetPaths.add(id);\n } else if (\n candidate instanceof HTMLLinkElement &&\n shouldIncludeLink(candidate)\n ) {\n const href = candidate.getAttribute(\"href\")?.trim() || candidate.href;\n if (href) stylesheetPaths.add(href);\n }\n }\n };\n\n for (const mutation of mutations) {\n const target = mutation.target;\n const element = target instanceof Element ? target : target.parentElement;\n\n if (!element || (!head.contains(element) && target !== head)) continue;\n\n // Check if this is a relevant element (one we would capture)\n const tagName = element.tagName;\n if (INCLUDE_TAGS.has(tagName)) {\n // For LINK, check if it's a stylesheet\n if (tagName === \"LINK\") {\n if (!shouldIncludeLink(element)) continue;\n }\n relevant = true;\n collectStylesheetPath(element);\n }\n\n // Also trigger for childList mutations on head itself (added/removed elements)\n if (mutation.type === \"childList\" && target === head) {\n relevant = true;\n }\n if (mutation.type === \"childList\") {\n for (const node of mutation.addedNodes) collectStylesheetPath(node);\n for (const node of mutation.removedNodes) collectStylesheetPath(node);\n }\n }\n return relevant ? { stylesheetPaths: [...stylesheetPaths] } : null;\n }\n\n destroy(): void {\n for (const docState of this.docObservers.values()) {\n docState.observer.disconnect();\n docState.subscriptions.clear();\n }\n this.docObservers.clear();\n this.activeSubscriptions = 0;\n }\n\n readPerfSnapshot(): { observers: number; subscriptions: number } {\n return {\n observers: this.docObservers.size,\n subscriptions: this.activeSubscriptions,\n };\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Legacy API (Backward Compatibility)\n// These functions delegate to the shared tracker for backward compatibility\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * State for a head watcher instance.\n * @deprecated Use getHeadTracker().subscribe() instead for better performance\n */\nexport interface HeadWatcher {\n /** The document being watched */\n doc: Document;\n /** Whether there have been mutations since last flush */\n hasMutations: boolean;\n /** Stop watching */\n stop: () => void;\n}\n\n/**\n * Starts watching a document's <head> for mutations.\n * @deprecated Use getHeadTracker().subscribe() instead for better performance\n */\nexport function watchHead(doc: Document, onMutation: () => void): HeadWatcher {\n const subscription = getHeadTracker().subscribe(doc, onMutation);\n\n // Wrap subscription in legacy HeadWatcher interface\n return {\n doc,\n get hasMutations() {\n return subscription.hasMutations;\n },\n set hasMutations(value: boolean) {\n subscription.hasMutations = value;\n },\n stop: () => subscription.unsubscribe(),\n };\n}\n\n/**\n * Checks if watcher has any pending head mutations.\n * @deprecated Access subscription.hasMutations directly\n */\nexport function hasPendingHeadChanges(watcher: HeadWatcher): boolean {\n return watcher.hasMutations;\n}\n\n/**\n * Flushes the head watcher, returning captured head content if there were changes.\n * @deprecated Use subscription.flush() directly\n */\nexport function flushHeadWatcher(\n watcher: HeadWatcher,\n isInitial: boolean,\n): string | undefined {\n if (!isInitial && !watcher.hasMutations) {\n return undefined;\n }\n watcher.hasMutations = false;\n return captureHead(watcher.doc);\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Head Capture\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Captures the <head> content from a document.\n *\n * - Includes: <style>, <link rel=\"stylesheet\">, <meta>, <base>\n * - Excludes: <script>, <title>, <link rel=\"icon/preload/etc\">\n * - Resolves relative URLs to absolute using document.baseURI\n *\n * @param doc - The document to capture head from\n * @returns Serialized head content (innerHTML for destination <head>)\n */\nexport function captureHead(doc: Document): string {\n const head = doc.head;\n if (!head) return \"\";\n\n const baseURI = doc.baseURI;\n const fragments: string[] = [];\n\n for (const child of Array.from(head.children)) {\n const tagName = child.tagName;\n\n // Skip non-included tags\n if (!INCLUDE_TAGS.has(tagName)) continue;\n\n // For <link>, only include stylesheets\n if (tagName === \"LINK\") {\n if (!shouldIncludeLink(child)) continue;\n }\n\n // Exclude Content-Security-Policy meta tags (they block srcdoc assets)\n if (tagName === \"META\") {\n const httpEquiv = child.getAttribute(\"http-equiv\")?.toLowerCase();\n const name = child.getAttribute(\"name\")?.toLowerCase();\n if (\n httpEquiv === \"content-security-policy\" ||\n name === \"content-security-policy\"\n ) {\n continue;\n }\n }\n\n // Clone and resolve URLs\n const clone = child.cloneNode(true) as Element;\n materializeStyleElementCssom(child, clone);\n resolveUrls(clone, baseURI);\n\n // Strip crossorigin from stylesheet links so they load in no-cors mode\n // in srcdoc projection iframes (which have a null origin that won't\n // match any server's Access-Control-Allow-Origin header)\n if (tagName === \"LINK\") {\n clone.removeAttribute(\"crossorigin\");\n }\n\n fragments.push(clone.outerHTML);\n }\n\n fragments.push(...captureAdoptedStyleSheets(doc));\n\n return fragments.join(\"\\n\");\n}\n\n/**\n * CSS-in-JS and framework runtimes can insert rules through CSSOM APIs, leaving\n * the DOM <style> text empty. Clone-time materialization preserves those rules\n * without mutating the live host document.\n */\nfunction materializeStyleElementCssom(source: Element, clone: Element): void {\n if (source.tagName !== \"STYLE\" || clone.tagName !== \"STYLE\") {\n return;\n }\n\n const style = source as HTMLStyleElement;\n const text = style.textContent ?? \"\";\n if (text.trim().length > 0) {\n return;\n }\n\n const cssText = serializeCssRules(style.sheet);\n if (cssText) {\n clone.textContent = cssText;\n }\n}\n\nfunction captureAdoptedStyleSheets(doc: Document): string[] {\n const sheets = Array.from(doc.adoptedStyleSheets ?? []);\n if (sheets.length === 0) {\n return [];\n }\n\n const fragments: string[] = [];\n for (const sheet of sheets) {\n const cssText = serializeCssRules(sheet);\n if (!cssText) {\n continue;\n }\n const style = doc.createElement(\"style\");\n style.setAttribute(\"data-projection-adopted-stylesheet\", \"true\");\n style.textContent = cssText;\n fragments.push(style.outerHTML);\n }\n return fragments;\n}\n\nfunction serializeCssRules(sheet: CSSStyleSheet | null): string {\n if (!sheet) {\n return \"\";\n }\n\n try {\n return Array.from(sheet.cssRules)\n .map((rule) => rule.cssText)\n .join(\"\\n\");\n } catch {\n // Cross-origin or otherwise unreadable stylesheet.\n return \"\";\n }\n}\n\nfunction shouldIncludeLink(element: Element): boolean {\n const rel = element.getAttribute(\"rel\");\n if (!rel) {\n return false;\n }\n return rel\n .toLowerCase()\n .split(/\\s+/)\n .some((token) => INCLUDE_LINK_RELS.has(token));\n}\n\n/**\n * Resolves relative URLs in an element to absolute URLs.\n */\nfunction resolveUrls(element: Element, baseURI: string): void {\n // Skip URL resolution if baseURI is not a valid HTTP(S) URL\n // (e.g., in test environments where baseURI is \"about:blank\")\n if (!baseURI || !baseURI.startsWith(\"http\")) {\n return;\n }\n\n // Resolve href attribute (for <link>, <base>)\n const href = element.getAttribute(\"href\");\n if (href && !isAbsoluteUrl(href)) {\n try {\n element.setAttribute(\"href\", new URL(href, baseURI).href);\n } catch {\n // Keep original href if URL resolution fails\n }\n }\n\n // Resolve src attribute (for future-proofing)\n const src = element.getAttribute(\"src\");\n if (src && !isAbsoluteUrl(src)) {\n try {\n element.setAttribute(\"src\", new URL(src, baseURI).href);\n } catch {\n // Keep original src if URL resolution fails\n }\n }\n}\n\n/**\n * Checks if a URL is absolute.\n */\nfunction isAbsoluteUrl(url: string): boolean {\n return /^(https?:)?\\/\\//i.test(url) || url.startsWith(\"data:\");\n}\n","/**\n * Capture-flush perf counters.\n *\n * Module-local mutable counters incremented by the hot paths that run inside\n * a combined-watch flush: the displayability walk's getComputedStyle reads,\n * the layout-kind style read during fiber serialization, and the\n * render-identity declaration walks. The flush resets them before capturing\n * and reads them after, shipping the totals on the emitted capture's `perf`\n * field — so the paths themselves never thread perf parameters through their\n * signatures. Increment-only: no DOM reads, no allocation.\n *\n * The same functions also run outside a flush (one-shot capture APIs); those\n * increments are simply discarded by the next flush's reset.\n */\n\ninterface CaptureFlushCounters {\n styleReadCount: number;\n identityNodesVisited: number;\n sourceVersionDomScanNodes: number;\n sourceVersionFiberSerializeNodes: number;\n sourceVersionFiberReductionNodes: number;\n sourceVersionFallbackScanNodes: number;\n}\n\nconst counters: CaptureFlushCounters = {\n styleReadCount: 0,\n identityNodesVisited: 0,\n sourceVersionDomScanNodes: 0,\n sourceVersionFiberSerializeNodes: 0,\n sourceVersionFiberReductionNodes: 0,\n sourceVersionFallbackScanNodes: 0,\n};\n\nconst producerReferencesByDocument = new Map<Document, number>();\nlet activeDocumentProducers = 0;\nlet activeRootObservers = 0;\nlet activeReactCommitSubscriptions = 0;\n\n/** Register one document producer and its one React commit subscription. */\nexport function registerDocumentCaptureProducer(\n document: Document,\n): () => void {\n const references = producerReferencesByDocument.get(document) ?? 0;\n if (references === 0) activeDocumentProducers += 1;\n producerReferencesByDocument.set(document, references + 1);\n activeReactCommitSubscriptions += 1;\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n const current = producerReferencesByDocument.get(document) ?? 0;\n if (current <= 1) {\n producerReferencesByDocument.delete(document);\n activeDocumentProducers = Math.max(0, activeDocumentProducers - 1);\n } else {\n producerReferencesByDocument.set(document, current - 1);\n }\n activeReactCommitSubscriptions = Math.max(\n 0,\n activeReactCommitSubscriptions - 1,\n );\n };\n}\n\n/** Register one independently observed projection root. */\nexport function registerCaptureRootObserver(): () => void {\n activeRootObservers += 1;\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n activeRootObservers = Math.max(0, activeRootObservers - 1);\n };\n}\n\nexport function readCaptureProducerCardinality(): {\n activeDocumentProducers: number;\n activeRootObservers: number;\n reactCommitSubscriptions: number;\n} {\n return {\n activeDocumentProducers,\n activeRootObservers,\n reactCommitSubscriptions: activeReactCommitSubscriptions,\n };\n}\n\n/** @internal Test isolation for producer ownership counters. */\nexport function _resetCaptureProducerCardinalityForTesting(): void {\n producerReferencesByDocument.clear();\n activeDocumentProducers = 0;\n activeRootObservers = 0;\n activeReactCommitSubscriptions = 0;\n}\n\n/** One getComputedStyle call on the capture path. */\nexport function countCaptureStyleRead(): void {\n counters.styleReadCount += 1;\n}\n\n/** One element/node visited by a render-identity declaration walk. */\nexport function countIdentityNodeVisited(): void {\n counters.identityNodesVisited += 1;\n}\n\nexport function countSourceVersionDomScanNode(): void {\n counters.sourceVersionDomScanNodes += 1;\n}\n\nexport function countSourceVersionFiberSerializeNode(): void {\n counters.sourceVersionFiberSerializeNodes += 1;\n}\n\nexport function countSourceVersionFiberReductionNode(): void {\n counters.sourceVersionFiberReductionNodes += 1;\n}\n\nexport function countSourceVersionFallbackScanNode(): void {\n counters.sourceVersionFallbackScanNodes += 1;\n}\n\nexport function resetCaptureFlushCounters(): void {\n counters.styleReadCount = 0;\n counters.identityNodesVisited = 0;\n counters.sourceVersionDomScanNodes = 0;\n counters.sourceVersionFiberSerializeNodes = 0;\n counters.sourceVersionFiberReductionNodes = 0;\n counters.sourceVersionFallbackScanNodes = 0;\n}\n\nexport function readCaptureFlushCounters(): Readonly<CaptureFlushCounters> {\n return { ...counters };\n}\n","import type { DomCapture } from \"../html/types\";\nimport { getHeadTracker } from \"../html/watch-head\";\nimport {\n readCaptureFlushCounters,\n readCaptureProducerCardinality,\n} from \"../shared/capture-perf\";\nimport type { CaptureProducerPerf } from \"./types\";\n\nexport interface BuildProjectionCapturePerfInput {\n readonly flushStartedAt: number;\n readonly snapshotMs: number;\n readonly identityMs: number;\n readonly html: DomCapture | undefined;\n readonly head?: string;\n readonly fiberNodeCount: number;\n readonly changedNodeEstimate: number;\n readonly fixedWindowTimersOpened: number;\n readonly maxSimultaneousTimers: number;\n readonly flushIntervalMs: number | null;\n readonly rawMutationRecords: number;\n readonly rawStateRecords: number;\n readonly rawPortalRecords: number;\n readonly producerCandidateNodes?: number;\n readonly producerVisitedNodes?: number;\n readonly candidateTargetsBeforeCoalescing: number;\n readonly candidateTargetsAfterCoalescing: number;\n readonly semanticDiscoveryNodesVisited?: number;\n readonly rootsPerBatch: number;\n readonly fullSnapshotReason: string | null;\n /** Closed-projection serializers can provide their already-known totals\n * without constructing a legacy DomCapture solely for instrumentation. */\n readonly htmlChars?: number;\n readonly domNodesSerialized?: number;\n readonly semanticNodesSerialized?: number;\n readonly annotationTargetsSerialized?: number;\n readonly stateTargetsSerialized?: number;\n readonly portalTargetsSerialized?: number;\n readonly observedFileEntries?: number;\n}\n\n/**\n * Assemble the producer receipt exclusively from facts already collected by\n * the real capture. This function performs no discovery traversal and no\n * destination diagnostic read.\n */\nexport function buildProjectionCapturePerf(\n input: BuildProjectionCapturePerfInput,\n): CaptureProducerPerf {\n const flushCounters = readCaptureFlushCounters();\n const cardinality = readCaptureProducerCardinality();\n const headCardinality = getHeadTracker().readPerfSnapshot();\n let htmlChars = input.html?.dom.html.length ?? 0;\n for (const portal of input.html?.portals ?? []) {\n htmlChars += portal.html.length;\n }\n\n return {\n flushStartedAt: input.flushStartedAt,\n flushMs: Date.now() - input.flushStartedAt,\n snapshotMs: input.snapshotMs,\n identityMs: input.identityMs,\n identityNodesVisited: flushCounters.identityNodesVisited,\n sourceVersionDomScanNodes: flushCounters.sourceVersionDomScanNodes,\n sourceVersionFiberSerializeNodes:\n flushCounters.sourceVersionFiberSerializeNodes,\n sourceVersionFiberReductionNodes:\n flushCounters.sourceVersionFiberReductionNodes,\n sourceVersionFallbackScanNodes:\n flushCounters.sourceVersionFallbackScanNodes,\n sourceVersionScanNodes:\n flushCounters.sourceVersionDomScanNodes +\n flushCounters.sourceVersionFiberSerializeNodes +\n flushCounters.sourceVersionFiberReductionNodes +\n flushCounters.sourceVersionFallbackScanNodes,\n styleReadCount: flushCounters.styleReadCount,\n htmlChars: input.htmlChars ?? htmlChars,\n headChars: input.head?.length ?? 0,\n fiberNodeCount: input.fiberNodeCount,\n changedNodeEstimate: input.changedNodeEstimate,\n ...cardinality,\n headObservers: headCardinality.observers,\n headSubscriptions: headCardinality.subscriptions,\n fixedWindowTimersOpened: input.fixedWindowTimersOpened,\n maxSimultaneousTimers: input.maxSimultaneousTimers,\n flushIntervalMs: input.flushIntervalMs,\n rawMutationRecords: input.rawMutationRecords,\n rawStateRecords: input.rawStateRecords,\n rawPortalRecords: input.rawPortalRecords,\n producerCandidateNodes:\n input.producerCandidateNodes ?? input.candidateTargetsBeforeCoalescing,\n producerVisitedNodes:\n input.producerVisitedNodes ?? input.candidateTargetsAfterCoalescing,\n candidateTargetsBeforeCoalescing: input.candidateTargetsBeforeCoalescing,\n candidateTargetsAfterCoalescing: input.candidateTargetsAfterCoalescing,\n semanticDiscoveryNodesVisited: input.semanticDiscoveryNodesVisited ?? 0,\n domNodesSerialized: input.domNodesSerialized ?? null,\n semanticNodesSerialized:\n input.semanticNodesSerialized ?? input.fiberNodeCount,\n annotationTargetsSerialized:\n input.annotationTargetsSerialized ??\n input.html?.declared.containedAnchors.length ??\n 0,\n stateTargetsSerialized:\n input.stateTargetsSerialized ?? input.html?.states.length ?? 0,\n portalTargetsSerialized:\n input.portalTargetsSerialized ?? input.html?.portals?.length ?? 0,\n headSerializations: input.head === undefined ? 0 : 1,\n observedFileEntries:\n input.observedFileEntries ??\n Object.keys(input.html?.declared.observedVersions ?? {}).length,\n batchesEmitted: 1,\n rootsPerBatch: input.rootsPerBatch,\n fullSnapshotReason: input.fullSnapshotReason,\n };\n}\n","/**\n * CSS Selector Utilities\n *\n * Pure functions for generating CSS selectors.\n */\n\n/**\n * Generates a unique CSS selector path for an element.\n *\n * Uses nth-of-type notation when needed for uniqueness among siblings.\n *\n * @param element - Element to generate selector for\n * @param root - Optional root element to stop at (selector will be relative to this)\n * @returns CSS selector path (e.g., \"body > div > button:nth-of-type(2)\")\n *\n * @example\n * ```ts\n * generateSelector(document.querySelector('button'));\n * // \"body > div > button\"\n *\n * generateSelector(button, container);\n * // \"div > button\" (relative to container)\n * ```\n */\nexport function generateSelector(element: Element, root?: Element): string {\n // Special cases for well-known elements\n if (!root) {\n if (element === document.documentElement) return \":root\";\n if (element === document.head) return \"head\";\n if (element === document.body) return \"body\";\n }\n\n // If element is the root, return empty string\n if (root && element === root) return \"\";\n\n const parts: string[] = [];\n let current: Element | null = element;\n const stopAt = root ?? document.documentElement;\n\n while (current && current !== stopAt) {\n const parent: Element | null = current.parentElement;\n if (!parent) break;\n\n const tagName = current.tagName.toLowerCase();\n\n // Count same-type siblings to determine if :nth-of-type is needed\n let index = 1;\n let sibling = current.previousElementSibling;\n while (sibling) {\n if (sibling.tagName === current.tagName) index++;\n sibling = sibling.previousElementSibling;\n }\n\n let sameTypeSiblings = 0;\n for (const child of parent.children) {\n if (child.tagName === current.tagName) sameTypeSiblings++;\n }\n\n if (sameTypeSiblings > 1) {\n parts.unshift(`${tagName}:nth-of-type(${index})`);\n } else {\n parts.unshift(tagName);\n }\n\n current = parent;\n }\n\n // Handle edge cases\n if (parts.length === 0) {\n if (element === document.body) return \"body\";\n if (element === document.head) return \"head\";\n return \"\";\n }\n\n const path = parts.join(\" > \");\n\n // Anchor to root with :scope so querySelector matches at the correct depth.\n // Without this, \"div > div > div:nth-of-type(2)\" is ambiguous — it can match\n // any ancestor chain of divs at any depth within the subtree, not just the\n // specific depth from the root. :scope pins the first segment to a direct\n // child of the querySelector target.\n if (root) return `:scope > ${path}`;\n\n return path;\n}\n\n/**\n * Finds the Lowest Common Ancestor (LCA) of a set of nodes.\n *\n * The LCA is the deepest element that is an ancestor of all provided nodes.\n * Useful for determining the minimal subtree that contains all mutations.\n *\n * @param nodes - Set of DOM nodes to find common ancestor for\n * @returns The LCA element, or null if no common ancestor found\n */\nexport function findLowestCommonAncestor(nodes: Set<Node>): Element | null {\n if (nodes.size === 0) return null;\n\n // Build ancestor chains for each node (from root to node)\n const ancestorChains: Element[][] = [];\n\n for (const node of nodes) {\n const chain: Element[] = [];\n let current: Node | null =\n node instanceof Element ? node : node.parentElement;\n\n while (current && current !== document) {\n if (current instanceof Element) {\n chain.unshift(current);\n }\n current = current.parentNode;\n }\n\n if (chain.length > 0) {\n ancestorChains.push(chain);\n }\n }\n\n if (ancestorChains.length === 0) {\n return document.documentElement;\n }\n\n // Find the deepest common ancestor by comparing chains\n let lca: Element = document.documentElement;\n const firstChain = ancestorChains[0]!;\n const minLength = Math.min(...ancestorChains.map((c) => c.length));\n\n for (let i = 0; i < minLength; i++) {\n const candidate = firstChain[i];\n if (candidate && ancestorChains.every((chain) => chain[i] === candidate)) {\n lca = candidate;\n } else {\n break;\n }\n }\n\n return lca;\n}\n","/**\n * DOM Watcher\n *\n * Tracks DOM mutations using MutationObserver.\n * Collects mutated elements for later flushing.\n * Assigns unique data-dom-id attributes for reference tracking.\n */\n\nimport { findLowestCommonAncestor } from \"./selectors\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// DOM ID Assignment\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Attribute name for DOM element IDs */\nexport const DOM_ID_ATTR = \"data-dom-id\";\n\n// Module-level singleton state for ID generation (shared across all watchers)\nlet sessionHash: string | null = null;\nlet idCounter = 0;\n\n/**\n * Gets or generates the session hash (idempotent).\n * Returns the same 4-character hash for all calls within this context.\n */\nfunction getOrCreateSessionHash(): string {\n if (sessionHash === null) {\n sessionHash = Math.random().toString(36).substring(2, 6);\n }\n return sessionHash;\n}\n\n/**\n * Gets the current session hash.\n * Creates one if it doesn't exist yet.\n */\nexport function getSessionHash(): string {\n return getOrCreateSessionHash();\n}\n\n/**\n * Resets the session state. Primarily for testing.\n * @internal\n */\nexport function _resetSessionState(): void {\n sessionHash = null;\n idCounter = 0;\n}\n\n/**\n * Assigns a unique data-dom-id to an element.\n * ONLY assigns if the element doesn't already have one.\n * @returns The assigned or existing ID\n */\nfunction assignDomId(element: Element): string {\n const existing = element.getAttribute(DOM_ID_ATTR);\n if (existing !== null) {\n return existing;\n }\n\n const id = `${getOrCreateSessionHash()}-${idCounter++}`;\n element.setAttribute(DOM_ID_ATTR, id);\n return id;\n}\n\n/**\n * Return the stable projection identity for one host element, assigning it\n * when needed. Producer serializers call this while they are already visiting\n * an exact changed region, so React's synchronous commit notification does not\n * have to race MutationObserver's later ID-bookkeeping delivery.\n *\n * Editor-owned descendants remain opaque. The contenteditable boundary itself\n * is addressable, but nothing underneath it receives projection attributes.\n */\nexport function ensureProjectionDomId(element: Element): string | null {\n const existing = element.getAttribute(DOM_ID_ATTR);\n if (existing !== null) return existing;\n if (hasContentEditableAncestor(element)) return null;\n return assignDomId(element);\n}\n\n/**\n * Returns true if the element itself has contenteditable set.\n * This is a cheap own-property check (no ancestor traversal).\n */\nfunction isContentEditableRoot(element: Element): boolean {\n return element.getAttribute(\"contenteditable\") !== null;\n}\n\n/**\n * Returns true if any ancestor (excluding the element itself) carries\n * contenteditable. Used to keep mutation-time inserts inside an editor's\n * subtree from receiving data-dom-id, while still stamping a freshly\n * mounted contenteditable element when it's added at the top of an\n * `assignDomIdToTree` call.\n */\nfunction hasContentEditableAncestor(element: Element): boolean {\n let current: Element | null = element.parentElement;\n while (current) {\n if (current.getAttribute(\"contenteditable\") !== null) {\n return true;\n }\n current = current.parentElement;\n }\n return false;\n}\n\n/**\n * Assigns data-dom-id to an element and its descendants.\n *\n * Stamps a contenteditable element itself (so it remains addressable as\n * a layer — selectable on the canvas, resolvable from the layers panel),\n * but never descends into its subtree: editors like ProseMirror own\n * their internal DOM and will destroy/recreate children that receive\n * foreign attributes, creating a MutationObserver feedback loop.\n *\n * If `root` is already inside a contenteditable subtree (e.g. a node\n * added by an editor via mutation), it is left untouched entirely.\n */\nfunction assignDomIdToTree(root: Element): void {\n if (hasContentEditableAncestor(root)) {\n return;\n }\n ensureProjectionDomId(root);\n if (isContentEditableRoot(root)) {\n return;\n }\n // Use a manual TreeWalker-style loop so we can stamp contenteditable\n // boundaries without descending into them, without an ancestor check\n // on every element.\n const stack: Element[] = [];\n for (let i = root.children.length - 1; i >= 0; i--) {\n stack.push(root.children[i] as Element);\n }\n while (stack.length > 0) {\n const element = stack.pop()!;\n ensureProjectionDomId(element);\n if (isContentEditableRoot(element)) {\n continue;\n }\n for (let i = element.children.length - 1; i >= 0; i--) {\n stack.push(element.children[i] as Element);\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// DOM Watcher\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * State for a DOM watcher instance.\n */\nexport interface DomWatcher {\n /** The root element being watched */\n root: Element;\n /** Set of elements that have mutated since last flush */\n mutatedElements: Set<Element>;\n /** Elements added (per mutation record, top level only) since last flush.\n * Together with `mutatedElements.size` this estimates how many DOM nodes a\n * capture actually needs to cover — the perf denominator scoped captures\n * are judged against. */\n addedElementCount: number;\n /** Raw observer records received since the previous flush. */\n mutationRecordCount: number;\n /** Exact observer-local records retained for the regional projection path.\n * Nodes are source-realm references and never cross the wire. */\n projectionMutations: ProjectionDomMutation[];\n /**\n * Synchronously retain records already queued by MutationObserver. React's\n * commit hook calls this after each commit so DOM-producing and\n * semantic-only commits can be distinguished without guessing at the later\n * observer microtask. The returned count excludes our own data-dom-id\n * bookkeeping records.\n */\n takePendingRecords: () => number;\n /** Stop watching */\n stop: () => void;\n}\n\nexport interface ProjectionDomMutation {\n readonly type: \"attributes\" | \"characterData\" | \"childList\";\n readonly target: Node;\n readonly attributeName?: string | null;\n /** Producer-local baseline for final-state scalar coalescing. */\n readonly oldValue?: string | null;\n readonly addedNodes?: readonly Node[];\n readonly removedNodes?: readonly Node[];\n readonly previousSibling?: Node | null;\n readonly nextSibling?: Node | null;\n}\n\n/**\n * Starts watching an element for DOM mutations.\n *\n * Mutations are collected in a Set and can be flushed via getDirtyElements().\n * The watcher does NOT debounce or automatically trigger updates - that's\n * the responsibility of the combined watch.ts.\n *\n * @param root - Element to watch\n * @param onMutation - Called when any mutation occurs (for triggering flush)\n * @returns DomWatcher instance\n *\n * @example\n * ```ts\n * const watcher = watchDom(document.body, () => {\n * // Mutation detected - schedule a flush\n * scheduleDebouncedFlush();\n * });\n *\n * // Later, get what changed and clear\n * const { lca, elements } = watcher.flush();\n * ```\n */\nexport function watchDom(root: Element, onMutation: () => void): DomWatcher {\n const mutatedElements = new Set<Element>();\n\n // Assign IDs to all existing elements in the tree\n assignDomIdToTree(root);\n\n const retainMutations = (\n mutations: readonly MutationRecord[],\n ): number => {\n // MutationObserver reports every write, while projection publishes final\n // state. Collapse repeated writes to the same scalar target to the first\n // old value and compare that with the final live value. A transient\n // set/remove pair is therefore no mutation at all.\n const scalarMutations: MutationRecord[] = [];\n const firstAttributeByTarget = new WeakMap<\n Element,\n Map<string, MutationRecord>\n >();\n const firstCharacterDataByTarget = new WeakMap<Node, MutationRecord>();\n for (const mutation of mutations) {\n if (mutation.type === \"attributes\" && mutation.attributeName !== null) {\n // Assigning stable IDs is producer bookkeeping. MutationObserver\n // reports those writes in a later delivery; treating them as\n // application changes would create a self-sustaining projection echo.\n if (mutation.attributeName === DOM_ID_ATTR) continue;\n const target = mutation.target as Element;\n const byName = firstAttributeByTarget.get(target) ?? new Map();\n if (!byName.has(mutation.attributeName)) {\n byName.set(mutation.attributeName, mutation);\n firstAttributeByTarget.set(target, byName);\n scalarMutations.push(mutation);\n }\n } else if (mutation.type === \"characterData\") {\n if (!firstCharacterDataByTarget.has(mutation.target)) {\n firstCharacterDataByTarget.set(mutation.target, mutation);\n scalarMutations.push(mutation);\n }\n } else {\n scalarMutations.push(mutation);\n }\n }\n\n let retained = 0;\n for (const mutation of scalarMutations) {\n // React and source-annotation helpers can idempotently write an\n // attribute during a commit. MutationObserver reports that write even\n // though the document's final state did not change. It is not DOM\n // evidence for the commit and must not suppress semantic discovery.\n //\n // `drainProjectionDomMutations` repeats this comparison against final\n // state, but that is a later and narrower answer: the check here decides\n // whether the producer wakes at all and whether the target joins\n // `mutatedElements` — the set the next capture's LCA is measured over.\n // Dropping it wakes the producer on a write that changed nothing and\n // widens the captured region to the untouched element.\n if (\n mutation.type === \"attributes\" &&\n mutation.attributeName !== null &&\n mutation.oldValue ===\n (mutation.target as Element).getAttribute(mutation.attributeName)\n ) {\n continue;\n }\n if (\n mutation.type === \"characterData\" &&\n mutation.oldValue === mutation.target.textContent\n ) {\n continue;\n }\n retained += 1;\n watcher.mutationRecordCount += 1;\n watcher.projectionMutations.push({\n type: mutation.type,\n target: mutation.target,\n ...(mutation.type === \"attributes\" || mutation.type === \"characterData\"\n ? { oldValue: mutation.oldValue }\n : {}),\n ...(mutation.type === \"attributes\"\n ? { attributeName: mutation.attributeName }\n : {}),\n ...(mutation.type === \"childList\"\n ? {\n addedNodes: Array.from(mutation.addedNodes),\n removedNodes: Array.from(mutation.removedNodes),\n previousSibling: mutation.previousSibling,\n nextSibling: mutation.nextSibling,\n }\n : {}),\n });\n const target =\n mutation.target instanceof Element\n ? mutation.target\n : mutation.target.parentElement;\n\n if (target && root.contains(target)) {\n mutatedElements.add(target);\n }\n\n if (mutation.type === \"childList\") {\n // Assign IDs to newly added elements and their entire subtrees.\n // assignDomIdToTree skips contenteditable subtrees, so editors\n // like ProseMirror won't get foreign attributes.\n for (const node of mutation.addedNodes) {\n if (node instanceof Element && root.contains(node)) {\n assignDomIdToTree(node);\n watcher.addedElementCount += 1;\n }\n }\n\n // Track parent for childList mutations\n if (\n mutation.target instanceof Element &&\n root.contains(mutation.target)\n ) {\n mutatedElements.add(mutation.target);\n }\n }\n }\n return retained;\n };\n\n const observer = new MutationObserver((mutations) => {\n if (retainMutations(mutations) > 0 && mutatedElements.size > 0)\n onMutation();\n });\n\n observer.observe(root, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeOldValue: true,\n characterData: true,\n characterDataOldValue: true,\n });\n\n const watcher: DomWatcher = {\n root,\n mutatedElements,\n addedElementCount: 0,\n mutationRecordCount: 0,\n projectionMutations: [],\n takePendingRecords: () => retainMutations(observer.takeRecords()),\n stop: () => {\n observer.disconnect();\n mutatedElements.clear();\n watcher.mutationRecordCount = 0;\n watcher.projectionMutations.length = 0;\n },\n };\n return watcher;\n}\n\n/**\n * Flushes the watcher, returning the LCA of all mutations and clearing state.\n *\n * @returns The lowest common ancestor of all mutations, or null if no mutations\n */\nexport function flushDomWatcher(watcher: DomWatcher): Element | null {\n watcher.addedElementCount = 0;\n watcher.mutationRecordCount = 0;\n watcher.projectionMutations.length = 0;\n if (watcher.mutatedElements.size === 0) {\n return null;\n }\n\n const lca = findLowestCommonAncestor(watcher.mutatedElements);\n watcher.mutatedElements.clear();\n\n // If LCA is outside our root (shouldn't happen, but safety check)\n if (lca && !watcher.root.contains(lca) && lca !== watcher.root) {\n return watcher.root;\n }\n\n return lca;\n}\n\n/**\n * Detach the exact source records for one regional flush. This consumes the\n * same pending observation as the legacy LCA flush; callers choose one view,\n * never both.\n */\nexport function drainProjectionDomMutations(\n watcher: DomWatcher,\n): ProjectionDomMutation[] {\n const retained = watcher.projectionMutations.splice(0);\n const mutations: ProjectionDomMutation[] = [];\n const firstAttributeByTarget = new WeakMap<Element, Set<string>>();\n const firstCharacterDataTargets = new WeakSet<Node>();\n for (const mutation of retained) {\n const attributeName = mutation.attributeName;\n if (mutation.type === \"attributes\" && attributeName != null) {\n const target = mutation.target as Element;\n const names = firstAttributeByTarget.get(target) ?? new Set<string>();\n if (names.has(attributeName)) continue;\n names.add(attributeName);\n firstAttributeByTarget.set(target, names);\n if (mutation.oldValue === target.getAttribute(attributeName)) {\n continue;\n }\n mutations.push({\n type: \"attributes\",\n target,\n attributeName,\n });\n continue;\n }\n if (mutation.type === \"characterData\") {\n if (firstCharacterDataTargets.has(mutation.target)) continue;\n firstCharacterDataTargets.add(mutation.target);\n if (mutation.oldValue === mutation.target.textContent) continue;\n mutations.push({ type: \"characterData\", target: mutation.target });\n continue;\n }\n mutations.push(mutation);\n }\n watcher.mutatedElements.clear();\n watcher.addedElementCount = 0;\n watcher.mutationRecordCount = 0;\n return mutations;\n}\n\n/**\n * Checks if watcher has any pending mutations.\n */\nexport function hasPendingMutations(watcher: DomWatcher): boolean {\n return watcher.mutatedElements.size > 0;\n}\n","/**\n * Declared Capture Facts (producer-side)\n *\n * Computes the `DeclaredCaptureFacts` a capture producer attaches to its\n * `DomCapture`. Everything here reads the LIVE DOM the producer already\n * holds — never the serialized HTML string — so the facts are ground truth\n * rather than a re-parse of the payload. See specs/canvas-determinism.md §4.\n */\n\nimport type { DeclaredCaptureFacts } from \"./types\";\n\n/**\n * Two annotation namespaces stamp the source-mapped iframe DOM:\n * - JSX: `data-tempo-filepath` + `data-tempo-position` + `data-tempo-modifiedts`\n * - HTML: `data-tempo-html-filepath` + `data-tempo-html-offset` +\n * `data-tempo-html-modifiedts`\n * A single element may carry BOTH (an HTML element nested inside a JSX host\n * that also got source-located), so each namespace is read independently.\n */\nconst SOURCE_ANNOTATED_SELECTOR =\n \"[data-tempo-filepath], [data-tempo-html-filepath]\";\n\ninterface AnnotationNamespace {\n filepathAttr: string;\n positionAttr: string;\n modifiedTsAttr: string;\n sourceVersionAttr: string;\n}\n\nconst NAMESPACES: readonly AnnotationNamespace[] = [\n {\n filepathAttr: \"data-tempo-filepath\",\n positionAttr: \"data-tempo-position\",\n modifiedTsAttr: \"data-tempo-modifiedts\",\n sourceVersionAttr: \"data-tempo-source-version\",\n },\n {\n filepathAttr: \"data-tempo-html-filepath\",\n positionAttr: \"data-tempo-html-offset\",\n modifiedTsAttr: \"data-tempo-html-modifiedts\",\n sourceVersionAttr: \"data-tempo-html-source-version\",\n },\n];\n\n/**\n * Compute the declared facts for a capture.\n *\n * @param targetElement - The element whose subtree is serialized into\n * `dom.html` (the mutation LCA for scoped captures, or the capture root\n * for whole-surface ones).\n * @param captureRoot - The watched root. `complete` is `targetElement ===\n * captureRoot`. The render-error probe searches the WHOLE root (the error\n * overlay is a surface-level fact, not necessarily inside the scoped LCA).\n * @param scopeSelector - The selector the producer already computed for\n * `targetElement` relative to `captureRoot` (\"\" for whole-surface).\n * Surfaced as `scopeSelector` only when the capture is not complete.\n * @param portalElements - Live portal root elements whose content the\n * producer also serializes into `portals`. Their annotations count toward\n * `observedVersions`/`containedAnchors` exactly as the DOM subtree's do.\n */\nexport function computeDeclaredFacts(\n targetElement: Element,\n captureRoot: Element,\n scopeSelector: string,\n portalElements: readonly Element[],\n): DeclaredCaptureFacts {\n const observedVersions: Record<string, number> = {};\n const observedSourceVersions: Record<string, string> = {};\n const anchorSet = new Set<string>();\n\n const visit = (element: Element): void => {\n for (const ns of NAMESPACES) {\n const filepath = element.getAttribute(ns.filepathAttr);\n if (filepath == null || filepath.length === 0) continue;\n\n const modifiedTsRaw = element.getAttribute(ns.modifiedTsAttr);\n if (modifiedTsRaw != null) {\n const modifiedTs = Number(modifiedTsRaw);\n if (!Number.isNaN(modifiedTs)) {\n const existing = observedVersions[filepath];\n if (existing === undefined || modifiedTs > existing) {\n observedVersions[filepath] = modifiedTs;\n // Co-locate the content-version token with the newest render: it\n // rides the same element that just set the file's MAX modifiedts.\n // Clear a stale token from an older render when the newest element\n // carries none (a mid-HMR mixed tree, or an old-SDK element).\n const version = element.getAttribute(ns.sourceVersionAttr);\n if (version != null && version.length > 0) {\n observedSourceVersions[filepath] = version;\n } else {\n delete observedSourceVersions[filepath];\n }\n }\n }\n }\n\n const position = element.getAttribute(ns.positionAttr);\n if (position != null && position.length > 0) {\n anchorSet.add(`${filepath} ${position}`);\n }\n }\n };\n\n // The serialized population: the target subtree (including the target\n // element itself, whose annotations travel in `dom.attributes`) plus every\n // portal root and its descendants.\n const walkRoots: readonly Element[] = [targetElement, ...portalElements];\n for (const root of walkRoots) {\n if (root.matches(SOURCE_ANNOTATED_SELECTOR)) visit(root);\n for (const annotated of root.querySelectorAll(SOURCE_ANNOTATED_SELECTOR)) {\n visit(annotated);\n }\n }\n\n const complete = targetElement === captureRoot;\n\n return {\n complete,\n scopeSelector: complete ? null : scopeSelector,\n observedVersions,\n observedSourceVersions,\n containedAnchors: Array.from(anchorSet),\n renderError: computeRenderError(captureRoot),\n };\n}\n\n/**\n * Render-error boundary state for a capture root. Non-null iff a\n * `[data-render-error=\"true\"]` element exists anywhere in the live root\n * subtree (or is the root itself); its `data-render-error-message` becomes\n * `message` when present.\n */\nfunction computeRenderError(\n captureRoot: Element,\n): DeclaredCaptureFacts[\"renderError\"] {\n const errorElement = captureRoot.matches('[data-render-error=\"true\"]')\n ? captureRoot\n : captureRoot.querySelector('[data-render-error=\"true\"]');\n if (!errorElement) return null;\n return {\n message: errorElement.getAttribute(\"data-render-error-message\"),\n };\n}\n","import { countCaptureStyleRead } from \"../shared/capture-perf\";\nimport type { CaptureDisplayability } from \"./types\";\n\n/** Elements whose descendants do not contribute projected pixels/content. */\nconst IGNORED_CONTENT_TAGS = new Set([\n \"DATALIST\",\n \"LINK\",\n \"META\",\n \"NOSCRIPT\",\n \"SCRIPT\",\n \"STYLE\",\n \"TEMPLATE\",\n]);\n\nconst VISUAL_ASSET_TAGS = new Set([\n \"AUDIO\",\n \"CANVAS\",\n \"EMBED\",\n \"IFRAME\",\n \"IMG\",\n \"INPUT\",\n \"OBJECT\",\n \"SELECT\",\n \"SVG\",\n \"TEXTAREA\",\n \"VIDEO\",\n]);\n\n/**\n * Measures displayable structure in a live, styled document.\n *\n * The capture root itself is excluded because `DomCapture.dom.html` contains\n * its children. Supplemental roots are included because portal updates carry\n * each portal root's `outerHTML`. A null result means no browsing context was\n * available, so callers must omit the proof rather than infer it from markup.\n */\nexport function measureComputedDisplayability(\n captureRoot: Element,\n supplementalRoots: readonly Element[] = [],\n): CaptureDisplayability | null {\n const doc = captureRoot.ownerDocument;\n const view = doc.defaultView;\n if (\n !view ||\n !captureRoot.isConnected ||\n supplementalRoots.some(\n (root) => root.ownerDocument !== doc || !root.isConnected,\n )\n ) {\n return null;\n }\n\n const result: CaptureDisplayability = {\n version: 1,\n elementCount: 0,\n paintedElementCount: 0,\n nonEmptyTextNodeCount: 0,\n visualAssetCount: 0,\n };\n\n try {\n const rootBlocked = hasBlockingElementInChain(captureRoot, view);\n const rootTextVisible =\n !rootBlocked && elementHasVisibleComputedVisibility(captureRoot, view);\n for (const child of Array.from(captureRoot.childNodes)) {\n visitNode(child, rootBlocked, rootTextVisible, view, result);\n }\n\n for (const supplementalRoot of supplementalRoots) {\n visitNode(\n supplementalRoot,\n hasBlockingElementInChain(supplementalRoot.parentElement, view),\n true,\n view,\n result,\n );\n }\n } catch {\n // A producer declaration is proof. If style inspection is unavailable for\n // any part of the render domain, omit the whole profile conservatively.\n return null;\n }\n\n return result;\n}\n\nfunction visitNode(\n node: Node,\n blockedByAncestor: boolean,\n parentTextVisible: boolean,\n view: Window,\n result: CaptureDisplayability,\n): void {\n if (node.nodeType === 3) {\n if (\n !blockedByAncestor &&\n parentTextVisible &&\n (node.textContent?.trim().length ?? 0) > 0\n ) {\n result.nonEmptyTextNodeCount += 1;\n }\n return;\n }\n if (node.nodeType !== 1) return;\n\n const element = node as Element;\n const blocked = blockedByAncestor || elementBlocksSubtree(element, view);\n if (blocked) return;\n\n const visible = elementHasVisibleComputedVisibility(element, view);\n if (visible) {\n result.elementCount += 1;\n if (elementPaintsOwnPixels(element, view)) {\n result.paintedElementCount = (result.paintedElementCount ?? 0) + 1;\n }\n if (VISUAL_ASSET_TAGS.has(element.tagName)) {\n result.visualAssetCount += 1;\n }\n }\n\n for (const child of Array.from(element.childNodes)) {\n visitNode(child, false, visible, view, result);\n }\n}\n\nfunction elementPaintsOwnPixels(element: Element, view: Window): boolean {\n countCaptureStyleRead();\n const style = view.getComputedStyle(element);\n if (colorCanPaint(style.backgroundColor)) return true;\n if (style.backgroundImage && style.backgroundImage !== \"none\") return true;\n if (style.boxShadow && style.boxShadow !== \"none\") return true;\n if (\n style.outlineStyle !== \"none\" &&\n parseFloat(style.outlineWidth) > 0 &&\n colorCanPaint(style.outlineColor)\n ) {\n return true;\n }\n for (const side of [\"Top\", \"Right\", \"Bottom\", \"Left\"] as const) {\n if (\n style[`border${side}Style`] !== \"none\" &&\n parseFloat(style[`border${side}Width`]) > 0 &&\n colorCanPaint(style[`border${side}Color`])\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction colorCanPaint(value: string): boolean {\n const normalized = value.trim().toLowerCase().replace(/ /g, \"\");\n if (!normalized || normalized === \"transparent\") return false;\n return !(\n /^rgba\\([^)]*,0(?:\\.0+)?\\)$/.test(normalized) ||\n /^rgb\\([^)]*\\/0(?:\\.0+)?\\)$/.test(normalized)\n );\n}\n\nfunction hasBlockingElementInChain(\n start: Element | null,\n view: Window,\n): boolean {\n for (let element = start; element; element = element.parentElement) {\n if (elementBlocksSubtree(element, view)) return true;\n }\n return false;\n}\n\nfunction elementBlocksSubtree(element: Element, view: Window): boolean {\n if (IGNORED_CONTENT_TAGS.has(element.tagName)) return true;\n if (element.hasAttribute(\"hidden\")) return true;\n if (element.tagName === \"DIALOG\" && !element.hasAttribute(\"open\")) {\n return true;\n }\n if (\n element.tagName === \"INPUT\" &&\n element.getAttribute(\"type\")?.trim().toLowerCase() === \"hidden\"\n ) {\n return true;\n }\n\n countCaptureStyleRead();\n const style = view.getComputedStyle(element);\n const opacity = style.opacity.trim();\n return (\n style.display === \"none\" ||\n (opacity.length > 0 && Number(opacity) <= 0) ||\n style.getPropertyValue(\"content-visibility\") === \"hidden\"\n );\n}\n\nfunction elementHasVisibleComputedVisibility(\n element: Element,\n view: Window,\n): boolean {\n countCaptureStyleRead();\n const visibility = view.getComputedStyle(element).visibility;\n return visibility !== \"hidden\" && visibility !== \"collapse\";\n}\n","/**\n * DOM Capture\n *\n * One-shot capture of DOM content and element states.\n */\n\nimport { computeDeclaredFacts } from \"./declared-facts\";\nimport { measureComputedDisplayability } from \"./displayability\";\nimport { generateSelector } from \"./selectors\";\nimport type { DomCapture, ElementState } from \"./types\";\n\nexport interface CollectElementStatesOptions {\n /** Whether to include document-level scroll via the :root selector. */\n includeDocumentScroll?: boolean;\n}\n\n/**\n * Captures the current state of an element as a DomCapture.\n *\n * @param element - Element to capture\n * @returns DomCapture containing HTML and element states\n *\n * @example\n * ```ts\n * const snapshot = capture(document.body);\n * // { dom: { selector: \"body\", html: \"...\" }, states: [...] }\n * ```\n */\nexport function capture(element: Element): DomCapture {\n return captureWithSupplementalRoots(element, []);\n}\n\n/** Internal complete-capture primitive used when a higher-level producer also\n * serializes supplemental roots such as owned React portals. */\nexport function captureWithSupplementalRoots(\n element: Element,\n supplementalRoots: readonly Element[],\n): DomCapture {\n // Sync form state to attributes before serializing\n syncFormStateToAttributes(element);\n\n // Selector relative to itself = \"\" (this IS the container)\n const selector = generateSelector(element, element);\n // Use innerHTML - we capture the children, not the container itself\n const html = removeScriptTags(element.innerHTML);\n const attributes = captureAttributes(element);\n const documentElementAttributes = element.ownerDocument\n ? captureAttributes(element.ownerDocument.documentElement)\n : undefined;\n const bodyAttributes = element.ownerDocument?.body\n ? captureAttributes(element.ownerDocument.body)\n : undefined;\n const baseUrl = element.ownerDocument?.baseURI;\n const states = collectElementStates(element);\n const displayability = measureComputedDisplayability(\n element,\n supplementalRoots,\n );\n\n return {\n // Whole-surface one-shot: the element is both the capture root and the\n // serialized scope, so `complete` is true and there is no scope selector.\n declared: computeDeclaredFacts(element, element, \"\", supplementalRoots),\n ...(displayability && { displayability }),\n dom: {\n selector,\n html,\n attributes,\n documentElementAttributes,\n bodyAttributes,\n },\n states,\n baseUrl,\n };\n}\n\n/**\n * Syncs form element state (DOM properties) to HTML attributes.\n *\n * Form elements like checkboxes, selects, and inputs have runtime state\n * that isn't reflected in their HTML attributes. This syncs that state\n * to attributes so it survives serialization.\n */\nfunction syncFormStateToAttributes(root: Element): void {\n // Checkboxes and radios\n for (const input of root.querySelectorAll(\n 'input[type=\"checkbox\"], input[type=\"radio\"]',\n )) {\n const el = input as HTMLInputElement;\n if (el.checked) {\n el.setAttribute(\"checked\", \"\");\n } else {\n el.removeAttribute(\"checked\");\n }\n }\n\n // Text inputs\n for (const input of root.querySelectorAll(\n 'input:not([type=\"checkbox\"]):not([type=\"radio\"])',\n )) {\n const el = input as HTMLInputElement;\n if (el.value !== el.getAttribute(\"value\")) {\n el.setAttribute(\"value\", el.value);\n }\n }\n\n // Textareas\n for (const textarea of root.querySelectorAll(\"textarea\")) {\n const el = textarea as HTMLTextAreaElement;\n if (el.value !== el.textContent) {\n el.textContent = el.value;\n }\n if (el.hasAttribute(\"value\")) {\n el.removeAttribute(\"value\");\n }\n }\n\n // Selects\n for (const select of root.querySelectorAll(\"select\")) {\n const el = select as HTMLSelectElement;\n for (const option of el.options) {\n if (option.selected) {\n option.setAttribute(\"selected\", \"\");\n } else {\n option.removeAttribute(\"selected\");\n }\n }\n }\n}\n\n/**\n * Removes all script tags from HTML string.\n */\nexport function removeScriptTags(html: string): string {\n return html.replace(/<script\\b[^>]*>[\\s\\S]*?<\\/script>/gi, \"\");\n}\n\n/**\n * Captures attributes from an element into a serializable map.\n */\nexport function captureAttributes(element: Element): Record<string, string> {\n const attrs: Record<string, string> = {};\n for (const attr of Array.from(element.attributes)) {\n attrs[attr.name] = attr.value;\n }\n return attrs;\n}\n\n/**\n * Collects current element states from a root element.\n *\n * Walks form elements and scrollable containers to collect their runtime state.\n */\nexport function collectElementStates(\n root: Element,\n options: CollectElementStatesOptions = {},\n): ElementState[] {\n const { includeDocumentScroll = true } = options;\n const states: ElementState[] = [];\n\n // Collect form states\n for (const input of root.querySelectorAll(\"input\")) {\n const el = input as HTMLInputElement;\n const isCheckable = el.type === \"checkbox\" || el.type === \"radio\";\n const hasNonDefault = isCheckable\n ? el.checked !== el.defaultChecked\n : el.value !== el.defaultValue;\n\n if (hasNonDefault) {\n const selector = generateSelector(el, root);\n if (isCheckable) {\n states.push({ selector, checked: el.checked });\n } else {\n states.push({ selector, value: el.value });\n }\n }\n }\n\n for (const textarea of root.querySelectorAll(\"textarea\")) {\n const el = textarea as HTMLTextAreaElement;\n if (el.value !== el.defaultValue) {\n const selector = generateSelector(el, root);\n states.push({ selector, value: el.value });\n }\n }\n\n for (const select of root.querySelectorAll(\"select\")) {\n const el = select as HTMLSelectElement;\n for (const option of el.options) {\n if (option.selected !== option.defaultSelected) {\n const selector = generateSelector(option, root);\n states.push({ selector, selected: option.selected });\n }\n }\n }\n\n // Collect scroll states - always include root and document-level scroll\n // so that scrolling back to 0 is properly communicated.\n states.push({\n selector: \"\",\n scrollTop: root.scrollTop,\n scrollLeft: root.scrollLeft,\n });\n\n // Check document-level scroll (scrollingElement, usually <html>)\n // This handles the common case where scroll is on documentElement, not body\n if (includeDocumentScroll) {\n const scrollingEl = root.ownerDocument?.scrollingElement;\n if (scrollingEl && scrollingEl !== root) {\n states.push({\n selector: \":root\",\n scrollTop: scrollingEl.scrollTop,\n scrollLeft: scrollingEl.scrollLeft,\n });\n }\n }\n\n for (const el of root.querySelectorAll(\"*\")) {\n if (el.scrollTop > 0 || el.scrollLeft > 0) {\n const selector = generateSelector(el, root);\n states.push({\n selector,\n scrollTop: el.scrollTop,\n scrollLeft: el.scrollLeft,\n });\n }\n }\n\n return states;\n}\n","/**\n * State Watcher\n *\n * Tracks element state changes (form values, scroll positions) via events.\n * Much more efficient than DOM traversal - only tracks elements that received events.\n */\n\nimport { generateSelector } from \"./selectors\";\nimport type { ElementState } from \"./types\";\n\n/**\n * State for a state watcher instance.\n */\nexport interface StateWatcher {\n /** The root element being watched */\n root: Element;\n /** Elements that have received scroll events */\n scrolledElements: Set<Element>;\n /** Elements that have received input/change events */\n changedFormElements: Set<Element>;\n /** Raw input/change/scroll events accepted since the previous flush. */\n stateRecordCount: number;\n /** Last event kind per form target for exact regional state capture. */\n projectionFormEvents: Map<Element, \"input\" | \"change\">;\n /** Stop watching */\n stop: () => void;\n}\n\nexport interface ProjectionStateEvent {\n readonly element: Element;\n readonly eventKind: \"scroll\" | \"input\" | \"change\";\n}\n\n/**\n * Starts watching an element for state changes (form input, scroll).\n *\n * Uses event listeners in capture phase to catch all events.\n * Changes are collected in Sets and can be flushed via flushStateWatcher().\n *\n * @param root - Element to watch\n * @param onStateChange - Called when any state change occurs (for triggering flush)\n * @returns StateWatcher instance\n */\nexport function watchState(\n root: Element,\n onStateChange: () => void,\n): StateWatcher {\n const scrolledElements = new Set<Element>();\n const changedFormElements = new Set<Element>();\n\n const handleScroll = (event: Event) => {\n const target = event.target;\n if (target instanceof Element && root.contains(target)) {\n scrolledElements.add(target);\n watcher.stateRecordCount += 1;\n onStateChange();\n } else if (target === document) {\n // Document-level scroll - scrollingElement is usually <html> which doesn't\n // satisfy root.contains() when root is <body>. We track this specially.\n const scrollTarget =\n document.scrollingElement || document.documentElement;\n if (scrollTarget) {\n // Use a marker for document-level scroll (we'll handle it specially in flush)\n scrolledElements.add(scrollTarget);\n watcher.stateRecordCount += 1;\n onStateChange();\n }\n }\n };\n\n const handleFormChange = (event: Event) => {\n if (event.target instanceof Element && root.contains(event.target)) {\n changedFormElements.add(event.target);\n watcher.projectionFormEvents.set(\n event.target,\n event.type === \"change\" ? \"change\" : \"input\",\n );\n watcher.stateRecordCount += 1;\n onStateChange();\n }\n };\n\n // Use capture phase to catch all events\n document.addEventListener(\"scroll\", handleScroll, true);\n document.addEventListener(\"input\", handleFormChange, true);\n document.addEventListener(\"change\", handleFormChange, true);\n\n const watcher: StateWatcher = {\n root,\n scrolledElements,\n changedFormElements,\n stateRecordCount: 0,\n projectionFormEvents: new Map(),\n stop: () => {\n document.removeEventListener(\"scroll\", handleScroll, true);\n document.removeEventListener(\"input\", handleFormChange, true);\n document.removeEventListener(\"change\", handleFormChange, true);\n scrolledElements.clear();\n changedFormElements.clear();\n watcher.stateRecordCount = 0;\n watcher.projectionFormEvents.clear();\n },\n };\n return watcher;\n}\n\n/**\n * Flushes the state watcher, collecting current states and clearing tracking.\n *\n * Only returns states for elements that have changed since last flush.\n * Elements with non-default state are re-added to tracking to ensure\n * they're reported again if HTML is replaced.\n *\n * @param watcher - The state watcher to flush\n * @returns Array of element states\n */\nexport function flushStateWatcher(watcher: StateWatcher): ElementState[] {\n const { root, scrolledElements, changedFormElements } = watcher;\n watcher.stateRecordCount = 0;\n watcher.projectionFormEvents.clear();\n const states: ElementState[] = [];\n\n // Swap to fresh sets\n const scrolled = new Set(scrolledElements);\n const changed = new Set(changedFormElements);\n scrolledElements.clear();\n changedFormElements.clear();\n\n // Process scrolled elements\n for (const el of scrolled) {\n // Check for document-level scroll (scrollingElement, usually <html>)\n const isDocumentScroll =\n el === document.scrollingElement || el === document.documentElement;\n\n // Skip elements not in root, unless it's document-level scroll\n if (!isDocumentScroll && !root.contains(el)) continue;\n\n // For document-level scroll, use special \":root\" selector\n // For elements within root, generate relative selector\n const selector = isDocumentScroll ? \":root\" : generateSelector(el, root);\n states.push({\n selector,\n scrollTop: el.scrollTop,\n scrollLeft: el.scrollLeft,\n });\n }\n\n // Process changed form elements\n for (const el of changed) {\n if (!root.contains(el)) continue;\n\n if (el instanceof HTMLInputElement) {\n const isCheckable = el.type === \"checkbox\" || el.type === \"radio\";\n const hasNonDefault = isCheckable\n ? el.checked !== el.defaultChecked\n : el.value !== el.defaultValue;\n\n if (hasNonDefault) {\n const selector = generateSelector(el, root);\n if (isCheckable) {\n states.push({ selector, checked: el.checked });\n } else {\n states.push({ selector, value: el.value });\n }\n changedFormElements.add(el);\n }\n } else if (el instanceof HTMLTextAreaElement) {\n if (el.value !== el.defaultValue) {\n const selector = generateSelector(el, root);\n states.push({ selector, value: el.value });\n changedFormElements.add(el);\n }\n } else if (el instanceof HTMLSelectElement) {\n let hasNonDefault = false;\n for (const option of el.options) {\n if (option.selected !== option.defaultSelected) {\n const selector = generateSelector(option, root);\n states.push({ selector, selected: option.selected });\n hasNonDefault = true;\n }\n }\n if (hasNonDefault) {\n changedFormElements.add(el);\n }\n }\n }\n\n return states;\n}\n\n/** Detach exact state targets for a regional projection flush. */\nexport function drainProjectionStateEvents(\n watcher: StateWatcher,\n): ProjectionStateEvent[] {\n const events: ProjectionStateEvent[] = [];\n for (const element of watcher.scrolledElements) {\n const isDocumentScroll =\n element === watcher.root.ownerDocument.scrollingElement ||\n element === watcher.root.ownerDocument.documentElement;\n events.push({\n element: isDocumentScroll ? watcher.root : element,\n eventKind: \"scroll\",\n });\n }\n for (const [element, eventKind] of watcher.projectionFormEvents) {\n events.push({ element, eventKind });\n }\n watcher.scrolledElements.clear();\n watcher.changedFormElements.clear();\n watcher.projectionFormEvents.clear();\n watcher.stateRecordCount = 0;\n return events;\n}\n\n/**\n * Checks if watcher has any pending state changes.\n */\nexport function hasPendingStateChanges(watcher: StateWatcher): boolean {\n return (\n watcher.scrolledElements.size > 0 || watcher.changedFormElements.size > 0\n );\n}\n","/**\n * Portal Element Watcher\n *\n * Wraps MutationObserver for a single portal element.\n * Reuses the same watch-dom and watch-state logic but scoped to the portal.\n */\n\nimport { removeScriptTags } from \"./capture\";\nimport { generateSelector } from \"./selectors\";\nimport type { PortalCoordinateSpace, PortalUpdate } from \"./types\";\nimport {\n drainProjectionDomMutations,\n flushDomWatcher,\n hasPendingMutations,\n watchDom,\n} from \"./watch-dom\";\nimport {\n drainProjectionStateEvents,\n flushStateWatcher,\n hasPendingStateChanges,\n type ProjectionStateEvent,\n watchState,\n} from \"./watch-state\";\n\n/** Counter shared by one-shot snapshots and live portal watchers. */\nlet portalIdCounter = 0;\n\n/** Attribute name for portal ID */\nexport const PORTAL_ID_ATTR = \"data-projection-portal-id\";\n\n/**\n * Reset portal ID counter. For testing only.\n * @internal\n */\nexport function _resetPortalIdCounter(): void {\n portalIdCounter = 0;\n}\n\n/** Assign a process-unique projection ID, or reuse an existing stable ID. */\nexport function getOrAssignPortalId(element: Element): string {\n const existing = element.getAttribute(PORTAL_ID_ATTR);\n if (existing) return existing;\n\n const id = `portal-${++portalIdCounter}`;\n element.setAttribute(PORTAL_ID_ATTR, id);\n return id;\n}\n\nexport interface PortalWatcherHandle {\n /** The portal's unique ID */\n id: string;\n\n /** The portal root element */\n element: Element;\n\n /** Check if there are pending changes */\n hasPendingChanges(): boolean;\n\n /** Existing watcher record counts; no DOM reads. */\n pendingRecordCount(): number;\n\n /** Clear retained regional candidates after a caller captured final state. */\n clearPendingChanges(): ProjectionStateEvent[];\n\n /** Flush changes and get update (or null if no changes) */\n flush(isInitial?: boolean): PortalUpdate | null;\n\n /** Resample CSS-dependent coordinates without serializing portal content. */\n resampleCoordinates(): PortalUpdate | null;\n\n /** Stop watching */\n stop(): void;\n}\n\n/**\n * Start watching a portal element for changes.\n *\n * @param element - The portal root element (direct child of body)\n * @param onTrigger - Called when mutations are detected (for debounce integration)\n */\nexport function watchPortal(\n element: Element,\n onTrigger: () => void,\n coordinateRoot?: Element,\n): PortalWatcherHandle {\n // Assign or retrieve stable ID\n const id = getOrAssignPortalId(element);\n\n // Start watchers\n const domWatcher = watchDom(element, onTrigger);\n const stateWatcher = watchState(element, onTrigger);\n\n return {\n id,\n element,\n\n hasPendingChanges(): boolean {\n return (\n hasPendingMutations(domWatcher) || hasPendingStateChanges(stateWatcher)\n );\n },\n\n pendingRecordCount(): number {\n return domWatcher.mutationRecordCount + stateWatcher.stateRecordCount;\n },\n\n clearPendingChanges(): ProjectionStateEvent[] {\n drainProjectionDomMutations(domWatcher);\n return drainProjectionStateEvents(stateWatcher);\n },\n\n flush(isInitial = false): PortalUpdate | null {\n const hasDomChanges = hasPendingMutations(domWatcher);\n const hasStateChanges = hasPendingStateChanges(stateWatcher);\n\n if (!isInitial && !hasDomChanges && !hasStateChanges) {\n return null;\n }\n\n // Get LCA of mutations or use root for initial\n let targetElement = element;\n if (!isInitial && hasDomChanges) {\n const lca = flushDomWatcher(domWatcher);\n if (lca && element.contains(lca)) {\n targetElement = lca;\n }\n } else {\n flushDomWatcher(domWatcher);\n }\n\n // Collect states\n const states = flushStateWatcher(stateWatcher);\n\n // Generate selector relative to portal root\n const selector = generateSelector(targetElement, element);\n // Use outerHTML to capture the portal root element itself, not just its children.\n // This is important because the portal root often has critical styling (e.g., position: fixed\n // for modal overlays) that must be preserved in the projection.\n const html = removeScriptTags(targetElement.outerHTML);\n\n const coordinateSpace = coordinateRoot\n ? capturePortalCoordinateSpace(coordinateRoot, element)\n : undefined;\n return {\n id,\n selector,\n html,\n states,\n ...(coordinateSpace && { coordinateSpace }),\n };\n },\n\n resampleCoordinates(): PortalUpdate | null {\n const coordinateSpace = coordinateRoot\n ? capturePortalCoordinateSpace(coordinateRoot, element)\n : undefined;\n if (!coordinateSpace) return null;\n\n return {\n id,\n selector: \"\",\n html: \"\",\n states: [],\n coordinateSpace,\n coordinatesOnly: true,\n };\n },\n\n stop(): void {\n domWatcher.stop();\n stateWatcher.stop();\n },\n };\n}\n\nexport function capturePortalCoordinateSpace(\n root: Element,\n portal?: Element,\n): PortalCoordinateSpace | undefined {\n const viewport = root.ownerDocument?.defaultView;\n if (!viewport) return undefined;\n\n const rect = root.getBoundingClientRect();\n return {\n origin: portal ? choosePortalCoordinateOrigin(rect, portal) : \"root\",\n rootViewportLeft: rect.left,\n rootViewportTop: rect.top,\n viewportWidth: viewport.innerWidth,\n viewportHeight: viewport.innerHeight,\n };\n}\n\nfunction choosePortalCoordinateOrigin(\n rootRect: DOMRect,\n portal: Element,\n): \"root\" | \"viewport\" {\n const portalRect = measurePortalBounds(portal);\n const localViewport = {\n left: 0,\n top: 0,\n right: rootRect.width,\n bottom: rootRect.height,\n };\n const coversSourceViewport =\n portalRect.left <= 0 &&\n portalRect.top <= 0 &&\n portalRect.right >= (portal.ownerDocument.defaultView?.innerWidth ?? 0) &&\n portalRect.bottom >= (portal.ownerDocument.defaultView?.innerHeight ?? 0);\n if (coversSourceViewport) return \"viewport\";\n\n // A floating surface that intersects its owning storyboard is anchored in\n // the shared source host's coordinate frame, even when both the direct and\n // rebased rectangles happen to fit inside the destination viewport.\n if (rectanglesOverlap(rootRect, portalRect)) return \"root\";\n\n const directScore = visibleArea(portalRect, localViewport);\n const rebasedScore = visibleArea(\n {\n left: portalRect.left - rootRect.left,\n top: portalRect.top - rootRect.top,\n right: portalRect.right - rootRect.left,\n bottom: portalRect.bottom - rootRect.top,\n },\n localViewport,\n );\n\n if (rebasedScore > directScore) return \"root\";\n if (directScore > rebasedScore) return \"viewport\";\n\n return \"viewport\";\n}\n\nfunction measurePortalBounds(portal: Element): RectBounds {\n const ownRect = portal.getBoundingClientRect();\n if (hasArea(ownRect)) return ownRect;\n\n // Library portals often add a zero-sized ownership container around the\n // actual backdrop/positioner. Base origin selection on what paints, not on\n // that implementation wrapper whose empty rect is timing-sensitive.\n let left = Number.POSITIVE_INFINITY;\n let top = Number.POSITIVE_INFINITY;\n let right = Number.NEGATIVE_INFINITY;\n let bottom = Number.NEGATIVE_INFINITY;\n for (const descendant of Array.from(portal.querySelectorAll(\"*\"))) {\n const rect = descendant.getBoundingClientRect();\n if (!hasArea(rect)) continue;\n left = Math.min(left, rect.left);\n top = Math.min(top, rect.top);\n right = Math.max(right, rect.right);\n bottom = Math.max(bottom, rect.bottom);\n }\n\n return Number.isFinite(left) ? { left, top, right, bottom } : ownRect;\n}\n\ntype RectBounds = Pick<DOMRect, \"left\" | \"top\" | \"right\" | \"bottom\">;\n\nfunction hasArea(rect: RectBounds): boolean {\n return rect.right > rect.left && rect.bottom > rect.top;\n}\n\nfunction visibleArea(\n rect: RectBounds,\n viewport: { left: number; top: number; right: number; bottom: number },\n): number {\n const width = Math.max(\n 0,\n Math.min(rect.right, viewport.right) - Math.max(rect.left, viewport.left),\n );\n const height = Math.max(\n 0,\n Math.min(rect.bottom, viewport.bottom) - Math.max(rect.top, viewport.top),\n );\n return width * height;\n}\n\nfunction rectanglesOverlap(a: RectBounds, b: RectBounds): boolean {\n return (\n a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top\n );\n}\n\n/**\n * Create a \"removed\" update for a portal that was removed from DOM.\n */\nexport function createPortalRemovedUpdate(id: string): PortalUpdate {\n return {\n id,\n selector: \"\",\n html: \"\",\n states: [],\n removed: true,\n };\n}\n","/**\n * Escape a value for interpolation into a double-quoted attribute selector,\n * the shape every projection lookup uses: `[attr=\"${cssEscape(value)}\"]`.\n *\n * Inside those quotes only `\"` and `\\` are syntactically significant, so the\n * fallback needs no wider escape table — `]`, `:` and `.` are literal there.\n * `CSS.escape` escapes for identifiers rather than quoted strings, which\n * over-escapes but resolves to the same characters inside the quotes.\n */\nexport function cssEscape(value: string): string {\n return globalThis.CSS?.escape\n ? globalThis.CSS.escape(value)\n : value.replace(/[\"\\\\]/g, \"\\\\$&\");\n}\n","export interface ProjectionObservedFile {\n /** Minimum timestamp across every serialized target from this file. */\n readonly modifiedTs: number;\n /** Present only when every serialized target reports the same exact token. */\n readonly sourceVersion?: string;\n}\n\nexport type ProjectionObservedFileMap = Readonly<\n Record<string, ProjectionObservedFile>\n>;\n\ninterface MutableObservedFile {\n modifiedTs: number;\n sourceVersion?: string;\n}\n\n/**\n * Accumulates freshness facts during a serializer's existing regional walk.\n * It never traverses the DOM itself. A fact covers the region only when every\n * target visited for that file is at least as new; exact versions are retained\n * only when all visited stamps agree.\n */\nexport class ProjectionObservedFileAccumulator {\n private readonly files = new Map<string, MutableObservedFile>();\n\n add(\n filepath: unknown,\n modifiedTsRaw: unknown,\n sourceVersionRaw: unknown,\n ): void {\n if (typeof filepath !== \"string\" || filepath.length === 0) return;\n const modifiedTs =\n typeof modifiedTsRaw === \"number\"\n ? modifiedTsRaw\n : typeof modifiedTsRaw === \"string\"\n ? Number(modifiedTsRaw)\n : Number.NaN;\n if (!Number.isFinite(modifiedTs)) return;\n const sourceVersion =\n typeof sourceVersionRaw === \"string\" && sourceVersionRaw.length > 0\n ? sourceVersionRaw\n : undefined;\n const current = this.files.get(filepath);\n if (!current) {\n this.files.set(filepath, {\n modifiedTs,\n sourceVersion,\n });\n return;\n }\n current.modifiedTs = Math.min(current.modifiedTs, modifiedTs);\n if (\n sourceVersion === undefined ||\n current.sourceVersion === undefined ||\n current.sourceVersion !== sourceVersion\n ) {\n current.sourceVersion = undefined;\n }\n }\n\n merge(files: ProjectionObservedFileMap | undefined): void {\n if (!files) return;\n for (const [filepath, fact] of Object.entries(files)) {\n this.add(filepath, fact.modifiedTs, fact.sourceVersion);\n }\n }\n\n addElement(element: Element): void {\n this.add(\n element.getAttribute(\"data-tempo-filepath\"),\n element.getAttribute(\"data-tempo-modifiedts\"),\n element.getAttribute(\"data-tempo-source-version\"),\n );\n this.add(\n element.getAttribute(\"data-tempo-html-filepath\"),\n element.getAttribute(\"data-tempo-html-modifiedts\"),\n element.getAttribute(\"data-tempo-html-source-version\"),\n );\n }\n\n snapshot(): ProjectionObservedFileMap {\n return Object.fromEntries(\n Array.from(this.files, ([filepath, fact]) => [\n filepath,\n {\n modifiedTs: fact.modifiedTs,\n ...(fact.sourceVersion !== undefined\n ? { sourceVersion: fact.sourceVersion }\n : {}),\n },\n ]),\n );\n }\n}\n","import { removeScriptTags } from \"../html/capture\";\nimport type { PortalCoordinateSpace } from \"../html/types\";\nimport { DOM_ID_ATTR, ensureProjectionDomId } from \"../html/watch-dom\";\nimport {\n capturePortalCoordinateSpace,\n PORTAL_ID_ATTR,\n} from \"../html/watch-portal\";\nimport { cssEscape } from \"./css-escape\";\nimport {\n ProjectionObservedFileAccumulator,\n type ProjectionObservedFileMap,\n} from \"./projection-observed-files\";\n\nexport const SOURCE_ANNOTATION_ATTRIBUTES = new Set([\n \"data-tempo-filepath\",\n \"data-tempo-position\",\n \"data-tempo-modifiedts\",\n \"data-tempo-source-version\",\n \"data-tempo-html-filepath\",\n \"data-tempo-html-offset\",\n \"data-tempo-html-modifiedts\",\n \"data-tempo-html-source-version\",\n]);\n\n/** Stable protocol identity for the watched wrapper. The wrapper itself is\n * host plumbing and is intentionally absent from full-snapshot HTML. */\nexport const PROJECTION_ROOT_TARGET_ID = \"$projection-root\";\n/** Stable destination-local target for exact `<html>` attribute changes. */\nexport const PROJECTION_DOCUMENT_ELEMENT_TARGET_ID = \"$projection-document\";\n\n/**\n * Upward repair ladder captured with the op: the id chain from the op's\n * addressed element's parent to the watched root (id-less ancestors skipped,\n * the root's sentinel implied). When the destination cannot resolve the op's\n * target it climbs this chain and requests one scoped region repair for the\n * first ancestor it knows, instead of escalating straight to a full snapshot.\n */\nexport interface ProjectionAncestryCarrier {\n readonly ancestorIds?: readonly string[];\n}\n\nexport interface ProjectionAttributePatch extends ProjectionAncestryCarrier {\n readonly kind: \"attributes\";\n readonly targetId: string;\n readonly attributes: Readonly<Record<string, string | null>>;\n}\n\nexport interface ProjectionRegionPatch extends ProjectionAncestryCarrier {\n readonly kind: \"children\";\n readonly targetId: string;\n readonly html: string;\n}\n\nexport interface ProjectionRemovePatch {\n readonly kind: \"remove\";\n readonly targetId: string;\n}\n\nexport interface ProjectionPlacePatch extends ProjectionAncestryCarrier {\n readonly kind: \"place\";\n readonly parentId: string;\n /** Stable ID of the exact top-level element represented by `html`. */\n readonly targetId: string;\n /** Insert immediately before this unchanged final sibling, or append. */\n readonly beforeId: string | null;\n readonly html: string;\n}\n\nexport interface ProjectionTextPatch extends ProjectionAncestryCarrier {\n readonly kind: \"text\";\n readonly parentId: string;\n /** The element after this exact non-element gap, or null for the end gap. */\n readonly beforeId: string | null;\n readonly html: string;\n}\n\nexport type ProjectionDomPatch =\n | ProjectionAttributePatch\n | ProjectionRegionPatch\n | ProjectionRemovePatch\n | ProjectionPlacePatch\n | ProjectionTextPatch;\n\nexport interface ProjectionAnnotationPatch extends ProjectionAncestryCarrier {\n readonly targetId: string;\n readonly attributes: Readonly<Record<string, string | null>>;\n}\n\nexport type ProjectionStatePatch = ProjectionAncestryCarrier &\n (\n | {\n readonly targetId: string;\n readonly kind: \"scroll\";\n readonly scrollTop: number;\n readonly scrollLeft: number;\n }\n | {\n readonly targetId: string;\n readonly kind: \"value\";\n readonly value: string;\n readonly selectionStart: number | null;\n readonly selectionEnd: number | null;\n }\n | {\n readonly targetId: string;\n readonly kind: \"checked\";\n readonly checked: boolean;\n }\n | {\n readonly targetId: string;\n readonly kind: \"selected\";\n readonly selectedIndices: readonly number[];\n }\n );\n\nexport type ProjectionPortalPatch =\n | ProjectionPortalReplacePatch\n | { readonly kind: \"remove\"; readonly portalId: string };\n\nexport interface ProjectionPortalReplacePatch {\n readonly kind: \"replace\";\n readonly portalId: string;\n readonly html: string;\n /** Where the source anchored this portal, so the destination can rebase it\n * out of the source viewport's frame into the mirrored root's. Absent when\n * the source realm has no measurable view. */\n readonly coordinateSpace?: PortalCoordinateSpace;\n /** The portal's frame moved without its DOM changing. Only `coordinateSpace`\n * applies; `html` is empty and the mirrored body — including its focus and\n * edit state — is left alone. */\n readonly coordinatesOnly?: boolean;\n}\n\nexport interface ProjectionPortalRegionCapture {\n readonly portal: ProjectionPortalPatch;\n readonly annotations: readonly ProjectionAnnotationPatch[];\n readonly observedFiles: ProjectionObservedFileMap;\n}\n\nexport interface ProjectionMutationInput {\n readonly type: \"attributes\" | \"characterData\" | \"childList\";\n readonly target: Node;\n readonly attributeName?: string | null;\n readonly addedNodes?: readonly Node[];\n readonly removedNodes?: readonly Node[];\n readonly previousSibling?: Node | null;\n readonly nextSibling?: Node | null;\n}\n\nexport interface ProjectionMutationPatch {\n readonly dom: readonly ProjectionDomPatch[];\n readonly annotations: readonly ProjectionAnnotationPatch[];\n readonly observedFiles?: ProjectionObservedFileMap;\n /** Source-realm-only candidates. They are consumed by the document\n * producer while assembling semantic work and are never serialized. */\n readonly localMetadataTargets: readonly Element[];\n}\n\n/**\n * Convert observer-local mutation records into declarative final-state\n * regions. Disjoint regions stay disjoint; nested work is swallowed by its\n * nearest surviving ancestor. Source metadata never becomes structure work.\n *\n * Capture never refuses: work on an element that lacks a stable id widens to\n * the nearest ancestor that has one (worst case the watched root itself), and\n * duplicate ids in the source document are represented as-is — the morphing\n * destination converges on whatever this capture describes.\n */\nexport function captureProjectionMutationPatch(\n root: Element,\n mutations: readonly ProjectionMutationInput[],\n options: { readonly regionalChildLists?: boolean } = {},\n): ProjectionMutationPatch {\n const fallbackRegions = new Set<Element>();\n const childListMutations: ProjectionMutationInput[] = [];\n const characterDataTargets: Node[] = [];\n const attributes = new Map<Element, Set<string>>();\n const annotations = new Map<Element, Set<string>>();\n const metadataTargets = new Set<Element>();\n const observedFiles = new ProjectionObservedFileAccumulator();\n\n for (const mutation of mutations) {\n const element = mutationTargetElement(mutation.target);\n if (!element || (element !== root && !root.contains(element))) continue;\n if (mutation.type === \"attributes\" && mutation.attributeName) {\n const targetMap = SOURCE_ANNOTATION_ATTRIBUTES.has(mutation.attributeName)\n ? annotations\n : attributes;\n const names = targetMap.get(element) ?? new Set<string>();\n names.add(mutation.attributeName);\n targetMap.set(element, names);\n if (targetMap === annotations) metadataTargets.add(element);\n continue;\n }\n if (mutation.type === \"characterData\") {\n characterDataTargets.push(mutation.target);\n } else {\n const carriesNoChildDetail =\n mutation.addedNodes === undefined &&\n mutation.removedNodes === undefined;\n if (options.regionalChildLists || carriesNoChildDetail) {\n // React can reuse an unkeyed DOM/Fiber slot for a different source\n // sibling. Its child-list target remains authoritative; the reused\n // child ids do not. Capture that exact parent's final children.\n fallbackRegions.add(element);\n } else {\n childListMutations.push(mutation);\n }\n }\n }\n\n const addedElements = coalesceElements(\n childListMutations.flatMap((mutation) =>\n Array.from(mutation.addedNodes ?? []).filter(\n (node): node is Element =>\n node instanceof Element && root.contains(node),\n ),\n ),\n );\n const removedElements = coalesceElements(\n childListMutations.flatMap((mutation) =>\n Array.from(mutation.removedNodes ?? []).filter(\n (node): node is Element =>\n node instanceof Element && !root.contains(node),\n ),\n ),\n );\n const coveredByAddedElement = (element: Element): boolean =>\n addedElements.some((added) => added === element || added.contains(element));\n\n const placements: ProjectionPlacePatch[] = [];\n const removals: ProjectionRemovePatch[] = [];\n const textGaps = new Map<string, ProjectionTextPatch>();\n\n for (const removed of removedElements) {\n const targetId = removed.getAttribute(DOM_ID_ATTR);\n // Missing removal targets are safe idempotent no-ops for contenteditable\n // internals and nodes that were both introduced and removed in this\n // collection window. They never justify widening to the parent body.\n if (targetId) removals.push({ kind: \"remove\", targetId });\n }\n\n // Place right-to-left so a newly-added next sibling is already available as\n // the exact anchor for the element before it.\n addedElements.sort(reverseDocumentOrder);\n for (const added of addedElements) {\n if (added.tagName.toLowerCase() === \"script\") continue;\n const parent = added.parentElement;\n if (!parent || (parent !== root && !root.contains(parent))) continue;\n const parentId = projectionTargetId(root, parent);\n const targetId = ensureProjectionDomId(added);\n if (!parentId || !targetId) {\n fallbackRegions.add(parent);\n continue;\n }\n const before = added.nextElementSibling;\n const beforeId = before ? ensureProjectionDomId(before) : null;\n if (before && !beforeId) {\n fallbackRegions.add(parent);\n continue;\n }\n const captured = capturePlacedElementWithoutAnnotations(added);\n placements.push({\n kind: \"place\",\n parentId,\n targetId,\n beforeId,\n html: captured.html,\n ancestorIds: captureProjectionAncestorIds(root, added),\n });\n mergeCapturedAnnotations(annotations, observedFiles, captured.annotations);\n }\n\n const captureTextGap = (parent: Element, before: Element | null): void => {\n if (coveredByAddedElement(parent)) return;\n const parentId = projectionTargetId(root, parent);\n const beforeId = before ? ensureProjectionDomId(before) : null;\n if (!parentId || (before && !beforeId)) {\n fallbackRegions.add(parent);\n return;\n }\n const key = `${parentId}\\u0000${beforeId ?? \"\"}`;\n textGaps.set(key, {\n kind: \"text\",\n parentId,\n beforeId,\n html: captureNonElementGap(parent, before),\n ancestorIds: captureProjectionAncestorIds(root, parent),\n });\n };\n\n for (const target of characterDataTargets) {\n const parent = target.parentElement;\n if (!parent || (parent !== root && !root.contains(parent))) continue;\n captureTextGap(parent, nextElementSibling(target));\n }\n for (const mutation of childListMutations) {\n const parent = mutation.target instanceof Element ? mutation.target : null;\n if (!parent || coveredByAddedElement(parent)) continue;\n for (const added of mutation.addedNodes ?? []) {\n if (added instanceof Element || added.parentNode !== parent) continue;\n captureTextGap(parent, nextElementSibling(added));\n }\n if (\n (mutation.removedNodes ?? []).some(\n (removed) => !(removed instanceof Element),\n )\n ) {\n const before = survivingNextElement(parent, mutation);\n if (before === undefined) fallbackRegions.add(parent);\n else captureTextGap(parent, before);\n }\n }\n\n // Unaddressable work widens to the nearest identifiable ancestor region;\n // its exact final state (annotations included, inline) rides in that\n // region's HTML instead of a separately addressed patch.\n for (const element of [...attributes.keys()]) {\n if (projectionTargetId(root, element)) continue;\n attributes.delete(element);\n fallbackRegions.add(widenToIdentifiableRegion(root, element));\n }\n for (const element of [...annotations.keys()]) {\n if (projectionTargetId(root, element)) continue;\n annotations.delete(element);\n fallbackRegions.add(widenToIdentifiableRegion(root, element));\n }\n for (const region of [...fallbackRegions]) {\n if (projectionTargetId(root, region)) continue;\n fallbackRegions.delete(region);\n fallbackRegions.add(widenToIdentifiableRegion(root, region));\n }\n\n const survivingRegions = coalesceRegions(fallbackRegions);\n // A region ships its innerHTML, so it carries every descendant's final\n // attributes but none of its own — `morphInner` writes the region's children\n // and never touches the region element itself. A strict descendant's\n // attribute op is therefore already said by the region and is dropped; the\n // region root's own is not, and has to survive alongside it.\n //\n // A placed element is the opposite case: `place` ships outerHTML, so the\n // element's own attributes ARE carried and self-coverage is correct there.\n const isInsideRegion = (element: Element): boolean =>\n survivingRegions.some(\n (region) => region !== element && region.contains(element),\n );\n for (const element of attributes.keys()) {\n if (isInsideRegion(element) || coveredByAddedElement(element)) {\n attributes.delete(element);\n }\n }\n\n const regionCaptures = new Map<Element, CapturedRegion>();\n for (const region of survivingRegions) {\n const captured = captureRegionWithoutAnnotations(region);\n regionCaptures.set(region, captured);\n mergeCapturedAnnotations(annotations, observedFiles, captured.annotations);\n }\n\n for (const element of annotations.keys()) observedFiles.addElement(element);\n\n const allTargets = new Set<Element>([\n ...survivingRegions,\n ...attributes.keys(),\n ...annotations.keys(),\n ]);\n const ids = new Map<Element, string>();\n for (const element of allTargets) {\n const id = projectionTargetId(root, element);\n if (id) ids.set(element, id);\n }\n\n return {\n dom: [\n ...removals.filter(\n (change) =>\n !survivingRegions.some((region) =>\n region.querySelector(\n `[${DOM_ID_ATTR}=\"${cssEscape(change.targetId)}\"]`,\n ),\n ),\n ),\n ...placements.filter(\n (change) => !isCoveredTargetId(root, survivingRegions, change.targetId),\n ),\n ...Array.from(textGaps.values()).filter(\n (change) => !isCoveredTargetId(root, survivingRegions, change.parentId),\n ),\n ...survivingRegions.map(\n (element): ProjectionRegionPatch => ({\n kind: \"children\",\n targetId: ids.get(element)!,\n html: regionCaptures.get(element)!.html,\n ancestorIds: captureProjectionAncestorIds(root, element),\n }),\n ),\n ...Array.from(\n attributes,\n ([element, names]): ProjectionAttributePatch => ({\n kind: \"attributes\",\n targetId: ids.get(element)!,\n attributes: captureFinalAttributes(element, names),\n ancestorIds: captureProjectionAncestorIds(root, element),\n }),\n ),\n ],\n annotations: Array.from(\n annotations,\n ([element, names]): ProjectionAnnotationPatch => ({\n targetId: ids.get(element)!,\n attributes: captureFinalAttributes(element, names),\n ancestorIds: captureProjectionAncestorIds(root, element),\n }),\n ),\n observedFiles: observedFiles.snapshot(),\n localMetadataTargets: Array.from(metadataTargets),\n };\n}\n\n/** Null when the element has no stable id or no representable state; the\n * caller simply skips it. Untracked state never blocks the stream. The\n * `root` bounds the repair-ladder chain walk. */\nexport function captureProjectionStatePatch(\n root: Element,\n element: Element,\n eventKind: \"scroll\" | \"input\" | \"change\",\n): ProjectionStatePatch | null {\n const targetId = element.getAttribute(DOM_ID_ATTR);\n if (!targetId) return null;\n const ancestorIds = captureProjectionAncestorIds(root, element);\n if (eventKind === \"scroll\") {\n return {\n targetId,\n kind: \"scroll\",\n scrollTop: element.scrollTop,\n scrollLeft: element.scrollLeft,\n ancestorIds,\n };\n }\n if (element instanceof HTMLInputElement) {\n if (element.type === \"checkbox\" || element.type === \"radio\") {\n return { targetId, kind: \"checked\", checked: element.checked, ancestorIds };\n }\n return {\n targetId,\n kind: \"value\",\n value: element.value,\n selectionStart: element.selectionStart,\n selectionEnd: element.selectionEnd,\n ancestorIds,\n };\n }\n if (element instanceof HTMLTextAreaElement) {\n return {\n targetId,\n kind: \"value\",\n value: element.value,\n selectionStart: element.selectionStart,\n selectionEnd: element.selectionEnd,\n ancestorIds,\n };\n }\n if (element instanceof HTMLSelectElement) {\n const selectedIndices: number[] = [];\n for (let index = 0; index < element.options.length; index += 1) {\n if (element.options[index]?.selected) selectedIndices.push(index);\n }\n return { targetId, kind: \"selected\", selectedIndices, ancestorIds };\n }\n return null;\n}\n\n/** Capture a complete portal final state without hiding source metadata in\n * HTML. Null when the portal was never stamped; such a portal is invisible to\n * the destination and skipping it cannot make the mirror worse.\n *\n * `coordinateRoot` is the watched root the portal belongs to; passing it\n * measures the source frame the destination needs to rebase the portal. */\nexport function captureProjectionPortalRegion(\n element: Element,\n removed = false,\n coordinateRoot?: Element,\n): ProjectionPortalRegionCapture | null {\n const portalId = element.getAttribute(PORTAL_ID_ATTR);\n if (!portalId) return null;\n if (removed) {\n return {\n portal: { kind: \"remove\", portalId },\n annotations: [],\n observedFiles: {},\n };\n }\n\n const liveElements = [element, ...element.querySelectorAll(\"*\")];\n for (const live of liveElements) ensureProjectionDomId(live);\n const clone = element.cloneNode(true) as Element;\n for (const script of clone.querySelectorAll(\"script\")) script.remove();\n const cloneElements = [clone, ...clone.querySelectorAll(\"*\")];\n const annotations: ProjectionAnnotationPatch[] = [];\n const observedFiles = new ProjectionObservedFileAccumulator();\n for (const detached of detachSourceAnnotations(liveElements, cloneElements)) {\n annotations.push({\n targetId: detached.targetId,\n attributes: captureFinalAttributes(detached.element, detached.names),\n ancestorIds: captureProjectionAncestorIds(element, detached.element),\n });\n observedFiles.addElement(detached.element);\n }\n const coordinateSpace = coordinateRoot\n ? capturePortalCoordinateSpace(coordinateRoot, element)\n : undefined;\n return {\n portal: {\n kind: \"replace\",\n portalId,\n html: removeScriptTags(clone.outerHTML),\n ...(coordinateSpace && { coordinateSpace }),\n },\n annotations,\n observedFiles: observedFiles.snapshot(),\n };\n}\n\n/** The coordinate-refresh half of a portal capture: a stylesheet change can\n * move a portal without mutating it, and re-sending its body would cost the\n * destination's focus and edit state for nothing. */\nexport function captureProjectionPortalCoordinates(\n root: Element,\n element: Element,\n): ProjectionPortalReplacePatch | null {\n const portalId = element.getAttribute(PORTAL_ID_ATTR);\n const coordinateSpace = capturePortalCoordinateSpace(root, element);\n if (!portalId || !coordinateSpace) return null;\n return {\n kind: \"replace\",\n portalId,\n html: \"\",\n coordinateSpace,\n coordinatesOnly: true,\n };\n}\n\nfunction mutationTargetElement(target: Node): Element | null {\n return target instanceof Element ? target : target.parentElement;\n}\n\nfunction projectionTargetId(root: Element, element: Element): string | null {\n return element === root\n ? PROJECTION_ROOT_TARGET_ID\n : element.getAttribute(DOM_ID_ATTR);\n}\n\nfunction coalesceElements(elements: readonly Element[]): Element[] {\n const unique = Array.from(new Set(elements));\n return unique.filter(\n (candidate) =>\n !unique.some((other) => other !== candidate && other.contains(candidate)),\n );\n}\n\nfunction reverseDocumentOrder(left: Element, right: Element): number {\n if (left === right) return 0;\n const position = left.compareDocumentPosition(right);\n if (position & 4) return 1;\n if (position & 2) return -1;\n return 0;\n}\n\nfunction nextElementSibling(node: Node): Element | null {\n let current = node.nextSibling;\n while (current && !(current instanceof Element))\n current = current.nextSibling;\n return current;\n}\n\nfunction survivingNextElement(\n parent: Element,\n mutation: ProjectionMutationInput,\n): Element | null | undefined {\n const next = mutation.nextSibling;\n if (next?.parentNode === parent) {\n return next instanceof Element ? next : nextElementSibling(next);\n }\n const previous = mutation.previousSibling;\n if (previous?.parentNode === parent) return nextElementSibling(previous);\n return parent.childNodes.length === 0 ? null : undefined;\n}\n\nfunction captureNonElementGap(parent: Element, before: Element | null): string {\n const nodes: Node[] = [];\n let current = before ? before.previousSibling : parent.lastChild;\n while (current && !(current instanceof Element)) {\n nodes.unshift(current.cloneNode(true));\n current = current.previousSibling;\n }\n const container = parent.ownerDocument.createElement(\"div\");\n container.append(...nodes);\n return container.innerHTML;\n}\n\nfunction capturePlacedElementWithoutAnnotations(\n element: Element,\n): CapturedRegion {\n const liveElements = [element, ...element.querySelectorAll(\"*\")];\n for (const live of liveElements) ensureProjectionDomId(live);\n const clone = element.cloneNode(true) as Element;\n if (clone.tagName.toLowerCase() === \"script\") {\n return { html: \"\", annotations: [] };\n }\n for (const script of clone.querySelectorAll(\"script\")) script.remove();\n const cloneElements = [clone, ...clone.querySelectorAll(\"*\")];\n // Serialize only after the annotations are off the clone.\n const annotations = detachSourceAnnotations(liveElements, cloneElements);\n return { html: clone.outerHTML, annotations };\n}\n\nfunction mergeCapturedAnnotations(\n target: Map<Element, Set<string>>,\n observedFiles: ProjectionObservedFileAccumulator,\n incoming: readonly DetachedAnnotation[],\n): void {\n for (const { element, names } of incoming) {\n const existing = target.get(element) ?? new Set<string>();\n for (const name of names) existing.add(name);\n target.set(element, existing);\n observedFiles.addElement(element);\n }\n}\n\nfunction isCoveredTargetId(\n root: Element,\n regions: readonly Element[],\n targetId: string,\n): boolean {\n const target =\n targetId === PROJECTION_ROOT_TARGET_ID\n ? root\n : root.querySelector(`[${DOM_ID_ATTR}=\"${cssEscape(targetId)}\"]`);\n return target\n ? regions.some((region) => region === target || region.contains(target))\n : false;\n}\n\n\nfunction coalesceRegions(regions: ReadonlySet<Element>): Element[] {\n const candidates = Array.from(regions);\n return candidates.filter(\n (candidate) =>\n !candidates.some(\n (other) => other !== candidate && other.contains(candidate),\n ),\n );\n}\n\nexport function captureFinalAttributes(\n element: Element,\n names: ReadonlySet<string>,\n): Readonly<Record<string, string | null>> {\n return Object.fromEntries(\n Array.from(names, (name) => [name, element.getAttribute(name)]),\n );\n}\n\n/** One live element's source annotations, lifted off the clone that mirrors it. */\nexport interface DetachedAnnotation {\n readonly element: Element;\n readonly targetId: string;\n readonly names: ReadonlySet<string>;\n}\n\n/**\n * Move the source annotations off a clone, reporting what each live element\n * carried. `live` and `clone` must be index-aligned enumerations of the same\n * subtree — every caller builds them from the same root-inclusion choice.\n *\n * Annotations are only lifted out of the HTML when the element can be\n * addressed separately; an id-less element keeps them inline instead.\n */\nexport function detachSourceAnnotations(\n live: readonly Element[],\n clone: readonly Element[],\n): DetachedAnnotation[] {\n const detached: DetachedAnnotation[] = [];\n for (let index = 0; index < live.length; index += 1) {\n const element = live[index];\n const copy = clone[index];\n if (!element || !copy) continue;\n const targetId = element.getAttribute(DOM_ID_ATTR);\n if (!targetId) continue;\n const names = new Set<string>();\n for (const name of SOURCE_ANNOTATION_ATTRIBUTES) {\n if (!element.hasAttribute(name)) continue;\n names.add(name);\n copy.removeAttribute(name);\n }\n if (names.size > 0) detached.push({ element, targetId, names });\n }\n return detached;\n}\n\nexport interface CapturedRegion {\n readonly html: string;\n readonly annotations: readonly DetachedAnnotation[];\n}\n\nexport function captureRegionWithoutAnnotations(\n element: Element,\n): CapturedRegion {\n const liveDescendants = Array.from(element.querySelectorAll(\"*\"));\n for (const live of liveDescendants) ensureProjectionDomId(live);\n const clone = element.cloneNode(true) as Element;\n for (const script of clone.querySelectorAll(\"script\")) script.remove();\n const cloneDescendants = Array.from(clone.querySelectorAll(\"*\"));\n // Serialize only after the annotations are off the clone.\n const annotations = detachSourceAnnotations(liveDescendants, cloneDescendants);\n return { html: clone.innerHTML, annotations };\n}\n\n/** Nearest self-or-ancestor with a stable id, else the watched root. */\nfunction widenToIdentifiableRegion(root: Element, element: Element): Element {\n for (\n let current: Element | null = element;\n current && current !== root;\n current = current.parentElement\n ) {\n if (current.getAttribute(DOM_ID_ATTR)) return current;\n }\n return root;\n}\n\n/** The element's parent-and-up id chain, lowest first, root excluded (the\n * root's sentinel is destination knowledge). Id-less ancestors are skipped. */\nexport function captureProjectionAncestorIds(\n root: Element,\n element: Element,\n): string[] {\n const ids: string[] = [];\n for (\n let current = element.parentElement;\n current && current !== root;\n current = current.parentElement\n ) {\n const id = current.getAttribute(DOM_ID_ATTR);\n if (id) ids.push(id);\n }\n return ids;\n}\n","import { FiberTag } from \"../fiber/react-types\";\nimport { DOM_ID_ATTR, ensureProjectionDomId } from \"../html/watch-dom\";\nimport type {\n ProjectionLayerMetadataSnapshot,\n ProjectionLayerNode,\n ProjectionLayerProps,\n ProjectionLayerRegionSnapshot,\n ProjectionLayerRootSnapshot,\n} from \"./projection-layer-snapshot\";\nimport type { ProjectionObservedFileMap } from \"./projection-observed-files\";\nimport { SOURCE_ANNOTATION_ATTRIBUTES } from \"./projection-patch\";\nimport type { ProjectionLayerPatch } from \"./projection-root-accumulator\";\n\nexport const DOM_LAYER_ROOT_ID = \"dom:$projection-root\";\nconst DOM_LAYER_FIBER_PREFIX = \"dom:\";\n\nexport interface ProjectionDomLayerTargets {\n readonly structural: readonly Element[];\n readonly metadata: readonly Element[];\n}\n\n/**\n * One serializer per watched root lifetime. DOM ids are lookup anchors copied\n * into the destination; they are not semantic identity because source code can\n * duplicate them with cloneNode(true). Element object identity is not copied,\n * so a WeakMap gives every live source element one stable semantic identity\n * without mutating the source's representationally valid duplicate ids.\n */\nexport interface ProjectionDomLayerSerializer {\n serializeRoot(\n root: Element,\n observedFiles?: ProjectionObservedFileMap,\n ): ProjectionLayerRootSnapshot;\n capturePatch(\n root: Element,\n targets: ProjectionDomLayerTargets,\n observedFiles?: ProjectionObservedFileMap,\n ): ProjectionLayerPatch | undefined;\n}\n\nexport function createProjectionDomLayerSerializer(): ProjectionDomLayerSerializer {\n let nextElementId = 1;\n const elementIds = new WeakMap<Element, string>();\n const domIdOwners = new Map<string, Element>();\n const identity: DomLayerIdentity = {\n layerIdForElement(_root, element) {\n const existing = elementIds.get(element);\n if (existing) return existing;\n const id = `${DOM_LAYER_FIBER_PREFIX}element:${nextElementId++}`;\n elementIds.set(element, id);\n return id;\n },\n bindableDomIdForElement(root, element) {\n const domId = ensureProjectionDomId(element);\n if (!domId) return null;\n const owner = domIdOwners.get(domId);\n if (owner === element) return domId;\n if (!owner || !root.contains(owner)) {\n domIdOwners.set(domId, element);\n return domId;\n }\n return null;\n },\n };\n\n return {\n serializeRoot(root, observedFiles = {}) {\n return serializeProjectionDomLayerRootWithIdentity(\n root,\n observedFiles,\n identity,\n );\n },\n capturePatch(root, targets, observedFiles = {}) {\n return captureProjectionDomLayerPatchFromTargets(\n root,\n targets,\n observedFiles,\n identity,\n );\n },\n };\n}\n\ninterface DomLayerIdentity {\n readonly layerIdForElement: (root: Element, element: Element) => string;\n readonly bindableDomIdForElement: (\n root: Element,\n element: Element,\n ) => string | null;\n}\n\nconst dataDomLayerIdentity: DomLayerIdentity = {\n layerIdForElement: domLayerIdForElement,\n bindableDomIdForElement: (_root, element) => ensureProjectionDomId(element),\n};\n\n/**\n * Build the semantic layer tree for a document that has no React Fiber root.\n *\n * Projection's DOM lane already owns stable `data-dom-id` identities. Reusing\n * those identities here keeps a plain HTML page selectable in exactly the same\n * way as a host-only React tree, without pretending that source components or\n * editable React props exist.\n */\nexport function serializeProjectionDomLayerRoot(\n root: Element,\n observedFiles: ProjectionObservedFileMap = {},\n): ProjectionLayerRootSnapshot {\n return serializeProjectionDomLayerRootWithIdentity(\n root,\n observedFiles,\n dataDomLayerIdentity,\n );\n}\n\nfunction serializeProjectionDomLayerRootWithIdentity(\n root: Element,\n observedFiles: ProjectionObservedFileMap,\n identity: DomLayerIdentity,\n): ProjectionLayerRootSnapshot {\n return {\n semantic: {\n kind: \"layers\",\n tree: serializeDomLayerRootNode(root, identity),\n },\n observedFiles,\n };\n}\n\n/** Build exact semantic deltas from source-realm mutation targets. */\nfunction captureProjectionDomLayerPatchFromTargets(\n root: Element,\n targets: ProjectionDomLayerTargets,\n observedFiles: ProjectionObservedFileMap,\n identity: DomLayerIdentity,\n): ProjectionLayerPatch | undefined {\n const structuralTargets = new Set(\n targets.structural.filter(\n (target) => target === root || root.contains(target),\n ),\n );\n const metadataTargets = new Set(\n targets.metadata.filter(\n (target) => target === root || root.contains(target),\n ),\n );\n\n // A parent replacement already carries the final semantic subtree for every\n // descendant. Keep only the widest disjoint regions, matching the DOM patch\n // coalescer's final-state contract.\n const regions = Array.from(structuralTargets).filter(\n (candidate) =>\n !Array.from(structuralTargets).some(\n (other) => other !== candidate && other.contains(candidate),\n ),\n );\n const regionSnapshots: ProjectionLayerRegionSnapshot[] = regions.map(\n (target) => ({\n targetFiberId: layerIdForTarget(root, target, identity),\n tree:\n target === root\n ? serializeDomLayerRootNode(root, identity)\n : serializeDomLayerNode(root, target, identity),\n observedFiles,\n }),\n );\n\n const metadataSnapshots: ProjectionLayerMetadataSnapshot[] = [];\n for (const target of metadataTargets) {\n if (\n target !== root &&\n regions.some((region) => region === root || region.contains(target))\n ) {\n continue;\n }\n metadataSnapshots.push({\n targetFiberId: layerIdForTarget(root, target, identity),\n props: captureProjectionDomLayerProps(target),\n });\n }\n\n if (regionSnapshots.length === 0 && metadataSnapshots.length === 0) {\n return undefined;\n }\n return {\n ...(regionSnapshots.length > 0 ? { regions: regionSnapshots } : {}),\n ...(metadataSnapshots.length > 0 ? { metadata: metadataSnapshots } : {}),\n };\n}\n\nexport function serializeProjectionDomLayerRegion(\n root: Element,\n target: Element,\n observedFiles: ProjectionObservedFileMap = {},\n): ProjectionLayerRegionSnapshot {\n return {\n targetFiberId: layerIdForTarget(root, target, dataDomLayerIdentity),\n tree:\n target === root\n ? serializeDomLayerRootNode(root, dataDomLayerIdentity)\n : serializeDomLayerNode(root, target, dataDomLayerIdentity),\n observedFiles,\n };\n}\n\nexport function captureProjectionDomLayerMetadata(\n element: Element,\n): ProjectionLayerMetadataSnapshot | null {\n const domId = element.getAttribute(DOM_ID_ATTR);\n if (!domId) return null;\n return {\n targetFiberId: projectionDomLayerId(domId),\n props: captureProjectionDomLayerProps(element),\n };\n}\n\nfunction serializeDomLayerRootNode(\n root: Element,\n identity: DomLayerIdentity,\n): ProjectionLayerNode {\n const name = root.tagName.toLowerCase();\n return {\n kind: \"fragment\",\n name,\n domId: null,\n elementTag: null,\n source: {\n kind: \"react-fiber\",\n fiber: {\n tag: FiberTag.HostRoot,\n name,\n id: DOM_LAYER_ROOT_ID,\n },\n },\n children: Array.from(root.children).map((child) =>\n serializeDomLayerNode(root, child, identity),\n ),\n };\n}\n\nfunction serializeDomLayerNode(\n root: Element,\n element: Element,\n identity: DomLayerIdentity,\n): ProjectionLayerNode {\n const domId = identity.bindableDomIdForElement(root, element);\n const name = element.tagName.toLowerCase();\n return {\n kind: \"host\",\n name,\n domId,\n elementTag: name,\n props: captureProjectionDomLayerProps(element),\n source: {\n kind: \"react-fiber\",\n fiber: {\n tag: FiberTag.HostComponent,\n name,\n id: identity.layerIdForElement(root, element),\n },\n },\n children: Array.from(element.children).map((child) =>\n serializeDomLayerNode(root, child, identity),\n ),\n };\n}\n\nfunction layerIdForTarget(\n root: Element,\n target: Element,\n identity: DomLayerIdentity,\n): string {\n if (target === root) return DOM_LAYER_ROOT_ID;\n return identity.layerIdForElement(root, target);\n}\n\nexport function projectionDomLayerId(domId: string): string {\n return `${DOM_LAYER_FIBER_PREFIX}${domId}`;\n}\n\nfunction domLayerIdForElement(root: Element, element: Element): string {\n const domId = ensureProjectionDomId(element);\n if (domId) return projectionDomLayerId(domId);\n const path: number[] = [];\n let current: Element | null = element;\n while (current && current !== root) {\n const parent: Element | null = current.parentElement;\n if (!parent) break;\n path.push(Array.from(parent.children).indexOf(current));\n current = parent;\n }\n return `${DOM_LAYER_FIBER_PREFIX}path:${path.reverse().join(\".\")}`;\n}\n\nexport function captureProjectionDomLayerProps(\n element: Element,\n): ProjectionLayerProps | undefined {\n const props: Record<string, unknown> = {};\n const className = element.getAttribute(\"class\");\n if (className) props.className = className;\n const style = parseInlineStyle(element.getAttribute(\"style\"));\n if (style) props.style = style;\n\n for (const name of SOURCE_ANNOTATION_ATTRIBUTES) {\n const value = element.getAttribute(name);\n if (value === null) continue;\n if (name === \"data-tempo-position\" || name === \"data-tempo-modifiedts\") {\n const numeric = Number(value);\n if (Number.isFinite(numeric)) props[name] = numeric;\n } else {\n props[name] = value;\n }\n }\n for (const name of [\n \"data-tempo-supports-style\",\n \"data-tempo-supports-classname\",\n \"data-tempo-supports-children\",\n ]) {\n const value = element.getAttribute(name);\n if (value === \"true\" || value === \"false\") props[name] = value === \"true\";\n }\n return Object.keys(props).length > 0\n ? (props as unknown as ProjectionLayerProps)\n : undefined;\n}\n\nfunction parseInlineStyle(\n value: string | null,\n): Readonly<Record<string, string>> | undefined {\n if (!value) return undefined;\n const style: Record<string, string> = {};\n for (const declaration of value.split(\";\")) {\n const separator = declaration.indexOf(\":\");\n if (separator < 0) continue;\n const property = declaration.slice(0, separator).trim();\n const propertyValue = declaration.slice(separator + 1).trim();\n if (property && propertyValue) style[property] = propertyValue;\n }\n return Object.keys(style).length > 0 ? style : undefined;\n}\n","/**\n * Closed, destination-ready semantic snapshots for projection roots.\n *\n * This module deliberately serializes raw Fibers directly into the shape the\n * Canvas layer binder needs. It does not create an EnrichedFiberNode, copy an\n * arbitrary component prop bag, or capture computed-style/layout facts.\n * Source annotations and exact observed-file facts are collected during the\n * same Fiber enumeration that creates the semantic tree.\n */\n\nimport { type Fiber, FiberTag, type FiberTagValue } from \"../fiber/react-types\";\nimport { getDisplayName, getDomElement, getProps } from \"../fiber/serialize\";\nimport { ensureProjectionDomId } from \"../html/watch-dom\";\nimport {\n ProjectionObservedFileAccumulator,\n type ProjectionObservedFileMap,\n} from \"./projection-observed-files\";\n\nexport type ProjectionLayerKind = \"host\" | \"component\" | \"fragment\";\n\n/** The complete top-level prop allowlist consumed by LayerSnapshot today. */\nexport interface ProjectionLayerProps {\n readonly className?: string;\n readonly style?: Readonly<Record<string, string>>;\n readonly \"data-tempo-filepath\"?: string;\n readonly \"data-tempo-position\"?: number;\n readonly \"data-tempo-modifiedts\"?: number;\n readonly \"data-tempo-source-version\"?: string;\n readonly \"data-tempo-html-filepath\"?: string;\n readonly \"data-tempo-html-offset\"?: string;\n readonly \"data-tempo-html-modifiedts\"?: string;\n readonly \"data-tempo-html-source-version\"?: string;\n readonly \"data-tempo-supports-style\"?: boolean;\n readonly \"data-tempo-supports-classname\"?: boolean;\n readonly \"data-tempo-supports-children\"?: boolean;\n}\n\nexport interface ProjectionLayerSource {\n readonly kind: \"react-fiber\";\n readonly fiber: {\n readonly tag: FiberTagValue;\n readonly name: string;\n /** Stable for this serializer's source-document lifetime. */\n readonly id: string;\n };\n}\n\ninterface ProjectionLayerNodeBase {\n readonly name: string;\n readonly props?: ProjectionLayerProps;\n readonly source: ProjectionLayerSource;\n readonly children: readonly ProjectionLayerNode[];\n}\n\nexport interface ProjectionHostLayerNode extends ProjectionLayerNodeBase {\n readonly kind: \"host\";\n /** Identity hint for destination binding; elements cannot cross realms.\n * Null when the host element could not be stamped (contenteditable\n * interiors) — such a node binds without a destination element. */\n readonly domId: string | null;\n readonly elementTag: string;\n}\n\nexport interface ProjectionElementlessLayerNode\n extends ProjectionLayerNodeBase {\n readonly kind: \"component\" | \"fragment\";\n readonly domId: null;\n readonly elementTag: null;\n}\n\nexport type ProjectionLayerNode =\n | ProjectionHostLayerNode\n | ProjectionElementlessLayerNode;\n\n/**\n * The semantic slice of a self-contained full root baseline. The outer full\n * capture assembler adds the DOM, annotation, runtime-state, and portal\n * domains; those concerns do not belong in the Fiber serializer's interface.\n */\nexport interface ProjectionLayerRootSnapshot {\n readonly semantic:\n | { readonly kind: \"layers\"; readonly tree: ProjectionLayerNode | null }\n | { readonly kind: \"dom-only\" };\n readonly observedFiles: ProjectionObservedFileMap;\n}\n\n/**\n * One final-state semantic region. `targetFiberId` names the currently\n * published layer-tree node being replaced; `tree` is the replacement rooted\n * at that slot, or null when the committed Fiber branch disappeared.\n */\nexport interface ProjectionLayerRegionSnapshot {\n readonly targetFiberId: string;\n readonly tree: ProjectionLayerNode | null;\n readonly observedFiles: ProjectionObservedFileMap;\n}\n\n/** Exact non-structural facts for one already-published semantic node. */\nexport interface ProjectionLayerMetadataSnapshot {\n readonly targetFiberId: string;\n readonly props?: ProjectionLayerProps;\n}\n\nexport interface ProjectionLayerSerializationResult {\n readonly snapshot: ProjectionLayerRootSnapshot;\n readonly fiberNodesVisited: number;\n readonly semanticNodesSerialized: number;\n}\n\nexport interface ProjectionLayerRegionSerializationResult {\n readonly region: ProjectionLayerRegionSnapshot;\n readonly fiberNodesVisited: number;\n readonly semanticNodesSerialized: number;\n}\n\nexport interface ProjectionLayerSerializer {\n /** Serialize one committed Fiber root in one synchronous enumeration. */\n serialize(root: Fiber): ProjectionLayerSerializationResult;\n /** Stable only for this source-document serializer lifetime. */\n fiberId(fiber: Fiber): string;\n /** Read a previously assigned ID without growing the identity registry. */\n knownFiberId(fiber: Fiber): string | null;\n /** Serialize one exact replacement region, preserving its published ID. */\n serializeRegion(root: Fiber): ProjectionLayerRegionSerializationResult;\n /** Capture only the allowlisted facts of one existing semantic node. */\n captureMetadata(\n root: Fiber,\n options?: { readonly sourceAnnotations?: \"fiber\" | \"live-host\" },\n ): ProjectionLayerMetadataSnapshot;\n}\n\nconst COMPONENT_TAGS: ReadonlySet<FiberTagValue> = new Set([\n FiberTag.FunctionComponent,\n FiberTag.ClassComponent,\n FiberTag.ForwardRef,\n FiberTag.MemoComponent,\n FiberTag.SimpleMemoComponent,\n FiberTag.LazyComponent,\n]);\n\n/**\n * Create one serializer per source-document lifetime. Its private Fiber ID\n * registry pairs React's current/alternate objects while avoiding realm-global\n * identity state and keeping the serializer free of the legacy enriched path.\n */\nexport function createProjectionLayerSerializer(): ProjectionLayerSerializer {\n let nextFiberId = 1;\n const fiberIds = new WeakMap<Fiber, string>();\n\n const fiberId = (fiber: Fiber): string => {\n const direct = fiberIds.get(fiber);\n if (direct) return direct;\n const alternate = fiber.alternate ? fiberIds.get(fiber.alternate) : null;\n if (alternate) {\n fiberIds.set(fiber, alternate);\n return alternate;\n }\n const id = String(nextFiberId++);\n fiberIds.set(fiber, id);\n if (fiber.alternate) fiberIds.set(fiber.alternate, id);\n return id;\n };\n\n const knownFiberId = (fiber: Fiber): string | null =>\n fiberIds.get(fiber) ??\n (fiber.alternate ? fiberIds.get(fiber.alternate) : undefined) ??\n null;\n\n const serialize = (root: Fiber): ProjectionLayerSerializationResult => {\n const observedFiles = new ProjectionObservedFileAccumulator();\n let fiberNodesVisited = 0;\n let semanticNodesSerialized = 0;\n\n const visit = (fiber: Fiber, emitLayer: boolean): ProjectionLayerNode[] => {\n fiberNodesVisited += 1;\n const name = getDisplayName(fiber);\n const kind = projectionKindForTag(fiber.tag);\n const included = isProjectionLayerFiber(fiber);\n const element = kind === \"host\" ? getDomElement(fiber) : null;\n const domId = element ? ensureProjectionDomId(element) : null;\n\n const props = included\n ? captureProjectionLayerProps(fiber, element)\n : undefined;\n if (props) {\n observedFiles.add(\n props[\"data-tempo-filepath\"],\n props[\"data-tempo-modifiedts\"],\n props[\"data-tempo-source-version\"],\n );\n observedFiles.add(\n props[\"data-tempo-html-filepath\"],\n props[\"data-tempo-html-modifiedts\"],\n props[\"data-tempo-html-source-version\"],\n );\n }\n\n // SVG is one Canvas layer, but its descendants still belong to the\n // certified render population and can carry observed-file facts.\n // Contenteditable is different: its descendants are presentation-owned\n // and deliberately receive neither projection IDs nor semantic nodes.\n const isSvgLeaf =\n included && kind === \"host\" && name.toLowerCase() === \"svg\";\n const isContentEditableBoundary =\n included &&\n kind === \"host\" &&\n element?.getAttribute(\"contenteditable\") !== null;\n const children: ProjectionLayerNode[] = [];\n if (!isContentEditableBoundary) {\n for (let child = fiber.child; child; child = child.sibling) {\n children.push(...visit(child, emitLayer && !isSvgLeaf));\n }\n }\n\n if (!emitLayer) return [];\n if (!included) return children;\n if (kind === null) return children;\n\n const source: ProjectionLayerSource = {\n kind: \"react-fiber\",\n fiber: { tag: fiber.tag, name, id: fiberId(fiber) },\n };\n let node: ProjectionLayerNode;\n if (kind === \"host\") {\n node = {\n kind,\n name,\n domId,\n elementTag: name,\n props,\n source,\n children: isSvgLeaf || isContentEditableBoundary ? [] : children,\n };\n } else {\n node = {\n kind,\n name,\n domId: null,\n elementTag: null,\n props,\n source,\n children,\n };\n }\n semanticNodesSerialized += 1;\n return [node];\n };\n\n const branches = visit(root, true);\n\n let tree: ProjectionLayerNode | null;\n if (branches.length === 1) {\n tree = branches[0] ?? null;\n } else if (root.tag === FiberTag.HostRoot) {\n const name = getDisplayName(root);\n tree = {\n kind: \"fragment\",\n name,\n domId: null,\n elementTag: null,\n source: {\n kind: \"react-fiber\",\n fiber: { tag: root.tag, name, id: fiberId(root) },\n },\n children: branches,\n };\n semanticNodesSerialized += 1;\n } else {\n tree = null;\n }\n\n return {\n snapshot: {\n semantic: { kind: \"layers\", tree },\n observedFiles: observedFiles.snapshot(),\n },\n fiberNodesVisited,\n semanticNodesSerialized,\n };\n };\n\n return {\n serialize,\n fiberId,\n knownFiberId,\n serializeRegion(root) {\n const targetFiberId = fiberId(root);\n const serialized = serialize(root);\n return {\n region: {\n targetFiberId,\n tree:\n serialized.snapshot.semantic.kind === \"layers\"\n ? serialized.snapshot.semantic.tree\n : null,\n observedFiles: serialized.snapshot.observedFiles,\n },\n fiberNodesVisited: serialized.fiberNodesVisited,\n semanticNodesSerialized: serialized.semanticNodesSerialized,\n };\n },\n captureMetadata(root, options) {\n return {\n targetFiberId: fiberId(root),\n props: captureProjectionLayerProps(\n root,\n root.tag === FiberTag.HostComponent ? getDomElement(root) : null,\n options?.sourceAnnotations ?? \"fiber\",\n ),\n };\n },\n };\n}\n\n/** True when the Fiber itself has one stable Canvas semantic node. */\nexport function isProjectionLayerFiber(fiber: Fiber): boolean {\n if (isTempoHiddenFiber(fiber)) return false;\n const kind = projectionKindForTag(fiber.tag);\n if (kind === null) return false;\n if (kind === \"host\") return true;\n\n // React can introduce Memo/ForwardRef/function wrapper Fibers for the exact\n // same authored JSX location. Exclude that wrapper by one stable semantic\n // rule instead of serializing it, minting an ID, then deleting its node in a\n // post-pass. Every Fiber that receives a projection ID is therefore a Fiber\n // the destination was actually given.\n const sourceKey = projectionFiberSourceKey(fiber);\n if (!sourceKey) return true;\n for (let parent = fiber.return; parent; parent = parent.return) {\n if (isTempoHiddenFiber(parent)) continue;\n const parentKind = projectionKindForTag(parent.tag);\n if (parentKind === null) continue;\n if (parentKind === \"host\") return true;\n return projectionFiberSourceKey(parent) !== sourceKey;\n }\n return true;\n}\n\nfunction projectionKindForTag(tag: FiberTagValue): ProjectionLayerKind | null {\n if (tag === FiberTag.HostComponent) return \"host\";\n if (COMPONENT_TAGS.has(tag)) return \"component\";\n return null;\n}\n\n/**\n * Ascend from a watched root's first host fiber to the topmost SOURCE-ANNOTATED\n * component fiber that renders it, so the semantic tree includes user-authored\n * wrapper components that own the root host element (a design-system\n * `PageFrame` between the storyboard slot and its first `<div>`). Serializing\n * from the host alone drops those fibers before the destination's transparency\n * rules can ever see them.\n *\n * The ascent anchors only on component fibers carrying a\n * `data-tempo-filepath`/`data-tempo-position` source tuple — an annotated\n * callsite is user JSX. It stops, without anchoring, at:\n * - any host fiber, HostRoot, or HostPortal (crossed out of this render's\n * own component chain);\n * - a Tempo-hidden fiber (`data-tempo-hide-fiber` plumbing);\n * - the first un-annotated component fiber — the SDK's own `<Component />`\n * storyboard callsite and other non-user plumbing are never annotated, so\n * a plain storyboard's tree still roots at its host element exactly as\n * before.\n * Non-semantic fibers (fragments, providers, modes, Suspense) neither anchor\n * nor stop the ascent.\n */\nexport function ascendToAnnotatedComponentRoot(fiber: Fiber): Fiber {\n let topmost = fiber;\n for (let parent = fiber.return; parent; parent = parent.return) {\n if (\n parent.tag === FiberTag.HostRoot ||\n parent.tag === FiberTag.HostPortal\n ) {\n break;\n }\n const kind = projectionKindForTag(parent.tag);\n if (kind === \"host\") break;\n if (isTempoHiddenFiber(parent)) break;\n if (kind === \"component\") {\n if (projectionFiberSourceKey(parent) === null) break;\n topmost = parent;\n }\n }\n return topmost;\n}\n\nfunction isTempoHiddenFiber(fiber: Fiber): boolean {\n const props = getProps(fiber);\n const direct = props?.[\"data-tempo-hide-fiber\"];\n const dataSet = props?.dataSet;\n const native =\n dataSet && typeof dataSet === \"object\"\n ? (dataSet as Record<string, unknown>).tempoHideFiber\n : undefined;\n const value = native ?? direct;\n return value === true || value === \"true\";\n}\n\nfunction captureProjectionLayerProps(\n fiber: Fiber,\n element: Element | null,\n sourceAnnotations: \"fiber\" | \"live-host\" = \"fiber\",\n): ProjectionLayerProps | undefined {\n const raw = getProps(fiber);\n const dataSet =\n raw?.dataSet && typeof raw.dataSet === \"object\"\n ? (raw.dataSet as Record<string, unknown>)\n : undefined;\n const read = (\n flatKey: string,\n dataSetKey: string,\n authority: \"source\" | \"fiber\" = \"source\",\n ): unknown => {\n if (\n authority === \"source\" &&\n element &&\n sourceAnnotations === \"live-host\"\n ) {\n return element.getAttribute(flatKey);\n }\n return dataSet && Object.hasOwn(dataSet, dataSetKey)\n ? dataSet[dataSetKey]\n : raw?.[flatKey];\n };\n\n const props: Record<string, unknown> = {};\n const putString = (flatKey: string, dataSetKey: string): void => {\n const value = read(flatKey, dataSetKey);\n if (typeof value === \"string\") props[flatKey] = value;\n };\n const putFiniteNumber = (flatKey: string, dataSetKey: string): void => {\n const value = read(flatKey, dataSetKey);\n const numeric =\n typeof value === \"number\"\n ? value\n : typeof value === \"string\"\n ? Number(value)\n : Number.NaN;\n if (Number.isFinite(numeric)) props[flatKey] = numeric;\n };\n const putStringified = (flatKey: string, dataSetKey: string): void => {\n const value = read(flatKey, dataSetKey);\n if (typeof value === \"string\" || typeof value === \"number\") {\n props[flatKey] = String(value);\n }\n };\n const putBoolean = (flatKey: string, dataSetKey: string): void => {\n // Capability flags describe the component contract carried by Fiber. A\n // live host mutation is authoritative only for source annotations; it\n // must not erase Fiber-only capabilities that have no DOM attribute.\n const value = read(flatKey, dataSetKey, \"fiber\");\n if (value === true || value === \"true\") props[flatKey] = true;\n if (value === false || value === \"false\") props[flatKey] = false;\n };\n\n putString(\"data-tempo-filepath\", \"tempoFilepath\");\n putFiniteNumber(\"data-tempo-position\", \"tempoPosition\");\n putFiniteNumber(\"data-tempo-modifiedts\", \"tempoModifiedts\");\n putString(\"data-tempo-source-version\", \"tempoSourceVersion\");\n putString(\"data-tempo-html-filepath\", \"tempoHtmlFilepath\");\n putStringified(\"data-tempo-html-offset\", \"tempoHtmlOffset\");\n putStringified(\"data-tempo-html-modifiedts\", \"tempoHtmlModifiedts\");\n putString(\"data-tempo-html-source-version\", \"tempoHtmlSourceVersion\");\n putBoolean(\"data-tempo-supports-style\", \"tempoSupportsStyle\");\n putBoolean(\"data-tempo-supports-classname\", \"tempoSupportsClassname\");\n putBoolean(\"data-tempo-supports-children\", \"tempoSupportsChildren\");\n\n if (element) {\n const className = element.getAttribute(\"class\");\n if (className !== null && className !== \"\") props.className = className;\n const style = parseInlineStyle(element.getAttribute(\"style\"));\n if (style) props.style = style;\n }\n\n return Object.keys(props).length > 0\n ? (props as unknown as ProjectionLayerProps)\n : undefined;\n}\n\nfunction parseInlineStyle(\n value: string | null,\n): Readonly<Record<string, string>> | undefined {\n if (!value) return undefined;\n const style: Record<string, string> = {};\n for (const declaration of value.split(\";\")) {\n const colon = declaration.indexOf(\":\");\n if (colon < 0) continue;\n const property = declaration.slice(0, colon).trim();\n const propertyValue = declaration.slice(colon + 1).trim();\n if (property) style[property] = propertyValue;\n }\n return Object.keys(style).length > 0 ? style : undefined;\n}\n\nfunction projectionFiberSourceKey(fiber: Fiber): string | null {\n // Only the source annotations are read here, and in the default \"fiber\"\n // authority those come from the Fiber's props alone. Passing no element\n // skips the className and inline-style capture this caller discards — the\n // walk below asks for this key once per visited Fiber and again per\n // ancestor.\n const props = captureProjectionLayerProps(fiber, null);\n const filepath = props?.[\"data-tempo-filepath\"];\n const position = props?.[\"data-tempo-position\"];\n return filepath && position !== undefined ? `${filepath}:${position}` : null;\n}\n","import { getFiberFromElement } from \"../fiber/capture\";\nimport { resolveCommittedFiber } from \"../fiber/serialize\";\nimport { captureAttributes, removeScriptTags } from \"../html/capture\";\nimport { DOM_ID_ATTR } from \"../html/watch-dom\";\nimport {\n capturePortalCoordinateSpace,\n PORTAL_ID_ATTR,\n} from \"../html/watch-portal\";\nimport { cssEscape } from \"./css-escape\";\nimport {\n type ProjectionDomLayerSerializer,\n serializeProjectionDomLayerRoot,\n} from \"./projection-dom-layers\";\nimport {\n ascendToAnnotatedComponentRoot,\n createProjectionLayerSerializer,\n type ProjectionLayerRootSnapshot,\n type ProjectionLayerSerializer,\n} from \"./projection-layer-snapshot\";\nimport {\n ProjectionObservedFileAccumulator,\n type ProjectionObservedFileMap,\n} from \"./projection-observed-files\";\nimport {\n captureFinalAttributes,\n captureProjectionAncestorIds,\n captureRegionWithoutAnnotations,\n detachSourceAnnotations,\n PROJECTION_ROOT_TARGET_ID,\n type ProjectionAnnotationPatch,\n type ProjectionPortalPatch,\n type ProjectionStatePatch,\n} from \"./projection-patch\";\n\nexport interface ProjectionFullDomSnapshot {\n /** Children of the watched source wrapper; the wrapper is host plumbing. */\n readonly html: string;\n /** Optional authored attributes for sources whose wrapper is content (for\n * example a static HTML `<body>`), rather than host-only plumbing. */\n readonly rootAttributes?: Readonly<Record<string, string>>;\n readonly documentElementAttributes: Readonly<Record<string, string>>;\n /** The source `<body>`'s authored attributes. Portals are mirrored into the\n * destination body, so its classes and data attributes are part of what they\n * render against. Absent for a source document with no body. */\n readonly bodyAttributes?: Readonly<Record<string, string>>;\n readonly baseUrl?: string;\n readonly annotations: readonly ProjectionAnnotationPatch[];\n readonly state: readonly ProjectionStatePatch[];\n readonly portals: readonly ProjectionPortalPatch[];\n}\n\nexport interface ProjectionFullSnapshot {\n readonly dom: ProjectionFullDomSnapshot;\n readonly layers: ProjectionLayerRootSnapshot;\n readonly observedFiles: ProjectionObservedFileMap;\n}\n\nexport interface ProjectionFullSnapshotCapture {\n readonly snapshot: ProjectionFullSnapshot;\n readonly fiberNodesVisited: number;\n readonly semanticNodesSerialized: number;\n /** Distinct stamped elements the baseline covers. Producer-local: the\n * destination is never told this and never validates against it. */\n readonly hostDomIdCount: number;\n}\n\nexport interface CaptureProjectionFullSnapshotOptions {\n readonly root: Element;\n readonly fiberTarget?: Element | null;\n readonly portals?: readonly Element[];\n /** One serializer per source-document/root lifetime preserves Fiber IDs. */\n readonly layerSerializer?: ProjectionLayerSerializer;\n /** One serializer per source-document/root lifetime preserves host element\n * semantic identity even when the page duplicates projection DOM ids. */\n readonly domLayerSerializer?: ProjectionDomLayerSerializer;\n}\n\n/**\n * One self-contained initial/reload/recovery baseline. Every O(N) operation is\n * performed in this single host pass family; ordinary updates never call it.\n * Capture never refuses: whatever the source document looks like — duplicate\n * ids, unstampable elements — is exactly what the destination should show.\n */\nexport function captureProjectionFullSnapshot(\n options: CaptureProjectionFullSnapshotOptions,\n): ProjectionFullSnapshotCapture {\n const fiberTarget = options.fiberTarget ?? options.root.firstElementChild;\n const serializer =\n options.layerSerializer ?? createProjectionLayerSerializer();\n const rawFiber = fiberTarget ? getFiberFromElement(fiberTarget) : null;\n const fiberLayers = rawFiber\n ? serializer.serialize(\n ascendToAnnotatedComponentRoot(resolveCommittedFiber(rawFiber)),\n )\n : null;\n\n const observedFiles = new ProjectionObservedFileAccumulator();\n for (const [file, fact] of Object.entries(\n fiberLayers?.snapshot.observedFiles ?? {},\n )) {\n observedFiles.add(file, fact.modifiedTs, fact.sourceVersion);\n }\n const { dom, hostDomIdCount } = captureFullDom(\n options.root,\n options.portals ?? [],\n observedFiles,\n );\n const observedFileSnapshot = observedFiles.snapshot();\n const layers =\n fiberLayers?.snapshot ??\n options.domLayerSerializer?.serializeRoot(\n options.root,\n observedFileSnapshot,\n ) ??\n serializeProjectionDomLayerRoot(options.root, observedFileSnapshot);\n\n return {\n snapshot: {\n dom,\n layers,\n observedFiles: observedFileSnapshot,\n },\n fiberNodesVisited: fiberLayers?.fiberNodesVisited ?? 0,\n semanticNodesSerialized:\n fiberLayers?.semanticNodesSerialized ?? hostDomIdCount + 1,\n hostDomIdCount,\n };\n}\n\nfunction captureFullDom(\n root: Element,\n portals: readonly Element[],\n observedFiles: ProjectionObservedFileAccumulator,\n): { dom: ProjectionFullDomSnapshot; hostDomIdCount: number } {\n const clone = root.cloneNode(true) as Element;\n for (const script of clone.querySelectorAll(\"script\")) script.remove();\n const annotations: ProjectionAnnotationPatch[] = [];\n // Producer-local, for the batch perf receipt only; never serialized.\n const hostDomIds = new Set<string>();\n stripAnnotationsAndCollectIds(\n root,\n clone,\n annotations,\n hostDomIds,\n observedFiles,\n false,\n );\n\n const portalPatches: ProjectionPortalPatch[] = [];\n for (const portal of portals) {\n if (!portal.isConnected) continue;\n const portalId = portal.getAttribute(PORTAL_ID_ATTR);\n if (!portalId) continue;\n const portalClone = portal.cloneNode(true) as Element;\n for (const script of portalClone.querySelectorAll(\"script\"))\n script.remove();\n stripAnnotationsAndCollectIds(\n portal,\n portalClone,\n annotations,\n hostDomIds,\n observedFiles,\n true,\n );\n const coordinateSpace = capturePortalCoordinateSpace(root, portal);\n portalPatches.push({\n kind: \"replace\",\n portalId,\n html: removeScriptTags(portalClone.outerHTML),\n ...(coordinateSpace && { coordinateSpace }),\n });\n }\n\n const body = root.ownerDocument.body;\n const dom: ProjectionFullDomSnapshot = {\n html: removeScriptTags(clone.innerHTML),\n documentElementAttributes: captureAttributes(\n root.ownerDocument.documentElement,\n ),\n ...(body ? { bodyAttributes: captureAttributes(body) } : {}),\n baseUrl: root.ownerDocument.baseURI,\n annotations,\n state: collectFullRuntimeState(root, portals),\n portals: portalPatches,\n };\n return { dom, hostDomIdCount: hostDomIds.size };\n}\n\nfunction stripAnnotationsAndCollectIds(\n liveRoot: Element,\n cloneRoot: Element,\n annotations: ProjectionAnnotationPatch[],\n hostDomIds: Set<string>,\n observedFiles: ProjectionObservedFileAccumulator,\n includeRoot: boolean,\n): void {\n const live = includeRoot\n ? [liveRoot, ...liveRoot.querySelectorAll(\"*\")]\n : Array.from(liveRoot.querySelectorAll(\"*\"));\n const clones = includeRoot\n ? [cloneRoot, ...cloneRoot.querySelectorAll(\"*\")]\n : Array.from(cloneRoot.querySelectorAll(\"*\"));\n for (const element of live) {\n const domId = element.getAttribute(DOM_ID_ATTR);\n if (domId) hostDomIds.add(domId);\n }\n for (const detached of detachSourceAnnotations(live, clones)) {\n annotations.push({\n targetId: detached.targetId,\n attributes: captureFinalAttributes(detached.element, detached.names),\n });\n observedFiles.addElement(detached.element);\n }\n}\n\nfunction collectFullRuntimeState(\n root: Element,\n portals: readonly Element[],\n): ProjectionStatePatch[] {\n const states: ProjectionStatePatch[] = [];\n for (const scope of [root, ...portals]) {\n for (const element of [scope, ...scope.querySelectorAll(\"*\")]) {\n const targetId = element.getAttribute(DOM_ID_ATTR);\n if (!targetId) continue;\n if (element.scrollTop !== 0 || element.scrollLeft !== 0) {\n states.push({\n targetId,\n kind: \"scroll\",\n scrollTop: element.scrollTop,\n scrollLeft: element.scrollLeft,\n });\n }\n if (element instanceof HTMLInputElement) {\n if (element.type === \"checkbox\" || element.type === \"radio\") {\n if (element.checked !== element.defaultChecked) {\n states.push({\n targetId,\n kind: \"checked\",\n checked: element.checked,\n });\n }\n } else if (element.value !== element.defaultValue) {\n states.push({\n targetId,\n kind: \"value\",\n value: element.value,\n selectionStart: element.selectionStart,\n selectionEnd: element.selectionEnd,\n });\n }\n } else if (\n element instanceof HTMLTextAreaElement &&\n element.value !== element.defaultValue\n ) {\n states.push({\n targetId,\n kind: \"value\",\n value: element.value,\n selectionStart: element.selectionStart,\n selectionEnd: element.selectionEnd,\n });\n } else if (element instanceof HTMLSelectElement) {\n const selectedIndices: number[] = [];\n let changed = false;\n for (\n let optionIndex = 0;\n optionIndex < element.options.length;\n optionIndex += 1\n ) {\n const option = element.options[optionIndex];\n if (!option) continue;\n if (option.selected) selectedIndices.push(optionIndex);\n if (option.selected !== option.defaultSelected) changed = true;\n }\n if (changed)\n states.push({ targetId, kind: \"selected\", selectedIndices });\n }\n }\n }\n return states;\n}\n\n/** One element's exact children-region final state. */\nexport interface ProjectionRegionCapture {\n readonly targetId: string;\n readonly html: string;\n /** Current parent-and-up id chain, for continuing the repair ladder. */\n readonly ancestorIds: readonly string[];\n readonly annotations: readonly ProjectionAnnotationPatch[];\n readonly state: readonly ProjectionStatePatch[];\n}\n\n/**\n * Capture one element's region on demand for the destination's scoped repair\n * ladder. Same capture routine as the hot patch builder: scripts stripped,\n * addressable annotations lifted out beside the HTML, descendant runtime state\n * included so a morphed repair isn't state-bare. Null when the id no longer\n * names a live element — the destination then climbs further up its known\n * chain.\n */\nexport function captureProjectionRegion(\n root: Element,\n targetId: string,\n portals: readonly Element[] = [],\n): ProjectionRegionCapture | null {\n const element = resolveRegionElement(root, targetId, portals);\n if (!element) return null;\n const captured = captureRegionWithoutAnnotations(element);\n const annotations = captured.annotations.map((detached) => ({\n targetId: detached.targetId,\n attributes: captureFinalAttributes(detached.element, detached.names),\n ancestorIds: captureProjectionAncestorIds(root, detached.element),\n }));\n return {\n targetId,\n html: captured.html,\n ancestorIds:\n element === root ? [] : captureProjectionAncestorIds(root, element),\n annotations,\n state: collectFullRuntimeState(element, []),\n };\n}\n\n/** Ingress validation for the untrusted repair-response wire value. */\nexport function isProjectionRegionCapture(\n value: unknown,\n): value is ProjectionRegionCapture {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const record = value as Record<string, unknown>;\n return (\n typeof record.targetId === \"string\" &&\n typeof record.html === \"string\" &&\n Array.isArray(record.ancestorIds) &&\n record.ancestorIds.every((id) => typeof id === \"string\") &&\n Array.isArray(record.annotations) &&\n Array.isArray(record.state)\n );\n}\n\nfunction resolveRegionElement(\n root: Element,\n targetId: string,\n portals: readonly Element[],\n): Element | null {\n if (targetId === PROJECTION_ROOT_TARGET_ID) return root;\n const selector = `[${DOM_ID_ATTR}=\"${cssEscape(targetId)}\"]`;\n const scopes = [root, ...portals.filter((portal) => portal.isConnected)];\n for (const scope of scopes) {\n const found = scope.matches(selector)\n ? scope\n : scope.querySelector(selector);\n if (found) return found;\n }\n return null;\n}\n","import type {\n CombinedProjectionBatch,\n CombinedProjectionProblem,\n} from \"./projection-batch\";\nimport type { ProjectionFullSnapshot } from \"./projection-full-snapshot\";\nimport type { ProjectionRootPatch } from \"./projection-root-accumulator\";\n\nexport const PROJECTION_FLUSH_WINDOW_MS = 500;\n\ntype Stop = () => void;\n\nexport interface ProjectionFlushTiming {\n readonly flushStartedAt: number;\n readonly flushIntervalMs: number | null;\n readonly fixedWindowTimersOpened: number;\n readonly maxSimultaneousTimers: number;\n}\n\nexport interface ProjectionProducerFlushContext extends ProjectionFlushTiming {\n readonly candidateRootCount: number;\n readonly initialForSession: boolean;\n readonly fullRequested: boolean;\n}\n\nexport interface ProjectionProducerScheduler {\n now(): number;\n schedule(callback: () => void, delayMs: number): Stop;\n}\n\ntype CapturedRoot =\n | { readonly kind: \"full\"; readonly snapshot: ProjectionFullSnapshot }\n | { readonly kind: \"patch\"; readonly patch: ProjectionRootPatch }\n | { readonly kind: \"problem\"; readonly problem: CombinedProjectionProblem }\n | null;\n\ninterface OutboxOptions {\n readonly scheduler?: ProjectionProducerScheduler;\n readonly flushWindowMs?: number;\n readonly onError?: (error: unknown) => void;\n captureRoot(\n rootId: string,\n context: ProjectionProducerFlushContext,\n ): CapturedRoot;\n captureHead(context: ProjectionProducerFlushContext): string | undefined;\n emit(batch: CombinedProjectionBatch): void;\n}\n\nexport interface ProjectionOutbox {\n bindSession(sessionId: string): void;\n addRoot(rootId: string): void;\n removeRoot(rootId: string): void;\n record(activity: {\n readonly rootIds?: readonly string[];\n readonly head?: boolean;\n }): void;\n /** One current self-contained baseline for one root. */\n requestFull(rootId: string): void;\n stop(): void;\n}\n\nconst defaultScheduler: ProjectionProducerScheduler = {\n now: () =>\n typeof performance === \"undefined\" ? Date.now() : performance.now(),\n schedule(callback, delayMs) {\n const timer = setTimeout(callback, delayMs);\n return () => clearTimeout(timer);\n },\n};\n\nexport interface ProjectionFixedWindow {\n schedule(): void;\n flushNow(): void;\n cancel(): void;\n reset(): void;\n stop(): void;\n}\n\n/** @internal One non-resetting timer shared by live and static source owners. */\nexport function createProjectionFixedWindow(options: {\n readonly scheduler?: ProjectionProducerScheduler;\n readonly flushWindowMs?: number;\n hasPending(): boolean;\n flush(timing: ProjectionFlushTiming): void;\n}): ProjectionFixedWindow {\n const scheduler = options.scheduler ?? defaultScheduler;\n const windowMs = options.flushWindowMs ?? PROJECTION_FLUSH_WINDOW_MS;\n if (windowMs < 0) throw new Error(\"flushWindowMs must be non-negative\");\n let cancelTimer: Stop | undefined;\n let stopped = false;\n let flushing = false;\n let flushAgain = false;\n let timersOpened = 0;\n let lastFlushAt: number | null = null;\n\n const cancel = () => {\n cancelTimer?.();\n cancelTimer = undefined;\n };\n const schedule = () => {\n if (stopped || !options.hasPending() || cancelTimer) return;\n timersOpened += 1;\n cancelTimer = scheduler.schedule(() => {\n cancelTimer = undefined;\n flushNow();\n }, windowMs);\n };\n function flushNow(): void {\n cancel();\n if (stopped || !options.hasPending()) return;\n if (flushing) {\n flushAgain = true;\n return;\n }\n flushing = true;\n do {\n flushAgain = false;\n const now = scheduler.now();\n const timing: ProjectionFlushTiming = {\n flushStartedAt: Date.now(),\n flushIntervalMs: lastFlushAt === null ? null : now - lastFlushAt,\n fixedWindowTimersOpened: timersOpened,\n maxSimultaneousTimers: timersOpened > 0 ? 1 : 0,\n };\n lastFlushAt = now;\n timersOpened = 0;\n options.flush(timing);\n } while (flushAgain && !stopped && options.hasPending());\n flushing = false;\n }\n\n return {\n schedule,\n flushNow,\n cancel,\n reset() {\n cancel();\n timersOpened = 0;\n lastFlushAt = null;\n },\n stop() {\n stopped = true;\n cancel();\n },\n };\n}\n\n/** @internal Ordered outbox for the one live-document producer. */\nexport function createProjectionOutbox(\n options: OutboxOptions,\n): ProjectionOutbox {\n const roots = new Set<string>();\n const dirty = new Set<string>();\n const full = new Set<string>();\n let dirtyHead = false;\n let sessionId: string | undefined;\n let sequence = 0;\n let stopped = false;\n let fixedWindow: ProjectionFixedWindow;\n\n const hasWork = () => dirtyHead || dirty.size > 0;\n const report = (error: unknown) => {\n try {\n options.onError?.(error);\n } catch {\n // Reporting cannot break recovery or cleanup.\n }\n };\n const assertActive = () => {\n if (stopped) throw new Error(\"Projection producer has been stopped\");\n };\n\n const restore = (\n failedSession: string,\n rootIds: readonly string[],\n includeHead: boolean,\n ) => {\n if (stopped || sessionId !== failedSession) return;\n for (const rootId of rootIds) {\n if (!roots.has(rootId)) continue;\n dirty.add(rootId);\n // Capture drains source-local candidates, so an unsent patch can only be\n // retried honestly as a current baseline.\n full.add(rootId);\n }\n dirtyHead ||= includeHead;\n fixedWindow.schedule();\n };\n\n const flushOnce = (timing: ProjectionFlushTiming) => {\n const activeSession = sessionId;\n if (stopped || !activeSession || !hasWork()) return;\n const rootIds = [...dirty];\n const fullRootIds = new Set(full);\n const includeHead = dirtyHead;\n const context: ProjectionProducerFlushContext = {\n ...timing,\n candidateRootCount: rootIds.length,\n initialForSession: sequence === 0,\n fullRequested: false,\n };\n dirty.clear();\n full.clear();\n dirtyHead = false;\n\n try {\n const changes: CombinedProjectionBatch[\"roots\"][number][] = [];\n for (const rootId of rootIds) {\n if (!roots.has(rootId)) continue;\n const captured = options.captureRoot(rootId, {\n ...context,\n fullRequested: fullRootIds.has(rootId),\n });\n if (!roots.has(rootId) || !captured) continue;\n changes.push({ rootId, ...captured });\n }\n if (stopped || sessionId !== activeSession) return;\n const head = includeHead ? options.captureHead(context) : undefined;\n if (stopped || sessionId !== activeSession) return;\n if (changes.length === 0 && head === undefined) return;\n const emittedSequence = sequence;\n options.emit({\n sessionId: activeSession,\n sequence: emittedSequence,\n ...(head === undefined ? {} : { head }),\n roots: changes,\n });\n if (sessionId === activeSession && sequence === emittedSequence) {\n sequence += 1;\n }\n } catch (error) {\n report(error);\n restore(activeSession, rootIds, includeHead);\n }\n };\n\n fixedWindow = createProjectionFixedWindow({\n scheduler: options.scheduler,\n flushWindowMs: options.flushWindowMs,\n hasPending: hasWork,\n flush: flushOnce,\n });\n\n return {\n bindSession(nextSessionId) {\n assertActive();\n if (!nextSessionId)\n throw new Error(\"Projection session ID must not be empty\");\n if (sessionId === nextSessionId) return;\n fixedWindow.reset();\n dirty.clear();\n full.clear();\n dirtyHead = true;\n sessionId = nextSessionId;\n sequence = 0;\n for (const rootId of roots.keys()) {\n dirty.add(rootId);\n full.add(rootId);\n }\n fixedWindow.schedule();\n },\n addRoot(rootId) {\n assertActive();\n if (!rootId) throw new Error(\"Projection root ID must not be empty\");\n if (roots.has(rootId)) return;\n roots.add(rootId);\n if (!sessionId) return;\n dirty.add(rootId);\n full.add(rootId);\n // A root that joined after the last head emission holds no copy of the\n // document head, and every later emission reaches every lane, so this is\n // the only moment a lane can be missing it.\n dirtyHead = true;\n if (sequence === 0) fixedWindow.schedule();\n else fixedWindow.flushNow();\n },\n removeRoot(rootId) {\n if (stopped || !roots.delete(rootId)) return;\n dirty.delete(rootId);\n full.delete(rootId);\n if (!hasWork()) fixedWindow.cancel();\n },\n record(activity) {\n if (stopped || !sessionId) return;\n dirtyHead ||= activity.head === true;\n for (const rootId of activity.rootIds ?? []) {\n if (roots.has(rootId)) dirty.add(rootId);\n }\n fixedWindow.schedule();\n },\n requestFull(rootId) {\n assertActive();\n if (!sessionId || !roots.has(rootId)) return;\n dirty.add(rootId);\n full.add(rootId);\n fixedWindow.flushNow();\n },\n stop() {\n if (stopped) return;\n stopped = true;\n fixedWindow.stop();\n roots.clear();\n dirty.clear();\n full.clear();\n dirtyHead = false;\n sessionId = undefined;\n },\n };\n}\n","/**\n * Portal Tracker\n *\n * Watches document.body for new subtrees and determines which watched element\n * (if any) they belong to by walking up the React fiber ancestry.\n *\n * ## How it works\n *\n * React portals render content outside their component's DOM location, but the\n * fiber tree maintains the logical parent-child relationship. When a new element\n * appears in body:\n *\n * 1. Get its fiber via getFiberFromElement\n * 2. Walk up fiber.return chain, collecting DOM nodes from stateNode\n * 3. Check if any collected DOM node is within a registered watcher's element\n * 4. If yes, notify that watcher\n *\n * ## Usage\n *\n * ```ts\n * const tracker = getPortalTracker();\n * const unregister = tracker.register({\n * element: myWatchedElement,\n * onPortalFound: (portalRoot) => startWatchingPortal(portalRoot),\n * onPortalRemoved: (portalRoot) => stopWatchingPortal(portalRoot),\n * });\n * ```\n */\n\nimport { getFiberFromElement } from \"../fiber/capture\";\nimport type { Fiber } from \"../fiber/react-types\";\n\n// Note: This module depends on the fiber module for React fiber tree traversal.\n// Both modules are at the same level (siblings in the module structure).\n\nexport interface PortalWatcher {\n /** The DOM element being watched for HTML projection */\n element: Element;\n /** Called when a portal belonging to this element is detected */\n onPortalFound: (portalRoot: Element) => void;\n /** Called when a tracked portal is removed from the DOM */\n onPortalRemoved: (portalRoot: Element) => void;\n}\n\nexport interface PortalTracker {\n /**\n * Register a watcher. Immediately scans existing body children for matches.\n * @returns Unregister function\n */\n register(watcher: PortalWatcher): () => void;\n\n /** Stop tracking and clean up. Call when done with all watching. */\n destroy(): void;\n}\n\n/** Module-level singleton */\nlet instance: PortalTrackerImpl | null = null;\n\n/**\n * Get the singleton PortalTracker instance.\n * Creates one if it doesn't exist.\n */\nexport function getPortalTracker(): PortalTracker {\n if (!instance) {\n instance = new PortalTrackerImpl();\n }\n return instance;\n}\n\n/**\n * Reset the singleton. For testing only.\n * @internal\n */\nexport function _resetPortalTrackerForTesting(): void {\n instance?.destroy();\n instance = null;\n}\n\n/** Whether React logically owns `candidate` below `root`, across portals. */\nexport function isElementOwnedByRoot(\n candidate: Element,\n root: Element,\n): boolean {\n const fiber = getFiberFromElement(candidate);\n if (!fiber) return false;\n\n let current: Fiber | null = fiber.return;\n while (current) {\n if (\n current.stateNode instanceof Element &&\n (current.stateNode === root || root.contains(current.stateNode))\n ) {\n return true;\n }\n current = current.return;\n }\n\n return false;\n}\n\n/**\n * Finds the topmost portal roots owned by `root`. Portal targets may be nested\n * below arbitrary non-React containers, so body-child-only scans are not\n * sufficient.\n */\nexport function findOwnedPortalRoots(root: Element): Element[] {\n const body = root.ownerDocument?.body;\n if (!body) return [];\n\n const portals: Element[] = [];\n const visit = (candidate: Element): void => {\n if (candidate === root || root.contains(candidate)) return;\n if (isElementOwnedByRoot(candidate, root)) {\n portals.push(candidate);\n return;\n }\n for (const child of Array.from(candidate.children)) visit(child);\n };\n\n for (const child of Array.from(body.children)) visit(child);\n return portals;\n}\n\nclass PortalTrackerImpl implements PortalTracker {\n private watchers = new Set<PortalWatcher>();\n private trackedPortals = new Map<Element, Set<PortalWatcher>>(); // portal element -> subscribed watchers\n private observer: MutationObserver | null = null;\n private pendingScanRoots = new Set<Element>();\n private scanScheduled = false;\n\n register(watcher: PortalWatcher): () => void {\n this.watchers.add(watcher);\n\n // Start observing if this is the first watcher\n if (this.watchers.size === 1) {\n this.startObserving();\n }\n\n // Initial scan: custom portal targets may be nested below body children.\n for (const child of Array.from(document.body.children)) {\n this.scanElementTree(child, watcher);\n }\n\n return () => this.unregister(watcher);\n }\n\n private unregister(watcher: PortalWatcher): void {\n this.watchers.delete(watcher);\n\n // Remove this watcher from all tracked portal subscriptions\n for (const [portal, owners] of this.trackedPortals) {\n owners.delete(watcher);\n if (owners.size === 0) {\n this.trackedPortals.delete(portal);\n }\n }\n\n // Stop observing if no watchers remain\n if (this.watchers.size === 0) {\n this.stopObserving();\n }\n }\n\n destroy(): void {\n this.stopObserving();\n this.watchers.clear();\n this.trackedPortals.clear();\n this.pendingScanRoots.clear();\n }\n\n private startObserving(): void {\n if (this.observer) return;\n\n this.observer = new MutationObserver(this.handleMutations);\n this.observer.observe(document.body, { childList: true, subtree: true });\n }\n\n private stopObserving(): void {\n this.observer?.disconnect();\n this.observer = null;\n }\n\n private handleMutations = (mutations: MutationRecord[]): void => {\n for (const mutation of mutations) {\n // Handle added nodes\n for (const node of mutation.addedNodes) {\n if (node instanceof Element) {\n // React attaches __reactFiber$* keys after DOM insertion. Coalesce a\n // mutation batch so nested additions are scanned only once.\n this.scheduleScan(node);\n }\n }\n\n // Handle removed nodes\n for (const node of mutation.removedNodes) {\n if (node instanceof Element) {\n for (const [portal, owners] of this.trackedPortals) {\n if (portal !== node && !node.contains(portal)) continue;\n for (const owner of owners) {\n owner.onPortalRemoved(portal);\n }\n this.trackedPortals.delete(portal);\n }\n }\n }\n }\n };\n\n private scheduleScan(element: Element): void {\n this.pendingScanRoots.add(element);\n if (this.scanScheduled) return;\n\n this.scanScheduled = true;\n queueMicrotask(() => {\n this.scanScheduled = false;\n const roots = Array.from(this.pendingScanRoots);\n this.pendingScanRoots.clear();\n\n for (const root of roots) {\n // An add+remove in one observer batch must not create a detached ghost.\n if (!root.isConnected) continue;\n if (roots.some((other) => other !== root && other.contains(root))) {\n continue;\n }\n this.scanElementTree(root);\n }\n });\n }\n\n /**\n * Scan until a topmost owned portal is found. Mutations inside an already\n * tracked portal are handled by that portal's own watcher.\n */\n private scanElementTree(element: Element, onlyWatcher?: PortalWatcher): void {\n const requestedWatchers = onlyWatcher\n ? this.watchers.has(onlyWatcher)\n ? [onlyWatcher]\n : []\n : Array.from(this.watchers);\n this.scanElementTreeForWatchers(element, requestedWatchers);\n }\n\n private scanElementTreeForWatchers(\n element: Element,\n requestedWatchers: readonly PortalWatcher[],\n ): void {\n const eligibleWatchers = requestedWatchers.filter(\n (watcher) =>\n watcher.element !== element &&\n !watcher.element.contains(element) &&\n !this.isInsidePortalOwnedByWatcher(element, watcher),\n );\n if (eligibleWatchers.length === 0) return;\n\n const matchedWatchers = this.checkElement(element, eligibleWatchers);\n const descendantWatchers = eligibleWatchers.filter(\n (watcher) => !matchedWatchers.has(watcher),\n );\n if (descendantWatchers.length === 0) return;\n\n for (const child of Array.from(element.children)) {\n this.scanElementTreeForWatchers(child, descendantWatchers);\n }\n }\n\n private isInsidePortalOwnedByWatcher(\n element: Element,\n watcher: PortalWatcher,\n ): boolean {\n for (const [portal, owners] of this.trackedPortals) {\n if (\n owners.has(watcher) &&\n (portal === element || portal.contains(element))\n ) {\n return true;\n }\n }\n return false;\n }\n\n /** Check ownership with one fiber walk, even when many roots are watched. */\n private checkElement(\n element: Element,\n watchers: readonly PortalWatcher[],\n ): Set<PortalWatcher> {\n const matched = new Set<PortalWatcher>();\n const fiber = getFiberFromElement(element);\n if (!fiber) return matched;\n\n let current: Fiber | null = fiber.return;\n while (current && matched.size < watchers.length) {\n if (current.stateNode instanceof Element) {\n for (const watcher of watchers) {\n if (\n !matched.has(watcher) &&\n (current.stateNode === watcher.element ||\n watcher.element.contains(current.stateNode))\n ) {\n matched.add(watcher);\n }\n }\n }\n current = current.return;\n }\n\n if (matched.size === 0) return matched;\n let owners = this.trackedPortals.get(element);\n if (!owners) {\n owners = new Set<PortalWatcher>();\n this.trackedPortals.set(element, owners);\n }\n for (const watcher of matched) {\n if (!this.watchers.has(watcher) || owners.has(watcher)) continue;\n owners.add(watcher);\n watcher.onPortalFound(element);\n }\n\n return matched;\n }\n}\n","import {\n type DomWatcher,\n drainProjectionDomMutations,\n type ProjectionDomMutation,\n watchDom,\n} from \"../html/watch-dom\";\nimport { type PortalWatcherHandle, watchPortal } from \"../html/watch-portal\";\nimport {\n drainProjectionStateEvents,\n type StateWatcher,\n watchState,\n} from \"../html/watch-state\";\nimport { getPortalTracker } from \"../shared/portal-tracker\";\nimport type {\n ProjectionLayerMetadataSnapshot,\n ProjectionLayerRegionSnapshot,\n} from \"./projection-layer-snapshot\";\nimport {\n ProjectionObservedFileAccumulator,\n type ProjectionObservedFileMap,\n} from \"./projection-observed-files\";\nimport {\n captureProjectionMutationPatch,\n captureProjectionPortalCoordinates,\n captureProjectionPortalRegion,\n captureProjectionStatePatch,\n type ProjectionAnnotationPatch,\n type ProjectionDomPatch,\n type ProjectionPortalPatch,\n type ProjectionStatePatch,\n} from \"./projection-patch\";\n\nexport interface ProjectionLayerPatch {\n readonly regions?: readonly ProjectionLayerRegionSnapshot[];\n readonly metadata?: readonly ProjectionLayerMetadataSnapshot[];\n}\n\nexport interface ProjectionRootPatch {\n readonly dom?: readonly ProjectionDomPatch[];\n readonly annotations?: readonly ProjectionAnnotationPatch[];\n readonly state?: readonly ProjectionStatePatch[];\n readonly portals?: readonly ProjectionPortalPatch[];\n readonly layers?: ProjectionLayerPatch;\n readonly observedFiles?: ProjectionObservedFileMap;\n}\n\nexport type ProjectionRootPatchResult =\n | {\n readonly kind: \"patch\";\n readonly patch: ProjectionRootPatch;\n /** DOM-derived metadata targets retained only for local Fiber capture. */\n readonly localMetadataTargets: readonly Element[];\n /** Exact source-realm targets for synthetic DOM Layers. They never\n * cross transport, so duplicate DOM ids remain unambiguous. */\n readonly localDomLayerTargets?: {\n readonly structural: readonly Element[];\n readonly metadata: readonly Element[];\n };\n }\n | { readonly kind: \"empty\" };\n\nexport interface ProjectionPortalRegistration {\n readonly onPortalFound: (portal: Element) => void;\n readonly onPortalRemoved: (portal: Element) => void;\n}\n\nexport interface CreateProjectionRootAccumulatorOptions {\n readonly root: Element;\n readonly onChange: () => void;\n /** Injection seam; the default delegates to the document portal tracker. */\n readonly registerPortals?: (\n registration: ProjectionPortalRegistration,\n ) => () => void;\n}\n\nexport interface ProjectionRootAccumulator {\n capturePatch(options?: {\n readonly regionalChildLists?: boolean;\n readonly retainDomLayerTargets?: boolean;\n }): ProjectionRootPatchResult;\n /**\n * Retain DOM records already queued for this root and return their count.\n * This is called synchronously at React's commit boundary; the caller owns\n * the scheduling signal for those records.\n */\n takePendingDomRecords(): number;\n /** Whether this root currently owns any portal. Document-wide changes that\n * can move a portal without mutating it (new styling) only need to schedule\n * the roots that answer yes. */\n hasPortals(): boolean;\n /** Current live portal roots for an explicit full baseline. */\n portalElements(): readonly Element[];\n /** Counters already maintained by observers; performs no discovery work. */\n perfSnapshot(): {\n readonly rawMutationRecords: number;\n readonly rawStateRecords: number;\n readonly rawPortalRecords: number;\n readonly candidateTargets: number;\n };\n stop(): void;\n}\n\n/**\n * One root-local final-state accumulator. Observer callbacks only retain exact\n * source targets and signal the document scheduler; serialization happens once\n * when the scheduler flushes.\n */\nexport function createProjectionRootAccumulator(\n options: CreateProjectionRootAccumulatorOptions,\n): ProjectionRootAccumulator {\n const dom: DomWatcher = watchDom(options.root, options.onChange);\n const state: StateWatcher = watchState(options.root, options.onChange);\n const portals = new Map<Element, PortalWatcherHandle>();\n const dirtyPortals = new Set<Element>();\n const removedPortals = new Map<string, ProjectionPortalPatch>();\n /** The coordinate space the destination last received per live portal,\n * serialized. Both sides of the comparison are built by the same capture\n * routine, so key order is fixed and the string is a sound identity — and\n * one that stays exhaustive if the coordinate space grows a field. */\n const sentPortalCoordinates = new Map<Element, string>();\n let stopped = false;\n\n // A host positions the watched root by styling an ANCESTOR of it (a\n // storyboard's frame carries the layout position), so the root can move in\n // its viewport without one mutation inside the watched subtree. Every\n // portal's coordinate space moves with it, and nothing else would notice.\n const ancestorsOf = (element: Element): Element[] => {\n const chain: Element[] = [];\n for (\n let ancestor = element.parentElement;\n ancestor;\n ancestor = ancestor.parentElement\n ) {\n chain.push(ancestor);\n }\n return chain;\n };\n const sameChain = (chain: Element[], other: Element[]): boolean =>\n chain.length === other.length &&\n chain.every((element, index) => element === other[index]);\n let observedAncestors: Element[] = [];\n const frameWatcher = new MutationObserver((records) => {\n if (stopped) return;\n // childList is observed only to notice the root being re-parented, which\n // moves it under ancestors this observer has never seen. Sibling churn\n // under an unchanged chain is not a coordinate signal, so it must not\n // become one — the chain is compared before anything is reported.\n let reparented = false;\n if (records.some((record) => record.type === \"childList\")) {\n const chain = ancestorsOf(options.root);\n reparented = !sameChain(chain, observedAncestors);\n if (reparented) observeAncestors(chain);\n }\n const restyled = records.some((record) => record.type === \"attributes\");\n if (!reparented && !restyled) return;\n if (portals.size === 0) return;\n options.onChange();\n });\n function observeAncestors(chain: Element[]): void {\n frameWatcher.disconnect();\n observedAncestors = chain;\n for (const ancestor of chain) {\n frameWatcher.observe(ancestor, {\n attributes: true,\n attributeFilter: [\"style\", \"class\"],\n childList: true,\n });\n }\n }\n observeAncestors(ancestorsOf(options.root));\n\n const registerPortals =\n options.registerPortals ??\n ((registration: ProjectionPortalRegistration) =>\n getPortalTracker().register({\n element: options.root,\n ...registration,\n }));\n const unregisterPortals = registerPortals({\n onPortalFound(portal) {\n if (stopped || portals.has(portal)) return;\n // No coordinate root: this lane captures a portal's frame with its\n // body, from the patch builder, rather than through the handle's own\n // legacy-envelope flush.\n const handle = watchPortal(portal, () => {\n dirtyPortals.add(portal);\n options.onChange();\n });\n portals.set(portal, handle);\n dirtyPortals.add(portal);\n options.onChange();\n },\n onPortalRemoved(portal) {\n const handle = portals.get(portal);\n if (!handle) return;\n removedPortals.set(handle.id, {\n kind: \"remove\",\n portalId: handle.id,\n });\n dirtyPortals.delete(portal);\n portals.delete(portal);\n sentPortalCoordinates.delete(portal);\n handle.stop();\n options.onChange();\n },\n });\n\n return {\n takePendingDomRecords() {\n if (stopped) return 0;\n return dom.takePendingRecords();\n },\n hasPortals() {\n return !stopped && portals.size > 0;\n },\n capturePatch(captureOptions) {\n if (stopped) throw new Error(\"Projection root accumulator has stopped\");\n const domMutations = drainProjectionDomMutations(dom);\n const localDomLayerTargets = captureOptions?.retainDomLayerTargets\n ? collectDomLayerTargets(options.root, domMutations)\n : undefined;\n const mutationPatch = captureProjectionMutationPatch(\n options.root,\n domMutations,\n captureOptions,\n );\n\n const states: ProjectionStatePatch[] = [];\n for (const event of drainProjectionStateEvents(state)) {\n const captured = captureProjectionStatePatch(\n options.root,\n event.element,\n event.eventKind,\n );\n if (captured) states.push(captured);\n }\n\n const portalPatches = Array.from(removedPortals.values());\n const portalAnnotations: ProjectionAnnotationPatch[] = [];\n const observedFiles = new ProjectionObservedFileAccumulator();\n observedFiles.merge(mutationPatch.observedFiles);\n removedPortals.clear();\n const resentPortals = new Set<Element>();\n for (const portal of dirtyPortals) {\n const handle = portals.get(portal);\n if (!handle) continue;\n const captured = captureProjectionPortalRegion(\n portal,\n false,\n options.root,\n );\n if (!captured) continue;\n resentPortals.add(portal);\n if (\n captured.portal.kind === \"replace\" &&\n captured.portal.coordinateSpace\n ) {\n sentPortalCoordinates.set(\n portal,\n JSON.stringify(captured.portal.coordinateSpace),\n );\n }\n portalPatches.push(captured.portal);\n portalAnnotations.push(...captured.annotations);\n observedFiles.merge(captured.observedFiles);\n for (const event of handle.clearPendingChanges()) {\n const statePatch = captureProjectionStatePatch(\n portal,\n event.element,\n event.eventKind,\n );\n if (statePatch) states.push(statePatch);\n }\n }\n dirtyPortals.clear();\n\n // The root can move, and new styling can move a portal, without either\n // one mutating the portal. Portals whose body this patch already carries\n // are current; the rest are worth a coordinate refresh, but only when\n // the frame actually moved — re-sending a body would cost destination\n // focus and edit state, and re-sending an unchanged frame is noise.\n for (const portal of portals.keys()) {\n if (resentPortals.has(portal)) continue;\n const coordinates = captureProjectionPortalCoordinates(\n options.root,\n portal,\n );\n if (!coordinates) continue;\n const measured = JSON.stringify(coordinates.coordinateSpace);\n if (sentPortalCoordinates.get(portal) === measured) continue;\n sentPortalCoordinates.set(portal, measured);\n portalPatches.push(coordinates);\n }\n\n const observedSnapshot = observedFiles.snapshot();\n const patch: ProjectionRootPatch = {\n ...(mutationPatch.dom.length > 0 ? { dom: mutationPatch.dom } : {}),\n ...(mutationPatch.annotations.length + portalAnnotations.length > 0\n ? {\n annotations: [...mutationPatch.annotations, ...portalAnnotations],\n }\n : {}),\n ...(states.length > 0 ? { state: states } : {}),\n ...(portalPatches.length > 0 ? { portals: portalPatches } : {}),\n ...(Object.keys(observedSnapshot).length > 0\n ? { observedFiles: observedSnapshot }\n : {}),\n };\n const hasLocalDomLayerTargets =\n localDomLayerTargets !== undefined &&\n (localDomLayerTargets.structural.length > 0 ||\n localDomLayerTargets.metadata.length > 0);\n return Object.keys(patch).length === 0 && !hasLocalDomLayerTargets\n ? { kind: \"empty\" }\n : {\n kind: \"patch\",\n patch,\n localMetadataTargets: mutationPatch.localMetadataTargets,\n ...(hasLocalDomLayerTargets ? { localDomLayerTargets } : {}),\n };\n },\n portalElements() {\n return Array.from(portals.keys());\n },\n perfSnapshot() {\n return {\n rawMutationRecords: dom.mutationRecordCount,\n rawStateRecords: state.stateRecordCount,\n rawPortalRecords:\n removedPortals.size +\n Array.from(portals.values()).reduce(\n (count, portal) => count + portal.pendingRecordCount(),\n 0,\n ),\n candidateTargets:\n dom.mutatedElements.size + dom.addedElementCount + dirtyPortals.size,\n };\n },\n stop() {\n if (stopped) return;\n stopped = true;\n unregisterPortals();\n frameWatcher.disconnect();\n dom.stop();\n state.stop();\n for (const portal of portals.values()) portal.stop();\n portals.clear();\n dirtyPortals.clear();\n removedPortals.clear();\n sentPortalCoordinates.clear();\n },\n };\n}\n\nfunction collectDomLayerTargets(\n root: Element,\n mutations: readonly ProjectionDomMutation[],\n): {\n readonly structural: readonly Element[];\n readonly metadata: readonly Element[];\n} {\n const structural = new Set<Element>();\n const metadata = new Set<Element>();\n for (const mutation of mutations) {\n const target =\n mutation.target instanceof Element\n ? mutation.target\n : mutation.target.parentElement;\n if (!target || (target !== root && !root.contains(target))) continue;\n if (mutation.type === \"childList\") structural.add(target);\n else if (mutation.type === \"attributes\") metadata.add(target);\n }\n return {\n structural: Array.from(structural),\n metadata: Array.from(metadata),\n };\n}\n","/**\n * Convert an `EnrichedFiberNode` (live capture from the combined watcher)\n * into a `SerializedFiber`-shaped tree that downstream JSX reconstruction\n * tooling (e.g. `@modules/codebase-editor`'s `reconstructJsxFromFiber`)\n * consumes.\n *\n * The combined watcher's default `sanitizeValue` already runs on the source\n * iframe and loses some type information by replacing non-JSON values with\n * marker strings (`\"[Function]\"`, `\"[Element:div]\"`, `\"[ReactElement]\"`,\n * etc.). This converter detects those markers on the parent side and\n * re-encodes them as `{ __type: \"unsupported\", reason }` so the\n * reconstructor can flag them as blockers instead of emitting them as bogus\n * string literals.\n *\n * The output shape is structurally compatible with\n * `@modules/codebase-editor`'s `SerializedFiber` — no direct dependency to\n * keep the module standalone.\n */\nimport { FiberTag, type FiberTagValue } from \"../fiber/react-types\";\nimport { cssEscape } from \"./css-escape\";\nimport type { EnrichedFiberNode } from \"./types\";\n\n// ── Structural mirror of @modules/codebase-editor's SerializedFiber ───\n// Kept type-compatible (string union for tag, __type marker for unsupported\n// values) so callers can pass the result directly to `reconstructJsxFromFiber`\n// without conversion. Duplication is the explicit cost of keeping\n// iframe-projection free of codebase-editor as a dependency.\n\nexport type DetachJsonPrimitive = string | number | boolean | null;\nexport type DetachJsonValue =\n | DetachJsonPrimitive\n | DetachJsonValue[]\n | { [key: string]: DetachJsonValue };\n\nexport type DetachReactElementReference = {\n __type: \"react-element\";\n fiber_id: string;\n};\n\nexport type DetachUnsupportedValue = {\n __type: \"unsupported\";\n reason: string;\n /** Structured kind of the unserializable value, when known. `\"function\"`\n * marks event handlers/callbacks — behavior-only props that fiber\n * reconstruction stubs with a no-op instead of refusing the transfer\n * (mirrors `codebase-editor`'s `UnsupportedSerializableValue.value_type`). */\n value_type?: \"function\";\n};\n\nexport type DetachSerializableValue =\n | DetachJsonValue\n | DetachReactElementReference\n | DetachUnsupportedValue\n | DetachSerializableValue[]\n | { [key: string]: DetachSerializableValue };\n\nexport type DetachFiberTag =\n | \"host\"\n | \"function\"\n | \"class\"\n | \"text\"\n | \"fragment\"\n | \"portal\"\n | \"memo\"\n | \"forward-ref\";\n\nexport interface DetachSerializedFiber {\n fiber_id: string;\n name: string;\n tag: DetachFiberTag | string;\n owner_fiber_id: string | null;\n key?: string | null;\n has_context_dependencies?: boolean;\n props: Record<string, DetachSerializableValue>;\n children: DetachSerializedFiber[];\n source?: {\n file: string;\n position: number;\n };\n}\n\nexport interface EnrichedNodeToSerializedFiberOptions {\n /** When set, every fiber that carries `data-tempo-filepath` +\n * `data-tempo-position` annotations gets its `source` field populated.\n * This is what enables detach-one-level: the orchestrator walks the\n * output tree, follows each descendant component's `source.file` to\n * parse that file's imports, and resolves cross-file identifier\n * references in the rendered subtree (e.g. `<Pill />` inside a\n * `<Wrapper />` whose `Pill` import lives in Wrapper.tsx, not the\n * call-site App.tsx). Without this, descendant components inline as\n * their host JSX instead of staying as JSX tags. */\n preserveSourceAnnotations?: boolean;\n /** Optional iframe document — used to recover text-node children of host\n * elements that the upstream fiber capture filtered out. The combined\n * watcher's default `fiberTags` filter drops HostText so the layer tree\n * stays manageable; for detach we still need text content, so we\n * walk the host element's DOM children and synthesize text fibers from\n * every direct `Text` node. Without this, `<div>Hello</div>` reconstructs\n * as `<div />` and the text disappears. */\n iframeDocument?: Document | null;\n}\n\nexport function enrichedNodeToSerializedFiber(\n node: EnrichedFiberNode,\n options: EnrichedNodeToSerializedFiberOptions = {},\n): DetachSerializedFiber {\n return convertNode(node, null, options);\n}\n\nfunction convertNode(\n node: EnrichedFiberNode,\n ownerFiberId: string | null,\n options: EnrichedNodeToSerializedFiberOptions,\n): DetachSerializedFiber {\n const tag = detachTagFromFiberTag(node.tag);\n const name = node.name;\n const ownerId = node.fiberId;\n\n const props = node.props ? detachPropsFromSanitized(node.props) : {};\n\n const children: DetachSerializedFiber[] = node.children.map((child) =>\n convertNode(child, ownerId, options),\n );\n\n // Recover host-text leaves that the combined watcher's `fiberTags` filter\n // drops. The fiber tree only reports HostComponent/FunctionComponent/...,\n // so a `<div>Hello</div>` arrives as a host fiber with `children: []`.\n // Walk the live DOM under the host's `domId` and synthesize a Text-tagged\n // child fiber for each direct Text node — the reconstructor renders these\n // as escaped JSX text content.\n if (\n tag === \"host\" &&\n children.length === 0 &&\n node.domId &&\n options.iframeDocument\n ) {\n const element = options.iframeDocument.querySelector(\n `[data-dom-id=\"${cssEscape(node.domId)}\"]`,\n );\n if (element) {\n let textIndex = 0;\n for (const childNode of Array.from(element.childNodes)) {\n if (childNode.nodeType === 3 /* Text */) {\n const text = childNode.textContent ?? \"\";\n if (text.length === 0) continue;\n children.push({\n fiber_id: `${node.fiberId}:text-${textIndex++}`,\n name: \"#text\",\n tag: \"text\",\n owner_fiber_id: ownerId,\n props: { text },\n children: [],\n });\n }\n }\n }\n }\n\n const result: DetachSerializedFiber = {\n fiber_id: node.fiberId,\n name,\n tag,\n owner_fiber_id: ownerFiberId,\n props,\n children,\n };\n if (node.hasContextDependencies) {\n result.has_context_dependencies = true;\n }\n\n if (options.preserveSourceAnnotations) {\n const source = detachSourceFromProps(node.props);\n if (source) result.source = source;\n }\n\n return result;\n}\n\nexport function detachTagFromFiberTag(\n tag: FiberTagValue,\n): DetachFiberTag | string {\n switch (tag) {\n case FiberTag.HostComponent:\n return \"host\";\n case FiberTag.HostText:\n return \"text\";\n case FiberTag.FunctionComponent:\n case FiberTag.IndeterminateComponent:\n return \"function\";\n case FiberTag.ClassComponent:\n return \"class\";\n case FiberTag.Fragment:\n return \"fragment\";\n case FiberTag.HostPortal:\n return \"portal\";\n case FiberTag.MemoComponent:\n case FiberTag.SimpleMemoComponent:\n return \"memo\";\n case FiberTag.ForwardRef:\n return \"forward-ref\";\n default:\n return String(tag);\n }\n}\n\nconst SANITIZED_MARKER_PATTERNS: {\n match: RegExp;\n reason: (raw: string) => string;\n value_type?: DetachUnsupportedValue[\"value_type\"];\n}[] = [\n {\n match: /^\\[Function\\]$/,\n reason: () => \"Functions cannot be serialized to JSX\",\n value_type: \"function\",\n },\n {\n match: /^\\[Symbol:.*\\]$/,\n reason: (raw) => `Symbols cannot be serialized to JSX: ${raw}`,\n },\n {\n match: /^\\[Element:.*\\]$/,\n reason: (raw) => `DOM elements cannot be serialized to JSX: ${raw}`,\n },\n {\n match: /^\\[Node:.*\\]$/,\n reason: (raw) => `DOM nodes cannot be serialized to JSX: ${raw}`,\n },\n {\n match: /^\\[Object\\]$/,\n reason: () => \"Object could not be JSON-serialized\",\n },\n {\n match: /^\\[Array\\(\\d+\\)\\]$/,\n reason: (raw) => `Large array cannot be serialized: ${raw}`,\n },\n {\n match: /^\\[ReactElement\\]$/,\n reason: () => \"Inline React elements in props cannot be reconstructed\",\n },\n];\n\nfunction classifyMaybeMarker(raw: string): DetachUnsupportedValue | null {\n for (const { match, reason, value_type } of SANITIZED_MARKER_PATTERNS) {\n if (match.test(raw)) {\n const marker: DetachUnsupportedValue = {\n __type: \"unsupported\",\n reason: reason(raw),\n };\n if (value_type) marker.value_type = value_type;\n return marker;\n }\n }\n return null;\n}\n\nconst TEMPO_DATA_PROP_PREFIX = \"data-tempo-\";\n\nexport function detachPropsFromSanitized(\n source: Record<string, unknown>,\n): Record<string, DetachSerializableValue> {\n const out: Record<string, DetachSerializableValue> = {};\n for (const [key, value] of Object.entries(source)) {\n if (key === \"children\") continue;\n // `data-tempo-*` props are Tempo's source-annotation channel and aren't\n // part of the user's authored JSX; stripping them keeps detached output\n // clean (the canvas will re-stamp them on the next HMR cycle).\n if (key.startsWith(TEMPO_DATA_PROP_PREFIX)) continue;\n out[key] = convertValue(value);\n }\n return out;\n}\n\nfunction convertValue(value: unknown): DetachSerializableValue {\n if (value === null || value === undefined) return null;\n if (typeof value === \"string\") {\n const marker = classifyMaybeMarker(value);\n if (marker) return marker;\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") return value;\n\n if (Array.isArray(value)) {\n return value.map((entry) => convertValue(entry));\n }\n\n if (typeof value === \"object\") {\n const out: Record<string, DetachSerializableValue> = {};\n for (const [key, entry] of Object.entries(\n value as Record<string, unknown>,\n )) {\n out[key] = convertValue(entry);\n }\n return out;\n }\n\n // Functions, symbols, etc. shouldn't survive sanitizeValue on the source\n // side, but guard defensively so the converter never produces a non-JSON\n // primitive type.\n return {\n __type: \"unsupported\",\n reason: `Unsupported runtime type: ${typeof value}`,\n };\n}\n\nexport function detachSourceFromProps(\n props: Record<string, unknown> | undefined,\n): { file: string; position: number } | null {\n if (!props) return null;\n const file = props[\"data-tempo-filepath\"];\n const position = props[\"data-tempo-position\"];\n if (typeof file !== \"string\" || file.length === 0) return null;\n const pos = typeof position === \"number\" ? position : Number(position);\n if (!Number.isFinite(pos)) return null;\n return { file, position: pos };\n}\n","/**\n * Cold, operation-scoped React semantic capture.\n *\n * The hot projection stream intentionally carries only destination-ready\n * layer facts. Copy, duplicate, drag, and detach occasionally need runtime\n * props for one selected branch. This serializer performs that richer walk\n * only when one of those operations explicitly asks for it, and returns only\n * the selected Fiber subtree rather than retaining or transporting a full\n * document Fiber tree.\n */\n\nimport type { Fiber, FiberProps } from \"../fiber/react-types\";\nimport { FiberTag } from \"../fiber/react-types\";\nimport { getDisplayName, getProps, sanitizeProps } from \"../fiber/serialize\";\nimport {\n detachPropsFromSanitized,\n detachSourceFromProps,\n detachTagFromFiberTag,\n type DetachSerializedFiber,\n} from \"./enriched-to-serialized-fiber\";\nimport { isProjectionLayerFiber } from \"./projection-layer-snapshot\";\n\nexport interface ProjectionSemanticFiberIdentity {\n /** Return the already-published identity without allocating a new one. */\n knownFiberId(fiber: Fiber): string | null;\n /** Allocate/recover the stable identity for a node inside the result. */\n fiberId(fiber: Fiber): string;\n}\n\n/** Structural guard used at transport boundaries. Runtime prop values are\n * already structured-cloned by the bridge, so the protocol only needs to pin\n * the closed tree envelope here. */\nexport function isProjectionSemanticSubtree(\n value: unknown,\n): value is DetachSerializedFiber {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const node = value as Record<string, unknown>;\n if (\n typeof node.fiber_id !== \"string\" ||\n typeof node.name !== \"string\" ||\n typeof node.tag !== \"string\" ||\n (node.owner_fiber_id !== null && typeof node.owner_fiber_id !== \"string\") ||\n !node.props ||\n typeof node.props !== \"object\" ||\n Array.isArray(node.props) ||\n !Array.isArray(node.children)\n ) {\n return false;\n }\n if (\n node.source !== undefined &&\n (!node.source ||\n typeof node.source !== \"object\" ||\n Array.isArray(node.source) ||\n typeof (node.source as Record<string, unknown>).file !== \"string\" ||\n typeof (node.source as Record<string, unknown>).position !== \"number\")\n ) {\n return false;\n }\n return node.children.every(isProjectionSemanticSubtree);\n}\n\n/**\n * Resolve one currently committed, previously published semantic node and\n * serialize only that node and its rendered descendants.\n */\nexport function captureProjectionSemanticSubtree(\n committedRoot: Fiber,\n targetFiberId: string,\n identity: ProjectionSemanticFiberIdentity,\n): DetachSerializedFiber | null {\n const target = findCurrentFiberByPublishedId(\n committedRoot,\n targetFiberId,\n identity.knownFiberId,\n );\n if (!target || !isProjectionLayerFiber(target)) return null;\n return serializeIncludedFiber(target, null, identity);\n}\n\nfunction findCurrentFiberByPublishedId(\n root: Fiber,\n targetFiberId: string,\n knownFiberId: (fiber: Fiber) => string | null,\n): Fiber | null {\n if (knownFiberId(root) === targetFiberId) return root;\n for (let child = root.child; child; child = child.sibling) {\n const found = findCurrentFiberByPublishedId(\n child,\n targetFiberId,\n knownFiberId,\n );\n if (found) return found;\n }\n return null;\n}\n\nfunction serializeIncludedFiber(\n fiber: Fiber,\n ownerFiberId: string | null,\n identity: ProjectionSemanticFiberIdentity,\n): DetachSerializedFiber {\n const fiberId = identity.fiberId(fiber);\n const normalizedProps = normalizeTempoDataSet(getProps(fiber));\n const sanitized = sanitizeProps(normalizedProps) ?? {};\n const children = serializeChildren(fiber, fiberId, identity);\n // React omits a HostText Fiber for the common single-primitive-child fast\n // path (`<button>Save</button>`). `sanitizeProps` correctly removes the\n // structural `children` prop, so preserve that authored output as the same\n // synthetic text leaf the old DOM-assisted detach capture produced. This\n // stays local to the selected host node and avoids a document/tree query.\n if (fiber.tag === FiberTag.HostComponent && children.length === 0) {\n const text = directPrimitiveChild(normalizedProps?.children);\n if (text !== null) {\n children.push({\n fiber_id: `${fiberId}:text-0`,\n name: \"#text\",\n tag: \"text\",\n owner_fiber_id: fiberId,\n props: { text },\n children: [],\n });\n }\n }\n const result: DetachSerializedFiber = {\n fiber_id: fiberId,\n name: getDisplayName(fiber),\n tag: detachTagFromFiberTag(fiber.tag),\n owner_fiber_id: ownerFiberId,\n props:\n fiber.tag === FiberTag.HostText\n ? { text: readHostText(fiber) }\n : detachPropsFromSanitized(sanitized),\n children,\n };\n if (fiber.key !== null) result.key = fiber.key;\n if (hasContextDependencies(fiber)) {\n result.has_context_dependencies = true;\n }\n const source = detachSourceFromProps(normalizedProps ?? undefined);\n if (source) result.source = source;\n return result;\n}\n\nfunction directPrimitiveChild(value: unknown): string | null {\n if (typeof value === \"string\") return value.length > 0 ? value : null;\n return typeof value === \"number\" ? String(value) : null;\n}\n\nfunction serializeChildren(\n parent: Fiber,\n ownerFiberId: string,\n identity: ProjectionSemanticFiberIdentity,\n): DetachSerializedFiber[] {\n const children: DetachSerializedFiber[] = [];\n for (let child = parent.child; child; child = child.sibling) {\n children.push(...serializeBranch(child, ownerFiberId, identity));\n }\n return children;\n}\n\n/**\n * Mirror the layer stream's include filter: non-layer React wrappers are\n * transparent and promote their descendants. HostText is the one deliberate\n * addition because edit operations need authored text even though the layer\n * panel does not model text as a standalone layer.\n */\nfunction serializeBranch(\n fiber: Fiber,\n ownerFiberId: string,\n identity: ProjectionSemanticFiberIdentity,\n): DetachSerializedFiber[] {\n if (isProjectionLayerFiber(fiber) || fiber.tag === FiberTag.HostText) {\n return [serializeIncludedFiber(fiber, ownerFiberId, identity)];\n }\n\n const promoted: DetachSerializedFiber[] = [];\n for (let child = fiber.child; child; child = child.sibling) {\n promoted.push(...serializeBranch(child, ownerFiberId, identity));\n }\n return promoted;\n}\n\nfunction readHostText(fiber: Fiber): string {\n if (typeof fiber.memoizedProps === \"string\") return fiber.memoizedProps;\n return fiber.stateNode instanceof Text ? fiber.stateNode.textContent : \"\";\n}\n\nfunction hasContextDependencies(fiber: Fiber): boolean {\n const dependencies = fiber.dependencies;\n return Boolean(\n dependencies &&\n typeof dependencies === \"object\" &&\n (dependencies as { firstContext?: unknown }).firstContext,\n );\n}\n\n/** Lift react-native-web's dataSet annotation carrier into the same flat keys\n * used by DOM and ordinary React fibers before source extraction. */\nfunction normalizeTempoDataSet(props: FiberProps | null): FiberProps | null {\n const dataSet = props?.dataSet;\n if (!props || !dataSet || typeof dataSet !== \"object\") return props;\n\n let extracted: Record<string, unknown> | null = null;\n let remaining: Record<string, unknown> | null = null;\n for (const [key, value] of Object.entries(\n dataSet as Record<string, unknown>,\n )) {\n if (key.startsWith(\"tempo\")) {\n (extracted ??= {})[\n `data-${key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}`\n ] = value;\n } else {\n (remaining ??= {})[key] = value;\n }\n }\n if (!extracted) return props;\n\n const normalized = { ...props, ...extracted };\n if (remaining) normalized.dataSet = remaining;\n else delete normalized.dataSet;\n return normalized;\n}\n","import { getFiberFromElement } from \"../fiber/capture\";\nimport type { Fiber, FiberRoot } from \"../fiber/react-types\";\nimport {\n isTransientFiberResolutionError,\n resolveCommittedFiber,\n} from \"../fiber/serialize\";\nimport type { FiberTagValue, SerializeFn } from \"../fiber/types\";\nimport { initHook } from \"../fiber/watch\";\nimport { captureHead, getHeadTracker } from \"../html/watch-head\";\nimport {\n registerCaptureRootObserver,\n registerDocumentCaptureProducer,\n resetCaptureFlushCounters,\n} from \"../shared/capture-perf\";\nimport type { DetachSerializedFiber } from \"./enriched-to-serialized-fiber\";\nimport type {\n CombinedProjectionBatch,\n ProjectionRenderErrorProblem,\n} from \"./projection-batch\";\nimport { buildProjectionCapturePerf } from \"./projection-capture-perf\";\nimport {\n createProjectionDomLayerSerializer,\n type ProjectionDomLayerSerializer,\n} from \"./projection-dom-layers\";\nimport {\n captureProjectionFullSnapshot,\n captureProjectionRegion,\n type ProjectionRegionCapture,\n} from \"./projection-full-snapshot\";\nimport {\n ascendToAnnotatedComponentRoot,\n createProjectionLayerSerializer,\n isProjectionLayerFiber,\n type ProjectionLayerMetadataSnapshot,\n type ProjectionLayerProps,\n type ProjectionLayerRegionSnapshot,\n type ProjectionLayerSerializer,\n} from \"./projection-layer-snapshot\";\nimport { ProjectionObservedFileAccumulator } from \"./projection-observed-files\";\nimport { isProjectionPendingOnly } from \"./projection-pending\";\nimport {\n createProjectionOutbox,\n type ProjectionProducerFlushContext,\n type ProjectionProducerScheduler,\n} from \"./projection-producer\";\nimport {\n createProjectionRootAccumulator,\n type ProjectionRootAccumulator,\n type ProjectionRootPatch,\n} from \"./projection-root-accumulator\";\nimport { captureProjectionSemanticSubtree } from \"./projection-semantic-subtree\";\nimport type {\n CaptureProducerPerf,\n EnrichedFiberConstraint,\n EnrichedFiberNode,\n} from \"./types\";\n\n/** The old customization fields remain accepted at the public SDK boundary,\n * but the document producer deliberately emits one closed DTO. */\nexport interface CombinedProjectionRootOptions<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n> {\n rootId: string;\n element: Element;\n selector?: string;\n serialize?: SerializeFn<T>;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n hideFiberProp?: string;\n}\n\nexport type {\n CombinedProjectionBatch,\n CombinedProjectionProblem,\n ProjectionRenderErrorProblem,\n} from \"./projection-batch\";\n\nexport interface CreateCombinedDocumentProducerOptions {\n document: Document;\n /** Return only after the batch has been synchronously handed to transport. */\n emit(batch: CombinedProjectionBatch): void;\n scheduler?: ProjectionProducerScheduler;\n flushWindowMs?: number;\n onError?: (error: unknown) => void;\n}\n\nexport interface CombinedDocumentProducer<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n> {\n bindSession(sessionId: string): void;\n watchRoot(options: CombinedProjectionRootOptions<T>): void;\n unwatchRoot(rootId: string): void;\n /** One current self-contained baseline for one root. Every baseline names\n * its root: a document-wide baseline would make one root's mount or\n * recovery re-serialize its healthy siblings. */\n requestFull(rootId: string): void;\n /** Cold query for one selected branch; never enters the hot batch stream. */\n captureSemanticSubtree(\n rootId: string,\n targetFiberId: string,\n ): DetachSerializedFiber | null;\n /** Cold scoped-repair query: one element's exact current children-region\n * final state, or null when the id no longer exists. Never enters the hot\n * batch stream. */\n captureRegion(\n rootId: string,\n targetId: string,\n ): ProjectionRegionCapture | null;\n stop(): void;\n}\n\ninterface RootRuntime<T extends EnrichedFiberConstraint> {\n readonly options: CombinedProjectionRootOptions<T>;\n readonly layerSerializer: ProjectionLayerSerializer;\n readonly domLayerSerializer: ProjectionDomLayerSerializer;\n dormant: boolean;\n accumulator: ProjectionRootAccumulator | null;\n stopObserver: (() => void) | null;\n references: number;\n committedFiber: Fiber | null;\n semanticMode: \"dom\" | \"fiber\" | null;\n renderError: ProjectionRenderErrorProblem | null;\n readonly pendingRegions: Map<string, Fiber>;\n readonly pendingMetadata: Map<\n string,\n { readonly fiber: Fiber; readonly sourceAnnotations: \"fiber\" | \"live-host\" }\n >;\n semanticDiscoveryNodesVisited: number;\n /** True from the drain that reported `suspended` until the one that finds\n * content again, so one pending episode costs exactly one problem. */\n suspendedEpisode: boolean;\n /** A full asked for while suspended, carried to the drain that can serve it.\n * The flush consumes its request set before capture, so without this a\n * baseline requested mid-episode would be dropped. */\n deferredFullRequest: boolean;\n}\n\ninterface RootCaptureStats {\n readonly perf: CaptureProducerPerf;\n}\n\n/**\n * One producer for one source document. Observer callbacks retain source-realm\n * targets; the fixed scheduler asks for their current final state once. Full\n * snapshots exist only for initial registration, explicit synchronization,\n * reload, and recovery.\n */\nexport function createCombinedDocumentProducer<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n>(options: CreateCombinedDocumentProducerOptions): CombinedDocumentProducer<T> {\n const reactHook = initHook();\n const roots = new Map<string, RootRuntime<T>>();\n const captureStats = new WeakMap<object, RootCaptureStats>();\n let stopped = false;\n let rootLifecycleObserver: MutationObserver | null = null;\n let headPerfContext: ProjectionProducerFlushContext | null = null;\n let headSnapshotMs = 0;\n\n const core = createProjectionOutbox({\n emit(batch) {\n const rootPerf = batch.roots.flatMap((change) => {\n const payload =\n change.kind === \"full\"\n ? change.snapshot\n : change.kind === \"patch\"\n ? change.patch\n : change.problem;\n return typeof payload === \"object\" && payload !== null\n ? [captureStats.get(payload)?.perf].filter(\n (perf): perf is CaptureProducerPerf => perf !== undefined,\n )\n : [];\n });\n const perf = aggregateBatchPerf(\n rootPerf,\n batch.head,\n headPerfContext,\n headSnapshotMs,\n batch.roots.length,\n );\n headPerfContext = null;\n headSnapshotMs = 0;\n const emitted: CombinedProjectionBatch = {\n sessionId: batch.sessionId,\n sequence: batch.sequence,\n ...(batch.head === undefined ? {} : { head: batch.head }),\n ...(perf ? { perf } : {}),\n roots: batch.roots,\n };\n options.emit(emitted);\n },\n scheduler: options.scheduler,\n flushWindowMs: options.flushWindowMs,\n onError: options.onError,\n captureRoot(rootId, flushContext) {\n const runtime = roots.get(rootId);\n if (runtime && !runtime.options.element.isConnected) {\n makeRootDormant(runtime);\n }\n if (runtime?.dormant) return null;\n if (!runtime?.accumulator) {\n return {\n kind: \"problem\",\n problem: { reason: \"missing-fiber-target\" },\n };\n }\n const observation = runtime.accumulator.perfSnapshot();\n resetCaptureFlushCounters();\n const captureStartedAt = Date.now();\n const renderError = readProjectionRenderError(runtime.options.element);\n if (renderError) {\n runtime.renderError = renderError;\n // Consume all pre-error candidates. They describe a DOM state that is\n // intentionally never published, and the eventual full baseline\n // supersedes them.\n runtime.accumulator.capturePatch();\n runtime.pendingRegions.clear();\n runtime.pendingMetadata.clear();\n runtime.semanticDiscoveryNodesVisited = 0;\n captureStats.set(renderError, {\n perf: makePerf({\n flushContext,\n observation,\n snapshotMs: Date.now() - captureStartedAt,\n semanticNodes: 0,\n domNodes: 0,\n htmlChars: 0,\n annotations: 0,\n states: 0,\n portals: 0,\n observedFiles: 0,\n candidatesAfter: 0,\n fullReason: fullReason(flushContext),\n }),\n });\n return { kind: \"problem\", problem: renderError };\n }\n\n // A Tempo Suspense boundary showing only its pending marker has no\n // representable state: the content it will show is still loading. Report\n // that and HOLD this flush's work — leaving the accumulator undrained is\n // what re-queues it, so the next drain sees these records alongside the\n // content commit. Because the episode ends by serving a full baseline,\n // the held records are then consumed and superseded wholesale — and a\n // root-element attribute mutated during the episode is lost with them,\n // since document-lane fulls carry no rootAttributes (the recorded\n // bounded edge of this design). Retained semantic candidates need no\n // special handling: `captureSemanticRegions` already drops any fiber\n // the committed root no longer contains.\n if (isProjectionPendingOnly(runtime.options.element)) {\n runtime.deferredFullRequest ||= flushContext.fullRequested;\n if (runtime.suspendedEpisode) return null;\n runtime.suspendedEpisode = true;\n const problem = { reason: \"suspended\" } as const;\n captureStats.set(problem, {\n perf: makePerf({\n flushContext,\n observation,\n snapshotMs: Date.now() - captureStartedAt,\n semanticNodes: 0,\n domNodes: 0,\n htmlChars: 0,\n annotations: 0,\n states: 0,\n portals: 0,\n observedFiles: 0,\n candidatesAfter: 0,\n fullReason: null,\n }),\n });\n return { kind: \"problem\", problem };\n }\n\n // Ending an episode means the subtree was just rebuilt from nothing, so\n // every fiber in it is new. A patch would carry semantic regions naming\n // ids the destination has never published, which it can only answer with\n // a resync baseline — one wasted round trip per suspense resolution.\n // Serve the baseline directly instead.\n const endedSuspendedEpisode = runtime.suspendedEpisode;\n runtime.suspendedEpisode = false;\n\n runtime.committedFiber = resolveWatchedCommittedFiber(\n undefined,\n runtime.options,\n );\n const semanticMode = runtime.committedFiber ? \"fiber\" : \"dom\";\n const semanticModeChanged =\n runtime.semanticMode !== null && runtime.semanticMode !== semanticMode;\n\n const fullRequested =\n flushContext.fullRequested ||\n runtime.deferredFullRequest ||\n endedSuspendedEpisode ||\n semanticModeChanged;\n if (fullRequested) {\n runtime.deferredFullRequest = false;\n // Consume observer-local candidates because this baseline supersedes\n // them with one current self-contained state.\n runtime.accumulator.capturePatch();\n runtime.pendingRegions.clear();\n runtime.pendingMetadata.clear();\n runtime.semanticDiscoveryNodesVisited = 0;\n const fiberTarget = resolveFiberTarget(runtime.options);\n const captured = captureProjectionFullSnapshot({\n root: runtime.options.element,\n fiberTarget,\n portals: runtime.accumulator.portalElements(),\n layerSerializer: runtime.layerSerializer,\n domLayerSerializer: runtime.domLayerSerializer,\n });\n const { snapshot } = captured;\n runtime.semanticMode = semanticMode;\n captureStats.set(snapshot, {\n perf: makePerf({\n flushContext,\n observation,\n snapshotMs: Date.now() - captureStartedAt,\n semanticNodes: captured.semanticNodesSerialized,\n domNodes: captured.hostDomIdCount,\n htmlChars:\n snapshot.dom.html.length +\n snapshot.dom.portals.reduce(\n (sum, portal) =>\n sum + (portal.kind === \"replace\" ? portal.html.length : 0),\n 0,\n ),\n annotations: snapshot.dom.annotations.length,\n states: snapshot.dom.state.length,\n portals: snapshot.dom.portals.length,\n observedFiles: Object.keys(snapshot.observedFiles).length,\n candidatesAfter: 1,\n fullReason: fullReason(flushContext),\n }),\n });\n return { kind: \"full\", snapshot };\n }\n\n const accumulated = runtime.accumulator.capturePatch({\n // MutationObserver's parent is stable across a React commit. The\n // unkeyed child ids React may reuse within that parent are not.\n regionalChildLists: true,\n retainDomLayerTargets: semanticMode === \"dom\",\n });\n if (accumulated.kind === \"patch\") {\n for (const element of accumulated.localMetadataTargets) {\n runtime.semanticDiscoveryNodesVisited += addElementFiberCandidate(\n runtime,\n element,\n );\n }\n }\n\n const regions = captureSemanticRegions(runtime);\n const metadata = captureSemanticMetadata(runtime, regions.coveredFibers);\n runtime.pendingRegions.clear();\n runtime.pendingMetadata.clear();\n\n const basePatch =\n accumulated.kind === \"patch\" ? accumulated.patch : ({} as const);\n const observedFiles = new ProjectionObservedFileAccumulator();\n observedFiles.merge(basePatch.observedFiles);\n for (const region of regions.snapshots) {\n observedFiles.merge(region.observedFiles);\n }\n const observedSnapshot = observedFiles.snapshot();\n const domLayerPatch =\n semanticMode === \"dom\"\n ? runtime.domLayerSerializer.capturePatch(\n runtime.options.element,\n accumulated.kind === \"patch\"\n ? (accumulated.localDomLayerTargets ?? {\n structural: [],\n metadata: [],\n })\n : { structural: [], metadata: [] },\n observedSnapshot,\n )\n : undefined;\n const patch: ProjectionRootPatch = {\n ...basePatch,\n ...(domLayerPatch\n ? { layers: domLayerPatch }\n : regions.snapshots.length > 0 || metadata.length > 0\n ? {\n layers: {\n ...(regions.snapshots.length > 0\n ? { regions: regions.snapshots }\n : {}),\n ...(metadata.length > 0 ? { metadata } : {}),\n },\n }\n : {}),\n ...(Object.keys(observedSnapshot).length > 0\n ? { observedFiles: observedSnapshot }\n : {}),\n };\n if (Object.keys(patch).length === 0) {\n runtime.semanticDiscoveryNodesVisited = 0;\n return null;\n }\n\n const semanticNodes = regions.semanticNodesSerialized;\n const semanticDiscoveryNodesVisited =\n runtime.semanticDiscoveryNodesVisited;\n runtime.semanticDiscoveryNodesVisited = 0;\n captureStats.set(patch, {\n perf: makePerf({\n flushContext,\n observation,\n snapshotMs: Date.now() - captureStartedAt,\n semanticNodes,\n domNodes: patch.dom?.length ?? 0,\n htmlChars: patchHtmlChars(patch),\n annotations: patch.annotations?.length ?? 0,\n states: patch.state?.length ?? 0,\n portals: patch.portals?.length ?? 0,\n observedFiles: Object.keys(observedSnapshot).length,\n candidatesAfter:\n (patch.dom?.length ?? 0) +\n regions.snapshots.length +\n metadata.length,\n semanticDiscoveryNodesVisited,\n fullReason: null,\n }),\n });\n return { kind: \"patch\", patch };\n },\n captureHead(flushContext) {\n // The head describes the document, not any one root. A root that cannot\n // render still shares the stylesheets its healthy siblings render with.\n if (flushContext.candidateRootCount === 0) resetCaptureFlushCounters();\n const startedAt = Date.now();\n const head = captureHead(options.document);\n headSnapshotMs = Date.now() - startedAt;\n headPerfContext = flushContext;\n return head;\n },\n });\n\n function recordReactCommit(commit: FiberRoot): void {\n if (stopped) return;\n const affectedRootIds: string[] = [];\n for (const [rootId, runtime] of roots) {\n if (runtime.dormant) continue;\n const current = resolveWatchedCommittedFiber(commit, runtime.options);\n if (!current || current === runtime.committedFiber) continue;\n if (\n runtime.renderError !== null ||\n readProjectionRenderError(runtime.options.element) !== null\n ) {\n // MutationObserver owns the explicit problem/clear transition. Keep\n // Fiber identity current without racing an ordinary patch against it.\n runtime.committedFiber = current;\n continue;\n }\n if (runtime.committedFiber) {\n runtime.semanticDiscoveryNodesVisited += recordCommitSemanticChanges(\n runtime,\n commit,\n runtime.committedFiber,\n current,\n );\n // React and MutationObserver are independent authorities. Record the\n // commit's semantic regions, then drain already-queued DOM records into\n // the same fixed window. Each stream contributes only its own domain.\n runtime.accumulator?.takePendingDomRecords();\n }\n runtime.committedFiber = current;\n affectedRootIds.push(rootId);\n }\n if (affectedRootIds.length > 0) core.record({ rootIds: affectedRootIds });\n }\n\n function startRootObserver(rootId: string, runtime: RootRuntime<T>): void {\n const unregisterRootObserver = registerCaptureRootObserver();\n try {\n const accumulator = createProjectionRootAccumulator({\n root: runtime.options.element,\n onChange() {\n if (!runtime.options.element.isConnected) {\n makeRootDormant(runtime);\n return;\n }\n const renderError = readProjectionRenderError(\n runtime.options.element,\n );\n if (renderError) {\n if (runtime.renderError === null) {\n runtime.renderError = renderError;\n // Problems are ordered events but do not wait for the hot window.\n core.requestFull(rootId);\n }\n return;\n }\n if (runtime.renderError !== null) {\n runtime.renderError = null;\n // This root's stream resumes on its own baseline. A sibling still\n // in a problem state owns its own recovery and never delays this\n // one.\n core.requestFull(rootId);\n return;\n }\n core.record({ rootIds: [rootId] });\n },\n });\n runtime.accumulator = accumulator;\n runtime.stopObserver = () => {\n try {\n accumulator.stop();\n } finally {\n unregisterRootObserver();\n if (runtime.accumulator === accumulator) runtime.accumulator = null;\n runtime.stopObserver = null;\n }\n };\n } catch (error) {\n unregisterRootObserver();\n throw error;\n }\n }\n\n function createRootRuntime(\n rootOptions: CombinedProjectionRootOptions<T>,\n references: number,\n ): RootRuntime<T> {\n return {\n options: rootOptions,\n layerSerializer: createProjectionLayerSerializer(),\n domLayerSerializer: createProjectionDomLayerSerializer(),\n dormant: false,\n accumulator: null,\n stopObserver: null,\n references,\n committedFiber: resolveWatchedCommittedFiber(undefined, rootOptions),\n semanticMode: null,\n renderError: readProjectionRenderError(rootOptions.element),\n pendingRegions: new Map(),\n pendingMetadata: new Map(),\n semanticDiscoveryNodesVisited: 0,\n suspendedEpisode: false,\n deferredFullRequest: false,\n };\n }\n\n function makeRootDormant(runtime: RootRuntime<T>): void {\n if (runtime.dormant) return;\n runCleanup(runtime.stopObserver ?? (() => {}));\n runtime.dormant = true;\n runtime.committedFiber = null;\n runtime.semanticMode = null;\n runtime.renderError = null;\n runtime.pendingRegions.clear();\n runtime.pendingMetadata.clear();\n runtime.semanticDiscoveryNodesVisited = 0;\n runtime.suspendedEpisode = false;\n runtime.deferredFullRequest = false;\n }\n\n function rebindRoot(\n rootId: string,\n previous: RootRuntime<T>,\n rootOptions: CombinedProjectionRootOptions<T>,\n references: number,\n ): RootRuntime<T> {\n // A hot-swap can replace the selector's element wholesale. Treat that as\n // element succession: the logical root survives, but Fiber identity must\n // restart from a fresh serializer and a fresh full baseline.\n makeRootDormant(previous);\n const runtime = createRootRuntime(rootOptions, references);\n roots.set(rootId, runtime);\n try {\n startRootObserver(rootId, runtime);\n } catch (error) {\n roots.set(rootId, previous);\n throw error;\n }\n core.requestFull(rootId);\n return runtime;\n }\n\n function reconcileSelectorRoots(): void {\n if (stopped) return;\n for (const [rootId, runtime] of roots) {\n const selector = runtime.options.selector;\n if (selector === undefined) continue;\n if (!runtime.dormant && !runtime.options.element.isConnected) {\n makeRootDormant(runtime);\n }\n if (!runtime.dormant) continue;\n const element = options.document.querySelector(selector);\n if (!element?.isConnected) continue;\n rebindRoot(\n rootId,\n runtime,\n { ...runtime.options, element },\n runtime.references,\n );\n }\n }\n\n function syncRootLifecycleObserver(): void {\n const hasSelectorRoots = Array.from(roots.values()).some(\n (runtime) => runtime.options.selector !== undefined,\n );\n if (hasSelectorRoots && !rootLifecycleObserver) {\n rootLifecycleObserver = new MutationObserver(reconcileSelectorRoots);\n rootLifecycleObserver.observe(options.document, {\n childList: true,\n subtree: true,\n });\n } else if (!hasSelectorRoots && rootLifecycleObserver) {\n rootLifecycleObserver.disconnect();\n rootLifecycleObserver = null;\n }\n }\n\n function resolveOwnedRootOptions(\n rootOptions: CombinedProjectionRootOptions<T>,\n ): CombinedProjectionRootOptions<T> {\n if (rootOptions.selector === undefined) return rootOptions;\n const element = options.document.querySelector(rootOptions.selector);\n if (!element) {\n throw new Error(\n `Projection root selector ${JSON.stringify(rootOptions.selector)} did not match`,\n );\n }\n return element === rootOptions.element\n ? rootOptions\n : { ...rootOptions, element };\n }\n\n function runCleanup(cleanup: () => void): void {\n try {\n cleanup();\n } catch (error) {\n try {\n options.onError?.(error);\n } catch {\n // Cleanup must continue when error reporting itself fails.\n }\n }\n }\n\n let stopReactCommits: () => void = () => {};\n let stopHeadChanges: () => void = () => {};\n try {\n stopReactCommits = reactHook.onCommit(recordReactCommit);\n const headSubscription = getHeadTracker().subscribe(\n options.document,\n () => {\n if (stopped) return;\n // New styling can move a portal without mutating it, so the roots that\n // own portals ride in the same batch as the head that moved them —\n // their capture refreshes any portal frame the styling changed.\n const rootIds: string[] = [];\n for (const [rootId, runtime] of roots) {\n if (runtime.accumulator?.hasPortals()) rootIds.push(rootId);\n }\n core.record({ head: true, rootIds });\n },\n );\n stopHeadChanges = () => headSubscription.unsubscribe();\n } catch (error) {\n runCleanup(stopReactCommits);\n core.stop();\n throw error;\n }\n const unregisterDocumentProducer = registerDocumentCaptureProducer(\n options.document,\n );\n\n return {\n bindSession: (sessionId) => core.bindSession(sessionId),\n watchRoot(requestedRootOptions) {\n if (stopped) throw new Error(\"Projection producer has been stopped\");\n const rootOptions = resolveOwnedRootOptions(requestedRootOptions);\n const existing = roots.get(rootOptions.rootId);\n if (existing) {\n if (\n existing.options.element === rootOptions.element &&\n existing.options.fiberSelector === rootOptions.fiberSelector &&\n existing.options.selector === rootOptions.selector\n ) {\n existing.references += 1;\n return;\n }\n if (\n existing.options.element !== rootOptions.element &&\n !existing.options.element.isConnected\n ) {\n rebindRoot(\n rootOptions.rootId,\n existing,\n rootOptions,\n existing.references + 1,\n );\n syncRootLifecycleObserver();\n return;\n }\n throw new Error(\n `Projection root ${JSON.stringify(rootOptions.rootId)} has conflicting options`,\n );\n }\n const runtime = createRootRuntime(rootOptions, 1);\n roots.set(rootOptions.rootId, runtime);\n try {\n startRootObserver(rootOptions.rootId, runtime);\n core.addRoot(rootOptions.rootId);\n syncRootLifecycleObserver();\n } catch (error) {\n roots.delete(rootOptions.rootId);\n runCleanup(runtime.stopObserver ?? (() => {}));\n syncRootLifecycleObserver();\n throw error;\n }\n },\n unwatchRoot(rootId) {\n const runtime = roots.get(rootId);\n if (!runtime) return;\n runtime.references -= 1;\n if (runtime.references > 0) return;\n roots.delete(rootId);\n core.removeRoot(rootId);\n runCleanup(runtime.stopObserver ?? (() => {}));\n syncRootLifecycleObserver();\n },\n requestFull: (rootId) => core.requestFull(rootId),\n captureSemanticSubtree(rootId, targetFiberId) {\n if (stopped) throw new Error(\"Projection producer has been stopped\");\n const runtime = roots.get(rootId);\n if (!runtime || runtime.dormant || !runtime.options.element.isConnected) {\n return null;\n }\n const current = resolveWatchedCommittedFiber(undefined, runtime.options);\n if (!current) return null;\n runtime.committedFiber = current;\n return captureProjectionSemanticSubtree(current, targetFiberId, {\n fiberId: runtime.layerSerializer.fiberId,\n knownFiberId: runtime.layerSerializer.knownFiberId,\n });\n },\n captureRegion(rootId, targetId) {\n if (stopped) throw new Error(\"Projection producer has been stopped\");\n const runtime = roots.get(rootId);\n if (!runtime || runtime.dormant || !runtime.options.element.isConnected) {\n return null;\n }\n return captureProjectionRegion(\n runtime.options.element,\n targetId,\n runtime.accumulator?.portalElements() ?? [],\n );\n },\n stop() {\n if (stopped) return;\n stopped = true;\n core.stop();\n for (const runtime of roots.values()) {\n runCleanup(runtime.stopObserver ?? (() => {}));\n }\n rootLifecycleObserver?.disconnect();\n rootLifecycleObserver = null;\n runCleanup(stopReactCommits);\n runCleanup(stopHeadChanges);\n unregisterDocumentProducer();\n roots.clear();\n },\n };\n}\n\nfunction readProjectionRenderError(\n root: Element,\n): ProjectionRenderErrorProblem | null {\n const sentinel = root.matches('[data-render-error=\"true\"]')\n ? root\n : root.querySelector('[data-render-error=\"true\"]');\n if (!sentinel) return null;\n return {\n reason: \"render-error\",\n message: sentinel.getAttribute(\"data-render-error-message\"),\n };\n}\n\nfunction resolveFiberTarget<T extends EnrichedFiberConstraint>(\n options: CombinedProjectionRootOptions<T>,\n): Element | null {\n return options.fiberSelector\n ? options.element.ownerDocument.querySelector(options.fiberSelector)\n : (options.element.firstElementChild ?? options.element);\n}\n\n/**\n * The committed generation of a fiber, or null when React has already\n * detached it. A commit hands the producer fibers React may have unmounted in\n * that same commit (a drag removal, a Fast Refresh remount); losing one of\n * them must cost only that fiber's contribution, never the whole commit\n * record — an unrecorded React commit freezes the receiver's settlement.\n */\nfunction resolveCommittedFiberOrNull(fiber: Fiber): Fiber | null {\n try {\n return resolveCommittedFiber(fiber);\n } catch (error) {\n if (!isTransientFiberResolutionError(error)) throw error;\n return null;\n }\n}\n\nfunction resolveWatchedCommittedFiber<T extends EnrichedFiberConstraint>(\n fiberRoot: FiberRoot | undefined,\n options: CombinedProjectionRootOptions<T>,\n): Fiber | null {\n const target = resolveFiberTarget(options);\n if (!target) return null;\n if (\n fiberRoot &&\n (fiberRoot.containerInfo === target ||\n target.contains(fiberRoot.containerInfo))\n ) {\n return fiberRoot.current;\n }\n const rawFiber = getFiberFromElement(target);\n if (!rawFiber) return null;\n const rawCommitted = resolveCommittedFiberOrNull(rawFiber);\n if (!rawCommitted) return null;\n // The watched endpoint must be the same fiber the full snapshot serializes\n // from (the topmost annotated wrapper component above the first host, when\n // one exists). Commit routing and semantic-region containment both compare\n // against this fiber, so an update scheduled by that wrapper is only\n // attributed to this root if the ascent happens here too.\n const committed = ascendToAnnotatedComponentRoot(rawCommitted);\n if (!fiberRoot) return committed;\n let root = committed;\n while (root.return) root = root.return;\n return root === fiberRoot.current || root === fiberRoot.current.alternate\n ? committed\n : null;\n}\n\n/**\n * React's development FiberRoot exposes both the exact scheduling Fibers and\n * their valid before/after generations only while `onCommitFiberRoot` is\n * executing. Discover the affected semantic regions at that boundary, then\n * defer serialization of those regions until the fixed final-state window\n * closes. Later commits can reuse both Fiber generations, so deferring the\n * comparison itself would lose the earlier change.\n *\n * The fallback is the changed watched endpoint itself. It preserves\n * correctness for renderers that do not expose updater tracking, while Tempo's\n * normal development renderer takes the exact K-candidate path.\n */\nfunction recordCommitSemanticChanges<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n commit: FiberRoot,\n previousRoot: Fiber,\n currentRoot: Fiber,\n): number {\n const candidates: Fiber[] = [];\n for (const scheduled of commit.memoizedUpdaters ?? []) {\n const candidate = resolveCommittedFiberOrNull(scheduled);\n if (!candidate) {\n // The commit unmounted its own scheduling component, so there is no\n // representable candidate for it. Its removal still changed the watched\n // tree: fall back to the whole watched root rather than dropping it.\n retainSemanticCandidate(candidates, currentRoot);\n continue;\n }\n if (fiberContains(currentRoot, candidate)) {\n retainSemanticCandidate(candidates, candidate);\n } else if (\n fiberContains(candidate, currentRoot) ||\n fiberContains(scheduled, previousRoot)\n ) {\n // The scheduling component wraps the selected projection boundary. Its\n // exact representable candidate is the watched root, never that outside\n // owner or any of its siblings.\n retainSemanticCandidate(candidates, currentRoot);\n }\n }\n if (candidates.length === 0) retainSemanticCandidate(candidates, currentRoot);\n\n let nodesVisited = 0;\n for (const candidate of candidates) {\n const currentCandidate = resolveCommittedFiberOrNull(candidate);\n if (!currentCandidate) {\n const rootBoundary = nearestProjectionBoundary(runtime, currentRoot);\n if (rootBoundary) addRegion(runtime, rootBoundary);\n continue;\n }\n const previousCandidate = currentCandidate.alternate;\n if (!previousCandidate) {\n const boundary = nearestProjectionBoundary(runtime, currentCandidate);\n if (boundary) addRegion(runtime, boundary);\n continue;\n }\n nodesVisited += collectChangedSemanticFibers(\n previousCandidate,\n currentCandidate,\n runtime,\n );\n }\n return nodesVisited;\n}\n\nfunction retainSemanticCandidate(candidates: Fiber[], candidate: Fiber): void {\n for (const existing of candidates) {\n if (fiberPair(existing, candidate) || fiberContains(existing, candidate)) {\n return;\n }\n }\n for (let index = candidates.length - 1; index >= 0; index -= 1) {\n const existing = candidates[index];\n if (existing && fiberContains(candidate, existing)) {\n candidates.splice(index, 1);\n }\n }\n candidates.push(candidate);\n}\n\nfunction collectChangedSemanticFibers<T extends EnrichedFiberConstraint>(\n previous: Fiber,\n current: Fiber,\n runtime: RootRuntime<T>,\n): number {\n let nodesVisited = 0;\n const visit = (before: Fiber, after: Fiber, boundary: Fiber): void => {\n nodesVisited += 1;\n if (before === after) return;\n const nextBoundary = isProjectionLayerFiber(after) ? after : boundary;\n if (!fiberPair(before, after)) {\n addRegion(runtime, nextBoundary);\n return;\n }\n if (!projectionPropsEqual(before, after, runtime.layerSerializer)) {\n addMetadata(runtime, after, \"fiber\");\n }\n if (before.child === after.child) return;\n\n let oldChild = before.child;\n let newChild = after.child;\n while (oldChild && newChild) {\n if (!fiberPair(oldChild, newChild)) {\n addRegion(runtime, nextBoundary);\n return;\n }\n visit(oldChild, newChild, nextBoundary);\n oldChild = oldChild.sibling;\n newChild = newChild.sibling;\n }\n if (oldChild || newChild) addRegion(runtime, nextBoundary);\n };\n\n const boundary = nearestProjectionBoundary(runtime, current);\n if (boundary) visit(previous, current, boundary);\n return nodesVisited;\n}\n\nfunction fiberPair(left: Fiber, right: Fiber): boolean {\n return left === right || left.alternate === right || right.alternate === left;\n}\n\nfunction nearestProjectionLayerFiber(fiber: Fiber): Fiber | null {\n let current: Fiber | null = fiber;\n while (current && !isProjectionLayerFiber(current)) current = current.return;\n return current;\n}\n\nfunction nearestProjectionBoundary<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n fiber: Fiber,\n): Fiber | null {\n let current: Fiber | null = fiber;\n while (current) {\n if (isProjectionLayerFiber(current)) return current;\n if (runtime.committedFiber && fiberPair(current, runtime.committedFiber)) {\n return current;\n }\n current = current.return;\n }\n return null;\n}\n\nfunction addElementFiberCandidate<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n element: Element,\n): number {\n const raw = getFiberFromElement(element);\n if (!raw) return 0;\n const committed = resolveCommittedFiber(raw);\n const candidate = nearestProjectionLayerFiber(committed);\n if (!candidate) return 0;\n // DOM observation is not evidence that the Fiber tree changed. React's\n // commit stream owns semantic regions. The only intentional crossover is a\n // source annotation stamped directly on a host element, whose exact live\n // value must update that one already-published semantic node.\n addMetadata(runtime, candidate, \"live-host\");\n return 1;\n}\n\nfunction addRegion<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n fiber: Fiber,\n): void {\n const id = runtime.layerSerializer.fiberId(fiber);\n for (const existing of runtime.pendingRegions.values()) {\n if (fiberContains(existing, fiber)) return;\n }\n for (const [existingId, existing] of runtime.pendingRegions) {\n if (fiberContains(fiber, existing))\n runtime.pendingRegions.delete(existingId);\n }\n runtime.pendingRegions.set(id, fiber);\n}\n\nfunction addMetadata<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n fiber: Fiber,\n sourceAnnotations: \"fiber\" | \"live-host\",\n): void {\n if (!isProjectionLayerFiber(fiber)) return;\n const id = runtime.layerSerializer.fiberId(fiber);\n const existing = runtime.pendingMetadata.get(id);\n runtime.pendingMetadata.set(id, {\n fiber,\n sourceAnnotations:\n existing?.sourceAnnotations === \"live-host\" ||\n sourceAnnotations === \"live-host\"\n ? \"live-host\"\n : \"fiber\",\n });\n}\n\nfunction fiberContains(ancestor: Fiber, candidate: Fiber): boolean {\n for (\n let current: Fiber | null = candidate;\n current;\n current = current.return\n ) {\n if (current === ancestor || current.alternate === ancestor) return true;\n }\n return false;\n}\n\nfunction projectionPropsEqual(\n before: Fiber,\n after: Fiber,\n serializer: ProjectionLayerSerializer,\n): boolean {\n const left = serializer.captureMetadata(before).props;\n const right = serializer.captureMetadata(after).props;\n return layerPropsEqual(left, right);\n}\n\nfunction layerPropsEqual(\n left: ProjectionLayerProps | undefined,\n right: ProjectionLayerProps | undefined,\n): boolean {\n if (left === right) return true;\n if (!left || !right) return left === right;\n const leftEntries = Object.entries(left);\n const rightEntries = Object.entries(right);\n if (leftEntries.length !== rightEntries.length) return false;\n for (const [key, value] of leftEntries) {\n const other = right[key as keyof ProjectionLayerProps];\n if (key === \"style\") {\n if (\n !recordEqual(\n value as Record<string, string>,\n other as Record<string, string>,\n )\n ) {\n return false;\n }\n } else if (value !== other) return false;\n }\n return true;\n}\n\nfunction recordEqual(\n left: Readonly<Record<string, string>> | undefined,\n right: Readonly<Record<string, string>> | undefined,\n): boolean {\n if (left === right) return true;\n if (!left || !right) return left === right;\n const keys = Object.keys(left);\n return (\n keys.length === Object.keys(right).length &&\n keys.every((key) => left[key] === right[key])\n );\n}\n\nfunction captureSemanticRegions<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n): {\n readonly snapshots: ProjectionLayerRegionSnapshot[];\n readonly coveredFibers: ReadonlySet<Fiber>;\n readonly semanticNodesSerialized: number;\n} {\n const snapshots: ProjectionLayerRegionSnapshot[] = [];\n const coveredFibers = new Set<Fiber>();\n let semanticNodesSerialized = 0;\n for (const retainedFiber of runtime.pendingRegions.values()) {\n const fiber = resolveCommittedFiber(retainedFiber);\n if (\n runtime.committedFiber &&\n !fiberContains(runtime.committedFiber, fiber)\n ) {\n continue;\n }\n const serialized = runtime.layerSerializer.serializeRegion(fiber);\n snapshots.push(serialized.region);\n coveredFibers.add(fiber);\n semanticNodesSerialized += serialized.semanticNodesSerialized;\n }\n return { snapshots, coveredFibers, semanticNodesSerialized };\n}\n\nfunction captureSemanticMetadata<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n coveredFibers: ReadonlySet<Fiber>,\n): ProjectionLayerMetadataSnapshot[] {\n const snapshots: ProjectionLayerMetadataSnapshot[] = [];\n for (const retained of runtime.pendingMetadata.values()) {\n if (\n Array.from(coveredFibers).some((region) =>\n fiberContains(region, retained.fiber),\n )\n ) {\n continue;\n }\n const fiber = resolveCommittedFiber(retained.fiber);\n if (\n runtime.committedFiber &&\n !fiberContains(runtime.committedFiber, fiber)\n ) {\n continue;\n }\n snapshots.push(\n runtime.layerSerializer.captureMetadata(fiber, {\n sourceAnnotations: retained.sourceAnnotations,\n }),\n );\n }\n return snapshots;\n}\n\nfunction patchHtmlChars(patch: ProjectionRootPatch): number {\n let chars = 0;\n for (const change of patch.dom ?? []) {\n if (\n change.kind === \"children\" ||\n change.kind === \"place\" ||\n change.kind === \"text\"\n ) {\n chars += change.html.length;\n }\n }\n for (const portal of patch.portals ?? []) {\n if (portal.kind === \"replace\") chars += portal.html.length;\n }\n return chars;\n}\n\nfunction fullReason(context: ProjectionProducerFlushContext): string {\n return context.initialForSession ? \"initial\" : \"explicit-full\";\n}\n\nfunction makePerf(input: {\n readonly flushContext: ProjectionProducerFlushContext;\n readonly observation: ReturnType<ProjectionRootAccumulator[\"perfSnapshot\"]>;\n readonly snapshotMs: number;\n readonly semanticNodes: number;\n readonly domNodes: number;\n readonly htmlChars: number;\n readonly annotations: number;\n readonly states: number;\n readonly portals: number;\n readonly observedFiles: number;\n readonly candidatesAfter: number;\n readonly semanticDiscoveryNodesVisited?: number;\n readonly fullReason: string | null;\n}): CaptureProducerPerf {\n return buildProjectionCapturePerf({\n flushStartedAt: input.flushContext.flushStartedAt,\n snapshotMs: input.snapshotMs,\n identityMs: 0,\n html: undefined,\n fiberNodeCount: input.semanticNodes,\n changedNodeEstimate: input.observation.candidateTargets,\n fixedWindowTimersOpened: input.flushContext.fixedWindowTimersOpened,\n maxSimultaneousTimers: input.flushContext.maxSimultaneousTimers,\n flushIntervalMs: input.flushContext.flushIntervalMs,\n rawMutationRecords: input.observation.rawMutationRecords,\n rawStateRecords: input.observation.rawStateRecords,\n rawPortalRecords: input.observation.rawPortalRecords,\n candidateTargetsBeforeCoalescing: input.observation.candidateTargets,\n candidateTargetsAfterCoalescing: input.candidatesAfter,\n semanticDiscoveryNodesVisited: input.semanticDiscoveryNodesVisited ?? 0,\n rootsPerBatch: input.flushContext.candidateRootCount,\n fullSnapshotReason: input.fullReason,\n htmlChars: input.htmlChars,\n domNodesSerialized: input.domNodes,\n semanticNodesSerialized: input.semanticNodes,\n annotationTargetsSerialized: input.annotations,\n stateTargetsSerialized: input.states,\n portalTargetsSerialized: input.portals,\n observedFileEntries: input.observedFiles,\n });\n}\n\nfunction aggregateBatchPerf(\n roots: readonly CaptureProducerPerf[],\n head: string | undefined,\n context: ProjectionProducerFlushContext | null,\n capturedHeadMs: number,\n rootsPerBatch: number,\n): CaptureProducerPerf | undefined {\n if (roots.length === 0) {\n if (!context) return undefined;\n return buildProjectionCapturePerf({\n flushStartedAt: context.flushStartedAt,\n snapshotMs: capturedHeadMs,\n identityMs: 0,\n html: undefined,\n head,\n fiberNodeCount: 0,\n changedNodeEstimate: 0,\n fixedWindowTimersOpened: context.fixedWindowTimersOpened,\n maxSimultaneousTimers: context.maxSimultaneousTimers,\n flushIntervalMs: context.flushIntervalMs,\n rawMutationRecords: 0,\n rawStateRecords: 0,\n rawPortalRecords: 0,\n candidateTargetsBeforeCoalescing: 0,\n candidateTargetsAfterCoalescing: 0,\n rootsPerBatch: 0,\n fullSnapshotReason: null,\n domNodesSerialized: 0,\n semanticNodesSerialized: 0,\n annotationTargetsSerialized: 0,\n stateTargetsSerialized: 0,\n portalTargetsSerialized: 0,\n observedFileEntries: 0,\n });\n }\n const sum = (read: (perf: CaptureProducerPerf) => number): number =>\n roots.reduce((total, perf) => total + read(perf), 0);\n const max = (read: (perf: CaptureProducerPerf) => number): number =>\n Math.max(...roots.map(read));\n const first = roots[0];\n if (!first) return undefined;\n const flushStartedAt = context?.flushStartedAt ?? first.flushStartedAt;\n const reasons = new Set(roots.map((perf) => perf.fullSnapshotReason));\n return {\n flushStartedAt,\n flushMs: Date.now() - flushStartedAt,\n snapshotMs: sum((perf) => perf.snapshotMs) + capturedHeadMs,\n identityMs: sum((perf) => perf.identityMs),\n identityNodesVisited: sum((perf) => perf.identityNodesVisited),\n sourceVersionDomScanNodes: sum((perf) => perf.sourceVersionDomScanNodes),\n sourceVersionFiberSerializeNodes: sum(\n (perf) => perf.sourceVersionFiberSerializeNodes,\n ),\n sourceVersionFiberReductionNodes: sum(\n (perf) => perf.sourceVersionFiberReductionNodes,\n ),\n sourceVersionFallbackScanNodes: sum(\n (perf) => perf.sourceVersionFallbackScanNodes,\n ),\n sourceVersionScanNodes: sum((perf) => perf.sourceVersionScanNodes),\n styleReadCount: sum((perf) => perf.styleReadCount),\n htmlChars: sum((perf) => perf.htmlChars),\n headChars: head?.length ?? 0,\n fiberNodeCount: sum((perf) => perf.fiberNodeCount),\n changedNodeEstimate: sum((perf) => perf.changedNodeEstimate),\n activeDocumentProducers: max((perf) => perf.activeDocumentProducers),\n activeRootObservers: max((perf) => perf.activeRootObservers),\n headObservers: max((perf) => perf.headObservers),\n headSubscriptions: max((perf) => perf.headSubscriptions),\n reactCommitSubscriptions: max((perf) => perf.reactCommitSubscriptions),\n fixedWindowTimersOpened:\n context?.fixedWindowTimersOpened ?? first.fixedWindowTimersOpened,\n maxSimultaneousTimers:\n context?.maxSimultaneousTimers ?? first.maxSimultaneousTimers,\n flushIntervalMs: context?.flushIntervalMs ?? first.flushIntervalMs,\n rawMutationRecords: sum((perf) => perf.rawMutationRecords),\n rawStateRecords: sum((perf) => perf.rawStateRecords),\n rawPortalRecords: sum((perf) => perf.rawPortalRecords),\n producerCandidateNodes: sum((perf) => perf.producerCandidateNodes),\n producerVisitedNodes: sum((perf) => perf.producerVisitedNodes),\n candidateTargetsBeforeCoalescing: sum(\n (perf) => perf.candidateTargetsBeforeCoalescing,\n ),\n candidateTargetsAfterCoalescing: sum(\n (perf) => perf.candidateTargetsAfterCoalescing,\n ),\n semanticDiscoveryNodesVisited: sum(\n (perf) => perf.semanticDiscoveryNodesVisited ?? 0,\n ),\n domNodesSerialized: roots.some((perf) => perf.domNodesSerialized === null)\n ? null\n : sum((perf) => perf.domNodesSerialized ?? 0),\n semanticNodesSerialized: sum((perf) => perf.semanticNodesSerialized),\n annotationTargetsSerialized: sum(\n (perf) => perf.annotationTargetsSerialized,\n ),\n stateTargetsSerialized: sum((perf) => perf.stateTargetsSerialized),\n portalTargetsSerialized: sum((perf) => perf.portalTargetsSerialized),\n headSerializations: head === undefined ? 0 : 1,\n observedFileEntries: sum((perf) => perf.observedFileEntries),\n batchesEmitted: 1,\n rootsPerBatch,\n fullSnapshotReason:\n reasons.size === 1 ? first.fullSnapshotReason : \"mixed-full\",\n };\n}\n","/**\n * Projection Snapshot\n *\n * Shared one-shot snapshot used by:\n * - capture APIs (single event)\n * - watch initial emission (first event in stream)\n */\n\nimport { findOwnedPortalRoots } from \"../shared/portal-tracker\";\nimport {\n captureWithSupplementalRoots,\n collectElementStates,\n removeScriptTags,\n} from \"./capture\";\nimport type { DomCapture, PortalUpdate } from \"./types\";\nimport { captureHead } from \"./watch-head\";\nimport {\n capturePortalCoordinateSpace,\n getOrAssignPortalId,\n} from \"./watch-portal\";\n\nexport function captureProjectionSnapshot(\n element: Element,\n supplementalRoots?: readonly Element[],\n): DomCapture {\n return {\n ...captureProjectionBodySnapshot(element, supplementalRoots),\n head: captureHead(element.ownerDocument ?? document),\n };\n}\n\n/**\n * Capture one complete root without re-reading document-scoped head state.\n *\n * A document producer calls this once per dirty root and captures the head at\n * most once for the enclosing batch. The legacy one-shot API above remains\n * self-contained for callers that truly need a single root plus head.\n */\nexport function captureProjectionBodySnapshot(\n element: Element,\n supplementalRoots?: readonly Element[],\n): Omit<DomCapture, \"head\"> {\n const { updates: portals, elements: portalElements } = supplementalRoots\n ? captureKnownPortals(supplementalRoots, element)\n : capturePortals(element);\n const baseCapture = captureWithSupplementalRoots(element, portalElements);\n\n return {\n ...baseCapture,\n portalsComplete: true,\n ...(portals.length > 0 ? { portals } : {}),\n };\n}\n\nexport function collectProjectionPortalElements(root: Element): Element[] {\n return capturePortals(root).elements;\n}\n\nfunction captureKnownPortals(\n roots: readonly Element[],\n ownerRoot: Element,\n): CapturedPortals {\n const updates: PortalUpdate[] = [];\n const elements: Element[] = [];\n for (const root of roots) {\n if (!root.isConnected) continue;\n const id = getOrAssignPortalId(root);\n const coordinateSpace = capturePortalCoordinateSpace(ownerRoot, root);\n updates.push({\n id,\n selector: \"\",\n html: removeScriptTags(root.outerHTML),\n states: collectElementStates(root, { includeDocumentScroll: false }),\n ...(coordinateSpace && { coordinateSpace }),\n });\n elements.push(root);\n }\n return { updates, elements };\n}\n\ninterface CapturedPortals {\n updates: PortalUpdate[];\n /** Live portal root elements, for declared-facts computation. */\n elements: Element[];\n}\n\nfunction capturePortals(root: Element): CapturedPortals {\n return captureKnownPortals(findOwnedPortalRoots(root), root);\n}\n","import { getFiberFromElement } from \"../fiber/capture\";\nimport { FiberTag } from \"../fiber/react-types\";\nimport {\n isTransientFiberResolutionError,\n resolveCommittedFiber,\n} from \"../fiber/serialize\";\nimport { countIdentityNodeVisited } from \"../shared/capture-perf\";\nimport type {\n EnrichedFiberConstraint,\n RenderHostIdentity,\n RenderHostIdentityDeclaration,\n} from \"./types\";\n\nconst SOURCE_IDENTITY_KEYS = [\n \"data-tempo-filepath\",\n \"data-tempo-position\",\n \"data-tempo-modifiedts\",\n \"data-tempo-source-version\",\n \"data-tempo-html-filepath\",\n \"data-tempo-html-offset\",\n \"data-tempo-html-modifiedts\",\n \"data-tempo-html-source-version\",\n] as const;\n\ntype SourceIdentityKey = (typeof SOURCE_IDENTITY_KEYS)[number];\n\nfunction normalizeIdentityValue(value: unknown): string | undefined {\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return String(value);\n }\n return undefined;\n}\n\nfunction sourceIdentityFromProps(\n props: Readonly<Record<string, unknown>> | undefined,\n): Partial<Record<SourceIdentityKey, string>> | undefined {\n if (!props) return undefined;\n const source: Partial<Record<SourceIdentityKey, string>> = {};\n for (const key of SOURCE_IDENTITY_KEYS) {\n const value = normalizeIdentityValue(props[key]);\n if (value !== undefined) source[key] = value;\n }\n return Object.keys(source).length > 0 ? source : undefined;\n}\n\nfunction sourceIdentityFromElement(\n element: Element,\n): Partial<Record<SourceIdentityKey, string>> | undefined {\n const source: Partial<Record<SourceIdentityKey, string>> = {};\n for (const key of SOURCE_IDENTITY_KEYS) {\n const value = element.getAttribute(key);\n if (value !== null) source[key] = value;\n }\n return Object.keys(source).length > 0 ? source : undefined;\n}\n\nfunction isContentEditableBoundary(\n props: Readonly<Record<string, unknown>> | undefined,\n): boolean {\n if (!props) return false;\n return (\n (props.contentEditable !== null && props.contentEditable !== undefined) ||\n (props.contenteditable !== null && props.contenteditable !== undefined)\n );\n}\n\nfunction finalizeDeclaration(\n hosts: RenderHostIdentity[],\n missingDomIdCount: number,\n): RenderHostIdentityDeclaration {\n const counts = new Map<string, number>();\n for (const host of hosts) {\n counts.set(host.domId, (counts.get(host.domId) ?? 0) + 1);\n }\n const duplicateDomIds = [...counts]\n .filter(([, count]) => count > 1)\n .map(([domId]) => domId)\n .sort();\n hosts.sort((left, right) => left.domId.localeCompare(right.domId));\n return { hosts, missingDomIdCount, duplicateDomIds };\n}\n\nexport function declareFiberHostIdentity<T extends EnrichedFiberConstraint>(\n tree: T,\n): RenderHostIdentityDeclaration {\n const hosts: RenderHostIdentity[] = [];\n let missingDomIdCount = 0;\n const visit = (node: EnrichedFiberConstraint): void => {\n countIdentityNodeVisited();\n if (node.insideContentEditable) return;\n const renderNode = node as EnrichedFiberConstraint & {\n tag?: number;\n name?: string;\n };\n if (renderNode.tag === FiberTag.HostComponent) {\n if (!node.domId) {\n missingDomIdCount += 1;\n } else {\n hosts.push({\n domId: node.domId,\n tag: renderNode.name?.toLowerCase() ?? \"\",\n source: sourceIdentityFromProps(node.props),\n });\n }\n if (isContentEditableBoundary(node.props)) return;\n }\n for (const child of node.children) {\n visit(child as EnrichedFiberConstraint);\n }\n };\n visit(tree);\n return finalizeDeclaration(hosts, missingDomIdCount);\n}\n\nexport function declareDomHostIdentity(\n captureRoot: Element,\n supplementalRoots: readonly Element[],\n): RenderHostIdentityDeclaration {\n const hosts: RenderHostIdentity[] = [];\n let missingDomIdCount = 0;\n const seenElements = new Set<Element>();\n const visit = (element: Element): void => {\n if (seenElements.has(element)) return;\n seenElements.add(element);\n countIdentityNodeVisited();\n const rawFiber = getFiberFromElement(element);\n if (rawFiber) {\n try {\n const fiber = resolveCommittedFiber(rawFiber);\n if (\n fiber.tag === FiberTag.HostComponent &&\n fiber.stateNode === element\n ) {\n const domId = element.getAttribute(\"data-dom-id\");\n if (!domId) {\n missingDomIdCount += 1;\n } else {\n hosts.push({\n domId,\n tag: element.localName.toLowerCase(),\n source: sourceIdentityFromElement(element),\n });\n }\n }\n } catch (error) {\n if (!isTransientFiberResolutionError(error)) throw error;\n // React can detach an alternate between DOM enumeration and this\n // identity read. Make the atomic candidate incomplete instead of\n // surfacing capture internals as an application runtime error.\n missingDomIdCount += 1;\n }\n }\n if (element.getAttribute(\"contenteditable\") !== null) return;\n for (const child of element.children) visit(child);\n };\n // The root snapshot serializes `captureRoot.innerHTML`, so the root itself\n // is outside the HTML arm even when it is a React-owned CanvasHost wrapper.\n // Portal snapshots use `outerHTML` and therefore include their roots.\n for (const child of captureRoot.children) visit(child);\n for (const root of supplementalRoots) visit(root);\n return finalizeDeclaration(hosts, missingDomIdCount);\n}\n\nexport function hostIdentityDeclarationsMatch(\n left: RenderHostIdentityDeclaration,\n right: RenderHostIdentityDeclaration,\n): boolean {\n if (\n left.missingDomIdCount !== 0 ||\n right.missingDomIdCount !== 0 ||\n left.duplicateDomIds.length !== 0 ||\n right.duplicateDomIds.length !== 0 ||\n left.hosts.length !== right.hosts.length\n ) {\n return false;\n }\n for (let index = 0; index < left.hosts.length; index += 1) {\n const leftHost = left.hosts[index];\n const rightHost = right.hosts[index];\n if (\n !leftHost ||\n !rightHost ||\n leftHost.domId !== rightHost.domId ||\n leftHost.tag !== rightHost.tag ||\n JSON.stringify(leftHost.source ?? {}) !==\n JSON.stringify(rightHost.source ?? {})\n ) {\n return false;\n }\n }\n return true;\n}\n","/**\n * Declared Capture Facts — fiber half\n *\n * The layers half of a combined capture declares its own observed source\n * versions, computed by walking the enriched fiber tree's annotated props\n * (the same props the DOM half reads as attributes). See\n * specs/canvas-determinism.md §4.\n */\n\nimport type { DomCapture } from \"../html/types\";\nimport type { CombinedCapture, EnrichedFiberConstraint } from \"./types\";\nimport {\n declareDomHostIdentity,\n declareFiberHostIdentity,\n hostIdentityDeclarationsMatch,\n} from \"./render-identity\";\n\n/** Both per-file version signals a fiber walk observes, mirroring\n * `computeDeclaredFacts` on the DOM side: the numeric mtime (`observedVersions`)\n * and the content-version token (`observedSourceVersions`, co-located with the\n * MAX-mtime element). Keys in both are the raw stamped filepath spellings\n * (consumers canonicalize on read). */\nexport interface FiberObservedVersions {\n observedVersions: Record<string, number>;\n observedSourceVersions: Record<string, string>;\n}\n\nexport interface RenderDeclarationScope {\n captureRoot: Element;\n supplementalRoots: readonly Element[];\n renderMode?: \"static-dom\";\n}\n\nexport function createRenderDeclarationScope(\n captureRoot: Element,\n supplementalRoots: readonly Element[],\n): RenderDeclarationScope {\n return {\n captureRoot,\n supplementalRoots,\n ...(captureRoot.getAttribute(\"data-tempo-render-mode\") === \"static-dom\" && {\n renderMode: \"static-dom\" as const,\n }),\n };\n}\n\n/**\n * Per-file MAX `data-tempo-modifiedts` / `data-tempo-html-modifiedts` among\n * a walked fiber tree's annotated props, across BOTH namespaces, plus the\n * `data-tempo-source-version` / `data-tempo-html-source-version` token\n * co-located with each file's newest (MAX-mtime) node. Keys are the raw\n * stamped filepath spellings (consumers canonicalize on read), mirroring\n * `computeDeclaredFacts` on the DOM side.\n */\nexport function computeObservedVersionsFromFiber<\n T extends EnrichedFiberConstraint,\n>(tree: T): FiberObservedVersions {\n const observedVersions: Record<string, number> = {};\n const observedSourceVersions: Record<string, string> = {};\n\n const record = (\n filepath: unknown,\n modifiedTsRaw: unknown,\n sourceVersionRaw: unknown,\n ): void => {\n if (typeof filepath !== \"string\" || filepath.length === 0) return;\n const modifiedTs =\n typeof modifiedTsRaw === \"number\"\n ? modifiedTsRaw\n : typeof modifiedTsRaw === \"string\"\n ? Number(modifiedTsRaw)\n : NaN;\n if (Number.isNaN(modifiedTs)) return;\n const existing = observedVersions[filepath];\n if (existing === undefined || modifiedTs > existing) {\n observedVersions[filepath] = modifiedTs;\n // The token rides the file's newest render — same co-location rule the\n // DOM-side walker uses. A newest node without a token clears any stale\n // token from an older render (old-SDK / mid-HMR mixed tree).\n if (typeof sourceVersionRaw === \"string\" && sourceVersionRaw.length > 0) {\n observedSourceVersions[filepath] = sourceVersionRaw;\n } else {\n delete observedSourceVersions[filepath];\n }\n }\n };\n\n const visit = (node: EnrichedFiberConstraint): void => {\n const props = node.props;\n record(\n props?.[\"data-tempo-filepath\"],\n props?.[\"data-tempo-modifiedts\"],\n props?.[\"data-tempo-source-version\"],\n );\n record(\n props?.[\"data-tempo-html-filepath\"],\n props?.[\"data-tempo-html-modifiedts\"],\n props?.[\"data-tempo-html-source-version\"],\n );\n for (const child of node.children) {\n visit(child as EnrichedFiberConstraint);\n }\n };\n\n visit(tree);\n return { observedVersions, observedSourceVersions };\n}\n\n/** Build the completeness facts shared by standing and one-shot captures.\n * `undefined` means the fiber arm was not sampled; `null` means it was sampled\n * and no root existed. Static DOM is authoritative only for a full HTML scope\n * in a document where React never registered a renderer. */\nexport function computeRenderDeclarations<T extends EnrichedFiberConstraint>(\n fiber: T | null | undefined,\n html: DomCapture | undefined,\n hasReactRenderer: boolean,\n document?: Document | null,\n identityScope?: RenderDeclarationScope,\n): Pick<\n CombinedCapture<T>,\n \"fiberDeclared\" | \"renderDeclared\" | \"renderIdentity\"\n> {\n const domIdentity = identityScope\n ? declareDomHostIdentity(\n identityScope.captureRoot,\n identityScope.supplementalRoots,\n )\n : undefined;\n const fiberIdentity = fiber ? declareFiberHostIdentity(fiber) : undefined;\n const identityMatching =\n domIdentity && fiberIdentity\n ? hostIdentityDeclarationsMatch(domIdentity, fiberIdentity)\n : undefined;\n return {\n ...(fiber !== undefined && {\n fiberDeclared: fiber\n ? {\n complete: true as const,\n ...(document && {\n domConsistent:\n identityMatching ??\n fiberHostIdentitiesAreLive(fiber, document),\n }),\n ...(fiberIdentity && { hostIdentity: fiberIdentity }),\n ...computeObservedVersionsFromFiber(fiber),\n }\n : null,\n }),\n ...(fiber\n ? { renderDeclared: { complete: true, kind: \"fiber\" } as const }\n : (identityScope?.renderMode === \"static-dom\" || !hasReactRenderer) &&\n html?.declared.complete === true\n ? {\n renderDeclared: {\n complete: true,\n kind: \"static-dom\",\n } as const,\n }\n : {}),\n ...(domIdentity && {\n renderIdentity: {\n dom: domIdentity,\n ...(fiberIdentity && { fiber: fiberIdentity }),\n ...(identityMatching !== undefined && {\n matching: identityMatching,\n }),\n },\n }),\n };\n}\n\n/** A React commit can leave `FiberRoot.current` describing host nodes that\n * have already been detached. A fiber arm is visible proof only when every\n * host identity it serialized still exists in the producer's live document. */\nexport function fiberHostIdentitiesAreLive<T extends EnrichedFiberConstraint>(\n fiber: T,\n document: Document,\n): boolean {\n const liveDomIds = new Set(\n Array.from(document.querySelectorAll<HTMLElement>(\"[data-dom-id]\"))\n .filter((element) => element.isConnected)\n .map((element) => element.getAttribute(\"data-dom-id\"))\n .filter((domId): domId is string => domId !== null),\n );\n const seenFiberDomIds = new Set<string>();\n const visit = (node: EnrichedFiberConstraint): boolean => {\n if (node.domId) {\n if (seenFiberDomIds.has(node.domId) || !liveDomIds.has(node.domId)) {\n return false;\n }\n seenFiberDomIds.add(node.domId);\n }\n return node.children.every((child) =>\n visit(child as EnrichedFiberConstraint),\n );\n };\n return visit(fiber);\n}\n","/**\n * Layout Kind\n *\n * Classifies a DOM element's container layout based on its computed styles,\n * and provides matching SVG icon markup for each kind.\n *\n * The four kinds mirror the \"draw\" tools in a typical design canvas:\n * - grid → display: grid\n * - row → flex stacking children vertically (flex-direction: column)\n * - column → flex stacking children horizontally (flex-direction: row)\n * - div → any other element that still counts as a layout parent\n * (position: relative|sticky|absolute)\n *\n * Plain statically positioned non-flex/non-grid elements are NOT layout\n * parents — drawing a child into them has no meaningful placement behavior,\n * so they return null.\n *\n * Naming follows the stacking metaphor: a \"row\" is one of a set of rows stacked\n * vertically, and a \"column\" is one of a set of columns placed side-by-side.\n */\n\nexport type ElementLayoutKind = \"row\" | \"column\" | \"grid\" | \"div\";\n\nexport function getElementLayoutKind(\n el: Element,\n style: CSSStyleDeclaration = getComputedStyle(el),\n): ElementLayoutKind | null {\n if (/grid/.test(style.display)) return \"grid\";\n if (/flex/.test(style.display)) {\n return /^column/.test(style.flexDirection) ? \"row\" : \"column\";\n }\n if (\n style.position === \"relative\" ||\n style.position === \"sticky\" ||\n style.position === \"absolute\"\n ) {\n return \"div\";\n }\n return null;\n}\n\n/** Static 12×12 SVG markup for each layout kind, stroked with `currentColor`\n * so the pill's text color drives the icon color. Shapes mirror the canvas\n * draw-tool icons (div / row / column / grid) — a filled rectangle split\n * into one, two stacked, two side-by-side, or four quadrants. */\nexport const LAYOUT_KIND_SVG: Record<ElementLayoutKind, string> = {\n div:\n '<svg width=\"12\" height=\"12\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">' +\n '<rect x=\"1.5\" y=\"1.5\" width=\"13\" height=\"13\" rx=\"3\" stroke=\"currentColor\"/>' +\n \"</svg>\",\n row:\n '<svg width=\"12\" height=\"12\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">' +\n '<rect x=\"1.5\" y=\"1.5\" width=\"13\" height=\"5.75\" rx=\"2\" stroke=\"currentColor\"/>' +\n '<rect x=\"1.5\" y=\"8.75\" width=\"13\" height=\"5.75\" rx=\"2\" stroke=\"currentColor\"/>' +\n \"</svg>\",\n column:\n '<svg width=\"12\" height=\"12\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">' +\n '<rect x=\"1.5\" y=\"1.5\" width=\"5.75\" height=\"13\" rx=\"2\" stroke=\"currentColor\"/>' +\n '<rect x=\"8.75\" y=\"1.5\" width=\"5.75\" height=\"13\" rx=\"2\" stroke=\"currentColor\"/>' +\n \"</svg>\",\n grid:\n '<svg width=\"12\" height=\"12\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">' +\n '<rect x=\"1.5\" y=\"1.5\" width=\"5.75\" height=\"5.75\" rx=\"1.5\" stroke=\"currentColor\"/>' +\n '<rect x=\"8.75\" y=\"1.5\" width=\"5.75\" height=\"5.75\" rx=\"1.5\" stroke=\"currentColor\"/>' +\n '<rect x=\"1.5\" y=\"8.75\" width=\"5.75\" height=\"5.75\" rx=\"1.5\" stroke=\"currentColor\"/>' +\n '<rect x=\"8.75\" y=\"8.75\" width=\"5.75\" height=\"5.75\" rx=\"1.5\" stroke=\"currentColor\"/>' +\n \"</svg>\",\n};\n","/**\n * Enriched Fiber Serializer\n *\n * Extends the default serializer with domId extraction from HostComponent\n * fibers and sanitized props from all component fibers.\n *\n * The domId comes from the `data-dom-id` attribute that the HTML watcher's\n * MutationObserver assigns to all DOM elements. By the time the debounce\n * fires and captureTree calls this serializer, the MutationObserver has\n * already assigned IDs (MutationObserver fires as microtask, debounce fires\n * as macrotask via setTimeout).\n */\n\nimport { getElementLayoutKind } from \"../../element-overlay/render/layout-kind\";\nimport { countCaptureStyleRead } from \"../shared/capture-perf\";\nimport type { SerializeFn } from \"../fiber/types\";\nimport type { Fiber } from \"../fiber/react-types\";\nimport type { EnrichedFiberNode } from \"./types\";\nimport {\n getDisplayName,\n getTag,\n getDomElement,\n sanitizeProps,\n getProps,\n} from \"../fiber/serialize\";\nimport { DOM_ID_ATTR } from \"../html/watch-dom\";\n\nlet nextFiberId = 1;\nlet fiberIdMap = new WeakMap<Fiber, string>();\n\n/**\n * Returns a stable ID for a fiber across re-renders.\n * React alternates current/work-in-progress fibers, so both alternates share one ID.\n */\nexport function getFiberId(fiber: Fiber): string {\n let id = fiberIdMap.get(fiber);\n if (id) return id;\n\n if (fiber.alternate) {\n id = fiberIdMap.get(fiber.alternate);\n if (id) {\n fiberIdMap.set(fiber, id);\n return id;\n }\n }\n\n id = String(nextFiberId++);\n fiberIdMap.set(fiber, id);\n if (fiber.alternate) {\n fiberIdMap.set(fiber.alternate, id);\n }\n return id;\n}\n\n/**\n * Test-only state reset for deterministic fiberId assertions.\n */\nexport function _resetFiberIdStateForTesting(): void {\n nextFiberId = 1;\n fiberIdMap = new WeakMap<Fiber, string>();\n}\n\n/**\n * Default enriched serializer for the combined module.\n *\n * Produces nodes with name, tag, domId (for HostComponents), and sanitized props.\n *\n * @example\n * ```ts\n * // Extend with additional fields:\n * interface MyNode extends EnrichedFiberNode { key?: string; }\n * const mySerialize: SerializeFn<MyNode> = (fiber) => ({\n * ...enrichedSerialize(fiber),\n * key: fiber.key ?? undefined,\n * });\n * ```\n */\n/**\n * react-native-web View/Text host components carry Tempo's source annotations in\n * a `dataSet` object instead of flat `data-*` props — RNW only flattens\n * dataSet→data-* onto the host DOM node, so the component fiber still reports\n * `dataSet`. Lift the `tempo*` keys out to flat `data-tempo-*` here, at capture,\n * so every downstream consumer (source extraction, modifiedts tracking, layer\n * building) sees one uniform shape and never has to know about `dataSet`. User\n * dataSet keys are preserved.\n */\nfunction normalizeTempoDataSet(\n props: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n const dataSet = props?.dataSet;\n if (!props || !dataSet || typeof dataSet !== \"object\") return props;\n\n let extracted: Record<string, unknown> | null = null;\n let remaining: Record<string, unknown> | null = null;\n for (const [key, value] of Object.entries(\n dataSet as Record<string, unknown>,\n )) {\n if (key.startsWith(\"tempo\")) {\n // \"tempoFilepath\" -> \"data-tempo-filepath\" (matches RNW's hyphenation).\n (extracted ??= {})[\n `data-${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`\n ] = value;\n } else {\n (remaining ??= {})[key] = value;\n }\n }\n if (!extracted) return props;\n\n const out = { ...props, ...extracted };\n if (remaining) out.dataSet = remaining;\n else delete out.dataSet;\n return out;\n}\n\nexport const enrichedSerialize: SerializeFn<EnrichedFiberNode> = (fiber) => {\n const domElement = getDomElement(fiber);\n return {\n fiberId: getFiberId(fiber),\n name: getDisplayName(fiber),\n tag: getTag(fiber),\n ...(hasContextDependencies(fiber) && { hasContextDependencies: true }),\n ...(domElement && {\n domId: domElement.getAttribute(DOM_ID_ATTR) ?? undefined,\n ...(hasContentEditableAncestor(domElement) && {\n insideContentEditable: true,\n }),\n layoutKind: layoutKindWithCountedStyleRead(domElement),\n }),\n props: normalizeTempoDataSet(sanitizeProps(getProps(fiber))),\n };\n};\n\n/** getElementLayoutKind's default style parameter is one getComputedStyle\n * call per host element — counted as a capture-path style read. */\nfunction layoutKindWithCountedStyleRead(element: Element) {\n countCaptureStyleRead();\n return getElementLayoutKind(element) ?? undefined;\n}\n\nfunction hasContentEditableAncestor(element: Element): boolean {\n let current = element.parentElement;\n while (current) {\n if (current.getAttribute(\"contenteditable\") !== null) return true;\n current = current.parentElement;\n }\n return false;\n}\n\nfunction hasContextDependencies(fiber: Fiber): boolean {\n const dependencies = fiber.dependencies;\n if (!dependencies || typeof dependencies !== \"object\") {\n return false;\n }\n\n return Boolean(\n (dependencies as { firstContext?: unknown }).firstContext,\n );\n}\n","import type { FiberRoot } from \"../fiber/react-types\";\nimport { serializeTree } from \"../fiber/serialize\";\nimport type { FiberTagValue, SerializeFn } from \"../fiber/types\";\nimport { captureTree, getCommittedFiberRoots } from \"../fiber/watch\";\nimport type { EnrichedFiberConstraint } from \"./types\";\n\nconst shouldHideFiberNode = (\n node: { props?: Record<string, unknown> },\n hideFiberProp: string | undefined,\n): boolean => {\n if (!hideFiberProp) {\n return false;\n }\n\n const value = node.props?.[hideFiberProp];\n return value === true || value === \"true\";\n};\n\nconst filterHiddenFiberNode = <T extends EnrichedFiberConstraint>(\n node: T,\n hideFiberProp: string,\n): T[] => {\n const children = node.children.flatMap((child) =>\n filterHiddenFiberNode(child as T, hideFiberProp),\n );\n return shouldHideFiberNode(node, hideFiberProp)\n ? children\n : [{ ...node, children } as T];\n};\n\nexport const filterHiddenFiberTree = <T extends EnrichedFiberConstraint>(\n tree: T | null,\n hideFiberProp?: string,\n): T | null => {\n if (!tree || !hideFiberProp) {\n return tree;\n }\n\n return filterHiddenFiberNode(tree, hideFiberProp)[0] ?? null;\n};\n\nexport const captureCombinedFiberTree = <\n T extends EnrichedFiberConstraint,\n>(options: {\n serialize: SerializeFn<T>;\n selector?: string;\n /** DOM scope whose contained React roots make up one document-level render. */\n rootElement?: Element;\n tags?: FiberTagValue[];\n hideFiberProp?: string;\n}): T | null => {\n const rootElement = options.rootElement;\n if (options.selector || !rootElement) {\n const tree = captureTree<T>({\n serialize: options.serialize,\n selector: options.selector,\n tags: options.tags,\n });\n return filterHiddenFiberTree(tree, options.hideFiberProp);\n }\n\n const roots = getCommittedFiberRoots().filter((root) =>\n rootBelongsToElement(root, rootElement),\n );\n const firstRoot = roots[0];\n if (!firstRoot) return null;\n const trees = roots\n .flatMap((root) =>\n serializeRootBranches(root, options.serialize, options.tags),\n )\n .flatMap((tree) =>\n options.hideFiberProp\n ? filterHiddenFiberNode(tree, options.hideFiberProp)\n : [tree],\n );\n\n if (trees.length === 0) {\n return {\n ...options.serialize(firstRoot.current),\n domId: undefined,\n props: undefined,\n children: [],\n } as unknown as T;\n }\n if (trees.length === 1) return trees[0] ?? null;\n\n // CombinedCapture has one tree-shaped layers arm. Use a real serialized\n // HostRoot as its fragment-like aggregate and place each independent root\n // below it. Consumers therefore see every root without inventing an opaque\n // second wire shape or falsely declaring one root to be the whole document.\n return {\n ...options.serialize(firstRoot.current),\n fiberId: \"__tempo_document_fiber_roots__\",\n domId: undefined,\n props: undefined,\n children: trees,\n } as unknown as T;\n};\n\nfunction rootBelongsToElement(root: FiberRoot, element: Element): boolean {\n const container = root.containerInfo;\n return container === element || element.contains(container);\n}\n\nfunction serializeRootBranches<T extends EnrichedFiberConstraint>(\n root: FiberRoot,\n serialize: SerializeFn<T>,\n tags: FiberTagValue[] | undefined,\n): T[] {\n const tagSet = tags && tags.length > 0 ? new Set(tags) : null;\n const branches: T[] = [];\n for (let fiber = root.current.child; fiber; fiber = fiber.sibling) {\n const tree = serializeTree(fiber, serialize);\n if (!tree) continue;\n branches.push(...filterTreeBranches(tree, tagSet));\n }\n return branches;\n}\n\n/** Filter one serialized branch while preserving every promoted child. The\n * generic fiber utility returns a single tree and therefore cannot represent\n * an excluded Fragment/HostRoot with multiple included children. */\nfunction filterTreeBranches<T extends EnrichedFiberConstraint>(\n tree: T,\n tags: ReadonlySet<FiberTagValue> | null,\n): T[] {\n if (!tags || !(\"tag\" in tree)) return [tree];\n const children = tree.children.flatMap((child) =>\n filterTreeBranches(child as T, tags),\n );\n return tags.has((tree as T & { tag: FiberTagValue }).tag)\n ? [{ ...tree, children } as T]\n : children;\n}\n","/**\n * Identity of this JS realm (one document evaluation), stamped on every\n * emitted capture. A consumer seeing the epoch change across captures of the\n * same logical watch has OBSERVED a document replacement — the signal is\n * carried by the capture itself, so it survives watch re-creation, relay\n * coalescing, and frame discards that strip replay-time markers like\n * `producerReset`.\n */\nexport const REALM_DOCUMENT_EPOCH = `${Date.now().toString(36)}-${Math.random()\n .toString(36)\n .slice(2, 10)}`;\n\nlet nextCaptureSequence = 0;\n\n/** Monotonic across every combined watcher and one-shot capture in this realm.\n * Watch restarts must not reset ordering: a delayed capture from the retired\n * watcher can otherwise arrive after and overwrite newer visible pixels. */\nexport function nextRealmCaptureSequence(): number {\n return nextCaptureSequence++;\n}\n","/**\n * Reverse-skew adapter for pre-projection-batch interact frames.\n *\n * Current Tempo clients consume the document producer's closed, regional\n * ProjectionBatch stream directly. Deployed older clients still ask the\n * newest workspace SDK for `start-combined-watcher`, so this adapter uses the\n * document producer only as a change clock and materializes the old complete\n * CombinedCapture envelope at that one compatibility boundary.\n */\n\nimport type { FiberTagValue, SerializeFn } from \"../fiber/types\";\nimport { initHook } from \"../fiber/watch\";\nimport {\n captureProjectionSnapshot,\n collectProjectionPortalElements,\n} from \"../html/snapshot\";\nimport type { DomCapture } from \"../html/types\";\nimport {\n computeRenderDeclarations,\n createRenderDeclarationScope,\n} from \"./declared-facts\";\nimport {\n createCombinedDocumentProducer,\n type CombinedProjectionBatch,\n} from \"./document-producer\";\nimport { enrichedSerialize } from \"./enriched-serialize\";\nimport { captureCombinedFiberTree } from \"./hide-fiber-tree\";\nimport { nextRealmCaptureSequence, REALM_DOCUMENT_EPOCH } from \"./realm-epoch\";\nimport type {\n CombinedCapture,\n CombinedCaptureProvenance,\n CombinedWatchTrigger,\n EnrichedFiberConstraint,\n EnrichedFiberNode,\n} from \"./types\";\n\nconst LEGACY_FLUSH_WINDOW_MS = 50;\nlet nextLegacyWatchId = 1;\n\nexport interface CombinedWatchOptions<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n> {\n debounceDelay?: number;\n /** Retained on the old wire; the fixed document scheduler supersedes it. */\n maxWait?: number;\n serialize?: SerializeFn<T>;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n hideFiberProp?: string;\n}\n\nexport type ResumeFlushPolicy = \"if-dirty\" | \"always\" | \"never\";\n\nexport interface CombinedWatchResumeOptions {\n flush?: ResumeFlushPolicy;\n triggers?: readonly CombinedWatchTrigger[];\n}\n\nexport type CombinedWatchHandle = (() => void) & {\n stop: () => void;\n pause: () => void;\n resume: (options?: CombinedWatchResumeOptions) => void;\n setPaused: (paused: boolean, options?: CombinedWatchResumeOptions) => void;\n};\n\nfunction realmHasReactRenderer(\n element: Element,\n localHook: ReturnType<typeof initHook>,\n): boolean {\n const view = element.ownerDocument.defaultView as\n | (Window & {\n __REACT_DEVTOOLS_GLOBAL_HOOK__?: { renderers?: Map<unknown, unknown> };\n })\n | null;\n return view && view !== window\n ? (view.__REACT_DEVTOOLS_GLOBAL_HOOK__?.renderers?.size ?? 0) > 0\n : localHook.hook.renderers.size > 0;\n}\n\nfunction captureLegacyEnvelope<T extends EnrichedFiberConstraint>(\n element: Element,\n hook: ReturnType<typeof initHook>,\n options: CombinedWatchOptions<T>,\n provenance: CombinedCaptureProvenance,\n coordinateOnlyPortalIds: ReadonlySet<string>,\n): CombinedCapture<T> {\n const supplementalRoots = collectProjectionPortalElements(element);\n const html = withCoordinateOnlyPortals(\n captureProjectionSnapshot(element, supplementalRoots),\n coordinateOnlyPortalIds,\n );\n const fiber = captureCombinedFiberTree<T>({\n rootElement: element,\n selector: options.fiberSelector,\n tags: options.fiberTags,\n hideFiberProp: options.hideFiberProp,\n serialize:\n options.serialize ?? (enrichedSerialize as unknown as SerializeFn<T>),\n });\n return {\n html,\n fiber,\n ...computeRenderDeclarations(\n fiber,\n html,\n realmHasReactRenderer(element, hook),\n element.ownerDocument,\n createRenderDeclarationScope(element, supplementalRoots),\n ),\n provenance,\n documentEpoch: REALM_DOCUMENT_EPOCH,\n sequence: nextRealmCaptureSequence(),\n };\n}\n\nfunction triggersForBatch(\n batch: CombinedProjectionBatch,\n): CombinedWatchTrigger[] {\n const triggers = new Set<CombinedWatchTrigger>();\n if (batch.head !== undefined) triggers.add(\"head\");\n for (const change of batch.roots) {\n if (change.kind !== \"patch\") {\n triggers.add(\"dom\");\n triggers.add(\"fiber\");\n continue;\n }\n const patch = change.patch;\n if (patch.dom?.length || patch.annotations?.length) triggers.add(\"dom\");\n if (patch.state?.length) triggers.add(\"state\");\n for (const portal of patch.portals ?? []) {\n // A portal moved by new styling is the head's doing, and this envelope\n // reports it as one refreshed coordinate space, not as portal content.\n if (portal.kind === \"replace\" && portal.coordinatesOnly) continue;\n // A portal is an arm of the same Fiber tree this envelope re-serializes\n // whole, so its content always arrives with a current fiber.\n triggers.add(\"portal\");\n triggers.add(\"fiber\");\n }\n if (patch.layers) triggers.add(\"fiber\");\n }\n return triggers.size > 0 ? [...triggers] : [\"dom\", \"fiber\"];\n}\n\n/** Portal ids this batch refreshed coordinates for without resending their\n * bodies. The old envelope always re-serializes every portal, so those are\n * downgraded back to coordinate-only updates to keep the destination's focus\n * and edit state inside an unchanged portal. */\nfunction coordinateOnlyPortalIds(batch: CombinedProjectionBatch): Set<string> {\n const ids = new Set<string>();\n for (const change of batch.roots) {\n if (change.kind !== \"patch\") continue;\n for (const portal of change.patch.portals ?? []) {\n if (portal.kind === \"replace\" && portal.coordinatesOnly) {\n ids.add(portal.portalId);\n }\n }\n }\n return ids;\n}\n\nfunction withCoordinateOnlyPortals(\n capture: DomCapture,\n portalIds: ReadonlySet<string>,\n): DomCapture {\n if (portalIds.size === 0 || !capture.portals) return capture;\n return {\n ...capture,\n portals: capture.portals.map((portal) =>\n portalIds.has(portal.id)\n ? { ...portal, html: \"\", states: [], coordinatesOnly: true }\n : portal,\n ),\n };\n}\n\n/** @deprecated Retained only for old clients talking to a new interact frame. */\nexport function watchCombined<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n>(\n element: Element,\n onChange: (capture: CombinedCapture<T>) => void,\n options: CombinedWatchOptions<T> = {},\n): CombinedWatchHandle {\n const rootId = `legacy-combined-root-${nextLegacyWatchId++}`;\n const sessionId = `legacy-combined-session-${nextLegacyWatchId++}`;\n const hook = initHook();\n let stopped = false;\n let paused = false;\n let dirtyWhilePaused = false;\n let resumeTriggers: readonly CombinedWatchTrigger[] | undefined;\n\n const producer = createCombinedDocumentProducer<T>({\n document: element.ownerDocument,\n flushWindowMs: options.debounceDelay ?? LEGACY_FLUSH_WINDOW_MS,\n emit(batch) {\n if (stopped) return;\n if (paused) {\n dirtyWhilePaused = true;\n return;\n }\n const provenance: CombinedCaptureProvenance =\n batch.sequence === 0\n ? { kind: \"initial\" }\n : {\n kind: \"watch\",\n triggers: resumeTriggers\n ? [...resumeTriggers]\n : triggersForBatch(batch),\n };\n resumeTriggers = undefined;\n onChange(\n captureLegacyEnvelope(\n element,\n hook,\n options,\n provenance,\n coordinateOnlyPortalIds(batch),\n ),\n );\n },\n });\n producer.bindSession(sessionId);\n producer.watchRoot({ rootId, element, fiberSelector: options.fiberSelector });\n // Preserve the legacy API's synchronous initial emission while keeping the\n // document producer as the sole observer/scheduler owner.\n producer.requestFull(rootId);\n\n const stop = () => {\n if (stopped) return;\n stopped = true;\n producer.stop();\n };\n const pause = () => {\n if (stopped || paused) return;\n paused = true;\n // The producer may have retained observer records that have not reached\n // its fixed-window callback yet. Conservatively rebuild once on resume;\n // the old destination values correctness over compatibility-path work.\n dirtyWhilePaused = true;\n };\n const resume = (resumeOptions?: CombinedWatchResumeOptions) => {\n if (stopped || !paused) return;\n paused = false;\n const policy = resumeOptions?.flush ?? \"if-dirty\";\n const shouldFlush =\n policy === \"always\" || (policy === \"if-dirty\" && dirtyWhilePaused);\n dirtyWhilePaused = false;\n if (shouldFlush) {\n resumeTriggers = [\"dom\", ...(resumeOptions?.triggers ?? [])];\n producer.requestFull(rootId);\n }\n };\n const setPaused = (\n nextPaused: boolean,\n resumeOptions?: CombinedWatchResumeOptions,\n ) => (nextPaused ? pause() : resume(resumeOptions));\n\n return Object.assign(stop, { stop, pause, resume, setPaused });\n}\n\n/**\n * Selector lifecycle for the old interact command. HMR may replace the target\n * element without replacing the document, so the binding is re-resolved and\n * the replacement begins with one complete legacy envelope.\n */\nexport function watchCombinedSelector<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n>(\n root: Document | Element,\n selector: string | undefined,\n onChange: (capture: CombinedCapture<T>) => void,\n options: CombinedWatchOptions<T> = {},\n): CombinedWatchHandle {\n const documentRoot = root.nodeType === 9;\n let activeElement: Element | null = null;\n let activeWatcher: CombinedWatchHandle | null = null;\n let targetObserver: MutationObserver | null = null;\n let stopped = false;\n let paused = false;\n let dirtyWhilePaused = false;\n let hasBound = false;\n\n const getTarget = () =>\n selector\n ? root.querySelector(selector)\n : documentRoot\n ? (root as Document).body\n : (root as Element);\n const disconnect = () => {\n targetObserver?.disconnect();\n targetObserver = null;\n };\n const stopActive = () => {\n activeWatcher?.stop();\n activeWatcher = null;\n activeElement = null;\n };\n // Observe the selector scope, not only the target's current parent: Vite\n // HMR can replace both the target and its parent in one mutation. Every\n // reconcile disconnects first, so each path that keeps watching must re-arm.\n const armSelectorObserver = () => {\n if (!selector) return;\n targetObserver = new MutationObserver(reconcile);\n targetObserver.observe(root, { childList: true, subtree: true });\n };\n\n const reconcile = () => {\n if (stopped) return;\n const target = getTarget();\n if (\n activeElement &&\n (!activeElement.isConnected || activeElement !== target)\n ) {\n stopActive();\n dirtyWhilePaused = true;\n }\n disconnect();\n if (!target || paused) {\n if (!paused && selector) {\n targetObserver = new MutationObserver(reconcile);\n targetObserver.observe(root, {\n attributes: true,\n childList: true,\n subtree: true,\n });\n }\n return;\n }\n // Still watching the same target: nothing to rebind, but `disconnect()`\n // above dropped the selector observer, and every capture ends in a\n // reconcile — leaving it dropped blinds the watcher to the first target\n // swap after the first change.\n if (activeWatcher) {\n armSelectorObserver();\n return;\n }\n\n const rebind = hasBound;\n hasBound = true;\n activeElement = target;\n activeWatcher = watchCombined(\n target,\n (capture) => {\n if (!target.isConnected || target !== getTarget()) {\n reconcile();\n return;\n }\n onChange(\n rebind && capture.provenance?.kind === \"initial\"\n ? {\n ...capture,\n provenance: {\n kind: \"watch\",\n triggers: [\"selector-rebind\"],\n },\n }\n : capture,\n );\n queueMicrotask(reconcile);\n },\n options,\n );\n armSelectorObserver();\n };\n\n reconcile();\n const stop = () => {\n if (stopped) return;\n stopped = true;\n disconnect();\n stopActive();\n };\n const pause = () => {\n if (stopped || paused) return;\n paused = true;\n dirtyWhilePaused = true;\n disconnect();\n activeWatcher?.pause();\n };\n const resume = (resumeOptions?: CombinedWatchResumeOptions) => {\n if (stopped || !paused) return;\n paused = false;\n if (activeWatcher) {\n activeWatcher.resume(resumeOptions);\n dirtyWhilePaused = false;\n } else if (\n (resumeOptions?.flush ?? \"if-dirty\") === \"always\" ||\n dirtyWhilePaused\n ) {\n dirtyWhilePaused = false;\n reconcile();\n }\n queueMicrotask(reconcile);\n };\n const setPaused = (\n nextPaused: boolean,\n resumeOptions?: CombinedWatchResumeOptions,\n ) => (nextPaused ? pause() : resume(resumeOptions));\n return Object.assign(stop, { stop, pause, resume, setPaused });\n}\n","/**\n * Document Projection PostMessage Interface\n *\n * Provides one ordered ProjectionBatch stream carrying exact DOM, head, and\n * semantic-layer changes from a source iframe to its destination.\n *\n * ## Usage\n *\n * ### Source Side (in iframe)\n * ```ts\n * import { initHook } from '@modules/iframe-projection/fiber';\n * initHook(); // Before React loads\n *\n * import { startCombinedSourceInterface } from '@modules/iframe-projection/combined/postmessage';\n * startCombinedSourceInterface();\n * ```\n *\n * ### Dest Side (parent window)\n * ```ts\n * import { watchProjectionBatchesIframe } from '@modules/iframe-projection/combined/postmessage';\n *\n * const watcher = await watchProjectionBatchesIframe(iframe, {\n * sessionId: 'source-document-1',\n * rootId: 'storyboard-1',\n * selector: '#root',\n * onBatch: (batch) => destination.enqueue(batch),\n * });\n *\n * watcher.stop();\n * ```\n */\n\nimport type { FiberTagValue, SerializeFn } from \"../fiber/types\";\nimport {\n type CombinedDocumentProducer,\n type CombinedProjectionBatch,\n createCombinedDocumentProducer,\n} from \"./document-producer\";\nimport type { DetachSerializedFiber } from \"./enriched-to-serialized-fiber\";\nimport { decodeCombinedProjectionBatch } from \"./projection-batch\";\nimport {\n isProjectionRegionCapture,\n type ProjectionRegionCapture,\n} from \"./projection-full-snapshot\";\nimport { isProjectionSemanticSubtree } from \"./projection-semantic-subtree\";\nimport type {\n CombinedCapture,\n EnrichedFiberConstraint,\n EnrichedFiberNode,\n} from \"./types\";\nimport { type CombinedWatchHandle, watchCombinedSelector } from \"./watch\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Message Types\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Marker to identify our messages (shared across all iframe-projection protocols) */\nconst MESSAGE_MARKER = \"__iframeProjection\" as const;\n\ninterface BaseMessage {\n [MESSAGE_MARKER]: true;\n}\n\n// Handshake\ninterface CombinedSourceReadyMessage extends BaseMessage {\n type: \"combined-source-ready\";\n}\ninterface CombinedPingCommand extends BaseMessage {\n type: \"combined-ping\";\n}\ninterface CombinedPongResponse extends BaseMessage {\n type: \"combined-pong\";\n}\n\n// Watcher lifecycle\ninterface StartCombinedWatcherCommand extends BaseMessage {\n type: \"start-combined-watcher\";\n requestId: string;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n debounceDelay?: number;\n maxWait?: number;\n}\ninterface CombinedWatcherStartedResponse extends BaseMessage {\n type: \"combined-watcher-started\";\n requestId: string;\n watcherId: string;\n}\ninterface StopCombinedWatcherCommand extends BaseMessage {\n type: \"stop-combined-watcher\";\n watcherId: string;\n}\ninterface SetCombinedWatcherPausedCommand extends BaseMessage {\n type: \"set-combined-watcher-paused\";\n watcherId: string;\n paused: boolean;\n}\ninterface CombinedWatcherStoppedResponse extends BaseMessage {\n type: \"combined-watcher-stopped\";\n watcherId: string;\n}\n\n// Exact document projection lifecycle. The same command names are used by the\n// iframe and Electron page bridges; only their delivery mechanism differs.\ninterface StartProjectionWatcherCommand extends BaseMessage {\n type: \"start-projection-watcher\";\n requestId: string;\n sessionId: string;\n rootId: string;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n}\ninterface ProjectionWatcherStartedResponse extends BaseMessage {\n type: \"projection-watcher-started\";\n requestId: string;\n watcherId: string;\n}\ninterface RequestProjectionFullCommand extends BaseMessage {\n type: \"request-projection-full\";\n watcherId: string;\n}\ninterface CaptureProjectionSemanticSubtreeCommand extends BaseMessage {\n type: \"capture-projection-semantic-subtree\";\n requestId: string;\n watcherId: string;\n targetFiberId: string;\n}\ninterface ProjectionSemanticSubtreeResponse extends BaseMessage {\n type: \"projection-semantic-subtree-response\";\n requestId: string;\n subtree: DetachSerializedFiber | null;\n error?: string;\n}\ninterface CaptureProjectionRegionCommand extends BaseMessage {\n type: \"capture-projection-region\";\n requestId: string;\n watcherId: string;\n targetId: string;\n}\ninterface ProjectionRegionResponse extends BaseMessage {\n type: \"projection-region-response\";\n requestId: string;\n region: ProjectionRegionCapture | null;\n error?: string;\n}\ninterface StopProjectionWatcherCommand extends BaseMessage {\n type: \"stop-projection-watcher\";\n watcherId: string;\n}\ninterface CancelProjectionWatcherCommand extends BaseMessage {\n type: \"cancel-projection-watcher\";\n requestId: string;\n}\ninterface ProjectionWatcherStoppedResponse extends BaseMessage {\n type: \"projection-watcher-stopped\";\n watcherId: string;\n}\n\n// Data\ninterface CombinedUpdateMessage extends BaseMessage {\n type: \"combined-update\";\n watcherId: string;\n capture: CombinedCapture;\n}\ninterface ProjectionBatchUpdateMessage extends BaseMessage {\n type: \"projection-batch\";\n batch: CombinedProjectionBatch;\n}\n\n// Error\ninterface CombinedErrorMessage extends BaseMessage {\n type: \"combined-error\";\n error: string;\n requestId?: string;\n watcherId?: string;\n}\n\ntype CombinedMessage =\n | CombinedSourceReadyMessage\n | CombinedPingCommand\n | CombinedPongResponse\n | StartCombinedWatcherCommand\n | CombinedWatcherStartedResponse\n | StopCombinedWatcherCommand\n | SetCombinedWatcherPausedCommand\n | CombinedWatcherStoppedResponse\n | CombinedUpdateMessage\n | StartProjectionWatcherCommand\n | ProjectionWatcherStartedResponse\n | RequestProjectionFullCommand\n | CaptureProjectionSemanticSubtreeCommand\n | ProjectionSemanticSubtreeResponse\n | CaptureProjectionRegionCommand\n | ProjectionRegionResponse\n | StopProjectionWatcherCommand\n | CancelProjectionWatcherCommand\n | ProjectionWatcherStoppedResponse\n | ProjectionBatchUpdateMessage\n | CombinedErrorMessage;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Type Guards\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction isMessage(data: unknown): data is CombinedMessage {\n return (\n typeof data === \"object\" &&\n data !== null &&\n MESSAGE_MARKER in data &&\n (data as any)[MESSAGE_MARKER] === true\n );\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Source Side (iframe)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Active watchers by ID */\nconst combinedWatchers = new Map<string, CombinedWatchHandle>();\n\nlet nextCombinedWatcherId = 1;\nlet combinedSourceInitialized = false;\nlet combinedSourceCleanup: (() => void) | null = null;\n\nfunction installWhenDocumentBodyReady(install: () => () => void): () => void {\n let cancelled = false;\n let installedCleanup: (() => void) | null = null;\n let animationFrameId: number | null = null;\n let listeningForDomReady = false;\n\n const init = () => {\n listeningForDomReady = false;\n animationFrameId = null;\n if (cancelled) return;\n if (document.body) {\n installedCleanup = install();\n return;\n }\n animationFrameId = requestAnimationFrame(init);\n };\n\n if (document.readyState === \"loading\") {\n listeningForDomReady = true;\n document.addEventListener(\"DOMContentLoaded\", init);\n } else {\n init();\n }\n\n return () => {\n if (cancelled) return;\n cancelled = true;\n if (listeningForDomReady) {\n document.removeEventListener(\"DOMContentLoaded\", init);\n listeningForDomReady = false;\n }\n if (animationFrameId !== null) {\n cancelAnimationFrame(animationFrameId);\n animationFrameId = null;\n }\n installedCleanup?.();\n installedCleanup = null;\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\ntype ProjectionSourceEventType =\n | \"projection-watcher-started\"\n | \"projection-watcher-stopped\"\n | \"projection-batch\"\n | \"projection-semantic-subtree-response\"\n | \"projection-region-response\"\n | \"error\";\n\ninterface ProjectionSourceController {\n /** Returns true when the payload belongs to the exact projection protocol. */\n handleCommand(payload: unknown): boolean;\n stop(): void;\n}\n\n/**\n * Source-side ownership shared by postMessage iframes and Electron pages.\n * There is one producer per live source document; the transports only forward\n * its closed ProjectionBatch DTO and lifecycle commands.\n */\nfunction createProjectionSourceController<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n>(options: {\n document: Document;\n watcherIdPrefix: string;\n serialize?: SerializeFn<T>;\n hideFiberProp?: string;\n send(type: ProjectionSourceEventType, payload: Record<string, unknown>): void;\n}): ProjectionSourceController {\n type WatcherRegistration = {\n readonly rootId: string;\n readonly sessionId: string;\n readonly requestId: string;\n };\n\n const watchers = new Map<string, WatcherRegistration>();\n const pendingBatches: CombinedProjectionBatch[] = [];\n let nextWatcherId = 1;\n let producer: CombinedDocumentProducer<T> | null = null;\n let sessionId: string | null = null;\n let watchesEstablishing = 0;\n let stopped = false;\n\n const sendError = (\n error: unknown,\n scope: { requestId?: string; watcherId?: string } = {},\n ): void => {\n options.send(\"error\", {\n ...scope,\n error: error instanceof Error ? error.message : String(error),\n });\n };\n\n const publishBatch = (batch: CombinedProjectionBatch): void => {\n if (stopped) return;\n // A newly registered root can request an immediate full after sequence\n // zero. Keep acknowledgement ahead of any batch that registration causes.\n if (watchesEstablishing > 0) {\n pendingBatches.push(batch);\n return;\n }\n options.send(\"projection-batch\", { batch });\n };\n\n const flushPendingBatches = (): void => {\n if (stopped || watchesEstablishing > 0) return;\n for (const batch of pendingBatches.splice(0)) {\n options.send(\"projection-batch\", { batch });\n }\n };\n\n const getProducer = (\n requestedSessionId: string,\n ): CombinedDocumentProducer<T> => {\n if (sessionId !== null && sessionId !== requestedSessionId) {\n if (watchers.size > 0) {\n throw new Error(\n \"A source document cannot bind two projection sessions at once\",\n );\n }\n producer?.stop();\n producer = null;\n sessionId = null;\n pendingBatches.length = 0;\n }\n producer ??= createCombinedDocumentProducer<T>({\n document: options.document,\n emit: publishBatch,\n onError: (error) => sendError(error),\n });\n return producer;\n };\n\n const stopWatcher = (watcherId: string): void => {\n const registration = watchers.get(watcherId);\n if (!registration) return;\n producer?.unwatchRoot(registration.rootId);\n watchers.delete(watcherId);\n if (watchers.size === 0) {\n // An iframe or pooled page can remain alive after its destination\n // detaches. No observer, React subscription, or timer survives idle.\n producer?.stop();\n producer = null;\n sessionId = null;\n pendingBatches.length = 0;\n }\n options.send(\"projection-watcher-stopped\", { watcherId });\n };\n\n return {\n handleCommand(payload) {\n if (stopped || !isRecord(payload) || typeof payload.type !== \"string\") {\n return false;\n }\n\n if (payload.type === \"start-projection-watcher\") {\n const requestId =\n typeof payload.requestId === \"string\" ? payload.requestId : undefined;\n const requestedSessionId =\n typeof payload.sessionId === \"string\" ? payload.sessionId.trim() : \"\";\n const rootId =\n typeof payload.rootId === \"string\" ? payload.rootId.trim() : \"\";\n if (!requestId || !requestedSessionId || !rootId) {\n sendError(\n new Error(\n \"Exact projection watch requires requestId, sessionId, and rootId\",\n ),\n requestId ? { requestId } : {},\n );\n return true;\n }\n\n const selector =\n typeof payload.selector === \"string\" ? payload.selector : undefined;\n const fiberSelector =\n typeof payload.fiberSelector === \"string\"\n ? payload.fiberSelector\n : undefined;\n const fiberTags = Array.isArray(payload.fiberTags)\n ? (payload.fiberTags as FiberTagValue[])\n : undefined;\n const watcherId = `${options.watcherIdPrefix}-${nextWatcherId++}`;\n watchesEstablishing += 1;\n let watched = false;\n try {\n const element = selector\n ? options.document.querySelector(selector)\n : options.document.body;\n if (!element) {\n throw new Error(`Element not found: ${selector ?? \"body\"}`);\n }\n const activeProducer = getProducer(requestedSessionId);\n activeProducer.watchRoot({\n rootId,\n element,\n serialize: options.serialize,\n fiberSelector,\n fiberTags,\n hideFiberProp: options.hideFiberProp,\n });\n watched = true;\n if (sessionId !== requestedSessionId) {\n activeProducer.bindSession(requestedSessionId);\n sessionId = requestedSessionId;\n }\n watchers.set(watcherId, {\n rootId,\n sessionId: requestedSessionId,\n requestId,\n });\n options.send(\"projection-watcher-started\", {\n requestId,\n watcherId,\n });\n } catch (error) {\n if (watched) producer?.unwatchRoot(rootId);\n sendError(error, { requestId });\n } finally {\n watchesEstablishing -= 1;\n flushPendingBatches();\n }\n return true;\n }\n\n if (payload.type === \"request-projection-full\") {\n const watcherId =\n typeof payload.watcherId === \"string\" ? payload.watcherId : undefined;\n const registration = watcherId ? watchers.get(watcherId) : undefined;\n if (!registration || registration.sessionId !== sessionId) {\n if (watcherId) {\n sendError(new Error(\"Projection watcher is not active\"), {\n watcherId,\n });\n }\n return true;\n }\n producer?.requestFull(registration.rootId);\n return true;\n }\n\n if (payload.type === \"capture-projection-semantic-subtree\") {\n const requestId =\n typeof payload.requestId === \"string\" ? payload.requestId : undefined;\n const watcherId =\n typeof payload.watcherId === \"string\" ? payload.watcherId : undefined;\n const targetFiberId =\n typeof payload.targetFiberId === \"string\"\n ? payload.targetFiberId.trim()\n : \"\";\n const registration = watcherId ? watchers.get(watcherId) : undefined;\n if (!requestId || !registration || !targetFiberId) {\n if (requestId) {\n options.send(\"projection-semantic-subtree-response\", {\n requestId,\n subtree: null,\n error:\n \"Semantic subtree capture requires an active watcher and targetFiberId\",\n });\n }\n return true;\n }\n try {\n const subtree = producer?.captureSemanticSubtree(\n registration.rootId,\n targetFiberId,\n );\n options.send(\"projection-semantic-subtree-response\", {\n requestId,\n subtree: subtree ?? null,\n });\n } catch (error) {\n options.send(\"projection-semantic-subtree-response\", {\n requestId,\n subtree: null,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n return true;\n }\n\n if (payload.type === \"capture-projection-region\") {\n const requestId =\n typeof payload.requestId === \"string\" ? payload.requestId : undefined;\n const watcherId =\n typeof payload.watcherId === \"string\" ? payload.watcherId : undefined;\n const targetId =\n typeof payload.targetId === \"string\" ? payload.targetId.trim() : \"\";\n const registration = watcherId ? watchers.get(watcherId) : undefined;\n if (!requestId || !registration || !targetId) {\n if (requestId) {\n options.send(\"projection-region-response\", {\n requestId,\n region: null,\n error:\n \"Region capture requires an active watcher and targetId\",\n });\n }\n return true;\n }\n try {\n const region = producer?.captureRegion(\n registration.rootId,\n targetId,\n );\n options.send(\"projection-region-response\", {\n requestId,\n region: region ?? null,\n });\n } catch (error) {\n options.send(\"projection-region-response\", {\n requestId,\n region: null,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n return true;\n }\n\n if (payload.type === \"stop-projection-watcher\") {\n const watcherId =\n typeof payload.watcherId === \"string\" ? payload.watcherId : undefined;\n if (watcherId) stopWatcher(watcherId);\n return true;\n }\n\n if (payload.type === \"cancel-projection-watcher\") {\n const requestId =\n typeof payload.requestId === \"string\" ? payload.requestId : undefined;\n if (!requestId) return true;\n const entry = Array.from(watchers).find(\n ([, registration]) => registration.requestId === requestId,\n );\n if (entry) stopWatcher(entry[0]);\n return true;\n }\n\n return false;\n },\n stop() {\n if (stopped) return;\n stopped = true;\n producer?.stop();\n producer = null;\n sessionId = null;\n watchers.clear();\n pendingBatches.length = 0;\n },\n };\n}\n\nexport interface CombinedSourceOptions<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n> {\n targetOrigin?: string;\n /** Custom fiber serializer used for all watchers started via postMessage */\n serialize?: SerializeFn<T>;\n /** Hide fibers whose serialized props contain this truthy prop */\n hideFiberProp?: string;\n}\n\n/**\n * Starts the combined source-side postMessage interface.\n *\n * IMPORTANT: Call initHook() BEFORE React loads, then call this after DOM is ready.\n *\n * @param options - Source options\n * @returns Cleanup function\n */\nexport function startCombinedSourceInterface<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n>(options: CombinedSourceOptions<T> = {}): () => void {\n const { targetOrigin = \"*\", serialize, hideFiberProp } = options;\n\n if (combinedSourceInitialized) {\n console.warn(\"[combined-postmessage:source] Already initialized\");\n return combinedSourceCleanup || (() => {});\n }\n\n if (typeof window === \"undefined\" || window.parent === window) {\n console.log(\"[combined-postmessage:source] Not in iframe, skipping\");\n return () => {};\n }\n\n combinedSourceInitialized = true;\n let disposeDeferredInstall = () => {};\n let disposed = false;\n const cleanup = () => {\n if (disposed) return;\n disposed = true;\n disposeDeferredInstall();\n if (combinedSourceCleanup === cleanup) {\n combinedSourceCleanup = null;\n combinedSourceInitialized = false;\n }\n };\n combinedSourceCleanup = cleanup;\n const deferredInstall = installWhenDocumentBodyReady(() =>\n initCombinedSourceInterface(targetOrigin, serialize, hideFiberProp),\n );\n if (disposed) deferredInstall();\n else disposeDeferredInstall = deferredInstall;\n return cleanup;\n}\n\nfunction initCombinedSourceInterface<T extends EnrichedFiberConstraint>(\n targetOrigin: string,\n serialize?: SerializeFn<T>,\n hideFiberProp?: string,\n): () => void {\n (window as any).__IFRAME_PROJECTION_COMBINED_INTERFACE_ACTIVE__ = true;\n\n const send = (msg: CombinedMessage) => {\n window.parent.postMessage({ ...msg, [MESSAGE_MARKER]: true }, targetOrigin);\n };\n const projectionSource = createProjectionSourceController<T>({\n document,\n watcherIdPrefix: \"iframe-projection-watcher\",\n serialize,\n hideFiberProp,\n send(type, payload) {\n if (type === \"error\") {\n send({\n type: \"combined-error\",\n [MESSAGE_MARKER]: true,\n ...(payload as Omit<\n CombinedErrorMessage,\n typeof MESSAGE_MARKER | \"type\"\n >),\n });\n return;\n }\n send({\n type,\n [MESSAGE_MARKER]: true,\n ...payload,\n } as CombinedMessage);\n },\n });\n\n const handleMessage = (event: MessageEvent) => {\n const data = event.data;\n if (!isMessage(data)) return;\n if (projectionSource.handleCommand(data)) return;\n\n switch (data.type) {\n case \"combined-ping\":\n send({ type: \"combined-pong\", [MESSAGE_MARKER]: true });\n break;\n\n case \"start-combined-watcher\": {\n const {\n requestId,\n selector,\n fiberSelector,\n fiberTags,\n debounceDelay,\n maxWait,\n } = data;\n const watcherId = `combined-watcher-${nextCombinedWatcherId++}`;\n\n try {\n const pendingCaptures: CombinedCapture[] = [];\n let established = false;\n const watcher = watchCombinedSelector(\n document,\n selector,\n (capture) => {\n if (!established) {\n pendingCaptures.push(capture);\n return;\n }\n send({\n type: \"combined-update\",\n [MESSAGE_MARKER]: true,\n watcherId,\n capture,\n });\n },\n {\n debounceDelay,\n maxWait,\n ...(serialize && {\n serialize: serialize as unknown as SerializeFn<any>,\n }),\n fiberSelector,\n fiberTags,\n hideFiberProp,\n },\n );\n\n combinedWatchers.set(watcherId, watcher);\n send({\n type: \"combined-watcher-started\",\n [MESSAGE_MARKER]: true,\n requestId,\n watcherId,\n });\n established = true;\n for (const capture of pendingCaptures) {\n send({\n type: \"combined-update\",\n [MESSAGE_MARKER]: true,\n watcherId,\n capture,\n });\n }\n console.log(\n `[combined-postmessage:source] Started ${watcherId} on ${selector || \"body\"}`,\n );\n } catch (err) {\n send({\n type: \"combined-error\",\n [MESSAGE_MARKER]: true,\n requestId,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n break;\n }\n\n case \"stop-combined-watcher\": {\n const { watcherId } = data;\n const watcher = combinedWatchers.get(watcherId);\n\n if (watcher) {\n watcher.stop();\n combinedWatchers.delete(watcherId);\n send({\n type: \"combined-watcher-stopped\",\n [MESSAGE_MARKER]: true,\n watcherId,\n });\n console.log(`[combined-postmessage:source] Stopped ${watcherId}`);\n }\n break;\n }\n\n case \"set-combined-watcher-paused\": {\n const watcher = combinedWatchers.get(data.watcherId);\n watcher?.setPaused(data.paused);\n break;\n }\n }\n };\n\n window.addEventListener(\"message\", handleMessage);\n\n send({ type: \"combined-source-ready\", [MESSAGE_MARKER]: true });\n console.log(\n \"[combined-postmessage:source] Ready, sent combined-source-ready\",\n );\n\n return () => {\n window.removeEventListener(\"message\", handleMessage);\n projectionSource.stop();\n for (const [id, watcher] of combinedWatchers) {\n watcher.stop();\n console.log(`[combined-postmessage:source] Stopped ${id}`);\n }\n combinedWatchers.clear();\n delete (window as any).__IFRAME_PROJECTION_COMBINED_INTERFACE_ACTIVE__;\n console.log(\"[combined-postmessage:source] Cleaned up\");\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Deprecated CombinedCapture destination compatibility\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Handle for the pre-ProjectionBatch combined transport.\n *\n * @deprecated New projection consumers should use {@link ProjectionBatchWatcher}.\n * This remains an opt-in transport adapter for independent library consumers\n * and deployed destinations; it is not used by the Canvas hot path.\n */\nexport interface CombinedWatcher {\n id: string;\n stop: () => void;\n pause: () => void;\n resume: () => void;\n setPaused: (paused: boolean) => void;\n}\n\n/** @deprecated Use {@link WatchProjectionBatchesIframeOptions}. */\nexport interface WatchCombinedIframeOptions {\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n debounceDelay?: number;\n maxWait?: number;\n timeout?: number;\n targetOrigin?: string;\n onUpdate: (capture: CombinedCapture) => void;\n onError?: (error: Error) => void;\n}\n\n/** @deprecated Use {@link WatchProjectionBatchesPageOptions}. */\nexport interface WatchCombinedPageOptions {\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n debounceDelay?: number;\n maxWait?: number;\n timeout?: number;\n /** Cancels source-readiness and watcher establishment. */\n signal?: AbortSignal;\n onUpdate: (capture: CombinedCapture) => void;\n onError?: (error: Error) => void;\n}\n\n/**\n * Options for a cold, one-shot complete DOM + Fiber capture.\n *\n * @deprecated Exact live projection should use ProjectionBatch. This cold\n * query remains useful when a complete compatibility envelope is the result.\n */\nexport interface CaptureCombinedPageOptions {\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n timeout?: number;\n}\n\ntype LegacyCombinedChannelCommand =\n | { type: \"ping\" }\n | {\n type: \"start-watcher\";\n requestId: string;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n debounceDelay?: number;\n maxWait?: number;\n }\n | { type: \"set-watcher-paused\"; watcherId: string; paused: boolean }\n | { type: \"stop-watcher\"; watcherId: string }\n | {\n type: \"capture\";\n requestId: string;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n };\n\ntype LegacyCombinedChannelEvent =\n | { type: \"ready\" }\n | { type: \"watcher-started\"; requestId: string; watcherId: string }\n | { type: \"update\"; watcherId: string; capture: CombinedCapture }\n | {\n type: \"capture-response\";\n requestId: string;\n capture: CombinedCapture | null;\n }\n | {\n type: \"error\";\n error: string;\n requestId: unknown;\n watcherId: unknown;\n };\n\ninterface LegacyCombinedChannel {\n readonly readinessTimeoutMessage: string;\n nextWatcherRequestId(): string;\n nextCaptureRequestId(): string;\n send(command: LegacyCombinedChannelCommand): void;\n listen(listener: (event: LegacyCombinedChannelEvent) => void): () => void;\n}\n\nfunction normalizeLegacyCombinedChannelEvent(\n value: unknown,\n): LegacyCombinedChannelEvent | null {\n if (!isRecord(value) || typeof value.type !== \"string\") return null;\n switch (value.type) {\n case \"combined-source-ready\":\n case \"combined-pong\":\n case \"source-ready\":\n case \"pong\":\n return { type: \"ready\" };\n case \"combined-watcher-started\":\n case \"watcher-started\":\n return typeof value.requestId === \"string\" &&\n typeof value.watcherId === \"string\"\n ? {\n type: \"watcher-started\",\n requestId: value.requestId,\n watcherId: value.watcherId,\n }\n : null;\n case \"combined-update\":\n return typeof value.watcherId === \"string\" && isRecord(value.capture)\n ? {\n type: \"update\",\n watcherId: value.watcherId,\n capture: value.capture as unknown as CombinedCapture,\n }\n : null;\n case \"capture-response\":\n return typeof value.requestId === \"string\"\n ? {\n type: \"capture-response\",\n requestId: value.requestId,\n capture: isRecord(value.capture)\n ? (value.capture as unknown as CombinedCapture)\n : null,\n }\n : null;\n case \"combined-error\":\n case \"error\":\n return typeof value.error === \"string\"\n ? {\n type: \"error\",\n error: value.error,\n requestId: value.requestId,\n watcherId: value.watcherId,\n }\n : null;\n default:\n return null;\n }\n}\n\ntype ChannelResolution<T> =\n | { status: \"success\"; value: T }\n | { status: \"failure\"; error: Error }\n | undefined;\n\n/** The only thing a request/response wait needs of its transport. */\ninterface ListenableChannel<TEvent> {\n listen(listener: (event: TEvent) => void): () => void;\n}\n\n/**\n * Resolve one request against a channel: send, then settle on the first event\n * `receive` recognises. Without `retryInterval` the send happens once and\n * `timeout` bounds the wait; with it the send repeats until `timeout` elapses,\n * which is how a listener that may not exist yet is reached.\n *\n * The listener is registered before the first send so a synchronous reply\n * cannot be missed, and is removed on every exit path including one that\n * settles during registration.\n */\nfunction waitForChannelEvent<TEvent, T>(\n channel: ListenableChannel<TEvent>,\n options: {\n timeout: number;\n timeoutError: string;\n abortError: () => Error;\n signal?: AbortSignal;\n retryInterval?: number;\n send(): void;\n onAbort?: () => void;\n receive(event: TEvent): ChannelResolution<T>;\n },\n): Promise<T> {\n return new Promise((resolve, reject) => {\n if (options.signal?.aborted) {\n reject(options.abortError());\n return;\n }\n\n const startedAt = Date.now();\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let removeListener: (() => void) | null = null;\n let cleanupPending = false;\n\n const cleanup = (): void => {\n if (timer !== null) clearTimeout(timer);\n timer = null;\n options.signal?.removeEventListener(\"abort\", onAbort);\n if (removeListener) {\n bestEffort(removeListener);\n removeListener = null;\n } else {\n cleanupPending = true;\n }\n };\n const fail = (error: Error): void => {\n if (settled) return;\n settled = true;\n cleanup();\n reject(error);\n };\n const succeed = (value: T): void => {\n if (settled) return;\n settled = true;\n cleanup();\n resolve(value);\n };\n const onAbort = (): void => {\n bestEffort(() => options.onAbort?.());\n fail(options.abortError());\n };\n const receive = (event: TEvent): void => {\n if (settled) return;\n let resolution: ChannelResolution<T>;\n try {\n resolution = options.receive(event);\n } catch (error) {\n fail(errorFromUnknown(error));\n return;\n }\n if (resolution?.status === \"failure\") fail(resolution.error);\n else if (resolution?.status === \"success\") succeed(resolution.value);\n };\n\n options.signal?.addEventListener(\"abort\", onAbort, { once: true });\n try {\n const registeredListener = channel.listen(receive);\n if (cleanupPending) bestEffort(registeredListener);\n else removeListener = registeredListener;\n } catch (error) {\n fail(errorFromUnknown(error));\n return;\n }\n if (settled) return;\n\n const send = (): void => {\n if (settled) return;\n if (\n options.retryInterval !== undefined &&\n Date.now() - startedAt > options.timeout\n ) {\n fail(new Error(options.timeoutError));\n return;\n }\n try {\n options.send();\n } catch (error) {\n fail(errorFromUnknown(error));\n return;\n }\n if (!settled && options.retryInterval !== undefined) {\n timer = setTimeout(send, options.retryInterval);\n }\n };\n\n if (options.retryInterval === undefined) {\n timer = setTimeout(\n () => fail(new Error(options.timeoutError)),\n options.timeout,\n );\n }\n send();\n });\n}\n\nfunction waitForLegacyCombinedSourceReady(\n channel: LegacyCombinedChannel,\n timeout: number,\n signal?: AbortSignal,\n): Promise<void> {\n return waitForChannelEvent(channel, {\n timeout,\n signal,\n timeoutError: channel.readinessTimeoutMessage,\n abortError: combinedSetupAbortError,\n retryInterval: 100,\n send: () => channel.send({ type: \"ping\" }),\n receive: (event) =>\n event.type === \"ready\"\n ? { status: \"success\", value: undefined }\n : undefined,\n });\n}\n\nfunction requestLegacyCombinedWatcher(\n channel: LegacyCombinedChannel,\n options: Omit<\n Extract<LegacyCombinedChannelCommand, { type: \"start-watcher\" }>,\n \"type\" | \"requestId\"\n >,\n timeout: number,\n signal?: AbortSignal,\n): Promise<string> {\n const requestId = channel.nextWatcherRequestId();\n return waitForChannelEvent(channel, {\n timeout,\n signal,\n timeoutError: \"Timeout waiting for combined watcher to start\",\n abortError: combinedSetupAbortError,\n send: () => channel.send({ type: \"start-watcher\", requestId, ...options }),\n receive: (event) => {\n if (event.type === \"watcher-started\" && event.requestId === requestId) {\n return { status: \"success\", value: event.watcherId };\n }\n if (\n event.type === \"error\" &&\n (event.requestId === undefined || event.requestId === requestId)\n ) {\n return { status: \"failure\", error: new Error(event.error) };\n }\n return undefined;\n },\n });\n}\n\nasync function watchLegacyCombinedChannel(\n channel: LegacyCombinedChannel,\n options: {\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n debounceDelay?: number;\n maxWait?: number;\n timeout?: number;\n signal?: AbortSignal;\n onUpdate(capture: CombinedCapture): void;\n onError?(error: Error): void;\n },\n): Promise<CombinedWatcher> {\n const timeout = options.timeout ?? 10000;\n await waitForLegacyCombinedSourceReady(channel, timeout, options.signal);\n\n let stopped = false;\n let watcherId: string | null = null;\n const pendingUpdates = new Map<string, CombinedCapture[]>();\n const removeListener = channel.listen((event) => {\n if (stopped) return;\n if (event.type === \"update\") {\n if (watcherId === null) {\n const updates = pendingUpdates.get(event.watcherId) ?? [];\n updates.push(event.capture);\n pendingUpdates.set(event.watcherId, updates);\n } else if (event.watcherId === watcherId) {\n options.onUpdate(event.capture);\n }\n return;\n }\n if (\n watcherId !== null &&\n event.type === \"error\" &&\n (event.watcherId === undefined || event.watcherId === watcherId)\n ) {\n options.onError?.(new Error(event.error));\n }\n });\n\n try {\n watcherId = await requestLegacyCombinedWatcher(\n channel,\n {\n selector: options.selector,\n fiberSelector: options.fiberSelector,\n fiberTags: options.fiberTags,\n debounceDelay: options.debounceDelay,\n maxWait: options.maxWait,\n },\n timeout,\n options.signal,\n );\n } catch (error) {\n stopped = true;\n bestEffort(removeListener);\n throw error;\n }\n\n const activeWatcherId = watcherId;\n if (options.signal?.aborted) {\n stopped = true;\n bestEffort(removeListener);\n bestEffort(() =>\n channel.send({ type: \"stop-watcher\", watcherId: activeWatcherId }),\n );\n throw combinedSetupAbortError();\n }\n\n for (const capture of pendingUpdates.get(activeWatcherId) ?? []) {\n options.onUpdate(capture);\n }\n pendingUpdates.clear();\n\n const setPaused = (paused: boolean): void => {\n if (stopped) return;\n bestEffort(() =>\n channel.send({\n type: \"set-watcher-paused\",\n watcherId: activeWatcherId,\n paused,\n }),\n );\n };\n return {\n id: activeWatcherId,\n pause: () => setPaused(true),\n resume: () => setPaused(false),\n setPaused,\n stop() {\n if (stopped) return;\n stopped = true;\n bestEffort(removeListener);\n bestEffort(() =>\n channel.send({ type: \"stop-watcher\", watcherId: activeWatcherId }),\n );\n },\n };\n}\n\nasync function captureLegacyCombinedChannel(\n channel: LegacyCombinedChannel,\n options: CaptureCombinedPageOptions,\n): Promise<CombinedCapture | null> {\n const timeout = options.timeout ?? 10000;\n await waitForLegacyCombinedSourceReady(channel, timeout);\n const requestId = channel.nextCaptureRequestId();\n return waitForChannelEvent(channel, {\n timeout,\n timeoutError: \"Timeout waiting for combined capture response\",\n abortError: combinedSetupAbortError,\n send: () =>\n channel.send({\n type: \"capture\",\n requestId,\n selector: options.selector,\n fiberSelector: options.fiberSelector,\n fiberTags: options.fiberTags,\n }),\n receive: (event) => {\n if (event.type === \"capture-response\" && event.requestId === requestId) {\n return { status: \"success\", value: event.capture };\n }\n if (\n event.type === \"error\" &&\n (event.requestId === undefined || event.requestId === requestId)\n ) {\n return { status: \"failure\", error: new Error(event.error) };\n }\n return undefined;\n },\n });\n}\n\ntype ProjectionChannelCommand =\n | { type: \"ping\" }\n | {\n type: \"start-projection-watcher\";\n requestId: string;\n sessionId: string;\n rootId: string;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n }\n | { type: \"cancel-projection-watcher\"; requestId: string }\n | { type: \"request-projection-full\"; watcherId: string }\n | {\n type: \"capture-projection-semantic-subtree\";\n requestId: string;\n watcherId: string;\n targetFiberId: string;\n }\n | {\n type: \"capture-projection-region\";\n requestId: string;\n watcherId: string;\n targetId: string;\n }\n | { type: \"stop-projection-watcher\"; watcherId: string };\n\ntype ProjectionChannelEvent =\n | { type: \"ready\" }\n | { type: \"watcher-started\"; requestId: string; watcherId: string }\n | { type: \"batch\"; batch: unknown }\n | {\n type: \"semantic-subtree\";\n requestId: string;\n subtree: unknown;\n error?: string;\n }\n | {\n type: \"region\";\n requestId: string;\n region: unknown;\n error?: string;\n }\n | {\n type: \"error\";\n error: string;\n requestId: unknown;\n watcherId: unknown;\n };\n\ninterface ProjectionChannel {\n readonly readinessTimeoutMessage: string;\n nextWatcherRequestId(): string;\n send(command: ProjectionChannelCommand): void;\n listen(listener: (event: ProjectionChannelEvent) => void): () => void;\n}\n\ninterface ProjectionChannelWatchOptions {\n sessionId: string;\n rootId: string;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n timeout?: number;\n signal?: AbortSignal;\n onBatch(batch: CombinedProjectionBatch): void;\n onError?(error: Error): void;\n}\n\nfunction normalizeProjectionChannelEvent(\n value: unknown,\n): ProjectionChannelEvent | null {\n if (!isRecord(value) || typeof value.type !== \"string\") return null;\n switch (value.type) {\n case \"combined-source-ready\":\n case \"combined-pong\":\n case \"source-ready\":\n case \"pong\":\n return { type: \"ready\" };\n case \"projection-watcher-started\":\n return typeof value.requestId === \"string\" &&\n typeof value.watcherId === \"string\"\n ? {\n type: \"watcher-started\",\n requestId: value.requestId,\n watcherId: value.watcherId,\n }\n : null;\n case \"projection-batch\":\n return { type: \"batch\", batch: value.batch };\n case \"projection-semantic-subtree-response\":\n return typeof value.requestId === \"string\"\n ? {\n type: \"semantic-subtree\",\n requestId: value.requestId,\n subtree: value.subtree,\n error: typeof value.error === \"string\" ? value.error : undefined,\n }\n : null;\n case \"projection-region-response\":\n return typeof value.requestId === \"string\"\n ? {\n type: \"region\",\n requestId: value.requestId,\n region: value.region,\n error: typeof value.error === \"string\" ? value.error : undefined,\n }\n : null;\n case \"combined-error\":\n case \"error\":\n return typeof value.error === \"string\"\n ? {\n type: \"error\",\n error: value.error,\n requestId: value.requestId,\n watcherId: value.watcherId,\n }\n : null;\n default:\n return null;\n }\n}\n\nfunction errorFromUnknown(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\nfunction bestEffort(action: () => void): void {\n try {\n action();\n } catch {\n // Reload and destruction are normal transport teardown boundaries.\n }\n}\n\nasync function waitForProjectionChannelReady(\n channel: ProjectionChannel,\n timeout: number,\n signal?: AbortSignal,\n): Promise<void> {\n await waitForChannelEvent(channel, {\n signal,\n timeout,\n timeoutError: channel.readinessTimeoutMessage,\n abortError: combinedSetupAbortError,\n retryInterval: 100,\n send: () => channel.send({ type: \"ping\" }),\n receive: (event) =>\n event.type === \"ready\"\n ? { status: \"success\", value: undefined }\n : undefined,\n });\n}\n\nfunction requestProjectionChannelWatcher(\n channel: ProjectionChannel,\n options: {\n sessionId: string;\n rootId: string;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n },\n timeout: number,\n signal?: AbortSignal,\n): Promise<string> {\n const requestId = channel.nextWatcherRequestId();\n return waitForChannelEvent(channel, {\n signal,\n timeout,\n timeoutError: \"Timeout waiting for projection watcher to start\",\n abortError: combinedSetupAbortError,\n onAbort: () =>\n channel.send({ type: \"cancel-projection-watcher\", requestId }),\n send: () =>\n channel.send({\n type: \"start-projection-watcher\",\n requestId,\n ...options,\n }),\n receive: (event) => {\n if (event.type === \"watcher-started\" && event.requestId === requestId) {\n return { status: \"success\", value: event.watcherId };\n }\n if (\n event.type === \"error\" &&\n (event.requestId === undefined || event.requestId === requestId)\n ) {\n return { status: \"failure\", error: new Error(event.error) };\n }\n return undefined;\n },\n });\n}\n\nlet nextProjectionSemanticQueryRequestId = 1;\n\nfunction requestProjectionChannelSemanticSubtree(\n channel: ProjectionChannel,\n watcherId: string,\n targetFiberId: string,\n timeout: number,\n signal: AbortSignal,\n): Promise<DetachSerializedFiber | null> {\n const requestId = `projection-semantic-query-${nextProjectionSemanticQueryRequestId++}`;\n return waitForChannelEvent(channel, {\n signal,\n timeout,\n timeoutError: \"Timeout waiting for projection semantic subtree\",\n abortError: () => new Error(\"Projection semantic query was cancelled\"),\n send: () =>\n channel.send({\n type: \"capture-projection-semantic-subtree\",\n requestId,\n watcherId,\n targetFiberId,\n }),\n receive: (event) => {\n if (event.type !== \"semantic-subtree\" || event.requestId !== requestId) {\n return undefined;\n }\n if (event.error) {\n return { status: \"failure\", error: new Error(event.error) };\n }\n if (\n event.subtree !== null &&\n !isProjectionSemanticSubtree(event.subtree)\n ) {\n return {\n status: \"failure\",\n error: new Error(\n \"Projection source returned an invalid semantic subtree\",\n ),\n };\n }\n return { status: \"success\", value: event.subtree };\n },\n });\n}\n\nlet nextProjectionRegionQueryRequestId = 1;\n\nfunction requestProjectionChannelRegion(\n channel: ProjectionChannel,\n watcherId: string,\n targetId: string,\n timeout: number,\n signal: AbortSignal,\n): Promise<ProjectionRegionCapture | null> {\n const requestId = `projection-region-query-${nextProjectionRegionQueryRequestId++}`;\n return waitForChannelEvent(channel, {\n signal,\n timeout,\n timeoutError: \"Timeout waiting for projection region capture\",\n abortError: () => new Error(\"Projection region query was cancelled\"),\n send: () =>\n channel.send({\n type: \"capture-projection-region\",\n requestId,\n watcherId,\n targetId,\n }),\n receive: (event) => {\n if (event.type !== \"region\" || event.requestId !== requestId) {\n return undefined;\n }\n if (event.error) {\n return { status: \"failure\", error: new Error(event.error) };\n }\n if (event.region !== null && !isProjectionRegionCapture(event.region)) {\n return {\n status: \"failure\",\n error: new Error(\n \"Projection source returned an invalid region capture\",\n ),\n };\n }\n return { status: \"success\", value: event.region };\n },\n });\n}\n\nasync function watchProjectionChannel(\n channel: ProjectionChannel,\n options: ProjectionChannelWatchOptions,\n): Promise<ProjectionBatchWatcher> {\n const {\n sessionId,\n rootId,\n selector,\n fiberSelector,\n fiberTags,\n timeout = 10000,\n signal,\n onBatch,\n onError,\n } = options;\n const normalizedSessionId = sessionId.trim();\n const normalizedRootId = rootId.trim();\n if (!normalizedSessionId) {\n throw new Error(\"Projection session ID must not be empty\");\n }\n if (!normalizedRootId) {\n throw new Error(\"Projection root ID must not be empty\");\n }\n\n await waitForProjectionChannelReady(channel, timeout, signal);\n\n let stopped = false;\n let watcherId: string | null = null;\n const pendingBatches: CombinedProjectionBatch[] = [];\n const removeListener = channel.listen((event) => {\n if (stopped) return;\n if (event.type === \"batch\") {\n const batch = decodeCombinedProjectionBatch(event.batch);\n if (!batch || batch.sessionId !== normalizedSessionId) return;\n if (watcherId === null) pendingBatches.push(batch);\n else onBatch(batch);\n return;\n }\n if (\n watcherId !== null &&\n event.type === \"error\" &&\n (event.watcherId === undefined || event.watcherId === watcherId)\n ) {\n onError?.(new Error(event.error));\n }\n });\n\n try {\n watcherId = await requestProjectionChannelWatcher(\n channel,\n {\n sessionId: normalizedSessionId,\n rootId: normalizedRootId,\n selector,\n fiberSelector,\n fiberTags,\n },\n timeout,\n signal,\n );\n } catch (error) {\n stopped = true;\n bestEffort(removeListener);\n throw error;\n }\n\n const activeWatcherId = watcherId;\n if (signal?.aborted) {\n stopped = true;\n bestEffort(removeListener);\n bestEffort(() =>\n channel.send({\n type: \"stop-projection-watcher\",\n watcherId: activeWatcherId,\n }),\n );\n throw combinedSetupAbortError();\n }\n\n for (const batch of pendingBatches) onBatch(batch);\n pendingBatches.length = 0;\n // Every in-flight on-demand query (semantic subtree and region capture),\n // so stopping the watcher cancels them instead of leaving them to time out.\n const pendingQueryControllers = new Set<AbortController>();\n\n return {\n id: activeWatcherId,\n requestFull() {\n if (stopped) return;\n bestEffort(() =>\n channel.send({\n type: \"request-projection-full\",\n watcherId: activeWatcherId,\n }),\n );\n },\n captureSemanticSubtree(targetFiberId) {\n if (stopped) {\n return Promise.reject(new Error(\"Projection watcher has been stopped\"));\n }\n const normalizedTargetFiberId = targetFiberId.trim();\n if (!normalizedTargetFiberId) {\n return Promise.reject(\n new Error(\"Projection semantic target ID must not be empty\"),\n );\n }\n const controller = new AbortController();\n pendingQueryControllers.add(controller);\n return requestProjectionChannelSemanticSubtree(\n channel,\n activeWatcherId,\n normalizedTargetFiberId,\n timeout,\n controller.signal,\n ).finally(() => pendingQueryControllers.delete(controller));\n },\n captureRegion(targetId) {\n if (stopped) {\n return Promise.reject(new Error(\"Projection watcher has been stopped\"));\n }\n const normalizedTargetId = targetId.trim();\n if (!normalizedTargetId) {\n return Promise.reject(\n new Error(\"Projection region target ID must not be empty\"),\n );\n }\n const controller = new AbortController();\n pendingQueryControllers.add(controller);\n return requestProjectionChannelRegion(\n channel,\n activeWatcherId,\n normalizedTargetId,\n timeout,\n controller.signal,\n ).finally(() => pendingQueryControllers.delete(controller));\n },\n stop() {\n if (stopped) return;\n stopped = true;\n for (const controller of pendingQueryControllers) controller.abort();\n pendingQueryControllers.clear();\n bestEffort(removeListener);\n bestEffort(() =>\n channel.send({\n type: \"stop-projection-watcher\",\n watcherId: activeWatcherId,\n }),\n );\n },\n };\n}\n\nlet nextLegacyIframeWatcherRequestId = 1;\n\nfunction createIframeLegacyCombinedChannel(\n contentWindow: Window,\n targetOrigin: string,\n): LegacyCombinedChannel {\n return {\n readinessTimeoutMessage:\n \"Timeout waiting for combined iframe source - did you call startCombinedSourceInterface()?\",\n nextWatcherRequestId: () =>\n `combined-watch-req-${nextLegacyIframeWatcherRequestId++}`,\n nextCaptureRequestId: () => {\n throw new Error(\"The legacy iframe transport has no one-shot capture\");\n },\n send(command) {\n let wireCommand: Record<string, unknown>;\n switch (command.type) {\n case \"ping\":\n wireCommand = { type: \"combined-ping\" };\n break;\n case \"start-watcher\":\n wireCommand = { ...command, type: \"start-combined-watcher\" };\n break;\n case \"set-watcher-paused\":\n wireCommand = {\n ...command,\n type: \"set-combined-watcher-paused\",\n };\n break;\n case \"stop-watcher\":\n wireCommand = { ...command, type: \"stop-combined-watcher\" };\n break;\n case \"capture\":\n throw new Error(\n \"The legacy iframe transport has no one-shot capture\",\n );\n }\n contentWindow.postMessage(\n { ...wireCommand, [MESSAGE_MARKER]: true },\n targetOrigin,\n );\n },\n listen(listener) {\n const handleMessage = (event: MessageEvent): void => {\n if (event.source !== contentWindow || !isMessage(event.data)) return;\n const normalized = normalizeLegacyCombinedChannelEvent(event.data);\n if (normalized) listener(normalized);\n };\n window.addEventListener(\"message\", handleMessage);\n return () => window.removeEventListener(\"message\", handleMessage);\n },\n };\n}\n\n/**\n * Watch an iframe through the pre-ProjectionBatch complete-capture protocol.\n *\n * @deprecated Use {@link watchProjectionBatchesIframe}. This adapter is\n * intentionally isolated from the exact Canvas projection path.\n */\nexport function watchCombinedIframe(\n iframe: HTMLIFrameElement,\n options: WatchCombinedIframeOptions,\n): Promise<CombinedWatcher> {\n const contentWindow = iframe.contentWindow;\n if (!contentWindow) {\n return Promise.reject(new Error(\"Cannot access iframe contentWindow\"));\n }\n return watchLegacyCombinedChannel(\n createIframeLegacyCombinedChannel(\n contentWindow,\n options.targetOrigin ?? \"*\",\n ),\n options,\n );\n}\n\nlet nextProjectionIframeWatcherRequestId = 1;\n\nfunction createIframeProjectionChannel(\n contentWindow: Window,\n targetOrigin: string,\n): ProjectionChannel {\n return {\n readinessTimeoutMessage:\n \"Timeout waiting for combined iframe source - did you call startCombinedSourceInterface()?\",\n nextWatcherRequestId: () =>\n `projection-iframe-watch-${nextProjectionIframeWatcherRequestId++}`,\n send(command) {\n const wireCommand =\n command.type === \"ping\"\n ? { type: \"combined-ping\", [MESSAGE_MARKER]: true }\n : { ...command, [MESSAGE_MARKER]: true };\n contentWindow.postMessage(wireCommand, targetOrigin);\n },\n listen(listener) {\n const handleMessage = (event: MessageEvent): void => {\n if (event.source !== contentWindow || !isMessage(event.data)) return;\n const normalized = normalizeProjectionChannelEvent(event.data);\n if (normalized) listener(normalized);\n };\n window.addEventListener(\"message\", handleMessage);\n return () => window.removeEventListener(\"message\", handleMessage);\n },\n };\n}\n\n/**\n * Subscribe directly to the iframe document's ordered ProjectionBatch stream.\n * Source capture remains live during destination previews; the watcher exposes\n * only explicit full recovery and teardown, never source-side pause/resume.\n */\nexport function watchProjectionBatchesIframe(\n iframe: HTMLIFrameElement,\n options: WatchProjectionBatchesIframeOptions,\n): Promise<ProjectionBatchWatcher> {\n const contentWindow = iframe.contentWindow;\n if (!contentWindow) {\n return Promise.reject(new Error(\"Cannot access iframe contentWindow\"));\n }\n return watchProjectionChannel(\n createIframeProjectionChannel(contentWindow, options.targetOrigin ?? \"*\"),\n options,\n );\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Webview Support (Electron IPC instead of postMessage)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface PageMessageHandle {\n send: (channel: string, ...args: unknown[]) => void;\n on: (channel: string, callback: (...args: unknown[]) => void) => () => void;\n}\n\nexport interface CombinedWebviewBridge {\n sendToHost: (channel: string, payload: unknown) => void;\n onCommand: (handler: (payload: unknown) => void) => () => void;\n}\n\nexport interface CombinedWebviewSourceOptions<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n> {\n serialize?: SerializeFn<T>;\n hideFiberProp?: string;\n}\n\n/**\n * One exact document-projection subscription over the frame-pool page bridge.\n * Source observation remains current while destination-local preview queues\n * pause; the transport itself has no pause operation.\n */\nexport interface ProjectionBatchWatcher {\n readonly id: string;\n requestFull(): void;\n /** Cold source-side capture of exactly one selected semantic branch. */\n captureSemanticSubtree(\n targetFiberId: string,\n ): Promise<DetachSerializedFiber | null>;\n /** Cold scoped-repair capture of one element's exact children region; null\n * when the id no longer exists at the source. */\n captureRegion(targetId: string): Promise<ProjectionRegionCapture | null>;\n stop(): void;\n}\n\nexport interface WatchProjectionBatchesIframeOptions {\n /** Lifecycle-owned identity. A reloaded iframe receives a new session. */\n sessionId: string;\n /** Stable identity used by the Canvas destination to route root-local work. */\n rootId: string;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n timeout?: number;\n targetOrigin?: string;\n /** Cancels source-readiness and watcher establishment. */\n signal?: AbortSignal;\n onBatch(batch: CombinedProjectionBatch): void;\n onError?(error: Error): void;\n}\n\nexport interface WatchProjectionBatchesPageOptions {\n /** Lifecycle-owned identity. A reloaded document receives a new session. */\n sessionId: string;\n /** Stable identity used by the Canvas destination to route root-local work. */\n rootId: string;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n timeout?: number;\n /** Cancels source-readiness and watcher establishment. */\n signal?: AbortSignal;\n onBatch(batch: CombinedProjectionBatch): void;\n onError?(error: Error): void;\n}\n\nlet webviewCombinedSourceInitialized = false;\nlet webviewCombinedSourceCleanup: (() => void) | null = null;\n\nexport function startCombinedSourceWebviewInterface<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n>(\n bridge: CombinedWebviewBridge,\n options: CombinedWebviewSourceOptions<T> = {},\n): () => void {\n if (webviewCombinedSourceInitialized) {\n console.warn(\"[combined-postmessage:webview-source] Already initialized\");\n return webviewCombinedSourceCleanup || (() => {});\n }\n\n webviewCombinedSourceInitialized = true;\n let disposeDeferredInstall = () => {};\n let disposed = false;\n const cleanup = () => {\n if (disposed) return;\n disposed = true;\n disposeDeferredInstall();\n if (webviewCombinedSourceCleanup === cleanup) {\n webviewCombinedSourceCleanup = null;\n webviewCombinedSourceInitialized = false;\n }\n };\n webviewCombinedSourceCleanup = cleanup;\n const deferredInstall = installWhenDocumentBodyReady(() =>\n initCombinedWebviewSourceInterface(bridge, options),\n );\n if (disposed) deferredInstall();\n else disposeDeferredInstall = deferredInstall;\n return cleanup;\n}\n\nfunction initCombinedWebviewSourceInterface<T extends EnrichedFiberConstraint>(\n bridge: CombinedWebviewBridge,\n options: CombinedWebviewSourceOptions<T>,\n): () => void {\n (window as any).__IFRAME_PROJECTION_COMBINED_WEBVIEW_INTERFACE_ACTIVE__ =\n true;\n\n const send = (type: string, payload: Record<string, unknown>) => {\n bridge.sendToHost(\"combined-projection:update\", { type, ...payload });\n };\n\n const projectionSource = createProjectionSourceController<T>({\n document,\n watcherIdPrefix: \"webview-projection-watcher\",\n serialize: options.serialize,\n hideFiberProp: options.hideFiberProp,\n send,\n });\n const legacyWatchers = new Map<string, CombinedWatchHandle>();\n let nextLegacyWatcherId = 1;\n\n const handleCommand = (payload: unknown) => {\n if (!isRecord(payload) || typeof payload.type !== \"string\") {\n return;\n }\n if (projectionSource.handleCommand(payload)) return;\n\n switch (payload.type) {\n case \"ping\": {\n send(\"pong\", {});\n break;\n }\n\n // Deprecated compatibility commands are deliberately handled after the\n // exact projection controller. They instantiate their own compatibility\n // envelope only when an old destination explicitly requests one.\n case \"start-watcher\": {\n const requestId =\n typeof payload.requestId === \"string\" ? payload.requestId : undefined;\n const selector =\n typeof payload.selector === \"string\" ? payload.selector : undefined;\n const fiberSelector =\n typeof payload.fiberSelector === \"string\"\n ? payload.fiberSelector\n : undefined;\n const fiberTags = Array.isArray(payload.fiberTags)\n ? (payload.fiberTags as FiberTagValue[])\n : undefined;\n const debounceDelay =\n typeof payload.debounceDelay === \"number\"\n ? payload.debounceDelay\n : undefined;\n const maxWait =\n typeof payload.maxWait === \"number\" ? payload.maxWait : undefined;\n const watcherId = `webview-combined-watcher-${nextLegacyWatcherId++}`;\n\n try {\n const pendingCaptures: CombinedCapture<T>[] = [];\n let established = false;\n const watcher = watchCombinedSelector<T>(\n document,\n selector,\n (capture) => {\n if (!established) {\n pendingCaptures.push(capture);\n return;\n }\n send(\"combined-update\", { watcherId, capture });\n },\n {\n debounceDelay,\n maxWait,\n fiberSelector,\n fiberTags,\n serialize: options.serialize,\n hideFiberProp: options.hideFiberProp,\n },\n );\n legacyWatchers.set(watcherId, watcher);\n send(\"watcher-started\", {\n watcherId,\n ...(requestId ? { requestId } : {}),\n });\n established = true;\n for (const capture of pendingCaptures) {\n send(\"combined-update\", { watcherId, capture });\n }\n } catch (error) {\n send(\"error\", {\n ...(requestId ? { requestId } : {}),\n error: error instanceof Error ? error.message : String(error),\n });\n }\n break;\n }\n\n case \"stop-watcher\": {\n const watcherId =\n typeof payload.watcherId === \"string\" ? payload.watcherId : undefined;\n if (!watcherId) break;\n const watcher = legacyWatchers.get(watcherId);\n if (!watcher) break;\n watcher.stop();\n legacyWatchers.delete(watcherId);\n send(\"watcher-stopped\", { watcherId });\n break;\n }\n\n case \"set-watcher-paused\": {\n const watcherId =\n typeof payload.watcherId === \"string\" ? payload.watcherId : undefined;\n if (!watcherId) break;\n legacyWatchers.get(watcherId)?.setPaused(payload.paused === true);\n break;\n }\n\n case \"capture\": {\n const requestId =\n typeof payload.requestId === \"string\" ? payload.requestId : undefined;\n if (!requestId) break;\n const selector =\n typeof payload.selector === \"string\" ? payload.selector : undefined;\n const fiberSelector =\n typeof payload.fiberSelector === \"string\"\n ? payload.fiberSelector\n : undefined;\n const fiberTags = Array.isArray(payload.fiberTags)\n ? (payload.fiberTags as FiberTagValue[])\n : undefined;\n\n try {\n let capture: CombinedCapture<T> | null = null;\n const watcher = watchCombinedSelector<T>(\n document,\n selector,\n (nextCapture) => {\n capture ??= nextCapture;\n },\n {\n fiberSelector,\n fiberTags,\n serialize: options.serialize,\n hideFiberProp: options.hideFiberProp,\n },\n );\n watcher.stop();\n send(\"capture-response\", { requestId, capture });\n } catch (error) {\n send(\"capture-response\", {\n requestId,\n capture: null,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n break;\n }\n }\n };\n\n const removeListener = bridge.onCommand(handleCommand);\n send(\"source-ready\", {});\n\n return () => {\n removeListener();\n projectionSource.stop();\n for (const watcher of legacyWatchers.values()) watcher.stop();\n legacyWatchers.clear();\n delete (window as any)\n .__IFRAME_PROJECTION_COMBINED_WEBVIEW_INTERFACE_ACTIVE__;\n };\n}\n\nlet nextLegacyPageWatcherRequestId = 1;\nlet nextLegacyPageCaptureRequestId = 1;\n\nfunction createPageLegacyCombinedChannel(\n page: PageMessageHandle,\n): LegacyCombinedChannel {\n return {\n readinessTimeoutMessage:\n \"Timeout waiting for combined source - did you call startCombinedSourceWebviewInterface()?\",\n nextWatcherRequestId: () =>\n `combined-page-watch-${nextLegacyPageWatcherRequestId++}`,\n nextCaptureRequestId: () =>\n `combined-capture-${nextLegacyPageCaptureRequestId++}`,\n send(command) {\n page.send(\"combined-projection:command\", command);\n },\n listen(listener) {\n return page.on(\"combined-projection:update\", (message) => {\n const normalized = normalizeLegacyCombinedChannelEvent(message);\n if (normalized) listener(normalized);\n });\n },\n };\n}\n\n/**\n * Watch a frame-pool page through the pre-ProjectionBatch complete-capture\n * protocol.\n *\n * @deprecated Use {@link watchProjectionBatchesPage}. This adapter is opt-in\n * and does not participate in the Canvas projection stream.\n */\nexport function watchCombinedPage(\n page: PageMessageHandle,\n options: WatchCombinedPageOptions,\n): Promise<CombinedWatcher> {\n return watchLegacyCombinedChannel(\n createPageLegacyCombinedChannel(page),\n options,\n );\n}\n\n/**\n * Capture one complete compatibility envelope from a frame-pool page.\n *\n * @deprecated Prefer exact ProjectionBatch streaming for live projection.\n * This remains a cold query and creates no persistent destination model.\n */\nexport function captureCombinedPage(\n page: PageMessageHandle,\n options: CaptureCombinedPageOptions = {},\n): Promise<CombinedCapture | null> {\n return captureLegacyCombinedChannel(\n createPageLegacyCombinedChannel(page),\n options,\n );\n}\n\n/**\n * Subscribe to the exact document producer owned by a frame-pool page.\n * Transport stays structural: it forwards ProjectionBatch and never rebuilds\n * a CombinedCapture compatibility envelope in the Canvas renderer.\n */\nexport function watchProjectionBatchesPage(\n page: PageMessageHandle,\n options: WatchProjectionBatchesPageOptions,\n): Promise<ProjectionBatchWatcher> {\n return watchProjectionChannel(createPageProjectionChannel(page), options);\n}\n\nlet nextProjectionPageWatcherRequestId = 1;\n\nfunction createPageProjectionChannel(\n page: PageMessageHandle,\n): ProjectionChannel {\n return {\n readinessTimeoutMessage:\n \"Timeout waiting for combined source - did you call startCombinedSourceWebviewInterface()?\",\n nextWatcherRequestId: () =>\n `projection-page-watch-${nextProjectionPageWatcherRequestId++}`,\n send(command) {\n page.send(\"combined-projection:command\", command);\n },\n listen(listener) {\n return page.on(\"combined-projection:update\", (message) => {\n const normalized = normalizeProjectionChannelEvent(message);\n if (normalized) listener(normalized);\n });\n },\n };\n}\n\nfunction combinedSetupAbortError(): Error {\n const error = new Error(\"Combined watcher setup aborted\");\n error.name = \"AbortError\";\n return error;\n}\n","import { startCombinedSourceInterface } from \"../../../modules/iframe-projection/combined/postmessage.ts\";\nimport type { FiberRoot } from \"../../../modules/iframe-projection/fiber/react-types.ts\";\nimport { initHook } from \"../../../modules/iframe-projection/fiber/watch.ts\";\nimport { isTempoInteractFrameName } from \"./interact-frame.ts\";\n\nconst PENDING_ROOTS_KEY = \"__tempoPendingFiberRoots\";\n\ntype BootstrapHook = ReturnType<typeof initHook>[\"hook\"] & {\n [PENDING_ROOTS_KEY]?: Map<number, FiberRoot>;\n};\n\n/**\n * Starts the combined DOM + React source used by Tempo's direct interact iframe.\n * The Vite plugin installs a synchronous hook first; replaying its latest roots\n * here closes the small gap while this lazy client module is loading.\n */\nexport function installTempoInteractProjectionSource(): () => void {\n if (\n typeof window === \"undefined\" ||\n window.parent === window ||\n !isTempoInteractFrameName(window.name)\n ) {\n return () => {};\n }\n\n const hookInterface = initHook();\n const hook = hookInterface.hook as BootstrapHook;\n const pendingRoots = hook[PENDING_ROOTS_KEY];\n if (pendingRoots) {\n hookInterface.seedCommittedRoots(pendingRoots);\n pendingRoots.clear();\n delete hook[PENDING_ROOTS_KEY];\n }\n\n return startCombinedSourceInterface();\n}\n"],"mappings":";;;;;;;;AAiCO,IAAM,WAAW;AAAA;AAAA,EAEtB,mBAAmB;AAAA;AAAA,EAGnB,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMhB,wBAAwB;AAAA;AAAA,EAGxB,UAAU;AAAA;AAAA,EAGV,YAAY;AAAA;AAAA,EAGZ,eAAe;AAAA;AAAA,EAGf,UAAU;AAAA;AAAA,EAGV,UAAU;AAAA;AAAA,EAGV,MAAM;AAAA;AAAA,EAGN,iBAAiB;AAAA;AAAA,EAGjB,iBAAiB;AAAA;AAAA,EAGjB,YAAY;AAAA;AAAA,EAGZ,UAAU;AAAA;AAAA,EAGV,mBAAmB;AAAA;AAAA,EAGnB,eAAe;AAAA;AAAA,EAGf,qBAAqB;AAAA;AAAA,EAGrB,eAAe;AAAA;AAAA,EAGf,0BAA0B;AAAA;AAAA,EAG1B,oBAAoB;AAAA;AAAA,EAGpB,uBAAuB;AAAA;AAAA,EAGvB,gBAAgB;AAAA;AAAA,EAGhB,oBAAoB;AAAA;AAAA,EAGpB,uBAAuB;AAAA;AAAA,EAGvB,gBAAgB;AAAA;AAAA,EAGhB,wBAAwB;AAAA;AAAA,EAGxB,eAAe;AAAA;AAAA,EAGf,eAAe;AACjB;;;ACjFO,SAAS,eAAe,OAAsB;AACnD,QAAM,EAAE,MAAM,IAAI,IAAI;AAGtB,MAAI,OAAO,SAAS,UAAU;AAC5B,WAAO;AAAA,EACT;AAGA,MAAI,QAAQ,SAAS,UAAU;AAC7B,WAAO;AAAA,EACT;AAGA,MAAI,OAAO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,EAAE,MAAM,yBAAyB,CAAC,cAAc,GAAG,KAAK,CAAC;AAC9D,UAAQ;AAAA,IACN;AAAA,EACF;AAEA,SAAO,MAAM;AACX,WAAO,oBAAoB,WAAW,aAAa;AACnD,qBAAiB,KAAK;AACtB,eAAW,CAAC,IAAI,OAAO,KAAK,kBAAkB;AAC5C,cAAQ,KAAK;AACb,cAAQ,IAAI,yCAAyC,EAAE,EAAE;AAAA,IAC3D;AACA,qBAAiB,MAAM;AACvB,WAAQ,OAAe;AACvB,YAAQ,IAAI,0CAA0C;AAAA,EACxD;AACF;;;ACnxBA,IAAM,oBAAoB;AAWnB,SAAS,uCAAmD;AACjE,MACE,OAAO,WAAW,eAClB,OAAO,WAAW,UAClB,CAAC,yBAAyB,OAAO,IAAI,GACrC;AACA,WAAO,MAAM;AAAA,IAAC;AAAA,EAChB;AAEA,QAAM,gBAAgB,SAAS;AAC/B,QAAM,OAAO,cAAc;AAC3B,QAAM,eAAe,KAAK,iBAAiB;AAC3C,MAAI,cAAc;AAChB,kBAAc,mBAAmB,YAAY;AAC7C,iBAAa,MAAM;AACnB,WAAO,KAAK,iBAAiB;AAAA,EAC/B;AAEA,SAAO,6BAA6B;AACtC;","names":["document","nextFiberId","isContentEditableBoundary","parseInlineStyle","instance","perf","boundary","document","normalizeTempoDataSet","hasContextDependencies","hasContentEditableAncestor","coordinateOnlyPortalIds"]}
1
+ {"version":3,"sources":["../../../../modules/iframe-projection/fiber/react-types.ts","../../../../modules/iframe-projection/fiber/serialize.ts","../../../../modules/iframe-projection/fiber/capture.ts","../../../../modules/iframe-projection/fiber/utils.ts","../../../../modules/iframe-projection/fiber/watch.ts","../../../../modules/iframe-projection/html/watch-head.ts","../../../../modules/iframe-projection/shared/capture-perf.ts","../../../../modules/iframe-projection/combined/projection-capture-perf.ts","../../../../modules/iframe-projection/html/declared-facts.ts","../../../../modules/iframe-projection/html/displayability.ts","../../../../modules/iframe-projection/html/selectors.ts","../../../../modules/iframe-projection/html/capture.ts","../../../../modules/iframe-projection/html/watch-dom.ts","../../../../modules/iframe-projection/html/watch-state.ts","../../../../modules/iframe-projection/html/watch-portal.ts","../../../../modules/iframe-projection/combined/css-escape.ts","../../../../modules/iframe-projection/combined/projection-observed-files.ts","../../../../modules/iframe-projection/combined/projection-patch.ts","../../../../modules/iframe-projection/combined/projection-full-snapshot.ts","../../../../modules/iframe-projection/combined/projection-layer-snapshot.ts","../../../../modules/iframe-projection/combined/projection-dom-layers.ts","../../../../modules/iframe-projection/combined/enriched-to-serialized-fiber.ts","../../../../modules/iframe-projection/combined/projection-semantic-subtree.ts","../../../../modules/iframe-projection/combined/projection-svelte-metadata.ts","../../../../modules/iframe-projection/combined/projection-svelte-layers.ts","../../../../modules/iframe-projection/combined/projection-layer-adapter.ts","../../../../modules/iframe-projection/combined/projection-producer.ts","../../../../modules/iframe-projection/shared/portal-tracker.ts","../../../../modules/iframe-projection/combined/projection-root-accumulator.ts","../../../../modules/iframe-projection/combined/document-producer.ts","../../../../modules/iframe-projection/combined/layer-framework.ts","../../../../modules/iframe-projection/html/snapshot.ts","../../../../modules/iframe-projection/combined/render-identity.ts","../../../../modules/iframe-projection/combined/declared-facts.ts","../../../../modules/element-overlay/render/layout-kind.ts","../../../../modules/iframe-projection/combined/enriched-serialize.ts","../../../../modules/iframe-projection/combined/hide-fiber-tree.ts","../../../../modules/iframe-projection/combined/realm-epoch.ts","../../../../modules/iframe-projection/combined/watch.ts","../../../../modules/iframe-projection/combined/postmessage.ts","../../canvas/interact-projection.ts"],"sourcesContent":["/**\n * React Internal Types\n *\n * These types are copied from React's source code. They are internal to React\n * and not exported publicly, so we define them here for type safety.\n *\n * ## Sources\n *\n * - Fiber, FiberRoot: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactInternalTypes.js\n * - WorkTags: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactWorkTags.js\n * - Hooks: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactFiberHooks.js\n * - Memo/ForwardRef/Lazy: https://github.com/facebook/react/blob/main/packages/react/src/\n *\n * ## Stability\n *\n * These structures have been stable since React 16 (Fiber architecture).\n * Major changes are rare, but this file should be updated if React's\n * internals change significantly.\n */\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Fiber Tags (WorkTag)\n// From: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactWorkTags.js\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * React Fiber tag values (WorkTag).\n *\n * These identify what kind of node a fiber represents and determine:\n * - How React processes the fiber during reconciliation\n * - What `stateNode` contains (DOM node, class instance, null)\n * - How `memoizedState` is structured (hooks list, class state, etc.)\n */\nexport const FiberTag = {\n /** Function component: `function MyComponent(props) { ... }` */\n FunctionComponent: 0,\n\n /** Class component: `class MyComponent extends React.Component` */\n ClassComponent: 1,\n\n /**\n * Component not yet determined to be function or class.\n * React resolves this on first render, then updates the tag.\n */\n IndeterminateComponent: 2,\n\n /** Root of a React tree (created by createRoot/render) */\n HostRoot: 3,\n\n /** React Portal: renders children into a different DOM container */\n HostPortal: 4,\n\n /** DOM element: div, span, button, etc. */\n HostComponent: 5,\n\n /** Text node: string/number children */\n HostText: 6,\n\n /** React.Fragment or <>...</> */\n Fragment: 7,\n\n /** StrictMode, ConcurrentMode, etc. */\n Mode: 8,\n\n /** Context.Consumer (legacy pattern) */\n ContextConsumer: 9,\n\n /** Context.Provider */\n ContextProvider: 10,\n\n /** React.forwardRef wrapper */\n ForwardRef: 11,\n\n /** React.Profiler for performance measurements */\n Profiler: 12,\n\n /** React.Suspense boundary */\n SuspenseComponent: 13,\n\n /** React.memo() wrapper */\n MemoComponent: 14,\n\n /** Simplified memo (internal optimization) */\n SimpleMemoComponent: 15,\n\n /** React.lazy() wrapper for code splitting */\n LazyComponent: 16,\n\n /** Incomplete class component (errored during render) */\n IncompleteClassComponent: 17,\n\n /** Dehydrated Suspense boundary (server-rendered) */\n DehydratedFragment: 18,\n\n /** SuspenseList for coordinating reveal order */\n SuspenseListComponent: 19,\n\n /** Scope component (experimental) */\n ScopeComponent: 21,\n\n /** Offscreen component (experimental, powers Activity) */\n OffscreenComponent: 22,\n\n /** Legacy hidden component (deprecated) */\n LegacyHiddenComponent: 23,\n\n /** Cache component (experimental) */\n CacheComponent: 24,\n\n /** Tracing marker (experimental) */\n TracingMarkerComponent: 25,\n\n /** Hoistable elements like <title>, <meta> (React 18.3+) */\n HostHoistable: 26,\n\n /** Singleton elements like <html>, <head>, <body> (React 18.3+) */\n HostSingleton: 27,\n} as const;\n\nexport type FiberTagValue = (typeof FiberTag)[keyof typeof FiberTag];\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Component Types (fiber.type)\n// From: https://github.com/facebook/react/blob/main/packages/react/src/\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** A React function component */\nexport interface FunctionComponent<P = Record<string, unknown>> {\n (props: P): unknown; // Returns ReactNode\n displayName?: string;\n name?: string;\n}\n\n/** A React class component constructor */\nexport interface ClassComponent<P = Record<string, unknown>> {\n new (props: P): { render(): unknown };\n displayName?: string;\n name?: string;\n}\n\n/**\n * React.memo() wrapper.\n * From: https://github.com/facebook/react/blob/main/packages/react/src/ReactMemo.js\n */\nexport interface MemoComponent<P = Record<string, unknown>> {\n $$typeof: symbol; // Symbol.for('react.memo')\n type: FunctionComponent<P> | ClassComponent<P>;\n compare: ((prevProps: P, nextProps: P) => boolean) | null;\n}\n\n/**\n * React.forwardRef() wrapper.\n * From: https://github.com/facebook/react/blob/main/packages/react/src/ReactForwardRef.js\n */\nexport interface ForwardRefComponent<P = Record<string, unknown>> {\n $$typeof: symbol; // Symbol.for('react.forward_ref')\n render: FunctionComponent<P>;\n displayName?: string;\n}\n\n/**\n * React.lazy() wrapper.\n * From: https://github.com/facebook/react/blob/main/packages/react/src/ReactLazy.js\n */\nexport interface LazyComponent {\n $$typeof: symbol; // Symbol.for('react.lazy')\n _payload: {\n _status: -1 | 0 | 1 | 2; // Uninitialized, Pending, Resolved, Rejected\n _result: unknown;\n };\n _init: (payload: unknown) => FunctionComponent | ClassComponent;\n}\n\n/**\n * Context.Provider type.\n */\nexport interface ContextProvider<T = unknown> {\n $$typeof: symbol; // Symbol.for('react.provider') or Symbol.for('react.context')\n _context: {\n Provider: unknown;\n Consumer: unknown;\n _currentValue: T;\n displayName?: string;\n };\n}\n\n/** All possible values for fiber.type */\nexport type FiberType =\n | string // HostComponent: \"div\", \"span\", etc.\n | FunctionComponent\n | ClassComponent\n | MemoComponent\n | ForwardRefComponent\n | LazyComponent\n | ContextProvider\n | symbol // Fragment, StrictMode, Profiler, etc.\n | null; // HostText\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Hooks (fiber.memoizedState for FunctionComponent)\n// From: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactFiberHooks.js\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * React Hook object (linked list node).\n *\n * For function components, fiber.memoizedState is the head of a linked list\n * of Hook objects, one for each hook call in the component.\n */\nexport interface Hook {\n /**\n * The current value of this hook. Contents depend on hook type:\n * - useState/useReducer: the state value\n * - useRef: { current: T }\n * - useMemo: [memoizedValue, dependencies]\n * - useCallback: [callback, dependencies]\n * - useEffect/useLayoutEffect: Effect object\n * - useContext: the context value\n */\n memoizedState: unknown;\n\n /** Base state for updates (used during state transitions) */\n baseState: unknown;\n\n /** Base queue of updates */\n baseQueue: HookUpdate | null;\n\n /** Queue of pending updates. Present for useState/useReducer, null for others */\n queue: HookQueue | null;\n\n /** Next hook in the linked list */\n next: Hook | null;\n}\n\n/**\n * Update queue for useState/useReducer.\n */\nexport interface HookQueue<S = unknown, A = unknown> {\n pending: HookUpdate<S, A> | null;\n lanes: number;\n dispatch: ((action: A) => void) | null;\n lastRenderedReducer: ((state: S, action: A) => S) | null;\n lastRenderedState: S | null;\n}\n\n/**\n * A state update object (circular linked list).\n */\nexport interface HookUpdate<S = unknown, A = unknown> {\n lane: number;\n revertLane: number;\n action: A;\n hasEagerState: boolean;\n eagerState: S | null;\n next: HookUpdate<S, A>;\n}\n\n/**\n * Effect hook object (memoizedState for useEffect/useLayoutEffect).\n */\nexport interface Effect {\n /** Effect type tag (HasEffect, Passive, Layout, etc.) */\n tag: number;\n /** The effect function */\n create: () => (() => void) | void;\n /** The cleanup function returned by create */\n destroy: (() => void) | undefined;\n /** Dependencies array */\n deps: unknown[] | null;\n /** Next effect in the circular linked list */\n next: Effect;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Ref Types\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Ref object created by useRef or createRef */\nexport interface RefObject<T = unknown> {\n current: T;\n}\n\n/** Callback ref function */\nexport type RefCallback<T = unknown> = (instance: T | null) => void;\n\n/** All possible values for fiber.ref */\nexport type FiberRef<T = unknown> = RefObject<T> | RefCallback<T> | null;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Props Type\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Props object passed to components */\nexport type FiberProps = Record<string, unknown> & {\n children?: unknown;\n};\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Fiber\n// From: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactInternalTypes.js\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * React Fiber node.\n *\n * A fiber is a unit of work in React's rendering engine. It maintains\n * component identity, state, tree relationships, and scheduling information.\n *\n * ## Key Properties for Serialization\n *\n * - `tag`: What kind of fiber (use FiberTag constants)\n * - `type`: The component function/class or DOM tag string\n * - `key`: React key prop for reconciliation\n * - `stateNode`: DOM element (HostComponent) or class instance (ClassComponent)\n * - `memoizedProps`: Current props\n * - `memoizedState`: Hooks linked list (FunctionComponent) or state object (ClassComponent)\n * - `child`/`sibling`/`return`: Tree navigation\n */\nexport interface Fiber {\n // ─── Core Identity ─────────────────────────────────────────────────────────\n\n /** Fiber type tag (FunctionComponent, HostComponent, etc.) */\n tag: FiberTagValue;\n\n /** Unique key among siblings (from key prop) */\n key: string | null;\n\n /** Element type for reconciliation (usually same as type) */\n elementType: FiberType;\n\n /**\n * The resolved function/class/string for this fiber.\n * - FunctionComponent: the function\n * - ClassComponent: the class constructor\n * - HostComponent: tag string (\"div\", \"span\", etc.)\n * - HostText: null\n */\n type: FiberType;\n\n /**\n * Local state associated with this fiber.\n * - HostComponent: the DOM Element\n * - HostText: the DOM Text node\n * - ClassComponent: the class instance\n * - HostRoot: the FiberRoot\n * - FunctionComponent: null\n */\n stateNode: Element | Text | object | null;\n\n // ─── Tree Structure ────────────────────────────────────────────────────────\n\n /** Parent fiber (\"return\" because processing returns to parent) */\n return: Fiber | null;\n\n /** First child (head of children linked list) */\n child: Fiber | null;\n\n /** Next sibling */\n sibling: Fiber | null;\n\n /** Position among siblings */\n index: number;\n\n // ─── Props and State ───────────────────────────────────────────────────────\n\n /** Ref attached to this fiber */\n ref: FiberRef;\n\n /** Ref cleanup function (React 19+) */\n refCleanup: (() => void) | null;\n\n /** Input props being processed */\n pendingProps: FiberProps;\n\n /** Props from most recent completed render */\n memoizedProps: FiberProps;\n\n /** Update queue */\n updateQueue: unknown;\n\n /**\n * State from most recent completed render.\n * - FunctionComponent: Hook linked list (first hook)\n * - ClassComponent: state object\n * - HostRoot: element to render\n */\n memoizedState: Hook | object | null;\n\n /** Context and event dependencies */\n dependencies: unknown;\n\n // ─── Effects and Flags ─────────────────────────────────────────────────────\n\n /** Bitfield of effects needed on this fiber */\n flags: number;\n\n /** Aggregate flags from descendants */\n subtreeFlags: number;\n\n /** Fibers to delete */\n deletions: Fiber[] | null;\n\n // ─── Scheduling ────────────────────────────────────────────────────────────\n\n /** Update lanes for this fiber */\n lanes: number;\n\n /** Aggregate lanes from descendants */\n childLanes: number;\n\n // ─── Alternate (Double Buffering) ──────────────────────────────────────────\n\n /**\n * Link to corresponding fiber in the alternate tree.\n *\n * React maintains current (on screen) and work-in-progress trees.\n * After commit, if you're on FiberRoot.current, alternate points to OLD tree.\n */\n alternate: Fiber | null;\n\n // ─── Mode ──────────────────────────────────────────────────────────────────\n\n /** Bitfield for StrictMode, ConcurrentMode, etc. */\n mode: number;\n\n // ─── Profiling (dev/profiling builds) ──────────────────────────────────────\n\n actualDuration?: number;\n actualStartTime?: number;\n selfBaseDuration?: number;\n treeBaseDuration?: number;\n\n // ─── Debug (dev only) ──────────────────────────────────────────────────────\n\n _debugInfo?: unknown;\n _debugOwner?: Fiber | null;\n _debugStack?: Error | null;\n _debugTask?: unknown;\n _debugNeedsRemount?: boolean;\n _debugHookTypes?: string[] | null;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// FiberRoot\n// From: https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactInternalTypes.js\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * FiberRoot - the root object for a React tree.\n *\n * Created by createRoot() or ReactDOM.render(). The `current` property\n * always points to the committed fiber tree (HostRoot fiber).\n */\nexport interface FiberRoot {\n /** The HostRoot fiber of the committed tree */\n current: Fiber;\n\n /** The DOM container element */\n containerInfo: Element;\n\n /** Whether this root is hydrating */\n hydrate: boolean;\n\n /** Pending work lanes */\n pendingLanes: number;\n\n /** Scheduler callback */\n callbackNode: unknown;\n callbackPriority: number;\n\n /** Suspense ping cache */\n pingCache: unknown;\n\n /** Completed work ready to commit */\n finishedWork: Fiber | null;\n\n /**\n * Development renderers retain the Fibers that scheduled the commit while\n * the DevTools commit hook is running, then clear the set immediately after\n * the hook returns. Tempo installs that hook before React, so the projection\n * producer can retain exact candidate anchors without walking the root.\n */\n memoizedUpdaters?: ReadonlySet<Fiber>;\n\n /** Legacy context */\n context: object | null;\n pendingContext: object | null;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// DevTools Hook\n// From: https://github.com/facebook/react/blob/main/packages/react-devtools-shared/src/hook.js\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * React renderer info passed to hook.inject().\n */\nexport interface ReactRenderer {\n version: string;\n rendererPackageName?: string;\n bundleType?: number; // 0 = production, 1 = development\n findFiberByHostInstance?: (instance: unknown) => Fiber | null;\n}\n\n/**\n * The React DevTools global hook.\n *\n * Must be installed on `window.__REACT_DEVTOOLS_GLOBAL_HOOK__` BEFORE\n * React loads. React checks for this exactly once at initialization.\n */\nexport interface DevToolsHook {\n /** Must be true for modern React (16+) to inject */\n supportsFiber: boolean;\n\n /** Map of renderer ID -> renderer info */\n renderers: Map<number, ReactRenderer>;\n\n /** Called by React to register itself. Returns renderer ID. */\n inject(renderer: ReactRenderer): number;\n\n /**\n * Called by React after each commit.\n * fiberRoot.current points to the freshly committed tree.\n */\n onCommitFiberRoot(\n rendererId: number,\n fiberRoot: FiberRoot,\n priority?: number,\n didError?: boolean\n ): void;\n\n /** Called when a fiber is about to unmount */\n onCommitFiberUnmount?(rendererId: number, fiber: Fiber): void;\n\n /** Dead code elimination check */\n checkDCE?(fn: Function): void;\n\n /** Called when render is scheduled */\n onScheduleFiberRoot?(): void;\n}\n\ndeclare global {\n interface Window {\n __REACT_DEVTOOLS_GLOBAL_HOOK__?: DevToolsHook;\n }\n}\n","/**\n * Fiber Serialization Helpers\n *\n * Utility functions for extracting data from React Fiber nodes.\n * Use these to build your custom serialize functions.\n *\n * @example\n * ```ts\n * import { getDisplayName, getTag, getProps, getKey } from './serialize';\n *\n * const mySerialize: SerializeFn<MyNode> = (fiber) => ({\n * name: getDisplayName(fiber),\n * tag: getTag(fiber),\n * key: getKey(fiber),\n * props: getProps(fiber),\n * });\n * ```\n */\n\nimport type { Fiber, FiberProps, Hook, FunctionComponent, ClassComponent, MemoComponent, ForwardRefComponent, FiberTagValue } from \"./react-types\";\nimport { FiberTag } from \"./react-types\";\nimport type { DefaultFiberNode, SerializeFn } from \"./types\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Name Resolution\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get the display name of a fiber.\n *\n * Resolution order:\n * 1. type.displayName (explicit name set on component)\n * 2. type.name (function/class name)\n * 3. Wrapped component name (for memo/forwardRef)\n * 4. Tag-based fallback (\"Fragment\", \"#text\", etc.)\n */\nexport function getDisplayName(fiber: Fiber): string {\n const { type, tag } = fiber;\n\n // HostComponent: DOM elements have string type\n if (typeof type === \"string\") {\n return type;\n }\n\n // HostText: text nodes\n if (tag === FiberTag.HostText) {\n return \"#text\";\n }\n\n // Function/Class components\n if (typeof type === \"function\") {\n const fn = type as FunctionComponent | ClassComponent;\n return fn.displayName || fn.name || \"Anonymous\";\n }\n\n // Object types (memo, forwardRef, lazy, context)\n if (type && typeof type === \"object\") {\n // React.memo\n if (\"type\" in type && (type as MemoComponent).type) {\n const inner = (type as MemoComponent).type;\n if (typeof inner === \"function\") {\n return (inner as FunctionComponent).displayName || (inner as FunctionComponent).name || \"Memo\";\n }\n }\n\n // React.forwardRef\n if (\"render\" in type && (type as ForwardRefComponent).render) {\n const render = (type as ForwardRefComponent).render;\n return (type as ForwardRefComponent).displayName || render.displayName || render.name || \"ForwardRef\";\n }\n\n // Context.Provider\n if (\"_context\" in type) {\n const ctx = (type as { _context: { displayName?: string } })._context;\n return ctx.displayName ? `${ctx.displayName}.Provider` : \"Context.Provider\";\n }\n }\n\n // Tag-based fallbacks\n const tagNames: Partial<Record<number, string>> = {\n [FiberTag.HostRoot]: \"HostRoot\",\n [FiberTag.Fragment]: \"Fragment\",\n [FiberTag.Mode]: \"Mode\",\n [FiberTag.ContextConsumer]: \"Context.Consumer\",\n [FiberTag.ContextProvider]: \"Context.Provider\",\n [FiberTag.Profiler]: \"Profiler\",\n [FiberTag.SuspenseComponent]: \"Suspense\",\n [FiberTag.SuspenseListComponent]: \"SuspenseList\",\n [FiberTag.OffscreenComponent]: \"Offscreen\",\n };\n\n return tagNames[tag] || `Unknown(${tag})`;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Basic Accessors\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Get the fiber's tag value */\nexport function getTag(fiber: Fiber): FiberTagValue {\n return fiber.tag as FiberTagValue;\n}\n\n/** Get the fiber's key (null if not set) */\nexport function getKey(fiber: Fiber): string | null {\n return fiber.key;\n}\n\n/** Get the fiber's index among siblings */\nexport function getIndex(fiber: Fiber): number {\n return fiber.index;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Props\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get the fiber's current props.\n *\n * Returns memoizedProps which reflect the most recent render.\n */\nexport function getProps(fiber: Fiber): FiberProps {\n return fiber.memoizedProps;\n}\n\n/**\n * Sanitize props for serialization.\n *\n * - Removes `children` (handled separately in tree)\n * - Converts functions to \"[Function]\"\n * - Converts DOM elements to \"[Element:tagName]\"\n * - Converts React elements to \"[ReactElement]\"\n * - Deep clones serializable objects\n * - Falls back to \"[Object]\" for non-serializable values\n */\nexport function sanitizeProps(props: FiberProps | null): Record<string, unknown> | undefined {\n if (!props) return undefined;\n\n const result: Record<string, unknown> = {};\n let hasProps = false;\n\n for (const [key, value] of Object.entries(props)) {\n // Skip children - handled in tree structure\n if (key === \"children\") continue;\n\n hasProps = true;\n result[key] = sanitizeValue(value);\n }\n\n return hasProps ? result : undefined;\n}\n\n/**\n * Sanitize a single value for serialization.\n */\nexport function sanitizeValue(value: unknown): unknown {\n if (value === null || value === undefined) {\n return value;\n }\n\n if (typeof value === \"function\") {\n return \"[Function]\";\n }\n\n if (typeof value === \"symbol\") {\n return `[Symbol:${value.description ?? \"\"}]`;\n }\n\n if (value instanceof Element) {\n return `[Element:${value.tagName.toLowerCase()}${value.id ? `#${value.id}` : \"\"}]`;\n }\n\n if (value instanceof Node) {\n return `[Node:${value.nodeName}]`;\n }\n\n if (Array.isArray(value)) {\n // For small arrays, serialize contents\n if (value.length <= 10) {\n return value.map(sanitizeValue);\n }\n return `[Array(${value.length})]`;\n }\n\n if (typeof value === \"object\") {\n // React element\n if (\"$$typeof\" in value) {\n return \"[ReactElement]\";\n }\n\n // Try to deep clone\n try {\n return JSON.parse(JSON.stringify(value));\n } catch {\n return \"[Object]\";\n }\n }\n\n // Primitives pass through\n return value;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// State Node (DOM Element)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get the DOM element for a HostComponent fiber.\n *\n * Returns null for non-host fibers or if stateNode isn't an Element.\n */\nexport function getDomElement(fiber: Fiber): Element | null {\n if (fiber.tag !== FiberTag.HostComponent) {\n return null;\n }\n return fiber.stateNode instanceof Element ? fiber.stateNode : null;\n}\n\n/**\n * Get the Text node for a HostText fiber.\n */\nexport function getTextNode(fiber: Fiber): Text | null {\n if (fiber.tag !== FiberTag.HostText) {\n return null;\n }\n return fiber.stateNode instanceof Text ? fiber.stateNode : null;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Hooks (Function Components)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get the hooks linked list for a function component.\n *\n * Returns null for non-function components or components without hooks.\n */\nexport function getHooks(fiber: Fiber): Hook | null {\n if (fiber.tag !== FiberTag.FunctionComponent) {\n return null;\n }\n // memoizedState is the head of the hooks linked list\n return fiber.memoizedState as Hook | null;\n}\n\n/**\n * Iterate over all hooks in a function component.\n *\n * @example\n * ```ts\n * for (const hook of iterateHooks(fiber)) {\n * console.log(hook.memoizedState);\n * }\n * ```\n */\nexport function* iterateHooks(fiber: Fiber): Generator<Hook> {\n let hook = getHooks(fiber);\n let count = 0;\n const maxHooks = 100; // Safety limit\n\n while (hook && count < maxHooks) {\n yield hook;\n hook = hook.next;\n count++;\n }\n}\n\n/**\n * Extract hook values as an array.\n *\n * Returns array of memoizedState values for each hook.\n */\nexport function getHookValues(fiber: Fiber): unknown[] {\n const values: unknown[] = [];\n for (const hook of iterateHooks(fiber)) {\n values.push(hook.memoizedState);\n }\n return values;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Tree Navigation\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Iterate over a fiber's children.\n *\n * @example\n * ```ts\n * for (const child of iterateChildren(fiber)) {\n * console.log(getDisplayName(child));\n * }\n * ```\n */\nexport function* iterateChildren(fiber: Fiber): Generator<Fiber> {\n let child = fiber.child;\n while (child) {\n yield child;\n child = child.sibling;\n }\n}\n\n/**\n * Get all children as an array.\n */\nexport function getChildren(fiber: Fiber): Fiber[] {\n return [...iterateChildren(fiber)];\n}\n\n/**\n * Walk up the tree to find the root fiber.\n *\n * Important: Uses FiberRoot.current to get the committed tree,\n * avoiding stale data from the work-in-progress tree.\n */\nexport function findRootFiber(fiber: Fiber): Fiber {\n // Walk up to HostRoot\n let current = fiber;\n while (current.return) {\n current = current.return;\n }\n\n // HostRoot's stateNode is FiberRoot, which has `.current`\n // pointing to the committed tree's root\n const stateNode = current.stateNode;\n if (\n stateNode &&\n typeof stateNode === \"object\" &&\n \"current\" in stateNode &&\n (stateNode as { current: Fiber }).current\n ) {\n return (stateNode as { current: Fiber }).current;\n }\n\n return current;\n}\n\n/**\n * Resolve a fiber to its committed-tree version.\n *\n * React double-buffers fibers: each host instance has up to two fiber\n * objects (`fiber` and `fiber.alternate`) that swap the \"current\" role on\n * every commit. The `__reactFiber$` pointer a DOM element carries is stamped\n * once at mount and never re-pointed, so after an odd number of commits it\n * refers to the NON-committed generation — its `memoizedProps` (and the\n * whole subtree walked from it) are one commit stale.\n *\n * Both generations' HostRoot fibers share one `FiberRoot` stateNode, but a\n * bailout can also make the generations share intermediate child lists. Walk\n * both return paths and use parent-child membership to preserve which original\n * endpoint each path represents, matching React's own current-fiber slow path.\n *\n * A fiber with no alternate that fails the check is kept as-is (a freshly\n * mounted node exists in only one generation; a detached fiber has no\n * better answer).\n *\n * Throws `isTransientFiberResolutionError` failures for a fiber React has\n * detached from the committed tree — an ordinary outcome for a caller holding\n * fibers React may unmount under it.\n */\nexport function resolveCommittedFiber(fiber: Fiber): Fiber {\n const alternate = fiber.alternate;\n if (!alternate) {\n return fiber;\n }\n\n let a = fiber;\n let b = alternate;\n for (;;) {\n const parentA = a.return;\n if (!parentA) break;\n const parentB = parentA.alternate;\n if (!parentB) {\n const nextParent = parentA.return;\n if (nextParent) {\n a = nextParent;\n b = nextParent;\n continue;\n }\n break;\n }\n\n if (parentA.child === parentB.child) {\n for (let child = parentA.child; child; child = child.sibling) {\n if (child === a) return fiber;\n if (child === b) return alternate;\n }\n throw new Error(\"Unable to resolve a mounted React fiber\");\n }\n\n if (a.return !== b.return) {\n a = parentA;\n b = parentB;\n } else {\n let found = false;\n for (let child = parentA.child; child; child = child.sibling) {\n if (child === a) {\n found = true;\n a = parentA;\n b = parentB;\n break;\n }\n if (child === b) {\n found = true;\n a = parentB;\n b = parentA;\n break;\n }\n }\n if (!found) {\n for (let child = parentB.child; child; child = child.sibling) {\n if (child === a) {\n found = true;\n a = parentB;\n b = parentA;\n break;\n }\n if (child === b) {\n found = true;\n a = parentA;\n b = parentB;\n break;\n }\n }\n }\n if (!found) {\n throw new Error(\"React fiber is absent from both parent generations\");\n }\n }\n\n if (a.alternate !== b) {\n throw new Error(\"React return fibers are not paired alternates\");\n }\n }\n\n if (a.tag !== FiberTag.HostRoot) {\n throw new Error(\"Unable to resolve an unmounted React fiber\");\n }\n const fiberRoot = a.stateNode as { current?: Fiber } | null;\n return fiberRoot?.current === a ? fiber : alternate;\n}\n\nconst TRANSIENT_FIBER_RESOLUTION_ERRORS = new Set([\n \"Unable to resolve a mounted React fiber\",\n \"React fiber is absent from both parent generations\",\n \"React return fibers are not paired alternates\",\n \"Unable to resolve an unmounted React fiber\",\n]);\n\n/**\n * Did `resolveCommittedFiber` fail because the fiber is no longer part of the\n * committed tree, rather than because the caller misused it?\n *\n * A fiber captured at one moment can be detached by any later commit — an\n * updater unmounted by the very commit that scheduled it, an alternate React\n * dropped between DOM enumeration and the identity read. Callers holding many\n * fibers treat this as \"this one has no answer\" and keep going; every other\n * error is a real defect and must keep propagating.\n */\nexport function isTransientFiberResolutionError(error: unknown): boolean {\n return (\n error instanceof Error &&\n TRANSIENT_FIBER_RESOLUTION_ERRORS.has(error.message)\n );\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Type Guards\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Check if fiber is a function component */\nexport function isFunctionComponent(fiber: Fiber): boolean {\n return fiber.tag === FiberTag.FunctionComponent;\n}\n\n/** Check if fiber is a class component */\nexport function isClassComponent(fiber: Fiber): boolean {\n return fiber.tag === FiberTag.ClassComponent;\n}\n\n/** Check if fiber is a React component (function or class) */\nexport function isComponent(fiber: Fiber): boolean {\n return fiber.tag === FiberTag.FunctionComponent || fiber.tag === FiberTag.ClassComponent;\n}\n\n/** Check if fiber is a DOM element */\nexport function isHostComponent(fiber: Fiber): boolean {\n return fiber.tag === FiberTag.HostComponent;\n}\n\n/** Check if fiber is a text node */\nexport function isHostText(fiber: Fiber): boolean {\n return fiber.tag === FiberTag.HostText;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Default Serializer\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Default serialize function.\n *\n * Produces nodes with just name and tag - the minimal representation.\n */\nexport const defaultSerialize: SerializeFn<DefaultFiberNode> = (fiber) => ({\n name: getDisplayName(fiber),\n tag: getTag(fiber),\n});\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Tree Serialization\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Options for serializeTree.\n */\nexport interface SerializeOptions {\n /** Maximum depth to traverse (default: unlimited) */\n maxDepth?: number;\n /** Whether to skip text nodes (default: true) */\n skipText?: boolean;\n}\n\n/**\n * Serialize a fiber tree using the provided serialize function.\n *\n * This is the core serialization function. It handles:\n * - Recursive tree traversal via child/sibling links\n * - Building children arrays\n * - Depth limiting\n * - Optional text node skipping\n *\n * @param fiber - Root fiber to serialize from\n * @param serialize - Function to serialize each fiber\n * @param options - Serialization options\n */\nexport function serializeTree<T extends { children: T[] }>(\n fiber: Fiber,\n serialize: (fiber: Fiber) => Omit<T, \"children\">,\n options: SerializeOptions = {}\n): T | null {\n const { maxDepth = Infinity, skipText = true } = options;\n\n function serializeNode(f: Fiber, depth: number): T | null {\n if (depth > maxDepth) return null;\n\n // Optionally skip text nodes\n if (skipText && f.tag === FiberTag.HostText) {\n return null;\n }\n\n // Serialize this node (without children)\n const nodeData = serialize(f);\n\n // Recursively serialize children\n const children: T[] = [];\n for (const child of iterateChildren(f)) {\n const serialized = serializeNode(child, depth + 1);\n if (serialized) {\n children.push(serialized);\n }\n }\n\n // Combine node data with children\n return { ...nodeData, children } as T;\n }\n\n return serializeNode(fiber, 0);\n}\n","/**\n * Fiber Tree Capture\n *\n * One-shot capture of a React fiber tree from a DOM element.\n *\n * @example\n * ```ts\n * // Default capture (name + tag)\n * const tree = capture(document.getElementById('root'));\n *\n * // Custom capture with more data\n * const tree = capture(rootEl, (fiber) => ({\n * name: getDisplayName(fiber),\n * tag: fiber.tag,\n * props: sanitizeProps(fiber.memoizedProps),\n * }));\n * ```\n */\n\nimport type { Fiber } from \"./react-types\";\nimport { FiberTag } from \"./react-types\";\nimport type { FiberNode, FiberNodeConstraint, DefaultFiberNode, SerializeFn } from \"./types\";\nimport { defaultSerialize, serializeTree, findRootFiber, type SerializeOptions } from \"./serialize\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Fiber Access from DOM\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Find the React fiber key on a DOM element.\n *\n * React attaches fibers to DOM elements using keys like `__reactFiber$abc123`.\n * The suffix is unique per React instance but consistent across all elements.\n */\nfunction findFiberKey(element: Element): string | null {\n return (\n Object.keys(element).find(\n (k) => k.startsWith(\"__reactFiber$\") || k.startsWith(\"__reactInternalInstance$\")\n ) ?? null\n );\n}\n\n/**\n * Find the React container key on a root element.\n *\n * Root containers (like #root) have `__reactContainer$` instead of `__reactFiber$`.\n */\nfunction findContainerKey(element: Element): string | null {\n return Object.keys(element).find((k) => k.startsWith(\"__reactContainer$\")) ?? null;\n}\n\n/**\n * Get the React fiber from a DOM element.\n *\n * Works with both regular elements (__reactFiber$) and\n * root containers (__reactContainer$).\n */\nexport function getFiberFromElement(element: Element): Fiber | null {\n // Try standard fiber key first\n const fiberKey = findFiberKey(element);\n if (fiberKey) {\n return (element as unknown as Record<string, Fiber>)[fiberKey] ?? null;\n }\n\n // For root containers, try container key\n const containerKey = findContainerKey(element);\n if (containerKey) {\n return (element as unknown as Record<string, Fiber>)[containerKey] ?? null;\n }\n\n return null;\n}\n\n/**\n * Check if React fiber data is available on this element.\n */\nexport function hasFiber(element: Element): boolean {\n return findFiberKey(element) !== null || findContainerKey(element) !== null;\n}\n\n/**\n * Check if any element in the document has React fiber data.\n *\n * Useful for detecting if React is present and has rendered.\n */\nexport function isReactAvailable(): boolean {\n const elements = document.querySelectorAll(\"*\");\n for (const el of elements) {\n if (hasFiber(el)) return true;\n }\n return false;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Capture\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Options for capture().\n */\nexport interface CaptureOptions extends SerializeOptions {\n /**\n * Whether to start from the committed root fiber.\n *\n * If true (default), walks up from the element's fiber to find the\n * root, then uses FiberRoot.current to ensure we're reading from\n * the committed tree (not the stale work-in-progress tree).\n *\n * If false, starts directly from the element's fiber.\n */\n fromRoot?: boolean;\n}\n\n/**\n * Capture the fiber tree from a DOM element.\n *\n * ## Default Behavior\n *\n * Returns nodes with `name`, `tag`, and `children`. This is the minimal\n * representation that captures the tree structure.\n *\n * ## Custom Serialization\n *\n * Pass a serialize function to control exactly what data each node has.\n * Your function receives the raw Fiber and returns everything except\n * `children` (we handle the recursion).\n *\n * @param element - DOM element to capture from\n * @param serialize - Optional custom serialize function\n * @param options - Capture options\n *\n * @example\n * ```ts\n * // Default capture\n * const tree = capture(document.getElementById('root'));\n * // tree: { name: \"App\", tag: 0, children: [...] }\n *\n * // Custom capture with props\n * interface MyNode {\n * name: string;\n * tag: number;\n * props?: Record<string, unknown>;\n * children: MyNode[];\n * }\n *\n * const tree = capture<MyNode>(rootEl, (fiber) => ({\n * name: getDisplayName(fiber),\n * tag: fiber.tag,\n * props: sanitizeProps(fiber.memoizedProps),\n * }));\n * ```\n */\nexport function capture(\n element: Element,\n options?: CaptureOptions\n): FiberNode<DefaultFiberNode> | null;\n\nexport function capture<T extends FiberNodeConstraint>(\n element: Element,\n serialize: SerializeFn<T>,\n options?: CaptureOptions\n): FiberNode<T> | null;\n\nexport function capture<T extends FiberNodeConstraint = DefaultFiberNode>(\n element: Element,\n serializeOrOptions?: SerializeFn<T> | CaptureOptions,\n maybeOptions?: CaptureOptions\n): FiberNode<T> | null {\n // Parse overloaded arguments\n let serialize: SerializeFn<T>;\n let options: CaptureOptions;\n\n if (typeof serializeOrOptions === \"function\") {\n serialize = serializeOrOptions;\n options = maybeOptions ?? {};\n } else {\n serialize = defaultSerialize as unknown as SerializeFn<T>;\n options = serializeOrOptions ?? {};\n }\n\n const { fromRoot = true, ...serializeOptions } = options;\n\n // Get fiber from element\n let fiber = getFiberFromElement(element);\n if (!fiber) {\n return null;\n }\n\n // Navigate to committed root if requested\n if (fromRoot) {\n const root = findRootFiber(fiber);\n // Start from first child of HostRoot (the app component)\n if (root.tag === FiberTag.HostRoot && root.child) {\n fiber = root.child;\n } else {\n fiber = root;\n }\n }\n\n // Serialize the tree\n return serializeTree(fiber, serialize, serializeOptions);\n}\n","/**\n * Fiber Tree Utilities\n *\n * Utility functions for working with serialized fiber trees.\n */\n\nimport type { FiberNodeConstraint, FiberTagValue } from \"./types\";\n\n/**\n * Filter a fiber tree, removing nodes with excluded tags.\n *\n * When a node is filtered out, its children are promoted to take its place\n * (recursively filtered as well). This allows hiding wrapper nodes like\n * Fragment, Mode, or ContextProvider while preserving the tree structure.\n *\n * @param tree - The root node (or null)\n * @param excludeTags - Set of tag values to exclude\n * @returns The filtered tree, or null if root was filtered and had no children\n *\n * @example\n * ```ts\n * import { FiberTag } from './types';\n *\n * // Filter out Fragment (7) and Mode (8) nodes\n * const filtered = filterTree(tree, new Set([\n * FiberTag.Fragment,\n * FiberTag.Mode,\n * ]));\n * ```\n *\n * @example\n * ```ts\n * // Hide common wrapper nodes\n * const WRAPPER_TAGS = new Set([\n * 7, // Fragment\n * 8, // Mode\n * 10, // ContextProvider\n * 11, // ForwardRef\n * 14, // MemoComponent\n * 15, // SimpleMemoComponent\n * ]);\n * const filtered = filterTree(tree, WRAPPER_TAGS);\n * ```\n */\nexport function filterTree<T extends FiberNodeConstraint & { tag: number }>(\n tree: T | null,\n excludeTags: Set<number>\n): T | null {\n if (tree === null) return null;\n\n // If root is excluded, promote its children (but there can only be one root)\n if (excludeTags.has(tree.tag)) {\n // Recursively filter children and return the first one (promoting it to root)\n const filteredChildren = filterChildren(tree.children, excludeTags);\n return filteredChildren.length > 0 ? filteredChildren[0]! : null;\n }\n\n // Root is not excluded, filter its children\n return {\n ...tree,\n children: filterChildren(tree.children, excludeTags),\n };\n}\n\n/**\n * Filter an array of children, promoting grandchildren when a child is filtered.\n */\nfunction filterChildren<T extends FiberNodeConstraint & { tag: number }>(\n children: T[],\n excludeTags: Set<number>\n): T[] {\n const result: T[] = [];\n\n for (const child of children) {\n if (excludeTags.has(child.tag)) {\n // Child is excluded - promote its filtered children\n const grandchildren = filterChildren(child.children, excludeTags);\n result.push(...grandchildren);\n } else {\n // Child is kept - recursively filter its children\n result.push({\n ...child,\n children: filterChildren(child.children, excludeTags),\n });\n }\n }\n\n return result;\n}\n\n/**\n * Common wrapper tags that can be hidden without losing semantic information.\n */\nexport const WRAPPER_TAGS = new Set([\n 7, // Fragment\n 8, // Mode (StrictMode)\n 10, // ContextProvider\n 11, // ForwardRef\n 14, // MemoComponent\n 15, // SimpleMemoComponent\n]);\n\n/**\n * Create a filter set from tag values.\n * Convenience function for creating filter sets.\n */\nexport function createTagFilter(...tags: number[]): Set<number> {\n return new Set(tags);\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Include-based Filtering\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Filter a fiber tree to only include nodes with specified tags.\n *\n * When a node is NOT in includeTags, it is removed and its children are\n * promoted to take its place (recursively filtered as well). This is the\n * inverse of filterTree which excludes tags.\n *\n * @param tree - The root node (or null)\n * @param includeTags - Set of tag values to keep\n * @returns The filtered tree, or null if root was filtered and had no children\n *\n * @example\n * ```ts\n * import { FiberTag } from './types';\n *\n * // Keep only FunctionComponent (0) and HostComponent (5) nodes\n * const filtered = filterTreeInclude(tree, new Set([\n * FiberTag.FunctionComponent,\n * FiberTag.HostComponent,\n * ]));\n * ```\n */\nexport function filterTreeInclude<T extends FiberNodeConstraint & { tag: FiberTagValue }>(\n tree: T | null,\n includeTags: Set<FiberTagValue>\n): T | null {\n if (tree === null) return null;\n\n // If root is NOT included, promote its children (but there can only be one root)\n if (!includeTags.has(tree.tag)) {\n const filteredChildren = filterChildrenInclude(tree.children, includeTags);\n return filteredChildren.length > 0 ? filteredChildren[0]! : null;\n }\n\n // Root is included, filter its children\n return {\n ...tree,\n children: filterChildrenInclude(tree.children, includeTags),\n };\n}\n\n/**\n * Filter an array of children, promoting grandchildren when a child is not included.\n */\nfunction filterChildrenInclude<T extends FiberNodeConstraint & { tag: FiberTagValue }>(\n children: T[],\n includeTags: Set<FiberTagValue>\n): T[] {\n const result: T[] = [];\n\n for (const child of children) {\n if (!includeTags.has(child.tag)) {\n // Child is NOT included - promote its filtered children\n const grandchildren = filterChildrenInclude(child.children, includeTags);\n result.push(...grandchildren);\n } else {\n // Child is included - keep it, recursively filter its children\n result.push({\n ...child,\n children: filterChildrenInclude(child.children, includeTags),\n });\n }\n }\n\n return result;\n}\n","/**\n * Fiber Tree Watching\n *\n * Stream fiber tree snapshots on React commits.\n *\n * ## Setup (Recommended)\n *\n * For guaranteed capture, call initHook() BEFORE React loads:\n *\n * ```ts\n * // At the VERY TOP of your entry file, before any React imports:\n * import { initHook } from '@modules/iframe-projection/fiber';\n *\n * initHook(); // Idempotent - safe to call multiple times\n *\n * // Now safe to import React\n * import React from 'react';\n * ```\n *\n * ## Watching\n *\n * After React mounts, call watch() to start receiving snapshots.\n * watch() will auto-initialize the hook if not already done.\n *\n * ```ts\n * const { stop } = watch((snapshot) => {\n * console.log('Tree updated:', snapshot.tree);\n * parent.postMessage(snapshot, '*');\n * });\n *\n * // Later: stop watching\n * stop();\n * ```\n *\n * ## How It Works\n *\n * - If no hook exists: creates one (works if called before React)\n * - If hook exists (e.g., DevTools extension): wraps it (works after React)\n * - If already initialized by us: reuses existing (idempotent)\n */\n\nimport { getFiberFromElement } from \"./capture\";\nimport type {\n DevToolsHook,\n Fiber,\n FiberRoot,\n ReactRenderer,\n} from \"./react-types\";\nimport { FiberTag } from \"./react-types\";\nimport {\n defaultSerialize,\n resolveCommittedFiber,\n type SerializeOptions,\n serializeTree,\n} from \"./serialize\";\nimport type {\n DefaultFiberNode,\n FiberNodeConstraint,\n FiberSnapshot,\n FiberTagValue,\n SerializeFn,\n} from \"./types\";\nimport { filterTreeInclude } from \"./utils\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// One-shot Capture (for validation)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Options for captureTree().\n */\nexport interface CaptureTreeOptions<\n T extends FiberNodeConstraint = DefaultFiberNode,\n> extends SerializeOptions {\n /**\n * CSS selector for the element to capture.\n * If not provided, captures the entire tree.\n */\n selector?: string;\n\n /**\n * Custom serialization function.\n * If not provided, uses defaultSerialize (name + tag).\n */\n serialize?: SerializeFn<T>;\n\n /**\n * Only include nodes with these tags in the tree.\n * Other nodes are filtered out and their children promoted.\n */\n tags?: FiberTagValue[];\n}\n\n/**\n * Capture the current fiber tree (one-shot).\n *\n * This uses the same logic as watch() to find the starting fiber,\n * ensuring consistency between watched deltas and captured snapshots.\n * Useful for validation that delta merging produces correct results.\n *\n * @returns The serialized tree, or null if no React root found\n *\n * @example\n * ```ts\n * // Capture full tree\n * const tree = captureTree();\n *\n * // Capture with same options as watcher\n * const tree = captureTree({ tags: [FiberTag.FunctionComponent] });\n * ```\n */\nexport function captureTree<T extends FiberNodeConstraint = DefaultFiberNode>(\n options: CaptureTreeOptions<T> = {},\n): T | null {\n const { selector, serialize, tags, ...serializeOptions } = options;\n const serializeFn =\n serialize ?? (defaultSerialize as unknown as SerializeFn<T>);\n const tagSet = tags && tags.length > 0 ? new Set(tags) : null;\n\n let startFiber: Fiber | null = null;\n\n if (selector) {\n // A selector is a self-contained root lookup: React stamps the selected\n // host element with its live fiber pointer. Do not require this bundle's\n // commit cache first. CanvasHost can contain more than one bundled copy of\n // iframe-projection; they share the marked global hook, but only the copy\n // that installed it owns the module-local `lastCommittedRoots` cache.\n const element = document.querySelector(selector);\n if (element) {\n const rawFiber = getFiberFromElement(element);\n startFiber = rawFiber ? resolveCommittedFiber(rawFiber) : null;\n }\n } else {\n const hook = getHook();\n if (!hook) return null;\n\n // Find a fiber root - try multiple approaches. Whole-document capture has\n // no DOM anchor, so it legitimately depends on the hook's root registry.\n let fiberRoot: FiberRoot | null = null;\n\n // 1. Try lastCommittedRoots (populated by our hook)\n for (const roots of lastCommittedRoots.values()) {\n for (const root of roots) {\n if (root.current) {\n fiberRoot = root;\n break;\n }\n }\n if (fiberRoot) break;\n }\n\n // 2. Try renderer.getFiberRoots() if available\n if (!fiberRoot) {\n for (const [_id, renderer] of hook.renderers) {\n const roots = (renderer as any).getFiberRoots?.();\n if (roots) {\n for (const root of roots) {\n if (root?.current) {\n fiberRoot = root;\n break;\n }\n }\n }\n if (fiberRoot) break;\n }\n }\n\n if (!fiberRoot) return null;\n\n // No selector: use first child of HostRoot (same as watch)\n const rootFiber = fiberRoot.current;\n if (rootFiber && rootFiber.tag === FiberTag.HostRoot && rootFiber.child) {\n startFiber = rootFiber.child;\n } else if (rootFiber) {\n startFiber = rootFiber;\n }\n }\n\n if (!startFiber) return null;\n\n // Serialize the tree\n let tree = serializeTree(startFiber, serializeFn, serializeOptions);\n\n // Apply tag filtering if specified\n if (tree && tagSet && \"tag\" in tree) {\n const filtered = filterTreeInclude(\n tree as unknown as FiberNodeConstraint & { tag: FiberTagValue },\n tagSet,\n );\n tree = filtered as unknown as typeof tree;\n }\n\n return tree;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Hook Initialization\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Symbol to mark hooks we've initialized */\nconst HOOK_MARKER = Symbol.for(\"iframe-projection-fiber-hook\");\n\n/** Handler types */\ntype CommitHandler = (\n fiberRoot: FiberRoot,\n rendererId: number,\n didError: boolean,\n) => void;\ntype InjectHandler = (renderer: ReactRenderer, rendererId: number) => void;\ntype UnmountHandler = (fiber: Fiber, rendererId: number) => void;\n\n/**\n * Interface returned by initHook() for registering callbacks.\n */\nexport interface HookInterface {\n /** Add a handler called on each React commit. Returns unsubscribe function. */\n onCommit: (handler: CommitHandler) => () => void;\n /** Add a handler called when React registers. Returns unsubscribe function. */\n onInject: (handler: InjectHandler) => () => void;\n /** Add a handler called when a fiber unmounts. Returns unsubscribe function. */\n onUnmount: (handler: UnmountHandler) => () => void;\n /** The underlying DevTools hook object */\n hook: DevToolsHook;\n /** Seed commits captured by a synchronous pre-module bootstrap. This updates\n * iframe-projection's cache without re-delivering them to a wrapped hook. */\n seedCommittedRoots: (roots: Iterable<readonly [number, FiberRoot]>) => void;\n}\n\n/** Extended hook type with our marker */\ninterface MarkedHook extends DevToolsHook {\n [HOOK_MARKER]: HookInterface;\n}\n\n/** Cached interface (module-level singleton) */\nlet cachedInterface: HookInterface | null = null;\n\n/** Every live committed fiber root per renderer ID. One React renderer can own\n * multiple roots in the same document (micro-frontends, portals mounted through\n * separate roots, and test harnesses all do this). */\nconst lastCommittedRoots = new Map<number, Set<FiberRoot>>();\n\nfunction rememberCommittedRoot(rendererId: number, root: FiberRoot): void {\n const roots = lastCommittedRoots.get(rendererId) ?? new Set<FiberRoot>();\n for (const previous of roots) {\n if (previous !== root && previous.containerInfo === root.containerInfo) {\n roots.delete(previous);\n }\n }\n // A HostRoot with no child is still a live, authoritative `root.render(null)`\n // result. Retain it; document-scope filtering excludes roots whose containers\n // no longer belong to the watched surface.\n roots.add(root);\n lastCommittedRoots.set(rendererId, roots);\n}\n\n/** Current roots captured by the hook, in commit-insertion order. */\nexport function getCommittedFiberRoots(): FiberRoot[] {\n return [...lastCommittedRoots.values()].flatMap((roots) => [...roots]);\n}\n\n/**\n * Reset the hook state. For testing only.\n * @internal\n */\nexport function _resetHookForTesting(): void {\n cachedInterface = null;\n lastCommittedRoots.clear();\n}\n\n/**\n * Initialize the DevTools hook for fiber watching.\n *\n * This function is idempotent - safe to call multiple times:\n * - If no hook exists: creates a new one\n * - If a hook exists (e.g., DevTools extension): wraps it\n * - If already initialized by us: returns existing interface\n *\n * For best results, call this BEFORE React loads. But if React DevTools\n * extension is installed, calling after React loads still works.\n *\n * @example\n * ```ts\n * // At top of entry file (before React):\n * initHook();\n *\n * // Or get the interface for manual handler registration:\n * const { onCommit } = initHook();\n * const unsubscribe = onCommit((root, id) => console.log('Commit!'));\n * ```\n */\nexport function initHook(): HookInterface {\n // Return cached if available\n if (cachedInterface) {\n return cachedInterface;\n }\n\n // Check for existing hook\n const existing =\n typeof window !== \"undefined\"\n ? (window as { __REACT_DEVTOOLS_GLOBAL_HOOK__?: DevToolsHook })\n .__REACT_DEVTOOLS_GLOBAL_HOOK__\n : undefined;\n\n // Already initialized by us (in case cachedInterface was cleared somehow)\n if (existing && HOOK_MARKER in existing) {\n cachedInterface = (existing as MarkedHook)[HOOK_MARKER];\n return cachedInterface;\n }\n\n // Create handler sets\n const commitHandlers = new Set<CommitHandler>();\n const injectHandlers = new Set<InjectHandler>();\n const unmountHandlers = new Set<UnmountHandler>();\n\n // Helper to create add/remove functions\n const createRegistrar =\n <T>(set: Set<T>) =>\n (handler: T): (() => void) => {\n set.add(handler);\n return () => set.delete(handler);\n };\n\n // Callbacks that dispatch to all registered handlers\n const callbacks: HookCallbacks = {\n onCommit: (root, id, didError) => {\n // Store for immediate snapshots when watch() starts\n rememberCommittedRoot(id, root);\n commitHandlers.forEach((h) => h(root, id, didError));\n },\n onInject: (renderer, id) => injectHandlers.forEach((h) => h(renderer, id)),\n onUnmount: (fiber, id) => unmountHandlers.forEach((h) => h(fiber, id)),\n };\n\n let hook: DevToolsHook;\n\n if (existing) {\n // Wrap existing hook (preserves DevTools extension functionality)\n wrapDevToolsHook(existing, callbacks);\n hook = existing;\n } else {\n // Create new hook\n hook = createDevToolsHook(callbacks);\n if (typeof window !== \"undefined\") {\n (\n window as { __REACT_DEVTOOLS_GLOBAL_HOOK__?: DevToolsHook }\n ).__REACT_DEVTOOLS_GLOBAL_HOOK__ = hook;\n }\n }\n\n // Build interface\n const hookInterface: HookInterface = {\n onCommit: createRegistrar(commitHandlers),\n onInject: createRegistrar(injectHandlers),\n onUnmount: createRegistrar(unmountHandlers),\n hook,\n seedCommittedRoots(roots) {\n for (const [rendererId, root] of roots) {\n rememberCommittedRoot(rendererId, root);\n }\n },\n };\n\n // Mark the hook so we recognize it later\n (hook as MarkedHook)[HOOK_MARKER] = hookInterface;\n cachedInterface = hookInterface;\n\n return hookInterface;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// DevTools Hook\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Callbacks for DevTools hook events.\n */\nexport interface HookCallbacks {\n /** Called when React injects a renderer */\n onInject?: (renderer: ReactRenderer, id: number) => void;\n /** Called after each React commit */\n onCommit?: (\n fiberRoot: FiberRoot,\n rendererId: number,\n didError: boolean,\n ) => void;\n /** Called when a fiber unmounts */\n onUnmount?: (fiber: Fiber, rendererId: number) => void;\n}\n\n/**\n * Create a React DevTools hook.\n *\n * Install this on `window.__REACT_DEVTOOLS_GLOBAL_HOOK__` BEFORE React loads.\n * React checks for this hook exactly once at initialization time.\n *\n * @param callbacks - Optional callbacks for hook events\n *\n * @example\n * ```ts\n * // Basic usage - just install the hook\n * window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = createDevToolsHook();\n *\n * // With callbacks\n * window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = createDevToolsHook({\n * onCommit: (root, id) => console.log('Commit!', root),\n * });\n * ```\n */\nexport function createDevToolsHook(callbacks?: HookCallbacks): DevToolsHook {\n const hook: DevToolsHook = {\n supportsFiber: true,\n renderers: new Map(),\n\n inject(renderer: ReactRenderer): number {\n const id = this.renderers.size + 1;\n this.renderers.set(id, renderer);\n callbacks?.onInject?.(renderer, id);\n return id;\n },\n\n onCommitFiberRoot(\n rendererId: number,\n fiberRoot: FiberRoot,\n _priority?: number,\n didError?: boolean,\n ): void {\n callbacks?.onCommit?.(fiberRoot, rendererId, didError === true);\n },\n\n onCommitFiberUnmount(rendererId: number, fiber: Fiber): void {\n callbacks?.onUnmount?.(fiber, rendererId);\n },\n\n // Required stubs for React compatibility\n checkDCE(_fn: Function): void {},\n onScheduleFiberRoot(): void {},\n };\n\n return hook;\n}\n\n/**\n * Wrap an existing DevTools hook to intercept events.\n *\n * Use this when React DevTools extension is already installed.\n * Preserves the original hook's functionality while adding your callbacks.\n *\n * @example\n * ```ts\n * if (window.__REACT_DEVTOOLS_GLOBAL_HOOK__) {\n * wrapDevToolsHook(window.__REACT_DEVTOOLS_GLOBAL_HOOK__, {\n * onCommit: (root) => console.log('Commit intercepted!'),\n * });\n * }\n * ```\n */\nexport function wrapDevToolsHook(\n hook: DevToolsHook,\n callbacks: HookCallbacks,\n): void {\n // Wrap inject\n if (callbacks.onInject) {\n const original = hook.inject.bind(hook);\n hook.inject = function (renderer: ReactRenderer): number {\n const id = original(renderer);\n callbacks.onInject!(renderer, id);\n return id;\n };\n }\n\n // Wrap onCommitFiberRoot\n if (callbacks.onCommit) {\n const original = hook.onCommitFiberRoot?.bind(hook);\n hook.onCommitFiberRoot = function (\n rendererId: number,\n fiberRoot: FiberRoot,\n priority?: number,\n didError?: boolean,\n ): void {\n callbacks.onCommit!(fiberRoot, rendererId, didError === true);\n original?.(rendererId, fiberRoot, priority, didError);\n };\n }\n\n // Wrap onCommitFiberUnmount\n if (callbacks.onUnmount) {\n const original = hook.onCommitFiberUnmount?.bind(hook);\n hook.onCommitFiberUnmount = function (\n rendererId: number,\n fiber: Fiber,\n ): void {\n callbacks.onUnmount!(fiber, rendererId);\n original?.(rendererId, fiber);\n };\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Hook Access\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get the installed DevTools hook, if any.\n */\nexport function getHook(): DevToolsHook | null {\n if (typeof window === \"undefined\") return null;\n return window.__REACT_DEVTOOLS_GLOBAL_HOOK__ ?? null;\n}\n\n/**\n * Check if React has connected to the hook.\n */\nexport function isReactConnected(): boolean {\n const hook = getHook();\n return hook !== null && hook.renderers.size > 0;\n}\n\n/**\n * Snapshot for diagnostics: whether {@link initHook} installed our marked hook on\n * `window.__REACT_DEVTOOLS_GLOBAL_HOOK__`, and whether React has registered a renderer.\n */\nexport function getFiberHookInjectionStatus(): {\n injected: boolean;\n reactConnected: boolean;\n} {\n const hook = getHook();\n if (!hook) {\n return { injected: false, reactConnected: false };\n }\n const injected = HOOK_MARKER in hook;\n const reactConnected = hook.renderers.size > 0;\n return { injected, reactConnected };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Watch\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Options for watch().\n */\nexport interface WatchOptions<T extends FiberNodeConstraint = DefaultFiberNode>\n extends SerializeOptions {\n /**\n * Callback receiving snapshots after each relevant commit.\n */\n onChange: (snapshot: FiberSnapshot<T>) => void;\n\n /**\n * CSS selector for the element to watch.\n * If not provided, watches the entire tree.\n *\n * When set, uses fiber flags for O(1) change detection:\n * - Checks `fiber.flags | fiber.subtreeFlags` to determine if subtree changed\n * - Only serializes when the subtree actually has changes\n * - Falls back to full serialization if element not found (may appear later)\n */\n selector?: string;\n\n /**\n * Only watch a specific renderer ID.\n * If not set, watches all renderers.\n */\n rendererId?: number;\n\n /**\n * Custom serialization function.\n * If not provided, uses defaultSerialize (name + tag).\n */\n serialize?: SerializeFn<T>;\n\n /**\n * Only include nodes with these tags in the tree.\n * Other nodes are filtered out and their children promoted.\n * @example tags: [FiberTag.FunctionComponent, FiberTag.HostComponent]\n */\n tags?: FiberTagValue[];\n}\n\n/**\n * Result of calling watch().\n */\nexport interface WatchHandle {\n /** Stop watching for updates */\n stop: () => void;\n}\n\n/**\n * Watch for fiber tree changes.\n *\n * Calls onChange with a FiberSnapshot after each React commit.\n * The snapshot contains a monotonically increasing sequence number\n * and the full serialized tree (or subtree if selector is specified).\n *\n * Automatically initializes the hook if not already done (via initHook()).\n *\n * @param options - Watch options including onChange callback\n *\n * @example\n * ```ts\n * // Default watch (name + tag)\n * const { stop } = watch({\n * onChange: (snapshot) => {\n * console.log(`Commit #${snapshot.sequence}:`, snapshot.tree);\n * }\n * });\n *\n * // Watch a specific subtree with tag filtering\n * const { stop } = watch({\n * selector: '#my-component',\n * tags: [FiberTag.FunctionComponent],\n * onChange: (snapshot) => sendToParent(snapshot),\n * });\n * ```\n */\nexport function watch<T extends FiberNodeConstraint = DefaultFiberNode>(\n options: WatchOptions<T>,\n): WatchHandle {\n const {\n onChange,\n selector,\n rendererId,\n serialize,\n tags,\n ...serializeOptions\n } = options;\n const serializeFn =\n serialize ?? (defaultSerialize as unknown as SerializeFn<T>);\n const tagSet = tags && tags.length > 0 ? new Set(tags) : null;\n\n // Initialize hook (idempotent) and get commit handler registrar\n const { onCommit } = initHook();\n\n // State\n let sequence = 0;\n let hasEmittedInitial = false;\n\n /**\n * React fiber flags that indicate actual RENDER changes (content changed).\n *\n * For delta optimization, we need to distinguish:\n * 1. RENDER flags: Indicate the component's output changed (affects DOM)\n * 2. EFFECT flags: Just mean effects need to run (don't affect DOM structure)\n * 3. STATIC flags: Always present on fibers with certain effect types\n *\n * We only care about RENDER flags when finding the minimal changed subtree,\n * because effect-only changes don't affect what gets serialized.\n *\n * RENDER flags (content changed):\n * Placement = 2 - Node needs to be inserted\n * Update = 4 - Node needs to update (state/props changed)\n * ChildDeletion = 16 - Child was deleted\n * ContentReset = 32 - Text content needs reset\n * Callback = 64 - Has callback (class components)\n * DidCapture = 128 - Error boundary captured error\n * ForceClientRender = 256 - Force client render\n * Ref = 512 - Ref changed\n * Snapshot = 1024 - Needs snapshot (getSnapshotBeforeUpdate)\n *\n * EFFECT flags (excluded - don't indicate content change):\n * Passive = 2048 - useEffect needs to run\n * Visibility = 8192 - Visibility changed (offscreen)\n * StoreConsistency = 32768 - Concurrent mode store check\n *\n * STATIC flags (excluded - always present, not work indicators):\n * RefStatic = 0x400000 (bit 22)\n * PassiveStatic = 0x800000 (bit 23)\n */\n const RENDER_CHANGE_FLAGS =\n 2 | // Placement\n 4 | // Update\n 16 | // ChildDeletion\n 32 | // ContentReset\n // 64 | // Callback - lifecycle callback, doesn't affect serialized output\n 128 | // DidCapture\n 256; // ForceClientRender\n // 512 | // Ref - ref changes don't affect serialized output\n // 1024; // Snapshot - getSnapshotBeforeUpdate, doesn't affect serialized output\n // = 2038 = 0x7F6\n\n /**\n * Check if a fiber subtree has changes using fiber flags.\n * Returns true if the subtree has any pending work (flags set).\n *\n * React's fiber.flags indicates work on this fiber.\n * React's fiber.subtreeFlags aggregates flags from all descendants.\n * If both are 0, nothing in the subtree changed.\n */\n const hasSubtreeChanges = (fiber: Fiber): boolean => {\n // flags and subtreeFlags are bitmasks indicating pending work\n // Mask out static flags (PassiveStatic, RefStatic, etc.) to get actual work flags\n const flags = ((fiber as any).flags ?? 0) & RENDER_CHANGE_FLAGS;\n const subtreeFlags =\n ((fiber as any).subtreeFlags ?? 0) & RENDER_CHANGE_FLAGS;\n return (flags | subtreeFlags) !== 0;\n };\n\n /**\n * Count how many \"filtered roots\" a fiber contributes to the filtered tree.\n * If the fiber is included, it contributes 1.\n * If filtered out, its children's contributions are summed (they get promoted).\n */\n const countFilteredRoots = (\n fiber: Fiber,\n includeTags: Set<FiberTagValue>,\n ): number => {\n if (includeTags.has(fiber.tag)) {\n return 1;\n }\n // Fiber is filtered out, count children's contributions\n let count = 0;\n let child = fiber.child;\n while (child) {\n count += countFilteredRoots(child, includeTags);\n child = child.sibling;\n }\n return count;\n };\n\n /**\n * Find all first-level changed subtrees.\n * Stops at the first changed node in each branch (doesn't descend further).\n * Returns array of { fiber, path } - may be multiple if siblings changed.\n *\n * \"First-level\" means we stop at the first changed node in each branch.\n * This emits a delta for EACH first-level changed node instead of finding\n * a common ancestor. The benefit is smaller payloads and naturally correct\n * paths even with tag filtering.\n *\n * Key properties:\n * 1. Never returns filtered-out nodes (only returns where isIncluded === true)\n * 2. Multiple deltas per commit possible, but never overlapping subtrees\n * 3. Path is built as we descend with proper offset tracking\n * 4. When a filtered-out node has direct changes, all its included\n * descendants are emitted (since we don't know exactly what changed)\n */\n const findChangedSubtrees = (\n startFiber: Fiber,\n includeTags: Set<FiberTagValue> | null,\n ): Array<{ fiber: Fiber; path: number[] }> => {\n const results: Array<{ fiber: Fiber; path: number[] }> = [];\n\n /**\n * @param currentPath Path to the nearest included ancestor\n * @param pendingOffset When inside a filtered-out node, the offset from\n * preceding siblings that needs to be added to path.\n * undefined means \"no pending offset\" (path is complete).\n * @param forceEmit When true, emit this node if included (used when a\n * filtered-out ancestor has direct changes)\n */\n const collect = (\n fiber: Fiber,\n currentPath: number[],\n pendingOffset: number | undefined,\n forceEmit: boolean,\n ): void => {\n const flags = ((fiber as any).flags ?? 0) & RENDER_CHANGE_FLAGS;\n const subtreeFlags =\n ((fiber as any).subtreeFlags ?? 0) & RENDER_CHANGE_FLAGS;\n const isIncluded = !includeTags || includeTags.has(fiber.tag);\n\n // If this node is included AND either:\n // - has direct changes, OR\n // - we're forced to emit (filtered ancestor had changes)\n // → collect it with the accumulated path\n if (isIncluded && (flags !== 0 || forceEmit)) {\n // Add pendingOffset to path if we have one (meaning we traversed\n // through filtered ancestors). undefined means path is already complete.\n const finalPath =\n pendingOffset !== undefined\n ? [...currentPath, pendingOffset]\n : currentPath;\n results.push({ fiber, path: finalPath });\n return;\n }\n\n // If this node is filtered out but has direct changes,\n // we need to emit all its included descendants\n const shouldForceChildren = !isIncluded && flags !== 0;\n\n // If no changes anywhere in subtree and not forcing → done\n if ((flags | subtreeFlags) === 0 && !forceEmit) {\n return;\n }\n\n // Descend into children\n let child = fiber.child;\n let filteredIndex = 0;\n\n while (child) {\n const childIsIncluded = !includeTags || includeTags.has(child.tag);\n // Compute child's index: add any pending offset to current filtered index\n const childIndex = (pendingOffset ?? 0) + filteredIndex;\n\n if (childIsIncluded) {\n // Child is included: if parent is included, add index to path and clear\n // pending. If parent is filtered, pass index as pending offset.\n collect(\n child,\n isIncluded ? [...currentPath, childIndex] : currentPath,\n isIncluded ? undefined : childIndex,\n shouldForceChildren || forceEmit,\n );\n } else {\n // Child is filtered out: pass accumulated offset to its descendants\n collect(\n child,\n currentPath,\n childIndex,\n shouldForceChildren || forceEmit,\n );\n }\n\n // Advance filtered index (account for promotion when filtering)\n filteredIndex += includeTags\n ? countFilteredRoots(child, includeTags)\n : 1;\n\n child = child.sibling;\n }\n };\n\n collect(startFiber, [], undefined, false);\n return results;\n };\n\n /**\n * Find the starting fiber for serialization.\n * If selector is specified, finds that element's fiber.\n * Otherwise returns the app component (first child of HostRoot).\n */\n const findStartFiber = (\n fiberRoot: FiberRoot,\n ): { fiber: Fiber | null; fromSelector: boolean } => {\n if (selector) {\n const element = document.querySelector(selector);\n if (element) {\n const fiber = getFiberFromElement(element);\n if (fiber) {\n // The element's raw fiber pointer is stamped once at mount and\n // alternates between the two double-buffered generations as\n // commits land; resolve to the committed one so serialized props\n // are never one commit stale.\n return { fiber: resolveCommittedFiber(fiber), fromSelector: true };\n }\n }\n // Selector specified but element not found - return null\n return { fiber: null, fromSelector: true };\n }\n\n // No selector - use full tree starting from app component\n const rootFiber = fiberRoot.current;\n if (rootFiber.tag === FiberTag.HostRoot && rootFiber.child) {\n return { fiber: rootFiber.child, fromSelector: false };\n }\n return { fiber: rootFiber, fromSelector: false };\n };\n\n // Handler for commits\n const handleCommit = (fiberRoot: FiberRoot, id: number): void => {\n if (rendererId !== undefined && id !== rendererId) return;\n\n // Find starting fiber (full tree or selector subtree)\n const { fiber: startFiber, fromSelector } = findStartFiber(fiberRoot);\n\n // Skip if no render changes in the tree (effect-only commits don't need re-serialization)\n // But always allow the first emission (for immediate snapshot on watch() start)\n if (hasEmittedInitial && startFiber && !hasSubtreeChanges(startFiber)) {\n return;\n }\n\n // Find all changed subtrees (may be multiple if siblings changed)\n // Falls back to full tree if no flags set or first emission\n const changedSubtrees =\n startFiber && hasSubtreeChanges(startFiber)\n ? findChangedSubtrees(startFiber, tagSet)\n : [{ fiber: startFiber, path: [] as number[] }];\n\n // If no changed subtrees found (can happen with filtering), emit full tree\n const subtreesToEmit =\n changedSubtrees.length > 0\n ? changedSubtrees\n : [{ fiber: startFiber, path: [] as number[] }];\n\n // Emit a delta for each changed subtree\n for (const { fiber, path } of subtreesToEmit) {\n if (!fiber) continue;\n\n let tree = serializeTree(fiber, serializeFn, serializeOptions);\n\n // Apply tag filtering if specified\n if (tree && tagSet && \"tag\" in tree) {\n const filtered = filterTreeInclude(\n tree as unknown as FiberNodeConstraint & { tag: FiberTagValue },\n tagSet,\n );\n tree = filtered as unknown as typeof tree;\n }\n\n if (!tree) continue; // Skip if filtering removed everything\n\n const snapshot: FiberSnapshot<T> = {\n sequence: sequence++,\n tree,\n path,\n };\n\n hasEmittedInitial = true;\n onChange(snapshot);\n }\n };\n\n // Register handler and get unsubscribe function\n const unsubscribe = onCommit(handleCommit);\n\n // Emit immediate snapshot if we have a last committed root\n if (rendererId !== undefined) {\n for (const root of lastCommittedRoots.get(rendererId) ?? []) {\n handleCommit(root, rendererId);\n }\n } else {\n // Emit for all renderers\n for (const [id, roots] of lastCommittedRoots) {\n for (const root of roots) {\n handleCommit(root, id);\n }\n }\n }\n\n return {\n stop: unsubscribe,\n };\n}\n","/**\n * Head Capture Utility\n *\n * Captures relevant <head> content from a document, excluding scripts\n * and resolving relative URLs to absolute.\n *\n * ## Shared Observer Pattern\n *\n * Uses a singleton HeadTracker that maintains one MutationObserver per document,\n * shared across all subscriptions. This avoids creating 50+ observers when there\n * are many watchers on the same page.\n */\n\n/** Elements to include from <head> */\nconst INCLUDE_TAGS = new Set([\"STYLE\", \"META\", \"BASE\", \"LINK\"]);\n\n/** Link rel values to include (stylesheet-related) */\nconst INCLUDE_LINK_RELS = new Set([\"stylesheet\"]);\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Head Tracker (Shared Observer)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * A subscription to head changes for a specific document.\n * Each subscription maintains its own hasMutations flag since they flush independently.\n */\nexport interface HeadSubscription {\n /** Whether there have been mutations since last flush */\n hasMutations: boolean;\n /** Flush and get head content. Returns content if isInitial or if mutations occurred. */\n flush(isInitial: boolean): string | undefined;\n /** Unsubscribe from head changes */\n unsubscribe(): void;\n}\n\nexport interface HeadMutationDetails {\n /** Vite stylesheet module ids whose style/link nodes changed in this batch. */\n stylesheetPaths: string[];\n}\n\n/**\n * Singleton tracker that manages shared MutationObservers for head watching.\n * One observer per document, shared across all subscriptions.\n */\nexport interface HeadTracker {\n /** Subscribe to head changes for a document */\n subscribe(\n doc: Document,\n onMutation: (details: HeadMutationDetails) => void,\n ): HeadSubscription;\n /** Clean up all observers */\n destroy(): void;\n /** Cardinality only; reads maintained collection sizes and performs no DOM\n * work. Used by the performance trace attached to an emitted capture. */\n readPerfSnapshot(): { observers: number; subscriptions: number };\n}\n\n/** Module-level singleton */\nlet instance: HeadTrackerImpl | null = null;\n\n/**\n * Get the singleton HeadTracker instance.\n */\nexport function getHeadTracker(): HeadTracker {\n if (!instance) {\n instance = new HeadTrackerImpl();\n }\n return instance;\n}\n\n/**\n * Reset the singleton. For testing only.\n * @internal\n */\nexport function _resetHeadTrackerForTesting(): void {\n instance?.destroy();\n instance = null;\n}\n\n/** Internal subscription implementation */\nclass HeadSubscriptionImpl implements HeadSubscription {\n hasMutations = false;\n private doc: Document;\n private callback: (details: HeadMutationDetails) => void;\n private onUnsubscribe: () => void;\n\n constructor(\n doc: Document,\n callback: (details: HeadMutationDetails) => void,\n onUnsubscribe: () => void,\n ) {\n this.doc = doc;\n this.callback = callback;\n this.onUnsubscribe = onUnsubscribe;\n }\n\n flush(isInitial: boolean): string | undefined {\n if (!isInitial && !this.hasMutations) {\n return undefined;\n }\n this.hasMutations = false;\n return captureHead(this.doc);\n }\n\n unsubscribe(): void {\n this.onUnsubscribe();\n }\n\n /** Called by tracker when relevant mutation detected */\n notifyMutation(details: HeadMutationDetails): void {\n this.hasMutations = true;\n this.callback(details);\n }\n}\n\n/** Per-document observer state */\ninterface DocObserverState {\n observer: MutationObserver;\n subscriptions: Set<HeadSubscriptionImpl>;\n}\n\nclass HeadTrackerImpl implements HeadTracker {\n private docObservers = new Map<Document, DocObserverState>();\n private activeSubscriptions = 0;\n\n subscribe(\n doc: Document,\n onMutation: (details: HeadMutationDetails) => void,\n ): HeadSubscription {\n let docState = this.docObservers.get(doc);\n\n // Create observer for this document if first subscription\n if (!docState) {\n docState = this.createDocObserver(doc);\n this.docObservers.set(doc, docState);\n }\n\n const subscription = new HeadSubscriptionImpl(doc, onMutation, () => {\n this.unsubscribe(doc, subscription);\n });\n docState.subscriptions.add(subscription);\n this.activeSubscriptions += 1;\n\n return subscription;\n }\n\n private createDocObserver(doc: Document): DocObserverState {\n const subscriptions = new Set<HeadSubscriptionImpl>();\n\n const notify = (details: HeadMutationDetails): void => {\n for (const sub of subscriptions) {\n sub.notifyMutation(details);\n }\n };\n\n const observeHead = (head: HTMLHeadElement): MutationObserver => {\n const observer = new MutationObserver((mutations) => {\n const details = this.readRelevantMutations(mutations, head);\n if (!details) return;\n notify(details);\n });\n observer.observe(head, {\n childList: true,\n subtree: true,\n attributes: true,\n characterData: true,\n });\n return observer;\n };\n\n if (doc.head) {\n return { observer: observeHead(doc.head), subscriptions };\n }\n\n // The document has no <head> yet — subscribers can attach before parsing\n // (e.g. a producer created from a frame preload). Watch for the head to\n // appear, then swap in the real observer and report one synthetic\n // mutation so subscribers capture the head they never saw arrive.\n const bootstrap = new MutationObserver(() => {\n const head = doc.head;\n if (!head) return;\n bootstrap.disconnect();\n state.observer = observeHead(head);\n notify({ stylesheetPaths: [] });\n });\n bootstrap.observe(doc, { childList: true, subtree: true });\n const state: DocObserverState = { observer: bootstrap, subscriptions };\n return state;\n }\n\n private unsubscribe(doc: Document, sub: HeadSubscriptionImpl): void {\n const docState = this.docObservers.get(doc);\n if (!docState) return;\n\n if (!docState.subscriptions.delete(sub)) return;\n this.activeSubscriptions = Math.max(0, this.activeSubscriptions - 1);\n\n // Disconnect observer if no more subscriptions for this document\n if (docState.subscriptions.size === 0) {\n docState.observer.disconnect();\n this.docObservers.delete(doc);\n }\n }\n\n /**\n * Check if mutations contain changes to elements we care about.\n * This filtering runs once per mutation batch (not once per subscription).\n */\n private readRelevantMutations(\n mutations: MutationRecord[],\n head: HTMLHeadElement,\n ): HeadMutationDetails | null {\n let relevant = false;\n const stylesheetPaths = new Set<string>();\n const collectStylesheetPath = (node: Node | null): void => {\n const element =\n node instanceof Element ? node : (node?.parentElement ?? null);\n if (!element) return;\n const candidates = [\n element,\n ...element.querySelectorAll(\n \"style[data-vite-dev-id], link[rel~='stylesheet']\",\n ),\n ];\n for (const candidate of candidates) {\n if (candidate instanceof HTMLStyleElement) {\n const id = candidate.getAttribute(\"data-vite-dev-id\")?.trim();\n if (id) stylesheetPaths.add(id);\n } else if (\n candidate instanceof HTMLLinkElement &&\n shouldIncludeLink(candidate)\n ) {\n const href = candidate.getAttribute(\"href\")?.trim() || candidate.href;\n if (href) stylesheetPaths.add(href);\n }\n }\n };\n\n for (const mutation of mutations) {\n const target = mutation.target;\n const element = target instanceof Element ? target : target.parentElement;\n\n if (!element || (!head.contains(element) && target !== head)) continue;\n\n // Check if this is a relevant element (one we would capture)\n const tagName = element.tagName;\n if (INCLUDE_TAGS.has(tagName)) {\n // For LINK, check if it's a stylesheet\n if (tagName === \"LINK\") {\n if (!shouldIncludeLink(element)) continue;\n }\n relevant = true;\n collectStylesheetPath(element);\n }\n\n // Also trigger for childList mutations on head itself (added/removed elements)\n if (mutation.type === \"childList\" && target === head) {\n relevant = true;\n }\n if (mutation.type === \"childList\") {\n for (const node of mutation.addedNodes) collectStylesheetPath(node);\n for (const node of mutation.removedNodes) collectStylesheetPath(node);\n }\n }\n return relevant ? { stylesheetPaths: [...stylesheetPaths] } : null;\n }\n\n destroy(): void {\n for (const docState of this.docObservers.values()) {\n docState.observer.disconnect();\n docState.subscriptions.clear();\n }\n this.docObservers.clear();\n this.activeSubscriptions = 0;\n }\n\n readPerfSnapshot(): { observers: number; subscriptions: number } {\n return {\n observers: this.docObservers.size,\n subscriptions: this.activeSubscriptions,\n };\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Legacy API (Backward Compatibility)\n// These functions delegate to the shared tracker for backward compatibility\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * State for a head watcher instance.\n * @deprecated Use getHeadTracker().subscribe() instead for better performance\n */\nexport interface HeadWatcher {\n /** The document being watched */\n doc: Document;\n /** Whether there have been mutations since last flush */\n hasMutations: boolean;\n /** Stop watching */\n stop: () => void;\n}\n\n/**\n * Starts watching a document's <head> for mutations.\n * @deprecated Use getHeadTracker().subscribe() instead for better performance\n */\nexport function watchHead(doc: Document, onMutation: () => void): HeadWatcher {\n const subscription = getHeadTracker().subscribe(doc, onMutation);\n\n // Wrap subscription in legacy HeadWatcher interface\n return {\n doc,\n get hasMutations() {\n return subscription.hasMutations;\n },\n set hasMutations(value: boolean) {\n subscription.hasMutations = value;\n },\n stop: () => subscription.unsubscribe(),\n };\n}\n\n/**\n * Checks if watcher has any pending head mutations.\n * @deprecated Access subscription.hasMutations directly\n */\nexport function hasPendingHeadChanges(watcher: HeadWatcher): boolean {\n return watcher.hasMutations;\n}\n\n/**\n * Flushes the head watcher, returning captured head content if there were changes.\n * @deprecated Use subscription.flush() directly\n */\nexport function flushHeadWatcher(\n watcher: HeadWatcher,\n isInitial: boolean,\n): string | undefined {\n if (!isInitial && !watcher.hasMutations) {\n return undefined;\n }\n watcher.hasMutations = false;\n return captureHead(watcher.doc);\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Head Capture\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Captures the <head> content from a document.\n *\n * - Includes: <style>, <link rel=\"stylesheet\">, <meta>, <base>\n * - Excludes: <script>, <title>, <link rel=\"icon/preload/etc\">\n * - Resolves relative URLs to absolute using document.baseURI\n *\n * @param doc - The document to capture head from\n * @returns Serialized head content (innerHTML for destination <head>)\n */\nexport function captureHead(doc: Document): string {\n const head = doc.head;\n if (!head) return \"\";\n\n const baseURI = doc.baseURI;\n const fragments: string[] = [];\n\n for (const child of Array.from(head.children)) {\n const tagName = child.tagName;\n\n // Skip non-included tags\n if (!INCLUDE_TAGS.has(tagName)) continue;\n\n // For <link>, only include stylesheets\n if (tagName === \"LINK\") {\n if (!shouldIncludeLink(child)) continue;\n if (isDisabledStylesheet(child)) continue;\n }\n\n // Exclude Content-Security-Policy meta tags (they block srcdoc assets)\n if (tagName === \"META\") {\n const httpEquiv = child.getAttribute(\"http-equiv\")?.toLowerCase();\n const name = child.getAttribute(\"name\")?.toLowerCase();\n if (\n httpEquiv === \"content-security-policy\" ||\n name === \"content-security-policy\"\n ) {\n continue;\n }\n }\n\n // Clone and resolve URLs\n let clone = child.cloneNode(true) as Element;\n materializeStyleElementCssom(child, clone);\n if (tagName === \"LINK\") {\n clone = materializeStylesheetLinkCssom(child, clone);\n }\n resolveUrls(clone, baseURI);\n\n // Strip crossorigin from stylesheet links so they load in no-cors mode\n // in srcdoc projection iframes (which have a null origin that won't\n // match any server's Access-Control-Allow-Origin header)\n if (clone.tagName === \"LINK\") {\n clone.removeAttribute(\"crossorigin\");\n } else if (clone.tagName === \"STYLE\") {\n escapeStyleForHtmlSerialization(clone);\n }\n\n fragments.push(clone.outerHTML);\n }\n\n fragments.push(...captureAdoptedStyleSheets(doc));\n\n return fragments.join(\"\\n\");\n}\n\n/**\n * Same-origin stylesheets are already readable in the source page. Preserve\n * their authored rules as an inline style before the projection crosses into\n * its null-origin document. Opaque cross-origin sheets remain links and may be\n * handled by a consumer-specific, policy-checked fallback later.\n */\nfunction materializeStylesheetLinkCssom(\n source: Element,\n clone: Element,\n): Element {\n const link = source as HTMLLinkElement;\n const cssText = serializeCssRules(link.sheet);\n if (!cssText) {\n return clone;\n }\n\n const style = source.ownerDocument.createElement(\"style\");\n for (const attribute of Array.from(source.attributes)) {\n if (\n [\n \"as\",\n \"crossorigin\",\n \"fetchpriority\",\n \"href\",\n \"integrity\",\n \"referrerpolicy\",\n \"rel\",\n ].includes(attribute.name.toLowerCase())\n ) {\n continue;\n }\n style.setAttribute(attribute.name, attribute.value);\n }\n style.setAttribute(\"data-projection-stylesheet-href\", link.href);\n style.textContent = absolutifyCssReferences(cssText, link.href);\n return style;\n}\n\n/**\n * CSS-in-JS and framework runtimes can insert rules through CSSOM APIs, leaving\n * the DOM <style> text empty. Clone-time materialization preserves those rules\n * without mutating the live host document.\n */\nfunction materializeStyleElementCssom(source: Element, clone: Element): void {\n if (source.tagName !== \"STYLE\" || clone.tagName !== \"STYLE\") {\n return;\n }\n\n const style = source as HTMLStyleElement;\n const text = style.textContent ?? \"\";\n if (text.trim().length > 0) {\n return;\n }\n\n const cssText = serializeCssRules(style.sheet);\n if (cssText) {\n clone.textContent = cssText;\n }\n}\n\nfunction captureAdoptedStyleSheets(doc: Document): string[] {\n const sheets = Array.from(doc.adoptedStyleSheets ?? []);\n if (sheets.length === 0) {\n return [];\n }\n\n const fragments: string[] = [];\n for (const sheet of sheets) {\n const cssText = serializeCssRules(sheet);\n if (!cssText) {\n continue;\n }\n const style = doc.createElement(\"style\");\n style.setAttribute(\"data-projection-adopted-stylesheet\", \"true\");\n style.textContent = cssText;\n escapeStyleForHtmlSerialization(style);\n fragments.push(style.outerHTML);\n }\n return fragments;\n}\n\nfunction escapeStyleForHtmlSerialization(style: Element): void {\n style.textContent = (style.textContent ?? \"\").replace(/<\\//gi, \"<\\\\/\");\n}\n\nfunction serializeCssRules(sheet: CSSStyleSheet | null): string {\n if (!sheet) {\n return \"\";\n }\n\n try {\n return Array.from(sheet.cssRules)\n .map((rule) => rule.cssText)\n .join(\"\\n\");\n } catch {\n // Cross-origin or otherwise unreadable stylesheet.\n return \"\";\n }\n}\n\nfunction absolutifyCssReferences(cssText: string, baseHref: string): string {\n if (!/^https?:/i.test(baseHref)) {\n return cssText;\n }\n\n const resolve = (value: string): string => {\n const trimmed = value.trim();\n if (\n !trimmed ||\n trimmed.startsWith(\"#\") ||\n /^(?:data|blob|javascript):/i.test(trimmed)\n ) {\n return /^javascript:/i.test(trimmed) ? \"\" : trimmed;\n }\n try {\n return new URL(trimmed, baseHref).href;\n } catch {\n return trimmed;\n }\n };\n\n return cssText\n .replace(\n /url\\(\\s*([\"']?)([^\"')]+)\\1\\s*\\)/gi,\n (_match, quote: string, value: string) =>\n `url(${quote}${resolve(value)}${quote})`,\n )\n .replace(\n /@import\\s+([\"'])([^\"']+)\\1/gi,\n (_match, quote: string, value: string) =>\n `@import ${quote}${resolve(value)}${quote}`,\n );\n}\n\nfunction shouldIncludeLink(element: Element): boolean {\n const rel = element.getAttribute(\"rel\");\n if (!rel) {\n return false;\n }\n return rel\n .toLowerCase()\n .split(/\\s+/)\n .some((token) => INCLUDE_LINK_RELS.has(token));\n}\n\nfunction isDisabledStylesheet(element: Element): boolean {\n const link = element as HTMLLinkElement;\n return link.disabled || link.sheet?.disabled === true;\n}\n\n/**\n * Resolves relative URLs in an element to absolute URLs.\n */\nfunction resolveUrls(element: Element, baseURI: string): void {\n // Skip URL resolution if baseURI is not a valid HTTP(S) URL\n // (e.g., in test environments where baseURI is \"about:blank\")\n if (!baseURI || !baseURI.startsWith(\"http\")) {\n return;\n }\n\n // Resolve href attribute (for <link>, <base>)\n const href = element.getAttribute(\"href\");\n if (href && !isAbsoluteUrl(href)) {\n try {\n element.setAttribute(\"href\", new URL(href, baseURI).href);\n } catch {\n // Keep original href if URL resolution fails\n }\n }\n\n // Resolve src attribute (for future-proofing)\n const src = element.getAttribute(\"src\");\n if (src && !isAbsoluteUrl(src)) {\n try {\n element.setAttribute(\"src\", new URL(src, baseURI).href);\n } catch {\n // Keep original src if URL resolution fails\n }\n }\n}\n\n/**\n * Checks if a URL is absolute.\n */\nfunction isAbsoluteUrl(url: string): boolean {\n return /^(https?:)?\\/\\//i.test(url) || url.startsWith(\"data:\");\n}\n","/**\n * Capture-flush perf counters.\n *\n * Module-local mutable counters incremented by the hot paths that run inside\n * a combined-watch flush: the displayability walk's getComputedStyle reads,\n * the layout-kind style read during fiber serialization, and the\n * render-identity declaration walks. The flush resets them before capturing\n * and reads them after, shipping the totals on the emitted capture's `perf`\n * field — so the paths themselves never thread perf parameters through their\n * signatures. Increment-only: no DOM reads, no allocation.\n *\n * The same functions also run outside a flush (one-shot capture APIs); those\n * increments are simply discarded by the next flush's reset.\n */\n\ninterface CaptureFlushCounters {\n styleReadCount: number;\n identityNodesVisited: number;\n sourceVersionDomScanNodes: number;\n sourceVersionFiberSerializeNodes: number;\n sourceVersionFiberReductionNodes: number;\n sourceVersionFallbackScanNodes: number;\n}\n\nconst counters: CaptureFlushCounters = {\n styleReadCount: 0,\n identityNodesVisited: 0,\n sourceVersionDomScanNodes: 0,\n sourceVersionFiberSerializeNodes: 0,\n sourceVersionFiberReductionNodes: 0,\n sourceVersionFallbackScanNodes: 0,\n};\n\nconst producerReferencesByDocument = new Map<Document, number>();\nlet activeDocumentProducers = 0;\nlet activeRootObservers = 0;\nlet activeReactCommitSubscriptions = 0;\n\n/** Register one document producer and its one React commit subscription. */\nexport function registerDocumentCaptureProducer(\n document: Document,\n): () => void {\n const references = producerReferencesByDocument.get(document) ?? 0;\n if (references === 0) activeDocumentProducers += 1;\n producerReferencesByDocument.set(document, references + 1);\n activeReactCommitSubscriptions += 1;\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n const current = producerReferencesByDocument.get(document) ?? 0;\n if (current <= 1) {\n producerReferencesByDocument.delete(document);\n activeDocumentProducers = Math.max(0, activeDocumentProducers - 1);\n } else {\n producerReferencesByDocument.set(document, current - 1);\n }\n activeReactCommitSubscriptions = Math.max(\n 0,\n activeReactCommitSubscriptions - 1,\n );\n };\n}\n\n/** Register one independently observed projection root. */\nexport function registerCaptureRootObserver(): () => void {\n activeRootObservers += 1;\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n activeRootObservers = Math.max(0, activeRootObservers - 1);\n };\n}\n\nexport function readCaptureProducerCardinality(): {\n activeDocumentProducers: number;\n activeRootObservers: number;\n reactCommitSubscriptions: number;\n} {\n return {\n activeDocumentProducers,\n activeRootObservers,\n reactCommitSubscriptions: activeReactCommitSubscriptions,\n };\n}\n\n/** @internal Test isolation for producer ownership counters. */\nexport function _resetCaptureProducerCardinalityForTesting(): void {\n producerReferencesByDocument.clear();\n activeDocumentProducers = 0;\n activeRootObservers = 0;\n activeReactCommitSubscriptions = 0;\n}\n\n/** One getComputedStyle call on the capture path. */\nexport function countCaptureStyleRead(): void {\n counters.styleReadCount += 1;\n}\n\n/** One element/node visited by a render-identity declaration walk. */\nexport function countIdentityNodeVisited(): void {\n counters.identityNodesVisited += 1;\n}\n\nexport function countSourceVersionDomScanNode(): void {\n counters.sourceVersionDomScanNodes += 1;\n}\n\nexport function countSourceVersionFiberSerializeNode(): void {\n counters.sourceVersionFiberSerializeNodes += 1;\n}\n\nexport function countSourceVersionFiberReductionNode(): void {\n counters.sourceVersionFiberReductionNodes += 1;\n}\n\nexport function countSourceVersionFallbackScanNode(): void {\n counters.sourceVersionFallbackScanNodes += 1;\n}\n\nexport function resetCaptureFlushCounters(): void {\n counters.styleReadCount = 0;\n counters.identityNodesVisited = 0;\n counters.sourceVersionDomScanNodes = 0;\n counters.sourceVersionFiberSerializeNodes = 0;\n counters.sourceVersionFiberReductionNodes = 0;\n counters.sourceVersionFallbackScanNodes = 0;\n}\n\nexport function readCaptureFlushCounters(): Readonly<CaptureFlushCounters> {\n return { ...counters };\n}\n","import type { DomCapture } from \"../html/types\";\nimport { getHeadTracker } from \"../html/watch-head\";\nimport {\n readCaptureFlushCounters,\n readCaptureProducerCardinality,\n} from \"../shared/capture-perf\";\nimport type { CaptureProducerPerf } from \"./types\";\n\nexport interface BuildProjectionCapturePerfInput {\n readonly flushStartedAt: number;\n readonly snapshotMs: number;\n readonly identityMs: number;\n readonly html: DomCapture | undefined;\n readonly head?: string;\n readonly fiberNodeCount: number;\n readonly changedNodeEstimate: number;\n readonly fixedWindowTimersOpened: number;\n readonly maxSimultaneousTimers: number;\n readonly flushIntervalMs: number | null;\n readonly rawMutationRecords: number;\n readonly rawStateRecords: number;\n readonly rawPortalRecords: number;\n readonly producerCandidateNodes?: number;\n readonly producerVisitedNodes?: number;\n readonly candidateTargetsBeforeCoalescing: number;\n readonly candidateTargetsAfterCoalescing: number;\n readonly semanticDiscoveryNodesVisited?: number;\n readonly rootsPerBatch: number;\n readonly fullSnapshotReason: string | null;\n /** Closed-projection serializers can provide their already-known totals\n * without constructing a legacy DomCapture solely for instrumentation. */\n readonly htmlChars?: number;\n readonly domNodesSerialized?: number;\n readonly semanticNodesSerialized?: number;\n readonly annotationTargetsSerialized?: number;\n readonly stateTargetsSerialized?: number;\n readonly portalTargetsSerialized?: number;\n readonly observedFileEntries?: number;\n}\n\n/**\n * Assemble the producer receipt exclusively from facts already collected by\n * the real capture. This function performs no discovery traversal and no\n * destination diagnostic read.\n */\nexport function buildProjectionCapturePerf(\n input: BuildProjectionCapturePerfInput,\n): CaptureProducerPerf {\n const flushCounters = readCaptureFlushCounters();\n const cardinality = readCaptureProducerCardinality();\n const headCardinality = getHeadTracker().readPerfSnapshot();\n let htmlChars = input.html?.dom.html.length ?? 0;\n for (const portal of input.html?.portals ?? []) {\n htmlChars += portal.html.length;\n }\n\n return {\n flushStartedAt: input.flushStartedAt,\n flushMs: Date.now() - input.flushStartedAt,\n snapshotMs: input.snapshotMs,\n identityMs: input.identityMs,\n identityNodesVisited: flushCounters.identityNodesVisited,\n sourceVersionDomScanNodes: flushCounters.sourceVersionDomScanNodes,\n sourceVersionFiberSerializeNodes:\n flushCounters.sourceVersionFiberSerializeNodes,\n sourceVersionFiberReductionNodes:\n flushCounters.sourceVersionFiberReductionNodes,\n sourceVersionFallbackScanNodes:\n flushCounters.sourceVersionFallbackScanNodes,\n sourceVersionScanNodes:\n flushCounters.sourceVersionDomScanNodes +\n flushCounters.sourceVersionFiberSerializeNodes +\n flushCounters.sourceVersionFiberReductionNodes +\n flushCounters.sourceVersionFallbackScanNodes,\n styleReadCount: flushCounters.styleReadCount,\n htmlChars: input.htmlChars ?? htmlChars,\n headChars: input.head?.length ?? 0,\n fiberNodeCount: input.fiberNodeCount,\n changedNodeEstimate: input.changedNodeEstimate,\n ...cardinality,\n headObservers: headCardinality.observers,\n headSubscriptions: headCardinality.subscriptions,\n fixedWindowTimersOpened: input.fixedWindowTimersOpened,\n maxSimultaneousTimers: input.maxSimultaneousTimers,\n flushIntervalMs: input.flushIntervalMs,\n rawMutationRecords: input.rawMutationRecords,\n rawStateRecords: input.rawStateRecords,\n rawPortalRecords: input.rawPortalRecords,\n producerCandidateNodes:\n input.producerCandidateNodes ?? input.candidateTargetsBeforeCoalescing,\n producerVisitedNodes:\n input.producerVisitedNodes ?? input.candidateTargetsAfterCoalescing,\n candidateTargetsBeforeCoalescing: input.candidateTargetsBeforeCoalescing,\n candidateTargetsAfterCoalescing: input.candidateTargetsAfterCoalescing,\n semanticDiscoveryNodesVisited: input.semanticDiscoveryNodesVisited ?? 0,\n domNodesSerialized: input.domNodesSerialized ?? null,\n semanticNodesSerialized:\n input.semanticNodesSerialized ?? input.fiberNodeCount,\n annotationTargetsSerialized:\n input.annotationTargetsSerialized ??\n input.html?.declared.containedAnchors.length ??\n 0,\n stateTargetsSerialized:\n input.stateTargetsSerialized ?? input.html?.states.length ?? 0,\n portalTargetsSerialized:\n input.portalTargetsSerialized ?? input.html?.portals?.length ?? 0,\n headSerializations: input.head === undefined ? 0 : 1,\n observedFileEntries:\n input.observedFileEntries ??\n Object.keys(input.html?.declared.observedVersions ?? {}).length,\n batchesEmitted: 1,\n rootsPerBatch: input.rootsPerBatch,\n fullSnapshotReason: input.fullSnapshotReason,\n };\n}\n","/**\n * Declared Capture Facts (producer-side)\n *\n * Computes the `DeclaredCaptureFacts` a capture producer attaches to its\n * `DomCapture`. Everything here reads the LIVE DOM the producer already\n * holds — never the serialized HTML string — so the facts are ground truth\n * rather than a re-parse of the payload. See specs/canvas-determinism.md §4.\n */\n\nimport type { DeclaredCaptureFacts } from \"./types\";\n\n/**\n * Two annotation namespaces stamp the source-mapped iframe DOM:\n * - JSX: `data-tempo-filepath` + `data-tempo-position` + `data-tempo-modifiedts`\n * - HTML: `data-tempo-html-filepath` + `data-tempo-html-offset` +\n * `data-tempo-html-modifiedts`\n * A single element may carry BOTH (an HTML element nested inside a JSX host\n * that also got source-located), so each namespace is read independently.\n */\nconst SOURCE_ANNOTATED_SELECTOR =\n \"[data-tempo-filepath], [data-tempo-html-filepath]\";\n\ninterface AnnotationNamespace {\n filepathAttr: string;\n positionAttr: string;\n modifiedTsAttr: string;\n sourceVersionAttr: string;\n}\n\nconst NAMESPACES: readonly AnnotationNamespace[] = [\n {\n filepathAttr: \"data-tempo-filepath\",\n positionAttr: \"data-tempo-position\",\n modifiedTsAttr: \"data-tempo-modifiedts\",\n sourceVersionAttr: \"data-tempo-source-version\",\n },\n {\n filepathAttr: \"data-tempo-html-filepath\",\n positionAttr: \"data-tempo-html-offset\",\n modifiedTsAttr: \"data-tempo-html-modifiedts\",\n sourceVersionAttr: \"data-tempo-html-source-version\",\n },\n];\n\n/**\n * Compute the declared facts for a capture.\n *\n * @param targetElement - The element whose subtree is serialized into\n * `dom.html` (the mutation LCA for scoped captures, or the capture root\n * for whole-surface ones).\n * @param captureRoot - The watched root. `complete` is `targetElement ===\n * captureRoot`. The render-error probe searches the WHOLE root (the error\n * overlay is a surface-level fact, not necessarily inside the scoped LCA).\n * @param scopeSelector - The selector the producer already computed for\n * `targetElement` relative to `captureRoot` (\"\" for whole-surface).\n * Surfaced as `scopeSelector` only when the capture is not complete.\n * @param portalElements - Live portal root elements whose content the\n * producer also serializes into `portals`. Their annotations count toward\n * `observedVersions`/`containedAnchors` exactly as the DOM subtree's do.\n */\nexport function computeDeclaredFacts(\n targetElement: Element,\n captureRoot: Element,\n scopeSelector: string,\n portalElements: readonly Element[],\n): DeclaredCaptureFacts {\n const observedVersions: Record<string, number> = {};\n const observedSourceVersions: Record<string, string> = {};\n const anchorSet = new Set<string>();\n\n const visit = (element: Element): void => {\n for (const ns of NAMESPACES) {\n const filepath = element.getAttribute(ns.filepathAttr);\n if (filepath == null || filepath.length === 0) continue;\n\n const modifiedTsRaw = element.getAttribute(ns.modifiedTsAttr);\n if (modifiedTsRaw != null) {\n const modifiedTs = Number(modifiedTsRaw);\n if (!Number.isNaN(modifiedTs)) {\n const existing = observedVersions[filepath];\n if (existing === undefined || modifiedTs > existing) {\n observedVersions[filepath] = modifiedTs;\n // Co-locate the content-version token with the newest render: it\n // rides the same element that just set the file's MAX modifiedts.\n // Clear a stale token from an older render when the newest element\n // carries none (a mid-HMR mixed tree, or an old-SDK element).\n const version = element.getAttribute(ns.sourceVersionAttr);\n if (version != null && version.length > 0) {\n observedSourceVersions[filepath] = version;\n } else {\n delete observedSourceVersions[filepath];\n }\n }\n }\n }\n\n const position = element.getAttribute(ns.positionAttr);\n if (position != null && position.length > 0) {\n anchorSet.add(`${filepath} ${position}`);\n }\n }\n };\n\n // The serialized population: the target subtree (including the target\n // element itself, whose annotations travel in `dom.attributes`) plus every\n // portal root and its descendants.\n const walkRoots: readonly Element[] = [targetElement, ...portalElements];\n for (const root of walkRoots) {\n if (root.matches(SOURCE_ANNOTATED_SELECTOR)) visit(root);\n for (const annotated of root.querySelectorAll(SOURCE_ANNOTATED_SELECTOR)) {\n visit(annotated);\n }\n }\n\n const complete = targetElement === captureRoot;\n\n return {\n complete,\n scopeSelector: complete ? null : scopeSelector,\n observedVersions,\n observedSourceVersions,\n containedAnchors: Array.from(anchorSet),\n renderError: computeRenderError(captureRoot),\n };\n}\n\n/**\n * Render-error boundary state for a capture root. Non-null iff a\n * `[data-render-error=\"true\"]` element exists anywhere in the live root\n * subtree (or is the root itself); its `data-render-error-message` becomes\n * `message` when present.\n */\nfunction computeRenderError(\n captureRoot: Element,\n): DeclaredCaptureFacts[\"renderError\"] {\n const errorElement = captureRoot.matches('[data-render-error=\"true\"]')\n ? captureRoot\n : captureRoot.querySelector('[data-render-error=\"true\"]');\n if (!errorElement) return null;\n return {\n message: errorElement.getAttribute(\"data-render-error-message\"),\n };\n}\n","import { countCaptureStyleRead } from \"../shared/capture-perf\";\nimport type { CaptureDisplayability } from \"./types\";\n\n/** Elements whose descendants do not contribute projected pixels/content. */\nconst IGNORED_CONTENT_TAGS = new Set([\n \"DATALIST\",\n \"LINK\",\n \"META\",\n \"NOSCRIPT\",\n \"SCRIPT\",\n \"STYLE\",\n \"TEMPLATE\",\n]);\n\nconst VISUAL_ASSET_TAGS = new Set([\n \"AUDIO\",\n \"CANVAS\",\n \"EMBED\",\n \"IFRAME\",\n \"IMG\",\n \"INPUT\",\n \"OBJECT\",\n \"SELECT\",\n \"SVG\",\n \"TEXTAREA\",\n \"VIDEO\",\n]);\n\n/**\n * Measures displayable structure in a live, styled document.\n *\n * The capture root itself is excluded because `DomCapture.dom.html` contains\n * its children. Supplemental roots are included because portal updates carry\n * each portal root's `outerHTML`. A null result means no browsing context was\n * available, so callers must omit the proof rather than infer it from markup.\n */\nexport function measureComputedDisplayability(\n captureRoot: Element,\n supplementalRoots: readonly Element[] = [],\n): CaptureDisplayability | null {\n const doc = captureRoot.ownerDocument;\n const view = doc.defaultView;\n if (\n !view ||\n !captureRoot.isConnected ||\n supplementalRoots.some(\n (root) => root.ownerDocument !== doc || !root.isConnected,\n )\n ) {\n return null;\n }\n\n const result: CaptureDisplayability = {\n version: 1,\n elementCount: 0,\n paintedElementCount: 0,\n nonEmptyTextNodeCount: 0,\n visualAssetCount: 0,\n };\n\n try {\n const rootBlocked = hasBlockingElementInChain(captureRoot, view);\n const rootTextVisible =\n !rootBlocked && elementHasVisibleComputedVisibility(captureRoot, view);\n for (const child of Array.from(captureRoot.childNodes)) {\n visitNode(child, rootBlocked, rootTextVisible, view, result);\n }\n\n for (const supplementalRoot of supplementalRoots) {\n visitNode(\n supplementalRoot,\n hasBlockingElementInChain(supplementalRoot.parentElement, view),\n true,\n view,\n result,\n );\n }\n } catch {\n // A producer declaration is proof. If style inspection is unavailable for\n // any part of the render domain, omit the whole profile conservatively.\n return null;\n }\n\n return result;\n}\n\nfunction visitNode(\n node: Node,\n blockedByAncestor: boolean,\n parentTextVisible: boolean,\n view: Window,\n result: CaptureDisplayability,\n): void {\n if (node.nodeType === 3) {\n if (\n !blockedByAncestor &&\n parentTextVisible &&\n (node.textContent?.trim().length ?? 0) > 0\n ) {\n result.nonEmptyTextNodeCount += 1;\n }\n return;\n }\n if (node.nodeType !== 1) return;\n\n const element = node as Element;\n const blocked = blockedByAncestor || elementBlocksSubtree(element, view);\n if (blocked) return;\n\n const visible = elementHasVisibleComputedVisibility(element, view);\n if (visible) {\n result.elementCount += 1;\n if (elementPaintsOwnPixels(element, view)) {\n result.paintedElementCount = (result.paintedElementCount ?? 0) + 1;\n }\n if (VISUAL_ASSET_TAGS.has(element.tagName)) {\n result.visualAssetCount += 1;\n }\n }\n\n for (const child of Array.from(element.childNodes)) {\n visitNode(child, false, visible, view, result);\n }\n}\n\nfunction elementPaintsOwnPixels(element: Element, view: Window): boolean {\n countCaptureStyleRead();\n const style = view.getComputedStyle(element);\n if (colorCanPaint(style.backgroundColor)) return true;\n if (style.backgroundImage && style.backgroundImage !== \"none\") return true;\n if (style.boxShadow && style.boxShadow !== \"none\") return true;\n if (\n style.outlineStyle !== \"none\" &&\n parseFloat(style.outlineWidth) > 0 &&\n colorCanPaint(style.outlineColor)\n ) {\n return true;\n }\n for (const side of [\"Top\", \"Right\", \"Bottom\", \"Left\"] as const) {\n if (\n style[`border${side}Style`] !== \"none\" &&\n parseFloat(style[`border${side}Width`]) > 0 &&\n colorCanPaint(style[`border${side}Color`])\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction colorCanPaint(value: string): boolean {\n const normalized = value.trim().toLowerCase().replace(/ /g, \"\");\n if (!normalized || normalized === \"transparent\") return false;\n return !(\n /^rgba\\([^)]*,0(?:\\.0+)?\\)$/.test(normalized) ||\n /^rgb\\([^)]*\\/0(?:\\.0+)?\\)$/.test(normalized)\n );\n}\n\nfunction hasBlockingElementInChain(\n start: Element | null,\n view: Window,\n): boolean {\n for (let element = start; element; element = element.parentElement) {\n if (elementBlocksSubtree(element, view)) return true;\n }\n return false;\n}\n\nfunction elementBlocksSubtree(element: Element, view: Window): boolean {\n if (IGNORED_CONTENT_TAGS.has(element.tagName)) return true;\n if (element.hasAttribute(\"hidden\")) return true;\n if (element.tagName === \"DIALOG\" && !element.hasAttribute(\"open\")) {\n return true;\n }\n if (\n element.tagName === \"INPUT\" &&\n element.getAttribute(\"type\")?.trim().toLowerCase() === \"hidden\"\n ) {\n return true;\n }\n\n countCaptureStyleRead();\n const style = view.getComputedStyle(element);\n const opacity = style.opacity.trim();\n return (\n style.display === \"none\" ||\n (opacity.length > 0 && Number(opacity) <= 0) ||\n style.getPropertyValue(\"content-visibility\") === \"hidden\"\n );\n}\n\nfunction elementHasVisibleComputedVisibility(\n element: Element,\n view: Window,\n): boolean {\n countCaptureStyleRead();\n const visibility = view.getComputedStyle(element).visibility;\n return visibility !== \"hidden\" && visibility !== \"collapse\";\n}\n","/**\n * CSS Selector Utilities\n *\n * Pure functions for generating CSS selectors.\n */\n\n/**\n * Generates a unique CSS selector path for an element.\n *\n * Uses nth-of-type notation when needed for uniqueness among siblings.\n *\n * @param element - Element to generate selector for\n * @param root - Optional root element to stop at (selector will be relative to this)\n * @returns CSS selector path (e.g., \"body > div > button:nth-of-type(2)\")\n *\n * @example\n * ```ts\n * generateSelector(document.querySelector('button'));\n * // \"body > div > button\"\n *\n * generateSelector(button, container);\n * // \"div > button\" (relative to container)\n * ```\n */\nexport function generateSelector(element: Element, root?: Element): string {\n // Special cases for well-known elements\n if (!root) {\n if (element === document.documentElement) return \":root\";\n if (element === document.head) return \"head\";\n if (element === document.body) return \"body\";\n }\n\n // If element is the root, return empty string\n if (root && element === root) return \"\";\n\n const parts: string[] = [];\n let current: Element | null = element;\n const stopAt = root ?? document.documentElement;\n\n while (current && current !== stopAt) {\n const parent: Element | null = current.parentElement;\n if (!parent) break;\n\n const tagName = current.tagName.toLowerCase();\n\n // Count same-type siblings to determine if :nth-of-type is needed\n let index = 1;\n let sibling = current.previousElementSibling;\n while (sibling) {\n if (sibling.tagName === current.tagName) index++;\n sibling = sibling.previousElementSibling;\n }\n\n let sameTypeSiblings = 0;\n for (const child of parent.children) {\n if (child.tagName === current.tagName) sameTypeSiblings++;\n }\n\n if (sameTypeSiblings > 1) {\n parts.unshift(`${tagName}:nth-of-type(${index})`);\n } else {\n parts.unshift(tagName);\n }\n\n current = parent;\n }\n\n // Handle edge cases\n if (parts.length === 0) {\n if (element === document.body) return \"body\";\n if (element === document.head) return \"head\";\n return \"\";\n }\n\n const path = parts.join(\" > \");\n\n // Anchor to root with :scope so querySelector matches at the correct depth.\n // Without this, \"div > div > div:nth-of-type(2)\" is ambiguous — it can match\n // any ancestor chain of divs at any depth within the subtree, not just the\n // specific depth from the root. :scope pins the first segment to a direct\n // child of the querySelector target.\n if (root) return `:scope > ${path}`;\n\n return path;\n}\n\n/**\n * Finds the Lowest Common Ancestor (LCA) of a set of nodes.\n *\n * The LCA is the deepest element that is an ancestor of all provided nodes.\n * Useful for determining the minimal subtree that contains all mutations.\n *\n * @param nodes - Set of DOM nodes to find common ancestor for\n * @returns The LCA element, or null if no common ancestor found\n */\nexport function findLowestCommonAncestor(nodes: Set<Node>): Element | null {\n if (nodes.size === 0) return null;\n\n // Build ancestor chains for each node (from root to node)\n const ancestorChains: Element[][] = [];\n\n for (const node of nodes) {\n const chain: Element[] = [];\n let current: Node | null =\n node instanceof Element ? node : node.parentElement;\n\n while (current && current !== document) {\n if (current instanceof Element) {\n chain.unshift(current);\n }\n current = current.parentNode;\n }\n\n if (chain.length > 0) {\n ancestorChains.push(chain);\n }\n }\n\n if (ancestorChains.length === 0) {\n return document.documentElement;\n }\n\n // Find the deepest common ancestor by comparing chains\n let lca: Element = document.documentElement;\n const firstChain = ancestorChains[0]!;\n const minLength = Math.min(...ancestorChains.map((c) => c.length));\n\n for (let i = 0; i < minLength; i++) {\n const candidate = firstChain[i];\n if (candidate && ancestorChains.every((chain) => chain[i] === candidate)) {\n lca = candidate;\n } else {\n break;\n }\n }\n\n return lca;\n}\n","/**\n * DOM Capture\n *\n * One-shot capture of DOM content and element states.\n */\n\nimport { computeDeclaredFacts } from \"./declared-facts\";\nimport { measureComputedDisplayability } from \"./displayability\";\nimport { generateSelector } from \"./selectors\";\nimport type { DomCapture, ElementState } from \"./types\";\n\nexport interface CollectElementStatesOptions {\n /** Whether to include document-level scroll via the :root selector. */\n includeDocumentScroll?: boolean;\n}\n\n/**\n * Captures the current state of an element as a DomCapture.\n *\n * @param element - Element to capture\n * @returns DomCapture containing HTML and element states\n *\n * @example\n * ```ts\n * const snapshot = capture(document.body);\n * // { dom: { selector: \"body\", html: \"...\" }, states: [...] }\n * ```\n */\nexport function capture(element: Element): DomCapture {\n return captureWithSupplementalRoots(element, []);\n}\n\n/** Internal complete-capture primitive used when a higher-level producer also\n * serializes supplemental roots such as owned React portals. */\nexport function captureWithSupplementalRoots(\n element: Element,\n supplementalRoots: readonly Element[],\n): DomCapture {\n // Sync form state to attributes before serializing\n syncFormStateToAttributes(element);\n\n // Selector relative to itself = \"\" (this IS the container)\n const selector = generateSelector(element, element);\n // Use innerHTML - we capture the children, not the container itself\n const html = removeScriptTags(element.innerHTML);\n const attributes = captureAttributes(element);\n const documentElementAttributes = element.ownerDocument\n ? captureAttributes(element.ownerDocument.documentElement)\n : undefined;\n const bodyAttributes = element.ownerDocument?.body\n ? captureAttributes(element.ownerDocument.body)\n : undefined;\n const baseUrl = element.ownerDocument?.baseURI;\n const states = collectElementStates(element);\n const displayability = measureComputedDisplayability(\n element,\n supplementalRoots,\n );\n\n return {\n // Whole-surface one-shot: the element is both the capture root and the\n // serialized scope, so `complete` is true and there is no scope selector.\n declared: computeDeclaredFacts(element, element, \"\", supplementalRoots),\n ...(displayability && { displayability }),\n dom: {\n selector,\n html,\n attributes,\n documentElementAttributes,\n bodyAttributes,\n },\n states,\n baseUrl,\n };\n}\n\n/**\n * Syncs form element state (DOM properties) to HTML attributes.\n *\n * Form elements like checkboxes, selects, and inputs have runtime state\n * that isn't reflected in their HTML attributes. This syncs that state\n * to attributes so it survives serialization.\n */\nfunction syncFormStateToAttributes(root: Element): void {\n // Checkboxes and radios\n for (const input of root.querySelectorAll(\n 'input[type=\"checkbox\"], input[type=\"radio\"]',\n )) {\n const el = input as HTMLInputElement;\n if (el.checked) {\n el.setAttribute(\"checked\", \"\");\n } else {\n el.removeAttribute(\"checked\");\n }\n }\n\n // Text inputs\n for (const input of root.querySelectorAll(\n 'input:not([type=\"checkbox\"]):not([type=\"radio\"])',\n )) {\n const el = input as HTMLInputElement;\n if (el.value !== el.getAttribute(\"value\")) {\n el.setAttribute(\"value\", el.value);\n }\n }\n\n // Textareas\n for (const textarea of root.querySelectorAll(\"textarea\")) {\n const el = textarea as HTMLTextAreaElement;\n if (el.value !== el.textContent) {\n el.textContent = el.value;\n }\n if (el.hasAttribute(\"value\")) {\n el.removeAttribute(\"value\");\n }\n }\n\n // Selects\n for (const select of root.querySelectorAll(\"select\")) {\n const el = select as HTMLSelectElement;\n for (const option of el.options) {\n if (option.selected) {\n option.setAttribute(\"selected\", \"\");\n } else {\n option.removeAttribute(\"selected\");\n }\n }\n }\n}\n\n/**\n * Removes all script tags from HTML string.\n */\nexport function removeScriptTags(html: string): string {\n return html.replace(/<script\\b[^>]*>[\\s\\S]*?<\\/script>/gi, \"\");\n}\n\n/**\n * Captures attributes from an element into a serializable map.\n */\nexport function captureAttributes(element: Element): Record<string, string> {\n const attrs: Record<string, string> = {};\n for (const attr of Array.from(element.attributes)) {\n attrs[attr.name] = attr.value;\n }\n return attrs;\n}\n\n/**\n * Collects current element states from a root element.\n *\n * Walks form elements and scrollable containers to collect their runtime state.\n */\nexport function collectElementStates(\n root: Element,\n options: CollectElementStatesOptions = {},\n): ElementState[] {\n const { includeDocumentScroll = true } = options;\n const states: ElementState[] = [];\n\n // Collect form states\n for (const input of root.querySelectorAll(\"input\")) {\n const el = input as HTMLInputElement;\n const isCheckable = el.type === \"checkbox\" || el.type === \"radio\";\n const hasNonDefault = isCheckable\n ? el.checked !== el.defaultChecked\n : el.value !== el.defaultValue;\n\n if (hasNonDefault) {\n const selector = generateSelector(el, root);\n if (isCheckable) {\n states.push({ selector, checked: el.checked });\n } else {\n states.push({ selector, value: el.value });\n }\n }\n }\n\n for (const textarea of root.querySelectorAll(\"textarea\")) {\n const el = textarea as HTMLTextAreaElement;\n if (el.value !== el.defaultValue) {\n const selector = generateSelector(el, root);\n states.push({ selector, value: el.value });\n }\n }\n\n for (const select of root.querySelectorAll(\"select\")) {\n const el = select as HTMLSelectElement;\n for (const option of el.options) {\n if (option.selected !== option.defaultSelected) {\n const selector = generateSelector(option, root);\n states.push({ selector, selected: option.selected });\n }\n }\n }\n\n // Collect scroll states - always include root and document-level scroll\n // so that scrolling back to 0 is properly communicated.\n states.push({\n selector: \"\",\n scrollTop: root.scrollTop,\n scrollLeft: root.scrollLeft,\n });\n\n // Check document-level scroll (scrollingElement, usually <html>)\n // This handles the common case where scroll is on documentElement, not body\n if (includeDocumentScroll) {\n const scrollingEl = root.ownerDocument?.scrollingElement;\n if (scrollingEl && scrollingEl !== root) {\n states.push({\n selector: \":root\",\n scrollTop: scrollingEl.scrollTop,\n scrollLeft: scrollingEl.scrollLeft,\n });\n }\n }\n\n for (const el of root.querySelectorAll(\"*\")) {\n if (el.scrollTop > 0 || el.scrollLeft > 0) {\n const selector = generateSelector(el, root);\n states.push({\n selector,\n scrollTop: el.scrollTop,\n scrollLeft: el.scrollLeft,\n });\n }\n }\n\n return states;\n}\n","/**\n * DOM Watcher\n *\n * Tracks DOM mutations using MutationObserver.\n * Collects mutated elements for later flushing.\n * Assigns unique data-dom-id attributes for reference tracking.\n */\n\nimport { findLowestCommonAncestor } from \"./selectors\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// DOM ID Assignment\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Attribute name for DOM element IDs */\nexport const DOM_ID_ATTR = \"data-dom-id\";\n\n// Module-level singleton state for ID generation (shared across all watchers)\nlet sessionHash: string | null = null;\nlet idCounter = 0;\n\n/**\n * Gets or generates the session hash (idempotent).\n * Returns the same 4-character hash for all calls within this context.\n */\nfunction getOrCreateSessionHash(): string {\n if (sessionHash === null) {\n sessionHash = Math.random().toString(36).substring(2, 6);\n }\n return sessionHash;\n}\n\n/**\n * Gets the current session hash.\n * Creates one if it doesn't exist yet.\n */\nexport function getSessionHash(): string {\n return getOrCreateSessionHash();\n}\n\n/**\n * Resets the session state. Primarily for testing.\n * @internal\n */\nexport function _resetSessionState(): void {\n sessionHash = null;\n idCounter = 0;\n}\n\n/**\n * Assigns a unique data-dom-id to an element.\n * ONLY assigns if the element doesn't already have one.\n * @returns The assigned or existing ID\n */\nfunction assignDomId(element: Element): string {\n const existing = element.getAttribute(DOM_ID_ATTR);\n if (existing !== null) {\n return existing;\n }\n\n const id = `${getOrCreateSessionHash()}-${idCounter++}`;\n element.setAttribute(DOM_ID_ATTR, id);\n return id;\n}\n\n/**\n * Return the stable projection identity for one host element, assigning it\n * when needed. Producer serializers call this while they are already visiting\n * an exact changed region, so React's synchronous commit notification does not\n * have to race MutationObserver's later ID-bookkeeping delivery.\n *\n * Editor-owned descendants remain opaque. The contenteditable boundary itself\n * is addressable, but nothing underneath it receives projection attributes.\n */\nexport function ensureProjectionDomId(element: Element): string | null {\n const existing = element.getAttribute(DOM_ID_ATTR);\n if (existing !== null) return existing;\n if (hasContentEditableAncestor(element)) return null;\n return assignDomId(element);\n}\n\n/**\n * Returns true if the element itself has contenteditable set.\n * This is a cheap own-property check (no ancestor traversal).\n */\nfunction isContentEditableRoot(element: Element): boolean {\n return element.getAttribute(\"contenteditable\") !== null;\n}\n\n/**\n * Returns true if any ancestor (excluding the element itself) carries\n * contenteditable. Used to keep mutation-time inserts inside an editor's\n * subtree from receiving data-dom-id, while still stamping a freshly\n * mounted contenteditable element when it's added at the top of an\n * `assignDomIdToTree` call.\n */\nfunction hasContentEditableAncestor(element: Element): boolean {\n let current: Element | null = element.parentElement;\n while (current) {\n if (current.getAttribute(\"contenteditable\") !== null) {\n return true;\n }\n current = current.parentElement;\n }\n return false;\n}\n\n/**\n * Assigns data-dom-id to an element and its descendants.\n *\n * Stamps a contenteditable element itself (so it remains addressable as\n * a layer — selectable on the canvas, resolvable from the layers panel),\n * but never descends into its subtree: editors like ProseMirror own\n * their internal DOM and will destroy/recreate children that receive\n * foreign attributes, creating a MutationObserver feedback loop.\n *\n * If `root` is already inside a contenteditable subtree (e.g. a node\n * added by an editor via mutation), it is left untouched entirely.\n */\nfunction assignDomIdToTree(root: Element): void {\n if (hasContentEditableAncestor(root)) {\n return;\n }\n ensureProjectionDomId(root);\n if (isContentEditableRoot(root)) {\n return;\n }\n // Use a manual TreeWalker-style loop so we can stamp contenteditable\n // boundaries without descending into them, without an ancestor check\n // on every element.\n const stack: Element[] = [];\n for (let i = root.children.length - 1; i >= 0; i--) {\n stack.push(root.children[i] as Element);\n }\n while (stack.length > 0) {\n const element = stack.pop()!;\n ensureProjectionDomId(element);\n if (isContentEditableRoot(element)) {\n continue;\n }\n for (let i = element.children.length - 1; i >= 0; i--) {\n stack.push(element.children[i] as Element);\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// DOM Watcher\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * State for a DOM watcher instance.\n */\nexport interface DomWatcher {\n /** The root element being watched */\n root: Element;\n /** Set of elements that have mutated since last flush */\n mutatedElements: Set<Element>;\n /** Elements added (per mutation record, top level only) since last flush.\n * Together with `mutatedElements.size` this estimates how many DOM nodes a\n * capture actually needs to cover — the perf denominator scoped captures\n * are judged against. */\n addedElementCount: number;\n /** Raw observer records received since the previous flush. */\n mutationRecordCount: number;\n /** Exact observer-local records retained for the regional projection path.\n * Nodes are source-realm references and never cross the wire. */\n projectionMutations: ProjectionDomMutation[];\n /**\n * Synchronously retain records already queued by MutationObserver. React's\n * commit hook calls this after each commit so DOM-producing and\n * semantic-only commits can be distinguished without guessing at the later\n * observer microtask. The returned count excludes our own data-dom-id\n * bookkeeping records.\n */\n takePendingRecords: () => number;\n /** Stop watching */\n stop: () => void;\n}\n\nexport interface ProjectionDomMutation {\n readonly type: \"attributes\" | \"characterData\" | \"childList\";\n readonly target: Node;\n readonly attributeName?: string | null;\n /** Producer-local baseline for final-state scalar coalescing. */\n readonly oldValue?: string | null;\n readonly addedNodes?: readonly Node[];\n readonly removedNodes?: readonly Node[];\n readonly previousSibling?: Node | null;\n readonly nextSibling?: Node | null;\n}\n\n/**\n * Starts watching an element for DOM mutations.\n *\n * Mutations are collected in a Set and can be flushed via getDirtyElements().\n * The watcher does NOT debounce or automatically trigger updates - that's\n * the responsibility of the combined watch.ts.\n *\n * @param root - Element to watch\n * @param onMutation - Called when any mutation occurs (for triggering flush)\n * @returns DomWatcher instance\n *\n * @example\n * ```ts\n * const watcher = watchDom(document.body, () => {\n * // Mutation detected - schedule a flush\n * scheduleDebouncedFlush();\n * });\n *\n * // Later, get what changed and clear\n * const { lca, elements } = watcher.flush();\n * ```\n */\nexport function watchDom(root: Element, onMutation: () => void): DomWatcher {\n const mutatedElements = new Set<Element>();\n\n // Assign IDs to all existing elements in the tree\n assignDomIdToTree(root);\n\n const retainMutations = (\n mutations: readonly MutationRecord[],\n ): number => {\n // MutationObserver reports every write, while projection publishes final\n // state. Collapse repeated writes to the same scalar target to the first\n // old value and compare that with the final live value. A transient\n // set/remove pair is therefore no mutation at all.\n const scalarMutations: MutationRecord[] = [];\n const firstAttributeByTarget = new WeakMap<\n Element,\n Map<string, MutationRecord>\n >();\n const firstCharacterDataByTarget = new WeakMap<Node, MutationRecord>();\n for (const mutation of mutations) {\n if (mutation.type === \"attributes\" && mutation.attributeName !== null) {\n // Assigning stable IDs is producer bookkeeping. MutationObserver\n // reports those writes in a later delivery; treating them as\n // application changes would create a self-sustaining projection echo.\n if (mutation.attributeName === DOM_ID_ATTR) continue;\n const target = mutation.target as Element;\n const byName = firstAttributeByTarget.get(target) ?? new Map();\n if (!byName.has(mutation.attributeName)) {\n byName.set(mutation.attributeName, mutation);\n firstAttributeByTarget.set(target, byName);\n scalarMutations.push(mutation);\n }\n } else if (mutation.type === \"characterData\") {\n if (!firstCharacterDataByTarget.has(mutation.target)) {\n firstCharacterDataByTarget.set(mutation.target, mutation);\n scalarMutations.push(mutation);\n }\n } else {\n scalarMutations.push(mutation);\n }\n }\n\n let retained = 0;\n for (const mutation of scalarMutations) {\n // React and source-annotation helpers can idempotently write an\n // attribute during a commit. MutationObserver reports that write even\n // though the document's final state did not change. It is not DOM\n // evidence for the commit and must not suppress semantic discovery.\n //\n // `drainProjectionDomMutations` repeats this comparison against final\n // state, but that is a later and narrower answer: the check here decides\n // whether the producer wakes at all and whether the target joins\n // `mutatedElements` — the set the next capture's LCA is measured over.\n // Dropping it wakes the producer on a write that changed nothing and\n // widens the captured region to the untouched element.\n if (\n mutation.type === \"attributes\" &&\n mutation.attributeName !== null &&\n mutation.oldValue ===\n (mutation.target as Element).getAttribute(mutation.attributeName)\n ) {\n continue;\n }\n if (\n mutation.type === \"characterData\" &&\n mutation.oldValue === mutation.target.textContent\n ) {\n continue;\n }\n retained += 1;\n watcher.mutationRecordCount += 1;\n watcher.projectionMutations.push({\n type: mutation.type,\n target: mutation.target,\n ...(mutation.type === \"attributes\" || mutation.type === \"characterData\"\n ? { oldValue: mutation.oldValue }\n : {}),\n ...(mutation.type === \"attributes\"\n ? { attributeName: mutation.attributeName }\n : {}),\n ...(mutation.type === \"childList\"\n ? {\n addedNodes: Array.from(mutation.addedNodes),\n removedNodes: Array.from(mutation.removedNodes),\n previousSibling: mutation.previousSibling,\n nextSibling: mutation.nextSibling,\n }\n : {}),\n });\n const target =\n mutation.target instanceof Element\n ? mutation.target\n : mutation.target.parentElement;\n\n if (target && root.contains(target)) {\n mutatedElements.add(target);\n }\n\n if (mutation.type === \"childList\") {\n // Assign IDs to newly added elements and their entire subtrees.\n // assignDomIdToTree skips contenteditable subtrees, so editors\n // like ProseMirror won't get foreign attributes.\n for (const node of mutation.addedNodes) {\n if (node instanceof Element && root.contains(node)) {\n assignDomIdToTree(node);\n watcher.addedElementCount += 1;\n }\n }\n\n // Track parent for childList mutations\n if (\n mutation.target instanceof Element &&\n root.contains(mutation.target)\n ) {\n mutatedElements.add(mutation.target);\n }\n }\n }\n return retained;\n };\n\n const observer = new MutationObserver((mutations) => {\n if (retainMutations(mutations) > 0 && mutatedElements.size > 0)\n onMutation();\n });\n\n observer.observe(root, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeOldValue: true,\n characterData: true,\n characterDataOldValue: true,\n });\n\n const watcher: DomWatcher = {\n root,\n mutatedElements,\n addedElementCount: 0,\n mutationRecordCount: 0,\n projectionMutations: [],\n takePendingRecords: () => retainMutations(observer.takeRecords()),\n stop: () => {\n observer.disconnect();\n mutatedElements.clear();\n watcher.mutationRecordCount = 0;\n watcher.projectionMutations.length = 0;\n },\n };\n return watcher;\n}\n\n/**\n * Flushes the watcher, returning the LCA of all mutations and clearing state.\n *\n * @returns The lowest common ancestor of all mutations, or null if no mutations\n */\nexport function flushDomWatcher(watcher: DomWatcher): Element | null {\n watcher.addedElementCount = 0;\n watcher.mutationRecordCount = 0;\n watcher.projectionMutations.length = 0;\n if (watcher.mutatedElements.size === 0) {\n return null;\n }\n\n const lca = findLowestCommonAncestor(watcher.mutatedElements);\n watcher.mutatedElements.clear();\n\n // If LCA is outside our root (shouldn't happen, but safety check)\n if (lca && !watcher.root.contains(lca) && lca !== watcher.root) {\n return watcher.root;\n }\n\n return lca;\n}\n\n/**\n * Detach the exact source records for one regional flush. This consumes the\n * same pending observation as the legacy LCA flush; callers choose one view,\n * never both.\n */\nexport function drainProjectionDomMutations(\n watcher: DomWatcher,\n): ProjectionDomMutation[] {\n const retained = watcher.projectionMutations.splice(0);\n const mutations: ProjectionDomMutation[] = [];\n const firstAttributeByTarget = new WeakMap<Element, Set<string>>();\n const firstCharacterDataTargets = new WeakSet<Node>();\n for (const mutation of retained) {\n const attributeName = mutation.attributeName;\n if (mutation.type === \"attributes\" && attributeName != null) {\n const target = mutation.target as Element;\n const names = firstAttributeByTarget.get(target) ?? new Set<string>();\n if (names.has(attributeName)) continue;\n names.add(attributeName);\n firstAttributeByTarget.set(target, names);\n if (mutation.oldValue === target.getAttribute(attributeName)) {\n continue;\n }\n mutations.push({\n type: \"attributes\",\n target,\n attributeName,\n });\n continue;\n }\n if (mutation.type === \"characterData\") {\n if (firstCharacterDataTargets.has(mutation.target)) continue;\n firstCharacterDataTargets.add(mutation.target);\n if (mutation.oldValue === mutation.target.textContent) continue;\n mutations.push({ type: \"characterData\", target: mutation.target });\n continue;\n }\n mutations.push(mutation);\n }\n watcher.mutatedElements.clear();\n watcher.addedElementCount = 0;\n watcher.mutationRecordCount = 0;\n return mutations;\n}\n\n/**\n * Checks if watcher has any pending mutations.\n */\nexport function hasPendingMutations(watcher: DomWatcher): boolean {\n return watcher.mutatedElements.size > 0;\n}\n","/**\n * State Watcher\n *\n * Tracks element state changes (form values, scroll positions) via events.\n * Much more efficient than DOM traversal - only tracks elements that received events.\n */\n\nimport { generateSelector } from \"./selectors\";\nimport type { ElementState } from \"./types\";\n\n/**\n * State for a state watcher instance.\n */\nexport interface StateWatcher {\n /** The root element being watched */\n root: Element;\n /** Elements that have received scroll events */\n scrolledElements: Set<Element>;\n /** Elements that have received input/change events */\n changedFormElements: Set<Element>;\n /** Raw input/change/scroll events accepted since the previous flush. */\n stateRecordCount: number;\n /** Last event kind per form target for exact regional state capture. */\n projectionFormEvents: Map<Element, \"input\" | \"change\">;\n /** Stop watching */\n stop: () => void;\n}\n\nexport interface ProjectionStateEvent {\n readonly element: Element;\n readonly eventKind: \"scroll\" | \"input\" | \"change\";\n}\n\n/**\n * Starts watching an element for state changes (form input, scroll).\n *\n * Uses event listeners in capture phase to catch all events.\n * Changes are collected in Sets and can be flushed via flushStateWatcher().\n *\n * @param root - Element to watch\n * @param onStateChange - Called when any state change occurs (for triggering flush)\n * @returns StateWatcher instance\n */\nexport function watchState(\n root: Element,\n onStateChange: () => void,\n): StateWatcher {\n const scrolledElements = new Set<Element>();\n const changedFormElements = new Set<Element>();\n\n const handleScroll = (event: Event) => {\n const target = event.target;\n if (target instanceof Element && root.contains(target)) {\n scrolledElements.add(target);\n watcher.stateRecordCount += 1;\n onStateChange();\n } else if (target === document) {\n // Document-level scroll - scrollingElement is usually <html> which doesn't\n // satisfy root.contains() when root is <body>. We track this specially.\n const scrollTarget =\n document.scrollingElement || document.documentElement;\n if (scrollTarget) {\n // Use a marker for document-level scroll (we'll handle it specially in flush)\n scrolledElements.add(scrollTarget);\n watcher.stateRecordCount += 1;\n onStateChange();\n }\n }\n };\n\n const handleFormChange = (event: Event) => {\n if (event.target instanceof Element && root.contains(event.target)) {\n changedFormElements.add(event.target);\n watcher.projectionFormEvents.set(\n event.target,\n event.type === \"change\" ? \"change\" : \"input\",\n );\n watcher.stateRecordCount += 1;\n onStateChange();\n }\n };\n\n // Use capture phase to catch all events\n document.addEventListener(\"scroll\", handleScroll, true);\n document.addEventListener(\"input\", handleFormChange, true);\n document.addEventListener(\"change\", handleFormChange, true);\n\n const watcher: StateWatcher = {\n root,\n scrolledElements,\n changedFormElements,\n stateRecordCount: 0,\n projectionFormEvents: new Map(),\n stop: () => {\n document.removeEventListener(\"scroll\", handleScroll, true);\n document.removeEventListener(\"input\", handleFormChange, true);\n document.removeEventListener(\"change\", handleFormChange, true);\n scrolledElements.clear();\n changedFormElements.clear();\n watcher.stateRecordCount = 0;\n watcher.projectionFormEvents.clear();\n },\n };\n return watcher;\n}\n\n/**\n * Flushes the state watcher, collecting current states and clearing tracking.\n *\n * Only returns states for elements that have changed since last flush.\n * Elements with non-default state are re-added to tracking to ensure\n * they're reported again if HTML is replaced.\n *\n * @param watcher - The state watcher to flush\n * @returns Array of element states\n */\nexport function flushStateWatcher(watcher: StateWatcher): ElementState[] {\n const { root, scrolledElements, changedFormElements } = watcher;\n watcher.stateRecordCount = 0;\n watcher.projectionFormEvents.clear();\n const states: ElementState[] = [];\n\n // Swap to fresh sets\n const scrolled = new Set(scrolledElements);\n const changed = new Set(changedFormElements);\n scrolledElements.clear();\n changedFormElements.clear();\n\n // Process scrolled elements\n for (const el of scrolled) {\n // Check for document-level scroll (scrollingElement, usually <html>)\n const isDocumentScroll =\n el === document.scrollingElement || el === document.documentElement;\n\n // Skip elements not in root, unless it's document-level scroll\n if (!isDocumentScroll && !root.contains(el)) continue;\n\n // For document-level scroll, use special \":root\" selector\n // For elements within root, generate relative selector\n const selector = isDocumentScroll ? \":root\" : generateSelector(el, root);\n states.push({\n selector,\n scrollTop: el.scrollTop,\n scrollLeft: el.scrollLeft,\n });\n }\n\n // Process changed form elements\n for (const el of changed) {\n if (!root.contains(el)) continue;\n\n if (el instanceof HTMLInputElement) {\n const isCheckable = el.type === \"checkbox\" || el.type === \"radio\";\n const hasNonDefault = isCheckable\n ? el.checked !== el.defaultChecked\n : el.value !== el.defaultValue;\n\n if (hasNonDefault) {\n const selector = generateSelector(el, root);\n if (isCheckable) {\n states.push({ selector, checked: el.checked });\n } else {\n states.push({ selector, value: el.value });\n }\n changedFormElements.add(el);\n }\n } else if (el instanceof HTMLTextAreaElement) {\n if (el.value !== el.defaultValue) {\n const selector = generateSelector(el, root);\n states.push({ selector, value: el.value });\n changedFormElements.add(el);\n }\n } else if (el instanceof HTMLSelectElement) {\n let hasNonDefault = false;\n for (const option of el.options) {\n if (option.selected !== option.defaultSelected) {\n const selector = generateSelector(option, root);\n states.push({ selector, selected: option.selected });\n hasNonDefault = true;\n }\n }\n if (hasNonDefault) {\n changedFormElements.add(el);\n }\n }\n }\n\n return states;\n}\n\n/** Detach exact state targets for a regional projection flush. */\nexport function drainProjectionStateEvents(\n watcher: StateWatcher,\n): ProjectionStateEvent[] {\n const events: ProjectionStateEvent[] = [];\n for (const element of watcher.scrolledElements) {\n const isDocumentScroll =\n element === watcher.root.ownerDocument.scrollingElement ||\n element === watcher.root.ownerDocument.documentElement;\n events.push({\n element: isDocumentScroll ? watcher.root : element,\n eventKind: \"scroll\",\n });\n }\n for (const [element, eventKind] of watcher.projectionFormEvents) {\n events.push({ element, eventKind });\n }\n watcher.scrolledElements.clear();\n watcher.changedFormElements.clear();\n watcher.projectionFormEvents.clear();\n watcher.stateRecordCount = 0;\n return events;\n}\n\n/**\n * Checks if watcher has any pending state changes.\n */\nexport function hasPendingStateChanges(watcher: StateWatcher): boolean {\n return (\n watcher.scrolledElements.size > 0 || watcher.changedFormElements.size > 0\n );\n}\n","/**\n * Portal Element Watcher\n *\n * Wraps MutationObserver for a single portal element.\n * Reuses the same watch-dom and watch-state logic but scoped to the portal.\n */\n\nimport { removeScriptTags } from \"./capture\";\nimport { generateSelector } from \"./selectors\";\nimport type { PortalCoordinateSpace, PortalUpdate } from \"./types\";\nimport {\n drainProjectionDomMutations,\n flushDomWatcher,\n hasPendingMutations,\n watchDom,\n} from \"./watch-dom\";\nimport {\n drainProjectionStateEvents,\n flushStateWatcher,\n hasPendingStateChanges,\n type ProjectionStateEvent,\n watchState,\n} from \"./watch-state\";\n\n/** Counter shared by one-shot snapshots and live portal watchers. */\nlet portalIdCounter = 0;\n\n/** Attribute name for portal ID */\nexport const PORTAL_ID_ATTR = \"data-projection-portal-id\";\n\n/**\n * Reset portal ID counter. For testing only.\n * @internal\n */\nexport function _resetPortalIdCounter(): void {\n portalIdCounter = 0;\n}\n\n/** Assign a process-unique projection ID, or reuse an existing stable ID. */\nexport function getOrAssignPortalId(element: Element): string {\n const existing = element.getAttribute(PORTAL_ID_ATTR);\n if (existing) return existing;\n\n const id = `portal-${++portalIdCounter}`;\n element.setAttribute(PORTAL_ID_ATTR, id);\n return id;\n}\n\nexport interface PortalWatcherHandle {\n /** The portal's unique ID */\n id: string;\n\n /** The portal root element */\n element: Element;\n\n /** Check if there are pending changes */\n hasPendingChanges(): boolean;\n\n /** Existing watcher record counts; no DOM reads. */\n pendingRecordCount(): number;\n\n /** Clear retained regional candidates after a caller captured final state. */\n clearPendingChanges(): ProjectionStateEvent[];\n\n /** Flush changes and get update (or null if no changes) */\n flush(isInitial?: boolean): PortalUpdate | null;\n\n /** Resample CSS-dependent coordinates without serializing portal content. */\n resampleCoordinates(): PortalUpdate | null;\n\n /** Stop watching */\n stop(): void;\n}\n\n/**\n * Start watching a portal element for changes.\n *\n * @param element - The portal root element (direct child of body)\n * @param onTrigger - Called when mutations are detected (for debounce integration)\n */\nexport function watchPortal(\n element: Element,\n onTrigger: () => void,\n coordinateRoot?: Element,\n): PortalWatcherHandle {\n // Assign or retrieve stable ID\n const id = getOrAssignPortalId(element);\n\n // Start watchers\n const domWatcher = watchDom(element, onTrigger);\n const stateWatcher = watchState(element, onTrigger);\n\n return {\n id,\n element,\n\n hasPendingChanges(): boolean {\n return (\n hasPendingMutations(domWatcher) || hasPendingStateChanges(stateWatcher)\n );\n },\n\n pendingRecordCount(): number {\n return domWatcher.mutationRecordCount + stateWatcher.stateRecordCount;\n },\n\n clearPendingChanges(): ProjectionStateEvent[] {\n drainProjectionDomMutations(domWatcher);\n return drainProjectionStateEvents(stateWatcher);\n },\n\n flush(isInitial = false): PortalUpdate | null {\n const hasDomChanges = hasPendingMutations(domWatcher);\n const hasStateChanges = hasPendingStateChanges(stateWatcher);\n\n if (!isInitial && !hasDomChanges && !hasStateChanges) {\n return null;\n }\n\n // Get LCA of mutations or use root for initial\n let targetElement = element;\n if (!isInitial && hasDomChanges) {\n const lca = flushDomWatcher(domWatcher);\n if (lca && element.contains(lca)) {\n targetElement = lca;\n }\n } else {\n flushDomWatcher(domWatcher);\n }\n\n // Collect states\n const states = flushStateWatcher(stateWatcher);\n\n // Generate selector relative to portal root\n const selector = generateSelector(targetElement, element);\n // Use outerHTML to capture the portal root element itself, not just its children.\n // This is important because the portal root often has critical styling (e.g., position: fixed\n // for modal overlays) that must be preserved in the projection.\n const html = removeScriptTags(targetElement.outerHTML);\n\n const coordinateSpace = coordinateRoot\n ? capturePortalCoordinateSpace(coordinateRoot, element)\n : undefined;\n return {\n id,\n selector,\n html,\n states,\n ...(coordinateSpace && { coordinateSpace }),\n };\n },\n\n resampleCoordinates(): PortalUpdate | null {\n const coordinateSpace = coordinateRoot\n ? capturePortalCoordinateSpace(coordinateRoot, element)\n : undefined;\n if (!coordinateSpace) return null;\n\n return {\n id,\n selector: \"\",\n html: \"\",\n states: [],\n coordinateSpace,\n coordinatesOnly: true,\n };\n },\n\n stop(): void {\n domWatcher.stop();\n stateWatcher.stop();\n },\n };\n}\n\nexport function capturePortalCoordinateSpace(\n root: Element,\n portal?: Element,\n): PortalCoordinateSpace | undefined {\n const viewport = root.ownerDocument?.defaultView;\n if (!viewport) return undefined;\n\n const rect = root.getBoundingClientRect();\n return {\n origin: portal ? choosePortalCoordinateOrigin(rect, portal) : \"root\",\n rootViewportLeft: rect.left,\n rootViewportTop: rect.top,\n viewportWidth: viewport.innerWidth,\n viewportHeight: viewport.innerHeight,\n };\n}\n\nfunction choosePortalCoordinateOrigin(\n rootRect: DOMRect,\n portal: Element,\n): \"root\" | \"viewport\" {\n const portalRect = measurePortalBounds(portal);\n const localViewport = {\n left: 0,\n top: 0,\n right: rootRect.width,\n bottom: rootRect.height,\n };\n const coversSourceViewport =\n portalRect.left <= 0 &&\n portalRect.top <= 0 &&\n portalRect.right >= (portal.ownerDocument.defaultView?.innerWidth ?? 0) &&\n portalRect.bottom >= (portal.ownerDocument.defaultView?.innerHeight ?? 0);\n if (coversSourceViewport) return \"viewport\";\n\n // A floating surface that intersects its owning storyboard is anchored in\n // the shared source host's coordinate frame, even when both the direct and\n // rebased rectangles happen to fit inside the destination viewport.\n if (rectanglesOverlap(rootRect, portalRect)) return \"root\";\n\n const directScore = visibleArea(portalRect, localViewport);\n const rebasedScore = visibleArea(\n {\n left: portalRect.left - rootRect.left,\n top: portalRect.top - rootRect.top,\n right: portalRect.right - rootRect.left,\n bottom: portalRect.bottom - rootRect.top,\n },\n localViewport,\n );\n\n if (rebasedScore > directScore) return \"root\";\n if (directScore > rebasedScore) return \"viewport\";\n\n return \"viewport\";\n}\n\nfunction measurePortalBounds(portal: Element): RectBounds {\n const ownRect = portal.getBoundingClientRect();\n if (hasArea(ownRect)) return ownRect;\n\n // Library portals often add a zero-sized ownership container around the\n // actual backdrop/positioner. Base origin selection on what paints, not on\n // that implementation wrapper whose empty rect is timing-sensitive.\n let left = Number.POSITIVE_INFINITY;\n let top = Number.POSITIVE_INFINITY;\n let right = Number.NEGATIVE_INFINITY;\n let bottom = Number.NEGATIVE_INFINITY;\n for (const descendant of Array.from(portal.querySelectorAll(\"*\"))) {\n const rect = descendant.getBoundingClientRect();\n if (!hasArea(rect)) continue;\n left = Math.min(left, rect.left);\n top = Math.min(top, rect.top);\n right = Math.max(right, rect.right);\n bottom = Math.max(bottom, rect.bottom);\n }\n\n return Number.isFinite(left) ? { left, top, right, bottom } : ownRect;\n}\n\ntype RectBounds = Pick<DOMRect, \"left\" | \"top\" | \"right\" | \"bottom\">;\n\nfunction hasArea(rect: RectBounds): boolean {\n return rect.right > rect.left && rect.bottom > rect.top;\n}\n\nfunction visibleArea(\n rect: RectBounds,\n viewport: { left: number; top: number; right: number; bottom: number },\n): number {\n const width = Math.max(\n 0,\n Math.min(rect.right, viewport.right) - Math.max(rect.left, viewport.left),\n );\n const height = Math.max(\n 0,\n Math.min(rect.bottom, viewport.bottom) - Math.max(rect.top, viewport.top),\n );\n return width * height;\n}\n\nfunction rectanglesOverlap(a: RectBounds, b: RectBounds): boolean {\n return (\n a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top\n );\n}\n\n/**\n * Create a \"removed\" update for a portal that was removed from DOM.\n */\nexport function createPortalRemovedUpdate(id: string): PortalUpdate {\n return {\n id,\n selector: \"\",\n html: \"\",\n states: [],\n removed: true,\n };\n}\n","/**\n * Escape a value for interpolation into a double-quoted attribute selector,\n * the shape every projection lookup uses: `[attr=\"${cssEscape(value)}\"]`.\n *\n * Inside those quotes only `\"` and `\\` are syntactically significant, so the\n * fallback needs no wider escape table — `]`, `:` and `.` are literal there.\n * `CSS.escape` escapes for identifiers rather than quoted strings, which\n * over-escapes but resolves to the same characters inside the quotes.\n */\nexport function cssEscape(value: string): string {\n return globalThis.CSS?.escape\n ? globalThis.CSS.escape(value)\n : value.replace(/[\"\\\\]/g, \"\\\\$&\");\n}\n","export interface ProjectionObservedFile {\n /** Minimum timestamp across every serialized target from this file. */\n readonly modifiedTs: number;\n /** Present only when every serialized target reports the same exact token. */\n readonly sourceVersion?: string;\n}\n\nexport type ProjectionObservedFileMap = Readonly<\n Record<string, ProjectionObservedFile>\n>;\n\ninterface MutableObservedFile {\n modifiedTs: number;\n sourceVersion?: string;\n}\n\n/**\n * Accumulates freshness facts during a serializer's existing regional walk.\n * It never traverses the DOM itself. A fact covers the region only when every\n * target visited for that file is at least as new; exact versions are retained\n * only when all visited stamps agree.\n */\nexport class ProjectionObservedFileAccumulator {\n private readonly files = new Map<string, MutableObservedFile>();\n\n add(\n filepath: unknown,\n modifiedTsRaw: unknown,\n sourceVersionRaw: unknown,\n ): void {\n if (typeof filepath !== \"string\" || filepath.length === 0) return;\n const modifiedTs =\n typeof modifiedTsRaw === \"number\"\n ? modifiedTsRaw\n : typeof modifiedTsRaw === \"string\"\n ? Number(modifiedTsRaw)\n : Number.NaN;\n if (!Number.isFinite(modifiedTs)) return;\n const sourceVersion =\n typeof sourceVersionRaw === \"string\" && sourceVersionRaw.length > 0\n ? sourceVersionRaw\n : undefined;\n const current = this.files.get(filepath);\n if (!current) {\n this.files.set(filepath, {\n modifiedTs,\n sourceVersion,\n });\n return;\n }\n current.modifiedTs = Math.min(current.modifiedTs, modifiedTs);\n if (\n sourceVersion === undefined ||\n current.sourceVersion === undefined ||\n current.sourceVersion !== sourceVersion\n ) {\n current.sourceVersion = undefined;\n }\n }\n\n merge(files: ProjectionObservedFileMap | undefined): void {\n if (!files) return;\n for (const [filepath, fact] of Object.entries(files)) {\n this.add(filepath, fact.modifiedTs, fact.sourceVersion);\n }\n }\n\n addElement(element: Element): void {\n this.add(\n element.getAttribute(\"data-tempo-filepath\"),\n element.getAttribute(\"data-tempo-modifiedts\"),\n element.getAttribute(\"data-tempo-source-version\"),\n );\n this.add(\n element.getAttribute(\"data-tempo-html-filepath\"),\n element.getAttribute(\"data-tempo-html-modifiedts\"),\n element.getAttribute(\"data-tempo-html-source-version\"),\n );\n }\n\n snapshot(): ProjectionObservedFileMap {\n return Object.fromEntries(\n Array.from(this.files, ([filepath, fact]) => [\n filepath,\n {\n modifiedTs: fact.modifiedTs,\n ...(fact.sourceVersion !== undefined\n ? { sourceVersion: fact.sourceVersion }\n : {}),\n },\n ]),\n );\n }\n}\n","import { removeScriptTags } from \"../html/capture\";\nimport type { PortalCoordinateSpace } from \"../html/types\";\nimport { DOM_ID_ATTR, ensureProjectionDomId } from \"../html/watch-dom\";\nimport {\n capturePortalCoordinateSpace,\n PORTAL_ID_ATTR,\n} from \"../html/watch-portal\";\nimport { cssEscape } from \"./css-escape\";\nimport {\n ProjectionObservedFileAccumulator,\n type ProjectionObservedFileMap,\n} from \"./projection-observed-files\";\n\nexport const SOURCE_ANNOTATION_ATTRIBUTES = new Set([\n \"data-tempo-filepath\",\n \"data-tempo-position\",\n \"data-tempo-modifiedts\",\n \"data-tempo-source-version\",\n \"data-tempo-html-filepath\",\n \"data-tempo-html-offset\",\n \"data-tempo-html-modifiedts\",\n \"data-tempo-html-source-version\",\n]);\n\n/** Stable protocol identity for the watched wrapper. The wrapper itself is\n * host plumbing and is intentionally absent from full-snapshot HTML. */\nexport const PROJECTION_ROOT_TARGET_ID = \"$projection-root\";\n/** Stable destination-local target for exact `<html>` attribute changes. */\nexport const PROJECTION_DOCUMENT_ELEMENT_TARGET_ID = \"$projection-document\";\n\n/**\n * Upward repair ladder captured with the op: the id chain from the op's\n * addressed element's parent to the watched root (id-less ancestors skipped,\n * the root's sentinel implied). When the destination cannot resolve the op's\n * target it climbs this chain and requests one scoped region repair for the\n * first ancestor it knows, instead of escalating straight to a full snapshot.\n */\nexport interface ProjectionAncestryCarrier {\n readonly ancestorIds?: readonly string[];\n}\n\nexport interface ProjectionAttributePatch extends ProjectionAncestryCarrier {\n readonly kind: \"attributes\";\n readonly targetId: string;\n readonly attributes: Readonly<Record<string, string | null>>;\n}\n\nexport interface ProjectionRegionPatch extends ProjectionAncestryCarrier {\n readonly kind: \"children\";\n readonly targetId: string;\n readonly html: string;\n}\n\nexport interface ProjectionRemovePatch {\n readonly kind: \"remove\";\n readonly targetId: string;\n}\n\nexport interface ProjectionPlacePatch extends ProjectionAncestryCarrier {\n readonly kind: \"place\";\n readonly parentId: string;\n /** Stable ID of the exact top-level element represented by `html`. */\n readonly targetId: string;\n /** Insert immediately before this unchanged final sibling, or append. */\n readonly beforeId: string | null;\n readonly html: string;\n}\n\nexport interface ProjectionTextPatch extends ProjectionAncestryCarrier {\n readonly kind: \"text\";\n readonly parentId: string;\n /** The element after this exact non-element gap, or null for the end gap. */\n readonly beforeId: string | null;\n readonly html: string;\n}\n\nexport type ProjectionDomPatch =\n | ProjectionAttributePatch\n | ProjectionRegionPatch\n | ProjectionRemovePatch\n | ProjectionPlacePatch\n | ProjectionTextPatch;\n\nexport interface ProjectionAnnotationPatch extends ProjectionAncestryCarrier {\n readonly targetId: string;\n readonly attributes: Readonly<Record<string, string | null>>;\n}\n\nexport type ProjectionStatePatch = ProjectionAncestryCarrier &\n (\n | {\n readonly targetId: string;\n readonly kind: \"scroll\";\n readonly scrollTop: number;\n readonly scrollLeft: number;\n }\n | {\n readonly targetId: string;\n readonly kind: \"value\";\n readonly value: string;\n readonly selectionStart: number | null;\n readonly selectionEnd: number | null;\n }\n | {\n readonly targetId: string;\n readonly kind: \"checked\";\n readonly checked: boolean;\n }\n | {\n readonly targetId: string;\n readonly kind: \"selected\";\n readonly selectedIndices: readonly number[];\n }\n );\n\nexport type ProjectionPortalPatch =\n | ProjectionPortalReplacePatch\n | { readonly kind: \"remove\"; readonly portalId: string };\n\nexport interface ProjectionPortalReplacePatch {\n readonly kind: \"replace\";\n readonly portalId: string;\n readonly html: string;\n /** Where the source anchored this portal, so the destination can rebase it\n * out of the source viewport's frame into the mirrored root's. Absent when\n * the source realm has no measurable view. */\n readonly coordinateSpace?: PortalCoordinateSpace;\n /** The portal's frame moved without its DOM changing. Only `coordinateSpace`\n * applies; `html` is empty and the mirrored body — including its focus and\n * edit state — is left alone. */\n readonly coordinatesOnly?: boolean;\n}\n\nexport interface ProjectionPortalRegionCapture {\n readonly portal: ProjectionPortalPatch;\n readonly annotations: readonly ProjectionAnnotationPatch[];\n readonly observedFiles: ProjectionObservedFileMap;\n}\n\nexport interface ProjectionMutationInput {\n readonly type: \"attributes\" | \"characterData\" | \"childList\";\n readonly target: Node;\n readonly attributeName?: string | null;\n readonly addedNodes?: readonly Node[];\n readonly removedNodes?: readonly Node[];\n readonly previousSibling?: Node | null;\n readonly nextSibling?: Node | null;\n}\n\nexport interface ProjectionMutationPatch {\n readonly dom: readonly ProjectionDomPatch[];\n readonly annotations: readonly ProjectionAnnotationPatch[];\n readonly observedFiles?: ProjectionObservedFileMap;\n /** Source-realm-only candidates. They are consumed by the document\n * producer while assembling semantic work and are never serialized. */\n readonly localMetadataTargets: readonly Element[];\n}\n\n/**\n * Convert observer-local mutation records into declarative final-state\n * regions. Disjoint regions stay disjoint; nested work is swallowed by its\n * nearest surviving ancestor. Source metadata never becomes structure work.\n *\n * Capture never refuses: work on an element that lacks a stable id widens to\n * the nearest ancestor that has one (worst case the watched root itself), and\n * duplicate ids in the source document are represented as-is — the morphing\n * destination converges on whatever this capture describes.\n */\nexport function captureProjectionMutationPatch(\n root: Element,\n mutations: readonly ProjectionMutationInput[],\n options: { readonly regionalChildLists?: boolean } = {},\n): ProjectionMutationPatch {\n const fallbackRegions = new Set<Element>();\n const childListMutations: ProjectionMutationInput[] = [];\n const characterDataTargets: Node[] = [];\n const attributes = new Map<Element, Set<string>>();\n const annotations = new Map<Element, Set<string>>();\n const metadataTargets = new Set<Element>();\n const observedFiles = new ProjectionObservedFileAccumulator();\n\n for (const mutation of mutations) {\n const element = mutationTargetElement(mutation.target);\n if (!element || (element !== root && !root.contains(element))) continue;\n if (mutation.type === \"attributes\" && mutation.attributeName) {\n const targetMap = SOURCE_ANNOTATION_ATTRIBUTES.has(mutation.attributeName)\n ? annotations\n : attributes;\n const names = targetMap.get(element) ?? new Set<string>();\n names.add(mutation.attributeName);\n targetMap.set(element, names);\n if (targetMap === annotations) metadataTargets.add(element);\n continue;\n }\n if (mutation.type === \"characterData\") {\n characterDataTargets.push(mutation.target);\n } else {\n const carriesNoChildDetail =\n mutation.addedNodes === undefined &&\n mutation.removedNodes === undefined;\n if (options.regionalChildLists || carriesNoChildDetail) {\n // React can reuse an unkeyed DOM/Fiber slot for a different source\n // sibling. Its child-list target remains authoritative; the reused\n // child ids do not. Capture that exact parent's final children.\n fallbackRegions.add(element);\n } else {\n childListMutations.push(mutation);\n }\n }\n }\n\n const addedElements = coalesceElements(\n childListMutations.flatMap((mutation) =>\n Array.from(mutation.addedNodes ?? []).filter(\n (node): node is Element =>\n node instanceof Element && root.contains(node),\n ),\n ),\n );\n const removedElements = coalesceElements(\n childListMutations.flatMap((mutation) =>\n Array.from(mutation.removedNodes ?? []).filter(\n (node): node is Element =>\n node instanceof Element && !root.contains(node),\n ),\n ),\n );\n const coveredByAddedElement = (element: Element): boolean =>\n addedElements.some((added) => added === element || added.contains(element));\n\n const placements: ProjectionPlacePatch[] = [];\n const removals: ProjectionRemovePatch[] = [];\n const textGaps = new Map<string, ProjectionTextPatch>();\n\n for (const removed of removedElements) {\n const targetId = removed.getAttribute(DOM_ID_ATTR);\n // Missing removal targets are safe idempotent no-ops for contenteditable\n // internals and nodes that were both introduced and removed in this\n // collection window. They never justify widening to the parent body.\n if (targetId) removals.push({ kind: \"remove\", targetId });\n }\n\n // Place right-to-left so a newly-added next sibling is already available as\n // the exact anchor for the element before it.\n addedElements.sort(reverseDocumentOrder);\n for (const added of addedElements) {\n if (added.tagName.toLowerCase() === \"script\") continue;\n const parent = added.parentElement;\n if (!parent || (parent !== root && !root.contains(parent))) continue;\n const parentId = projectionTargetId(root, parent);\n const targetId = ensureProjectionDomId(added);\n if (!parentId || !targetId) {\n fallbackRegions.add(parent);\n continue;\n }\n const before = added.nextElementSibling;\n const beforeId = before ? ensureProjectionDomId(before) : null;\n if (before && !beforeId) {\n fallbackRegions.add(parent);\n continue;\n }\n const captured = capturePlacedElementWithoutAnnotations(added);\n placements.push({\n kind: \"place\",\n parentId,\n targetId,\n beforeId,\n html: captured.html,\n ancestorIds: captureProjectionAncestorIds(root, added),\n });\n mergeCapturedAnnotations(annotations, observedFiles, captured.annotations);\n }\n\n const captureTextGap = (parent: Element, before: Element | null): void => {\n if (coveredByAddedElement(parent)) return;\n const parentId = projectionTargetId(root, parent);\n const beforeId = before ? ensureProjectionDomId(before) : null;\n if (!parentId || (before && !beforeId)) {\n fallbackRegions.add(parent);\n return;\n }\n const key = `${parentId}\\u0000${beforeId ?? \"\"}`;\n textGaps.set(key, {\n kind: \"text\",\n parentId,\n beforeId,\n html: captureNonElementGap(parent, before),\n ancestorIds: captureProjectionAncestorIds(root, parent),\n });\n };\n\n for (const target of characterDataTargets) {\n const parent = target.parentElement;\n if (!parent || (parent !== root && !root.contains(parent))) continue;\n captureTextGap(parent, nextElementSibling(target));\n }\n for (const mutation of childListMutations) {\n const parent = mutation.target instanceof Element ? mutation.target : null;\n if (!parent || coveredByAddedElement(parent)) continue;\n for (const added of mutation.addedNodes ?? []) {\n if (added instanceof Element || added.parentNode !== parent) continue;\n captureTextGap(parent, nextElementSibling(added));\n }\n if (\n (mutation.removedNodes ?? []).some(\n (removed) => !(removed instanceof Element),\n )\n ) {\n const before = survivingNextElement(parent, mutation);\n if (before === undefined) fallbackRegions.add(parent);\n else captureTextGap(parent, before);\n }\n }\n\n // Unaddressable work widens to the nearest identifiable ancestor region;\n // its exact final state (annotations included, inline) rides in that\n // region's HTML instead of a separately addressed patch.\n for (const element of [...attributes.keys()]) {\n if (projectionTargetId(root, element)) continue;\n attributes.delete(element);\n fallbackRegions.add(widenToIdentifiableRegion(root, element));\n }\n for (const element of [...annotations.keys()]) {\n if (projectionTargetId(root, element)) continue;\n annotations.delete(element);\n fallbackRegions.add(widenToIdentifiableRegion(root, element));\n }\n for (const region of [...fallbackRegions]) {\n if (projectionTargetId(root, region)) continue;\n fallbackRegions.delete(region);\n fallbackRegions.add(widenToIdentifiableRegion(root, region));\n }\n\n const survivingRegions = coalesceRegions(fallbackRegions);\n // A region ships its innerHTML, so it carries every descendant's final\n // attributes but none of its own — `morphInner` writes the region's children\n // and never touches the region element itself. A strict descendant's\n // attribute op is therefore already said by the region and is dropped; the\n // region root's own is not, and has to survive alongside it.\n //\n // A placed element is the opposite case: `place` ships outerHTML, so the\n // element's own attributes ARE carried and self-coverage is correct there.\n const isInsideRegion = (element: Element): boolean =>\n survivingRegions.some(\n (region) => region !== element && region.contains(element),\n );\n for (const element of attributes.keys()) {\n if (isInsideRegion(element) || coveredByAddedElement(element)) {\n attributes.delete(element);\n }\n }\n\n const regionCaptures = new Map<Element, CapturedRegion>();\n for (const region of survivingRegions) {\n const captured = captureRegionWithoutAnnotations(region);\n regionCaptures.set(region, captured);\n mergeCapturedAnnotations(annotations, observedFiles, captured.annotations);\n }\n\n for (const element of annotations.keys()) observedFiles.addElement(element);\n\n const allTargets = new Set<Element>([\n ...survivingRegions,\n ...attributes.keys(),\n ...annotations.keys(),\n ]);\n const ids = new Map<Element, string>();\n for (const element of allTargets) {\n const id = projectionTargetId(root, element);\n if (id) ids.set(element, id);\n }\n\n return {\n dom: [\n ...removals.filter(\n (change) =>\n !survivingRegions.some((region) =>\n region.querySelector(\n `[${DOM_ID_ATTR}=\"${cssEscape(change.targetId)}\"]`,\n ),\n ),\n ),\n ...placements.filter(\n (change) => !isCoveredTargetId(root, survivingRegions, change.targetId),\n ),\n ...Array.from(textGaps.values()).filter(\n (change) => !isCoveredTargetId(root, survivingRegions, change.parentId),\n ),\n ...survivingRegions.map(\n (element): ProjectionRegionPatch => ({\n kind: \"children\",\n targetId: ids.get(element)!,\n html: regionCaptures.get(element)!.html,\n ancestorIds: captureProjectionAncestorIds(root, element),\n }),\n ),\n ...Array.from(\n attributes,\n ([element, names]): ProjectionAttributePatch => ({\n kind: \"attributes\",\n targetId: ids.get(element)!,\n attributes: captureFinalAttributes(element, names),\n ancestorIds: captureProjectionAncestorIds(root, element),\n }),\n ),\n ],\n annotations: Array.from(\n annotations,\n ([element, names]): ProjectionAnnotationPatch => ({\n targetId: ids.get(element)!,\n attributes: captureFinalAttributes(element, names),\n ancestorIds: captureProjectionAncestorIds(root, element),\n }),\n ),\n observedFiles: observedFiles.snapshot(),\n localMetadataTargets: Array.from(metadataTargets),\n };\n}\n\n/** Null when the element has no stable id or no representable state; the\n * caller simply skips it. Untracked state never blocks the stream. The\n * `root` bounds the repair-ladder chain walk. */\nexport function captureProjectionStatePatch(\n root: Element,\n element: Element,\n eventKind: \"scroll\" | \"input\" | \"change\",\n): ProjectionStatePatch | null {\n const targetId = element.getAttribute(DOM_ID_ATTR);\n if (!targetId) return null;\n const ancestorIds = captureProjectionAncestorIds(root, element);\n if (eventKind === \"scroll\") {\n return {\n targetId,\n kind: \"scroll\",\n scrollTop: element.scrollTop,\n scrollLeft: element.scrollLeft,\n ancestorIds,\n };\n }\n if (element instanceof HTMLInputElement) {\n if (element.type === \"checkbox\" || element.type === \"radio\") {\n return { targetId, kind: \"checked\", checked: element.checked, ancestorIds };\n }\n return {\n targetId,\n kind: \"value\",\n value: element.value,\n selectionStart: element.selectionStart,\n selectionEnd: element.selectionEnd,\n ancestorIds,\n };\n }\n if (element instanceof HTMLTextAreaElement) {\n return {\n targetId,\n kind: \"value\",\n value: element.value,\n selectionStart: element.selectionStart,\n selectionEnd: element.selectionEnd,\n ancestorIds,\n };\n }\n if (element instanceof HTMLSelectElement) {\n const selectedIndices: number[] = [];\n for (let index = 0; index < element.options.length; index += 1) {\n if (element.options[index]?.selected) selectedIndices.push(index);\n }\n return { targetId, kind: \"selected\", selectedIndices, ancestorIds };\n }\n return null;\n}\n\n/** Capture a complete portal final state without hiding source metadata in\n * HTML. Null when the portal was never stamped; such a portal is invisible to\n * the destination and skipping it cannot make the mirror worse.\n *\n * `coordinateRoot` is the watched root the portal belongs to; passing it\n * measures the source frame the destination needs to rebase the portal. */\nexport function captureProjectionPortalRegion(\n element: Element,\n removed = false,\n coordinateRoot?: Element,\n): ProjectionPortalRegionCapture | null {\n const portalId = element.getAttribute(PORTAL_ID_ATTR);\n if (!portalId) return null;\n if (removed) {\n return {\n portal: { kind: \"remove\", portalId },\n annotations: [],\n observedFiles: {},\n };\n }\n\n const liveElements = [element, ...element.querySelectorAll(\"*\")];\n for (const live of liveElements) ensureProjectionDomId(live);\n const clone = element.cloneNode(true) as Element;\n for (const script of clone.querySelectorAll(\"script\")) script.remove();\n const cloneElements = [clone, ...clone.querySelectorAll(\"*\")];\n const annotations: ProjectionAnnotationPatch[] = [];\n const observedFiles = new ProjectionObservedFileAccumulator();\n for (const detached of detachSourceAnnotations(liveElements, cloneElements)) {\n annotations.push({\n targetId: detached.targetId,\n attributes: captureFinalAttributes(detached.element, detached.names),\n ancestorIds: captureProjectionAncestorIds(element, detached.element),\n });\n observedFiles.addElement(detached.element);\n }\n const coordinateSpace = coordinateRoot\n ? capturePortalCoordinateSpace(coordinateRoot, element)\n : undefined;\n return {\n portal: {\n kind: \"replace\",\n portalId,\n html: removeScriptTags(clone.outerHTML),\n ...(coordinateSpace && { coordinateSpace }),\n },\n annotations,\n observedFiles: observedFiles.snapshot(),\n };\n}\n\n/** The coordinate-refresh half of a portal capture: a stylesheet change can\n * move a portal without mutating it, and re-sending its body would cost the\n * destination's focus and edit state for nothing. */\nexport function captureProjectionPortalCoordinates(\n root: Element,\n element: Element,\n): ProjectionPortalReplacePatch | null {\n const portalId = element.getAttribute(PORTAL_ID_ATTR);\n const coordinateSpace = capturePortalCoordinateSpace(root, element);\n if (!portalId || !coordinateSpace) return null;\n return {\n kind: \"replace\",\n portalId,\n html: \"\",\n coordinateSpace,\n coordinatesOnly: true,\n };\n}\n\nfunction mutationTargetElement(target: Node): Element | null {\n return target instanceof Element ? target : target.parentElement;\n}\n\nfunction projectionTargetId(root: Element, element: Element): string | null {\n return element === root\n ? PROJECTION_ROOT_TARGET_ID\n : element.getAttribute(DOM_ID_ATTR);\n}\n\nfunction coalesceElements(elements: readonly Element[]): Element[] {\n const unique = Array.from(new Set(elements));\n return unique.filter(\n (candidate) =>\n !unique.some((other) => other !== candidate && other.contains(candidate)),\n );\n}\n\nfunction reverseDocumentOrder(left: Element, right: Element): number {\n if (left === right) return 0;\n const position = left.compareDocumentPosition(right);\n if (position & 4) return 1;\n if (position & 2) return -1;\n return 0;\n}\n\nfunction nextElementSibling(node: Node): Element | null {\n let current = node.nextSibling;\n while (current && !(current instanceof Element))\n current = current.nextSibling;\n return current;\n}\n\nfunction survivingNextElement(\n parent: Element,\n mutation: ProjectionMutationInput,\n): Element | null | undefined {\n const next = mutation.nextSibling;\n if (next?.parentNode === parent) {\n return next instanceof Element ? next : nextElementSibling(next);\n }\n const previous = mutation.previousSibling;\n if (previous?.parentNode === parent) return nextElementSibling(previous);\n return parent.childNodes.length === 0 ? null : undefined;\n}\n\nfunction captureNonElementGap(parent: Element, before: Element | null): string {\n const nodes: Node[] = [];\n let current = before ? before.previousSibling : parent.lastChild;\n while (current && !(current instanceof Element)) {\n nodes.unshift(current.cloneNode(true));\n current = current.previousSibling;\n }\n const container = parent.ownerDocument.createElement(\"div\");\n container.append(...nodes);\n return container.innerHTML;\n}\n\nfunction capturePlacedElementWithoutAnnotations(\n element: Element,\n): CapturedRegion {\n const liveElements = [element, ...element.querySelectorAll(\"*\")];\n for (const live of liveElements) ensureProjectionDomId(live);\n const clone = element.cloneNode(true) as Element;\n if (clone.tagName.toLowerCase() === \"script\") {\n return { html: \"\", annotations: [] };\n }\n for (const script of clone.querySelectorAll(\"script\")) script.remove();\n const cloneElements = [clone, ...clone.querySelectorAll(\"*\")];\n // Serialize only after the annotations are off the clone.\n const annotations = detachSourceAnnotations(liveElements, cloneElements);\n return { html: clone.outerHTML, annotations };\n}\n\nfunction mergeCapturedAnnotations(\n target: Map<Element, Set<string>>,\n observedFiles: ProjectionObservedFileAccumulator,\n incoming: readonly DetachedAnnotation[],\n): void {\n for (const { element, names } of incoming) {\n const existing = target.get(element) ?? new Set<string>();\n for (const name of names) existing.add(name);\n target.set(element, existing);\n observedFiles.addElement(element);\n }\n}\n\nfunction isCoveredTargetId(\n root: Element,\n regions: readonly Element[],\n targetId: string,\n): boolean {\n const target =\n targetId === PROJECTION_ROOT_TARGET_ID\n ? root\n : root.querySelector(`[${DOM_ID_ATTR}=\"${cssEscape(targetId)}\"]`);\n return target\n ? regions.some((region) => region === target || region.contains(target))\n : false;\n}\n\n\nfunction coalesceRegions(regions: ReadonlySet<Element>): Element[] {\n const candidates = Array.from(regions);\n return candidates.filter(\n (candidate) =>\n !candidates.some(\n (other) => other !== candidate && other.contains(candidate),\n ),\n );\n}\n\nexport function captureFinalAttributes(\n element: Element,\n names: ReadonlySet<string>,\n): Readonly<Record<string, string | null>> {\n return Object.fromEntries(\n Array.from(names, (name) => [name, element.getAttribute(name)]),\n );\n}\n\n/** One live element's source annotations, lifted off the clone that mirrors it. */\nexport interface DetachedAnnotation {\n readonly element: Element;\n readonly targetId: string;\n readonly names: ReadonlySet<string>;\n}\n\n/**\n * Move the source annotations off a clone, reporting what each live element\n * carried. `live` and `clone` must be index-aligned enumerations of the same\n * subtree — every caller builds them from the same root-inclusion choice.\n *\n * Annotations are only lifted out of the HTML when the element can be\n * addressed separately; an id-less element keeps them inline instead.\n */\nexport function detachSourceAnnotations(\n live: readonly Element[],\n clone: readonly Element[],\n): DetachedAnnotation[] {\n const detached: DetachedAnnotation[] = [];\n for (let index = 0; index < live.length; index += 1) {\n const element = live[index];\n const copy = clone[index];\n if (!element || !copy) continue;\n const targetId = element.getAttribute(DOM_ID_ATTR);\n if (!targetId) continue;\n const names = new Set<string>();\n for (const name of SOURCE_ANNOTATION_ATTRIBUTES) {\n if (!element.hasAttribute(name)) continue;\n names.add(name);\n copy.removeAttribute(name);\n }\n if (names.size > 0) detached.push({ element, targetId, names });\n }\n return detached;\n}\n\nexport interface CapturedRegion {\n readonly html: string;\n readonly annotations: readonly DetachedAnnotation[];\n}\n\nexport function captureRegionWithoutAnnotations(\n element: Element,\n): CapturedRegion {\n const liveDescendants = Array.from(element.querySelectorAll(\"*\"));\n for (const live of liveDescendants) ensureProjectionDomId(live);\n const clone = element.cloneNode(true) as Element;\n for (const script of clone.querySelectorAll(\"script\")) script.remove();\n const cloneDescendants = Array.from(clone.querySelectorAll(\"*\"));\n // Serialize only after the annotations are off the clone.\n const annotations = detachSourceAnnotations(liveDescendants, cloneDescendants);\n return { html: clone.innerHTML, annotations };\n}\n\n/** Nearest self-or-ancestor with a stable id, else the watched root. */\nfunction widenToIdentifiableRegion(root: Element, element: Element): Element {\n for (\n let current: Element | null = element;\n current && current !== root;\n current = current.parentElement\n ) {\n if (current.getAttribute(DOM_ID_ATTR)) return current;\n }\n return root;\n}\n\n/** The element's parent-and-up id chain, lowest first, root excluded (the\n * root's sentinel is destination knowledge). Id-less ancestors are skipped. */\nexport function captureProjectionAncestorIds(\n root: Element,\n element: Element,\n): string[] {\n const ids: string[] = [];\n for (\n let current = element.parentElement;\n current && current !== root;\n current = current.parentElement\n ) {\n const id = current.getAttribute(DOM_ID_ATTR);\n if (id) ids.push(id);\n }\n return ids;\n}\n","import { captureAttributes, removeScriptTags } from \"../html/capture\";\nimport { DOM_ID_ATTR } from \"../html/watch-dom\";\nimport {\n capturePortalCoordinateSpace,\n PORTAL_ID_ATTR,\n} from \"../html/watch-portal\";\nimport { cssEscape } from \"./css-escape\";\nimport type { ProjectionLayerAdapter } from \"./projection-layer-adapter\";\nimport type { ProjectionLayerRootSnapshot } from \"./projection-layer-snapshot\";\nimport {\n ProjectionObservedFileAccumulator,\n type ProjectionObservedFileMap,\n} from \"./projection-observed-files\";\nimport {\n captureFinalAttributes,\n captureProjectionAncestorIds,\n captureRegionWithoutAnnotations,\n detachSourceAnnotations,\n PROJECTION_ROOT_TARGET_ID,\n type ProjectionAnnotationPatch,\n type ProjectionPortalPatch,\n type ProjectionStatePatch,\n} from \"./projection-patch\";\n\nexport interface ProjectionFullDomSnapshot {\n /** Children of the watched source wrapper; the wrapper is host plumbing. */\n readonly html: string;\n /** Optional authored attributes for sources whose wrapper is content (for\n * example a static HTML `<body>`), rather than host-only plumbing. */\n readonly rootAttributes?: Readonly<Record<string, string>>;\n readonly documentElementAttributes: Readonly<Record<string, string>>;\n /** The source `<body>`'s authored attributes. Portals are mirrored into the\n * destination body, so its classes and data attributes are part of what they\n * render against. Absent for a source document with no body. */\n readonly bodyAttributes?: Readonly<Record<string, string>>;\n readonly baseUrl?: string;\n readonly annotations: readonly ProjectionAnnotationPatch[];\n readonly state: readonly ProjectionStatePatch[];\n readonly portals: readonly ProjectionPortalPatch[];\n}\n\nexport interface ProjectionFullSnapshot {\n readonly dom: ProjectionFullDomSnapshot;\n readonly layers: ProjectionLayerRootSnapshot;\n readonly observedFiles: ProjectionObservedFileMap;\n}\n\nexport interface ProjectionFullSnapshotCapture {\n readonly snapshot: ProjectionFullSnapshot;\n readonly fiberNodesVisited: number;\n readonly semanticNodesSerialized: number;\n /** Distinct stamped elements the baseline covers. Producer-local: the\n * destination is never told this and never validates against it. */\n readonly hostDomIdCount: number;\n}\n\nexport interface CaptureProjectionFullSnapshotOptions {\n readonly root: Element;\n readonly layerAdapter: ProjectionLayerAdapter;\n readonly fiberTarget?: Element | null;\n readonly portals?: readonly Element[];\n}\n\n/**\n * One self-contained initial/reload/recovery baseline. Every O(N) operation is\n * performed in this single host pass family; ordinary updates never call it.\n * Capture never refuses: whatever the source document looks like — duplicate\n * ids, unstampable elements — is exactly what the destination should show.\n */\nexport function captureProjectionFullSnapshot(\n options: CaptureProjectionFullSnapshotOptions,\n): ProjectionFullSnapshotCapture {\n const fiberTarget = options.fiberTarget ?? options.root.firstElementChild;\n const observedFiles = new ProjectionObservedFileAccumulator();\n const { dom, hostDomIdCount } = captureFullDom(\n options.root,\n options.portals ?? [],\n observedFiles,\n );\n const observedFileSnapshot = observedFiles.snapshot();\n const layerCapture = options.layerAdapter.captureFull(\n options.root,\n fiberTarget,\n observedFileSnapshot,\n );\n const layers = layerCapture.snapshot;\n observedFiles.merge(layers.observedFiles);\n const completeObservedFileSnapshot = observedFiles.snapshot();\n\n return {\n snapshot: {\n dom,\n layers,\n observedFiles: completeObservedFileSnapshot,\n },\n fiberNodesVisited: layerCapture.fiberNodesVisited,\n semanticNodesSerialized: layerCapture.semanticNodesSerialized,\n hostDomIdCount,\n };\n}\n\nfunction captureFullDom(\n root: Element,\n portals: readonly Element[],\n observedFiles: ProjectionObservedFileAccumulator,\n): { dom: ProjectionFullDomSnapshot; hostDomIdCount: number } {\n const clone = root.cloneNode(true) as Element;\n for (const script of clone.querySelectorAll(\"script\")) script.remove();\n const annotations: ProjectionAnnotationPatch[] = [];\n // Producer-local, for the batch perf receipt only; never serialized.\n const hostDomIds = new Set<string>();\n stripAnnotationsAndCollectIds(\n root,\n clone,\n annotations,\n hostDomIds,\n observedFiles,\n false,\n );\n\n const portalPatches: ProjectionPortalPatch[] = [];\n for (const portal of portals) {\n if (!portal.isConnected) continue;\n const portalId = portal.getAttribute(PORTAL_ID_ATTR);\n if (!portalId) continue;\n const portalClone = portal.cloneNode(true) as Element;\n for (const script of portalClone.querySelectorAll(\"script\"))\n script.remove();\n stripAnnotationsAndCollectIds(\n portal,\n portalClone,\n annotations,\n hostDomIds,\n observedFiles,\n true,\n );\n const coordinateSpace = capturePortalCoordinateSpace(root, portal);\n portalPatches.push({\n kind: \"replace\",\n portalId,\n html: removeScriptTags(portalClone.outerHTML),\n ...(coordinateSpace && { coordinateSpace }),\n });\n }\n\n const body = root.ownerDocument.body;\n const dom: ProjectionFullDomSnapshot = {\n html: removeScriptTags(clone.innerHTML),\n documentElementAttributes: captureAttributes(\n root.ownerDocument.documentElement,\n ),\n ...(body ? { bodyAttributes: captureAttributes(body) } : {}),\n baseUrl: root.ownerDocument.baseURI,\n annotations,\n state: collectFullRuntimeState(root, portals),\n portals: portalPatches,\n };\n return { dom, hostDomIdCount: hostDomIds.size };\n}\n\nfunction stripAnnotationsAndCollectIds(\n liveRoot: Element,\n cloneRoot: Element,\n annotations: ProjectionAnnotationPatch[],\n hostDomIds: Set<string>,\n observedFiles: ProjectionObservedFileAccumulator,\n includeRoot: boolean,\n): void {\n const live = includeRoot\n ? [liveRoot, ...liveRoot.querySelectorAll(\"*\")]\n : Array.from(liveRoot.querySelectorAll(\"*\"));\n const clones = includeRoot\n ? [cloneRoot, ...cloneRoot.querySelectorAll(\"*\")]\n : Array.from(cloneRoot.querySelectorAll(\"*\"));\n for (const element of live) {\n const domId = element.getAttribute(DOM_ID_ATTR);\n if (domId) hostDomIds.add(domId);\n }\n for (const detached of detachSourceAnnotations(live, clones)) {\n annotations.push({\n targetId: detached.targetId,\n attributes: captureFinalAttributes(detached.element, detached.names),\n });\n observedFiles.addElement(detached.element);\n }\n}\n\nfunction collectFullRuntimeState(\n root: Element,\n portals: readonly Element[],\n): ProjectionStatePatch[] {\n const states: ProjectionStatePatch[] = [];\n for (const scope of [root, ...portals]) {\n for (const element of [scope, ...scope.querySelectorAll(\"*\")]) {\n const targetId = element.getAttribute(DOM_ID_ATTR);\n if (!targetId) continue;\n if (element.scrollTop !== 0 || element.scrollLeft !== 0) {\n states.push({\n targetId,\n kind: \"scroll\",\n scrollTop: element.scrollTop,\n scrollLeft: element.scrollLeft,\n });\n }\n if (element instanceof HTMLInputElement) {\n if (element.type === \"checkbox\" || element.type === \"radio\") {\n if (element.checked !== element.defaultChecked) {\n states.push({\n targetId,\n kind: \"checked\",\n checked: element.checked,\n });\n }\n } else if (element.value !== element.defaultValue) {\n states.push({\n targetId,\n kind: \"value\",\n value: element.value,\n selectionStart: element.selectionStart,\n selectionEnd: element.selectionEnd,\n });\n }\n } else if (\n element instanceof HTMLTextAreaElement &&\n element.value !== element.defaultValue\n ) {\n states.push({\n targetId,\n kind: \"value\",\n value: element.value,\n selectionStart: element.selectionStart,\n selectionEnd: element.selectionEnd,\n });\n } else if (element instanceof HTMLSelectElement) {\n const selectedIndices: number[] = [];\n let changed = false;\n for (\n let optionIndex = 0;\n optionIndex < element.options.length;\n optionIndex += 1\n ) {\n const option = element.options[optionIndex];\n if (!option) continue;\n if (option.selected) selectedIndices.push(optionIndex);\n if (option.selected !== option.defaultSelected) changed = true;\n }\n if (changed)\n states.push({ targetId, kind: \"selected\", selectedIndices });\n }\n }\n }\n return states;\n}\n\n/** One element's exact children-region final state. */\nexport interface ProjectionRegionCapture {\n readonly targetId: string;\n readonly html: string;\n /** Current parent-and-up id chain, for continuing the repair ladder. */\n readonly ancestorIds: readonly string[];\n readonly annotations: readonly ProjectionAnnotationPatch[];\n readonly state: readonly ProjectionStatePatch[];\n}\n\n/**\n * Capture one element's region on demand for the destination's scoped repair\n * ladder. Same capture routine as the hot patch builder: scripts stripped,\n * addressable annotations lifted out beside the HTML, descendant runtime state\n * included so a morphed repair isn't state-bare. Null when the id no longer\n * names a live element — the destination then climbs further up its known\n * chain.\n */\nexport function captureProjectionRegion(\n root: Element,\n targetId: string,\n portals: readonly Element[] = [],\n): ProjectionRegionCapture | null {\n const element = resolveRegionElement(root, targetId, portals);\n if (!element) return null;\n const captured = captureRegionWithoutAnnotations(element);\n const annotations = captured.annotations.map((detached) => ({\n targetId: detached.targetId,\n attributes: captureFinalAttributes(detached.element, detached.names),\n ancestorIds: captureProjectionAncestorIds(root, detached.element),\n }));\n return {\n targetId,\n html: captured.html,\n ancestorIds:\n element === root ? [] : captureProjectionAncestorIds(root, element),\n annotations,\n state: collectFullRuntimeState(element, []),\n };\n}\n\n/** Ingress validation for the untrusted repair-response wire value. */\nexport function isProjectionRegionCapture(\n value: unknown,\n): value is ProjectionRegionCapture {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const record = value as Record<string, unknown>;\n return (\n typeof record.targetId === \"string\" &&\n typeof record.html === \"string\" &&\n Array.isArray(record.ancestorIds) &&\n record.ancestorIds.every((id) => typeof id === \"string\") &&\n Array.isArray(record.annotations) &&\n Array.isArray(record.state)\n );\n}\n\nfunction resolveRegionElement(\n root: Element,\n targetId: string,\n portals: readonly Element[],\n): Element | null {\n if (targetId === PROJECTION_ROOT_TARGET_ID) return root;\n const selector = `[${DOM_ID_ATTR}=\"${cssEscape(targetId)}\"]`;\n const scopes = [root, ...portals.filter((portal) => portal.isConnected)];\n for (const scope of scopes) {\n const found = scope.matches(selector)\n ? scope\n : scope.querySelector(selector);\n if (found) return found;\n }\n return null;\n}\n","/**\n * Closed, destination-ready semantic snapshots for projection roots.\n *\n * This module deliberately serializes raw Fibers directly into the shape the\n * Canvas layer binder needs. It does not create an EnrichedFiberNode, copy an\n * arbitrary component prop bag, or capture computed-style/layout facts.\n * Source annotations and exact observed-file facts are collected during the\n * same Fiber enumeration that creates the semantic tree.\n */\n\nimport { type Fiber, FiberTag, type FiberTagValue } from \"../fiber/react-types\";\nimport { getDisplayName, getDomElement, getProps } from \"../fiber/serialize\";\nimport { ensureProjectionDomId } from \"../html/watch-dom\";\nimport {\n ProjectionObservedFileAccumulator,\n type ProjectionObservedFileMap,\n} from \"./projection-observed-files\";\n\nexport type ProjectionLayerKind = \"host\" | \"component\" | \"fragment\";\n\n/** The complete top-level prop allowlist consumed by LayerSnapshot today. */\nexport interface ProjectionLayerProps {\n readonly className?: string;\n readonly style?: Readonly<Record<string, string>>;\n readonly \"data-tempo-filepath\"?: string;\n readonly \"data-tempo-position\"?: number;\n readonly \"data-tempo-modifiedts\"?: number;\n readonly \"data-tempo-source-version\"?: string;\n readonly \"data-tempo-html-filepath\"?: string;\n readonly \"data-tempo-html-offset\"?: string;\n readonly \"data-tempo-html-modifiedts\"?: string;\n readonly \"data-tempo-html-source-version\"?: string;\n readonly \"data-tempo-supports-style\"?: boolean;\n readonly \"data-tempo-supports-classname\"?: boolean;\n readonly \"data-tempo-supports-children\"?: boolean;\n}\n\nexport interface ProjectionLayerSource {\n readonly kind: \"react-fiber\";\n readonly fiber: {\n readonly tag: FiberTagValue;\n readonly name: string;\n /** Stable for this serializer's source-document lifetime. */\n readonly id: string;\n };\n}\n\ninterface ProjectionLayerNodeBase {\n readonly name: string;\n readonly props?: ProjectionLayerProps;\n readonly source: ProjectionLayerSource;\n readonly children: readonly ProjectionLayerNode[];\n}\n\nexport interface ProjectionHostLayerNode extends ProjectionLayerNodeBase {\n readonly kind: \"host\";\n /** Identity hint for destination binding; elements cannot cross realms.\n * Null when the host element could not be stamped (contenteditable\n * interiors) — such a node binds without a destination element. */\n readonly domId: string | null;\n readonly elementTag: string;\n}\n\nexport interface ProjectionElementlessLayerNode\n extends ProjectionLayerNodeBase {\n readonly kind: \"component\" | \"fragment\";\n readonly domId: null;\n readonly elementTag: null;\n}\n\nexport type ProjectionLayerNode =\n | ProjectionHostLayerNode\n | ProjectionElementlessLayerNode;\n\n/**\n * The semantic slice of a self-contained full root baseline. The outer full\n * capture assembler adds the DOM, annotation, runtime-state, and portal\n * domains; those concerns do not belong in the Fiber serializer's interface.\n */\nexport interface ProjectionLayerRootSnapshot {\n readonly semantic:\n | { readonly kind: \"layers\"; readonly tree: ProjectionLayerNode | null }\n | { readonly kind: \"dom-only\" };\n readonly observedFiles: ProjectionObservedFileMap;\n}\n\n/**\n * One final-state semantic region. `targetFiberId` names the currently\n * published layer-tree node being replaced; `tree` is the replacement rooted\n * at that slot, or null when the committed Fiber branch disappeared.\n */\nexport interface ProjectionLayerRegionSnapshot {\n readonly targetFiberId: string;\n readonly tree: ProjectionLayerNode | null;\n readonly observedFiles: ProjectionObservedFileMap;\n}\n\n/** Exact non-structural facts for one already-published semantic node. */\nexport interface ProjectionLayerMetadataSnapshot {\n readonly targetFiberId: string;\n readonly props?: ProjectionLayerProps;\n}\n\nexport interface ProjectionLayerSerializationResult {\n readonly snapshot: ProjectionLayerRootSnapshot;\n readonly fiberNodesVisited: number;\n readonly semanticNodesSerialized: number;\n}\n\nexport interface ProjectionLayerRegionSerializationResult {\n readonly region: ProjectionLayerRegionSnapshot;\n readonly fiberNodesVisited: number;\n readonly semanticNodesSerialized: number;\n}\n\nexport interface ProjectionLayerSerializer {\n /** Serialize one committed Fiber root in one synchronous enumeration. */\n serialize(root: Fiber): ProjectionLayerSerializationResult;\n /** Stable only for this source-document serializer lifetime. */\n fiberId(fiber: Fiber): string;\n /** Read a previously assigned ID without growing the identity registry. */\n knownFiberId(fiber: Fiber): string | null;\n /** Serialize one exact replacement region, preserving its published ID. */\n serializeRegion(root: Fiber): ProjectionLayerRegionSerializationResult;\n /** Capture only the allowlisted facts of one existing semantic node. */\n captureMetadata(\n root: Fiber,\n options?: { readonly sourceAnnotations?: \"fiber\" | \"live-host\" },\n ): ProjectionLayerMetadataSnapshot;\n}\n\nconst COMPONENT_TAGS: ReadonlySet<FiberTagValue> = new Set([\n FiberTag.FunctionComponent,\n FiberTag.ClassComponent,\n FiberTag.ForwardRef,\n FiberTag.MemoComponent,\n FiberTag.SimpleMemoComponent,\n FiberTag.LazyComponent,\n]);\n\n/**\n * Create one serializer per source-document lifetime. Its private Fiber ID\n * registry pairs React's current/alternate objects while avoiding realm-global\n * identity state and keeping the serializer free of the legacy enriched path.\n */\nexport function createProjectionLayerSerializer(): ProjectionLayerSerializer {\n let nextFiberId = 1;\n const fiberIds = new WeakMap<Fiber, string>();\n\n const fiberId = (fiber: Fiber): string => {\n const direct = fiberIds.get(fiber);\n if (direct) return direct;\n const alternate = fiber.alternate ? fiberIds.get(fiber.alternate) : null;\n if (alternate) {\n fiberIds.set(fiber, alternate);\n return alternate;\n }\n const id = String(nextFiberId++);\n fiberIds.set(fiber, id);\n if (fiber.alternate) fiberIds.set(fiber.alternate, id);\n return id;\n };\n\n const knownFiberId = (fiber: Fiber): string | null =>\n fiberIds.get(fiber) ??\n (fiber.alternate ? fiberIds.get(fiber.alternate) : undefined) ??\n null;\n\n const serialize = (root: Fiber): ProjectionLayerSerializationResult => {\n const observedFiles = new ProjectionObservedFileAccumulator();\n let fiberNodesVisited = 0;\n let semanticNodesSerialized = 0;\n\n const visit = (fiber: Fiber, emitLayer: boolean): ProjectionLayerNode[] => {\n fiberNodesVisited += 1;\n const name = getDisplayName(fiber);\n const kind = projectionKindForTag(fiber.tag);\n const included = isProjectionLayerFiber(fiber);\n const element = kind === \"host\" ? getDomElement(fiber) : null;\n const domId = element ? ensureProjectionDomId(element) : null;\n\n const props = included\n ? captureProjectionLayerProps(fiber, element)\n : undefined;\n if (props) {\n observedFiles.add(\n props[\"data-tempo-filepath\"],\n props[\"data-tempo-modifiedts\"],\n props[\"data-tempo-source-version\"],\n );\n observedFiles.add(\n props[\"data-tempo-html-filepath\"],\n props[\"data-tempo-html-modifiedts\"],\n props[\"data-tempo-html-source-version\"],\n );\n }\n\n // SVG is one Canvas layer, but its descendants still belong to the\n // certified render population and can carry observed-file facts.\n // Contenteditable is different: its descendants are presentation-owned\n // and deliberately receive neither projection IDs nor semantic nodes.\n const isSvgLeaf =\n included && kind === \"host\" && name.toLowerCase() === \"svg\";\n const isContentEditableBoundary =\n included &&\n kind === \"host\" &&\n element?.getAttribute(\"contenteditable\") !== null;\n const children: ProjectionLayerNode[] = [];\n if (!isContentEditableBoundary) {\n for (let child = fiber.child; child; child = child.sibling) {\n children.push(...visit(child, emitLayer && !isSvgLeaf));\n }\n }\n\n if (!emitLayer) return [];\n if (!included) return children;\n if (kind === null) return children;\n\n const source: ProjectionLayerSource = {\n kind: \"react-fiber\",\n fiber: { tag: fiber.tag, name, id: fiberId(fiber) },\n };\n let node: ProjectionLayerNode;\n if (kind === \"host\") {\n node = {\n kind,\n name,\n domId,\n elementTag: name,\n props,\n source,\n children: isSvgLeaf || isContentEditableBoundary ? [] : children,\n };\n } else {\n node = {\n kind,\n name,\n domId: null,\n elementTag: null,\n props,\n source,\n children,\n };\n }\n semanticNodesSerialized += 1;\n return [node];\n };\n\n const branches = visit(root, true);\n\n let tree: ProjectionLayerNode | null;\n if (branches.length === 1) {\n tree = branches[0] ?? null;\n } else if (root.tag === FiberTag.HostRoot) {\n const name = getDisplayName(root);\n tree = {\n kind: \"fragment\",\n name,\n domId: null,\n elementTag: null,\n source: {\n kind: \"react-fiber\",\n fiber: { tag: root.tag, name, id: fiberId(root) },\n },\n children: branches,\n };\n semanticNodesSerialized += 1;\n } else {\n tree = null;\n }\n\n return {\n snapshot: {\n semantic: { kind: \"layers\", tree },\n observedFiles: observedFiles.snapshot(),\n },\n fiberNodesVisited,\n semanticNodesSerialized,\n };\n };\n\n return {\n serialize,\n fiberId,\n knownFiberId,\n serializeRegion(root) {\n const targetFiberId = fiberId(root);\n const serialized = serialize(root);\n return {\n region: {\n targetFiberId,\n tree:\n serialized.snapshot.semantic.kind === \"layers\"\n ? serialized.snapshot.semantic.tree\n : null,\n observedFiles: serialized.snapshot.observedFiles,\n },\n fiberNodesVisited: serialized.fiberNodesVisited,\n semanticNodesSerialized: serialized.semanticNodesSerialized,\n };\n },\n captureMetadata(root, options) {\n return {\n targetFiberId: fiberId(root),\n props: captureProjectionLayerProps(\n root,\n root.tag === FiberTag.HostComponent ? getDomElement(root) : null,\n options?.sourceAnnotations ?? \"fiber\",\n ),\n };\n },\n };\n}\n\n/** True when the Fiber itself has one stable Canvas semantic node. */\nexport function isProjectionLayerFiber(fiber: Fiber): boolean {\n if (isTempoHiddenFiber(fiber)) return false;\n const kind = projectionKindForTag(fiber.tag);\n if (kind === null) return false;\n if (kind === \"host\") return true;\n\n // React can introduce Memo/ForwardRef/function wrapper Fibers for the exact\n // same authored JSX location. Exclude that wrapper by one stable semantic\n // rule instead of serializing it, minting an ID, then deleting its node in a\n // post-pass. Every Fiber that receives a projection ID is therefore a Fiber\n // the destination was actually given.\n const sourceKey = projectionFiberSourceKey(fiber);\n if (!sourceKey) return true;\n for (let parent = fiber.return; parent; parent = parent.return) {\n if (isTempoHiddenFiber(parent)) continue;\n const parentKind = projectionKindForTag(parent.tag);\n if (parentKind === null) continue;\n if (parentKind === \"host\") return true;\n return projectionFiberSourceKey(parent) !== sourceKey;\n }\n return true;\n}\n\nfunction projectionKindForTag(tag: FiberTagValue): ProjectionLayerKind | null {\n if (tag === FiberTag.HostComponent) return \"host\";\n if (COMPONENT_TAGS.has(tag)) return \"component\";\n return null;\n}\n\n/**\n * Ascend from a watched root's first host fiber to the topmost SOURCE-ANNOTATED\n * component fiber that renders it, so the semantic tree includes user-authored\n * wrapper components that own the root host element (a design-system\n * `PageFrame` between the storyboard slot and its first `<div>`). Serializing\n * from the host alone drops those fibers before the destination's transparency\n * rules can ever see them.\n *\n * The ascent anchors only on component fibers carrying a\n * `data-tempo-filepath`/`data-tempo-position` source tuple — an annotated\n * callsite is user JSX. It stops, without anchoring, at:\n * - any host fiber, HostRoot, or HostPortal (crossed out of this render's\n * own component chain);\n * - a Tempo-hidden fiber (`data-tempo-hide-fiber` plumbing);\n * - the first un-annotated component fiber — the SDK's own `<Component />`\n * storyboard callsite and other non-user plumbing are never annotated, so\n * a plain storyboard's tree still roots at its host element exactly as\n * before.\n * Non-semantic fibers (fragments, providers, modes, Suspense) neither anchor\n * nor stop the ascent.\n */\nexport function ascendToAnnotatedComponentRoot(fiber: Fiber): Fiber {\n let topmost = fiber;\n for (let parent = fiber.return; parent; parent = parent.return) {\n if (\n parent.tag === FiberTag.HostRoot ||\n parent.tag === FiberTag.HostPortal\n ) {\n break;\n }\n const kind = projectionKindForTag(parent.tag);\n if (kind === \"host\") break;\n if (isTempoHiddenFiber(parent)) break;\n if (kind === \"component\") {\n if (projectionFiberSourceKey(parent) === null) break;\n topmost = parent;\n }\n }\n return topmost;\n}\n\nfunction isTempoHiddenFiber(fiber: Fiber): boolean {\n const props = getProps(fiber);\n const direct = props?.[\"data-tempo-hide-fiber\"];\n const dataSet = props?.dataSet;\n const native =\n dataSet && typeof dataSet === \"object\"\n ? (dataSet as Record<string, unknown>).tempoHideFiber\n : undefined;\n const value = native ?? direct;\n return value === true || value === \"true\";\n}\n\nfunction captureProjectionLayerProps(\n fiber: Fiber,\n element: Element | null,\n sourceAnnotations: \"fiber\" | \"live-host\" = \"fiber\",\n): ProjectionLayerProps | undefined {\n const raw = getProps(fiber);\n const dataSet =\n raw?.dataSet && typeof raw.dataSet === \"object\"\n ? (raw.dataSet as Record<string, unknown>)\n : undefined;\n const read = (\n flatKey: string,\n dataSetKey: string,\n authority: \"source\" | \"fiber\" = \"source\",\n ): unknown => {\n if (\n authority === \"source\" &&\n element &&\n sourceAnnotations === \"live-host\"\n ) {\n return element.getAttribute(flatKey);\n }\n return dataSet && Object.hasOwn(dataSet, dataSetKey)\n ? dataSet[dataSetKey]\n : raw?.[flatKey];\n };\n\n const props: Record<string, unknown> = {};\n const putString = (flatKey: string, dataSetKey: string): void => {\n const value = read(flatKey, dataSetKey);\n if (typeof value === \"string\") props[flatKey] = value;\n };\n const putFiniteNumber = (flatKey: string, dataSetKey: string): void => {\n const value = read(flatKey, dataSetKey);\n const numeric =\n typeof value === \"number\"\n ? value\n : typeof value === \"string\"\n ? Number(value)\n : Number.NaN;\n if (Number.isFinite(numeric)) props[flatKey] = numeric;\n };\n const putStringified = (flatKey: string, dataSetKey: string): void => {\n const value = read(flatKey, dataSetKey);\n if (typeof value === \"string\" || typeof value === \"number\") {\n props[flatKey] = String(value);\n }\n };\n const putBoolean = (flatKey: string, dataSetKey: string): void => {\n // Capability flags describe the component contract carried by Fiber. A\n // live host mutation is authoritative only for source annotations; it\n // must not erase Fiber-only capabilities that have no DOM attribute.\n const value = read(flatKey, dataSetKey, \"fiber\");\n if (value === true || value === \"true\") props[flatKey] = true;\n if (value === false || value === \"false\") props[flatKey] = false;\n };\n\n putString(\"data-tempo-filepath\", \"tempoFilepath\");\n putFiniteNumber(\"data-tempo-position\", \"tempoPosition\");\n putFiniteNumber(\"data-tempo-modifiedts\", \"tempoModifiedts\");\n putString(\"data-tempo-source-version\", \"tempoSourceVersion\");\n putString(\"data-tempo-html-filepath\", \"tempoHtmlFilepath\");\n putStringified(\"data-tempo-html-offset\", \"tempoHtmlOffset\");\n putStringified(\"data-tempo-html-modifiedts\", \"tempoHtmlModifiedts\");\n putString(\"data-tempo-html-source-version\", \"tempoHtmlSourceVersion\");\n putBoolean(\"data-tempo-supports-style\", \"tempoSupportsStyle\");\n putBoolean(\"data-tempo-supports-classname\", \"tempoSupportsClassname\");\n putBoolean(\"data-tempo-supports-children\", \"tempoSupportsChildren\");\n\n if (element) {\n const className = element.getAttribute(\"class\");\n if (className !== null && className !== \"\") props.className = className;\n const style = parseInlineStyle(element.getAttribute(\"style\"));\n if (style) props.style = style;\n }\n\n return Object.keys(props).length > 0\n ? (props as unknown as ProjectionLayerProps)\n : undefined;\n}\n\nfunction parseInlineStyle(\n value: string | null,\n): Readonly<Record<string, string>> | undefined {\n if (!value) return undefined;\n const style: Record<string, string> = {};\n for (const declaration of value.split(\";\")) {\n const colon = declaration.indexOf(\":\");\n if (colon < 0) continue;\n const property = declaration.slice(0, colon).trim();\n const propertyValue = declaration.slice(colon + 1).trim();\n if (property) style[property] = propertyValue;\n }\n return Object.keys(style).length > 0 ? style : undefined;\n}\n\nfunction projectionFiberSourceKey(fiber: Fiber): string | null {\n // Only the source annotations are read here, and in the default \"fiber\"\n // authority those come from the Fiber's props alone. Passing no element\n // skips the className and inline-style capture this caller discards — the\n // walk below asks for this key once per visited Fiber and again per\n // ancestor.\n const props = captureProjectionLayerProps(fiber, null);\n const filepath = props?.[\"data-tempo-filepath\"];\n const position = props?.[\"data-tempo-position\"];\n return filepath && position !== undefined ? `${filepath}:${position}` : null;\n}\n","import { FiberTag } from \"../fiber/react-types\";\nimport { DOM_ID_ATTR, ensureProjectionDomId } from \"../html/watch-dom\";\nimport type {\n ProjectionLayerMetadataSnapshot,\n ProjectionLayerNode,\n ProjectionLayerProps,\n ProjectionLayerRegionSnapshot,\n ProjectionLayerRootSnapshot,\n} from \"./projection-layer-snapshot\";\nimport type { ProjectionObservedFileMap } from \"./projection-observed-files\";\nimport { SOURCE_ANNOTATION_ATTRIBUTES } from \"./projection-patch\";\nimport type { ProjectionLayerPatch } from \"./projection-root-accumulator\";\n\nexport const DOM_LAYER_ROOT_ID = \"dom:$projection-root\";\nconst DOM_LAYER_FIBER_PREFIX = \"dom:\";\n\nexport interface ProjectionDomLayerTargets {\n readonly structural: readonly Element[];\n readonly metadata: readonly Element[];\n}\n\n/**\n * One serializer per watched root lifetime. DOM ids are lookup anchors copied\n * into the destination; they are not semantic identity because source code can\n * duplicate them with cloneNode(true). Element object identity is not copied,\n * so a WeakMap gives every live source element one stable semantic identity\n * without mutating the source's representationally valid duplicate ids.\n */\nexport interface ProjectionDomLayerSerializer {\n serializeRoot(\n root: Element,\n observedFiles?: ProjectionObservedFileMap,\n ): ProjectionLayerRootSnapshot;\n capturePatch(\n root: Element,\n targets: ProjectionDomLayerTargets,\n observedFiles?: ProjectionObservedFileMap,\n ): ProjectionLayerPatch | undefined;\n}\n\nexport function createProjectionDomLayerSerializer(): ProjectionDomLayerSerializer {\n let nextElementId = 1;\n const elementIds = new WeakMap<Element, string>();\n const domIdOwners = new Map<string, Element>();\n const identity: DomLayerIdentity = {\n layerIdForElement(_root, element) {\n const existing = elementIds.get(element);\n if (existing) return existing;\n const id = `${DOM_LAYER_FIBER_PREFIX}element:${nextElementId++}`;\n elementIds.set(element, id);\n return id;\n },\n bindableDomIdForElement(root, element) {\n const domId = ensureProjectionDomId(element);\n if (!domId) return null;\n const owner = domIdOwners.get(domId);\n if (owner === element) return domId;\n if (!owner || !root.contains(owner)) {\n domIdOwners.set(domId, element);\n return domId;\n }\n return null;\n },\n };\n\n return {\n serializeRoot(root, observedFiles = {}) {\n return serializeProjectionDomLayerRootWithIdentity(\n root,\n observedFiles,\n identity,\n );\n },\n capturePatch(root, targets, observedFiles = {}) {\n return captureProjectionDomLayerPatchFromTargets(\n root,\n targets,\n observedFiles,\n identity,\n );\n },\n };\n}\n\ninterface DomLayerIdentity {\n readonly layerIdForElement: (root: Element, element: Element) => string;\n readonly bindableDomIdForElement: (\n root: Element,\n element: Element,\n ) => string | null;\n}\n\nconst dataDomLayerIdentity: DomLayerIdentity = {\n layerIdForElement: domLayerIdForElement,\n bindableDomIdForElement: (_root, element) => ensureProjectionDomId(element),\n};\n\n/**\n * Build the semantic layer tree for a document that has no React Fiber root.\n *\n * Projection's DOM lane already owns stable `data-dom-id` identities. Reusing\n * those identities here keeps a plain HTML page selectable in exactly the same\n * way as a host-only React tree, without pretending that source components or\n * editable React props exist.\n */\nexport function serializeProjectionDomLayerRoot(\n root: Element,\n observedFiles: ProjectionObservedFileMap = {},\n): ProjectionLayerRootSnapshot {\n return serializeProjectionDomLayerRootWithIdentity(\n root,\n observedFiles,\n dataDomLayerIdentity,\n );\n}\n\nfunction serializeProjectionDomLayerRootWithIdentity(\n root: Element,\n observedFiles: ProjectionObservedFileMap,\n identity: DomLayerIdentity,\n): ProjectionLayerRootSnapshot {\n return {\n semantic: {\n kind: \"layers\",\n tree: serializeDomLayerRootNode(root, identity),\n },\n observedFiles,\n };\n}\n\n/** Build exact semantic deltas from source-realm mutation targets. */\nfunction captureProjectionDomLayerPatchFromTargets(\n root: Element,\n targets: ProjectionDomLayerTargets,\n observedFiles: ProjectionObservedFileMap,\n identity: DomLayerIdentity,\n): ProjectionLayerPatch | undefined {\n const structuralTargets = new Set(\n targets.structural.filter(\n (target) => target === root || root.contains(target),\n ),\n );\n const metadataTargets = new Set(\n targets.metadata.filter(\n (target) => target === root || root.contains(target),\n ),\n );\n\n // A parent replacement already carries the final semantic subtree for every\n // descendant. Keep only the widest disjoint regions, matching the DOM patch\n // coalescer's final-state contract.\n const regions = Array.from(structuralTargets).filter(\n (candidate) =>\n !Array.from(structuralTargets).some(\n (other) => other !== candidate && other.contains(candidate),\n ),\n );\n const regionSnapshots: ProjectionLayerRegionSnapshot[] = regions.map(\n (target) => ({\n targetFiberId: layerIdForTarget(root, target, identity),\n tree:\n target === root\n ? serializeDomLayerRootNode(root, identity)\n : serializeDomLayerNode(root, target, identity),\n observedFiles,\n }),\n );\n\n const metadataSnapshots: ProjectionLayerMetadataSnapshot[] = [];\n for (const target of metadataTargets) {\n if (\n target !== root &&\n regions.some((region) => region === root || region.contains(target))\n ) {\n continue;\n }\n metadataSnapshots.push({\n targetFiberId: layerIdForTarget(root, target, identity),\n props: captureProjectionDomLayerProps(target),\n });\n }\n\n if (regionSnapshots.length === 0 && metadataSnapshots.length === 0) {\n return undefined;\n }\n return {\n ...(regionSnapshots.length > 0 ? { regions: regionSnapshots } : {}),\n ...(metadataSnapshots.length > 0 ? { metadata: metadataSnapshots } : {}),\n };\n}\n\nexport function serializeProjectionDomLayerRegion(\n root: Element,\n target: Element,\n observedFiles: ProjectionObservedFileMap = {},\n): ProjectionLayerRegionSnapshot {\n return {\n targetFiberId: layerIdForTarget(root, target, dataDomLayerIdentity),\n tree:\n target === root\n ? serializeDomLayerRootNode(root, dataDomLayerIdentity)\n : serializeDomLayerNode(root, target, dataDomLayerIdentity),\n observedFiles,\n };\n}\n\nexport function captureProjectionDomLayerMetadata(\n element: Element,\n): ProjectionLayerMetadataSnapshot | null {\n const domId = element.getAttribute(DOM_ID_ATTR);\n if (!domId) return null;\n return {\n targetFiberId: projectionDomLayerId(domId),\n props: captureProjectionDomLayerProps(element),\n };\n}\n\nfunction serializeDomLayerRootNode(\n root: Element,\n identity: DomLayerIdentity,\n): ProjectionLayerNode {\n const name = root.tagName.toLowerCase();\n return {\n kind: \"fragment\",\n name,\n domId: null,\n elementTag: null,\n source: {\n kind: \"react-fiber\",\n fiber: {\n tag: FiberTag.HostRoot,\n name,\n id: DOM_LAYER_ROOT_ID,\n },\n },\n children: Array.from(root.children).map((child) =>\n serializeDomLayerNode(root, child, identity),\n ),\n };\n}\n\nfunction serializeDomLayerNode(\n root: Element,\n element: Element,\n identity: DomLayerIdentity,\n): ProjectionLayerNode {\n const domId = identity.bindableDomIdForElement(root, element);\n const name = element.tagName.toLowerCase();\n return {\n kind: \"host\",\n name,\n domId,\n elementTag: name,\n props: captureProjectionDomLayerProps(element),\n source: {\n kind: \"react-fiber\",\n fiber: {\n tag: FiberTag.HostComponent,\n name,\n id: identity.layerIdForElement(root, element),\n },\n },\n children: Array.from(element.children).map((child) =>\n serializeDomLayerNode(root, child, identity),\n ),\n };\n}\n\nfunction layerIdForTarget(\n root: Element,\n target: Element,\n identity: DomLayerIdentity,\n): string {\n if (target === root) return DOM_LAYER_ROOT_ID;\n return identity.layerIdForElement(root, target);\n}\n\nexport function projectionDomLayerId(domId: string): string {\n return `${DOM_LAYER_FIBER_PREFIX}${domId}`;\n}\n\nfunction domLayerIdForElement(root: Element, element: Element): string {\n const domId = ensureProjectionDomId(element);\n if (domId) return projectionDomLayerId(domId);\n const path: number[] = [];\n let current: Element | null = element;\n while (current && current !== root) {\n const parent: Element | null = current.parentElement;\n if (!parent) break;\n path.push(Array.from(parent.children).indexOf(current));\n current = parent;\n }\n return `${DOM_LAYER_FIBER_PREFIX}path:${path.reverse().join(\".\")}`;\n}\n\nexport function captureProjectionDomLayerProps(\n element: Element,\n): ProjectionLayerProps | undefined {\n const props: Record<string, unknown> = {};\n const className = element.getAttribute(\"class\");\n if (className) props.className = className;\n const style = parseInlineStyle(element.getAttribute(\"style\"));\n if (style) props.style = style;\n\n for (const name of SOURCE_ANNOTATION_ATTRIBUTES) {\n const value = element.getAttribute(name);\n if (value === null) continue;\n if (name === \"data-tempo-position\" || name === \"data-tempo-modifiedts\") {\n const numeric = Number(value);\n if (Number.isFinite(numeric)) props[name] = numeric;\n } else {\n props[name] = value;\n }\n }\n for (const name of [\n \"data-tempo-supports-style\",\n \"data-tempo-supports-classname\",\n \"data-tempo-supports-children\",\n ]) {\n const value = element.getAttribute(name);\n if (value === \"true\" || value === \"false\") props[name] = value === \"true\";\n }\n return Object.keys(props).length > 0\n ? (props as unknown as ProjectionLayerProps)\n : undefined;\n}\n\nfunction parseInlineStyle(\n value: string | null,\n): Readonly<Record<string, string>> | undefined {\n if (!value) return undefined;\n const style: Record<string, string> = {};\n for (const declaration of value.split(\";\")) {\n const separator = declaration.indexOf(\":\");\n if (separator < 0) continue;\n const property = declaration.slice(0, separator).trim();\n const propertyValue = declaration.slice(separator + 1).trim();\n if (property && propertyValue) style[property] = propertyValue;\n }\n return Object.keys(style).length > 0 ? style : undefined;\n}\n","/**\n * Convert an `EnrichedFiberNode` (live capture from the combined watcher)\n * into a `SerializedFiber`-shaped tree that downstream JSX reconstruction\n * tooling (e.g. `@modules/codebase-editor`'s `reconstructJsxFromFiber`)\n * consumes.\n *\n * The combined watcher's default `sanitizeValue` already runs on the source\n * iframe and loses some type information by replacing non-JSON values with\n * marker strings (`\"[Function]\"`, `\"[Element:div]\"`, `\"[ReactElement]\"`,\n * etc.). This converter detects those markers on the parent side and\n * re-encodes them as `{ __type: \"unsupported\", reason }` so the\n * reconstructor can flag them as blockers instead of emitting them as bogus\n * string literals.\n *\n * The output shape is structurally compatible with\n * `@modules/codebase-editor`'s `SerializedFiber` — no direct dependency to\n * keep the module standalone.\n */\nimport { FiberTag, type FiberTagValue } from \"../fiber/react-types\";\nimport { cssEscape } from \"./css-escape\";\nimport type { EnrichedFiberNode } from \"./types\";\n\n// ── Structural mirror of @modules/codebase-editor's SerializedFiber ───\n// Kept type-compatible (string union for tag, __type marker for unsupported\n// values) so callers can pass the result directly to `reconstructJsxFromFiber`\n// without conversion. Duplication is the explicit cost of keeping\n// iframe-projection free of codebase-editor as a dependency.\n\nexport type DetachJsonPrimitive = string | number | boolean | null;\nexport type DetachJsonValue =\n | DetachJsonPrimitive\n | DetachJsonValue[]\n | { [key: string]: DetachJsonValue };\n\nexport type DetachReactElementReference = {\n __type: \"react-element\";\n fiber_id: string;\n};\n\nexport type DetachUnsupportedValue = {\n __type: \"unsupported\";\n reason: string;\n /** Structured kind of the unserializable value, when known. `\"function\"`\n * marks event handlers/callbacks — behavior-only props that fiber\n * reconstruction stubs with a no-op instead of refusing the transfer\n * (mirrors `codebase-editor`'s `UnsupportedSerializableValue.value_type`). */\n value_type?: \"function\";\n};\n\nexport type DetachSerializableValue =\n | DetachJsonValue\n | DetachReactElementReference\n | DetachUnsupportedValue\n | DetachSerializableValue[]\n | { [key: string]: DetachSerializableValue };\n\nexport type DetachFiberTag =\n | \"host\"\n | \"function\"\n | \"class\"\n | \"text\"\n | \"fragment\"\n | \"portal\"\n | \"memo\"\n | \"forward-ref\";\n\nexport interface DetachSerializedFiber {\n fiber_id: string;\n name: string;\n tag: DetachFiberTag | string;\n owner_fiber_id: string | null;\n key?: string | null;\n has_context_dependencies?: boolean;\n props: Record<string, DetachSerializableValue>;\n children: DetachSerializedFiber[];\n source?: {\n file: string;\n position: number;\n };\n}\n\nexport interface EnrichedNodeToSerializedFiberOptions {\n /** When set, every fiber that carries `data-tempo-filepath` +\n * `data-tempo-position` annotations gets its `source` field populated.\n * This is what enables detach-one-level: the orchestrator walks the\n * output tree, follows each descendant component's `source.file` to\n * parse that file's imports, and resolves cross-file identifier\n * references in the rendered subtree (e.g. `<Pill />` inside a\n * `<Wrapper />` whose `Pill` import lives in Wrapper.tsx, not the\n * call-site App.tsx). Without this, descendant components inline as\n * their host JSX instead of staying as JSX tags. */\n preserveSourceAnnotations?: boolean;\n /** Optional iframe document — used to recover text-node children of host\n * elements that the upstream fiber capture filtered out. The combined\n * watcher's default `fiberTags` filter drops HostText so the layer tree\n * stays manageable; for detach we still need text content, so we\n * walk the host element's DOM children and synthesize text fibers from\n * every direct `Text` node. Without this, `<div>Hello</div>` reconstructs\n * as `<div />` and the text disappears. */\n iframeDocument?: Document | null;\n}\n\nexport function enrichedNodeToSerializedFiber(\n node: EnrichedFiberNode,\n options: EnrichedNodeToSerializedFiberOptions = {},\n): DetachSerializedFiber {\n return convertNode(node, null, options);\n}\n\nfunction convertNode(\n node: EnrichedFiberNode,\n ownerFiberId: string | null,\n options: EnrichedNodeToSerializedFiberOptions,\n): DetachSerializedFiber {\n const tag = detachTagFromFiberTag(node.tag);\n const name = node.name;\n const ownerId = node.fiberId;\n\n const props = node.props ? detachPropsFromSanitized(node.props) : {};\n\n const children: DetachSerializedFiber[] = node.children.map((child) =>\n convertNode(child, ownerId, options),\n );\n\n // Recover host-text leaves that the combined watcher's `fiberTags` filter\n // drops. The fiber tree only reports HostComponent/FunctionComponent/...,\n // so a `<div>Hello</div>` arrives as a host fiber with `children: []`.\n // Walk the live DOM under the host's `domId` and synthesize a Text-tagged\n // child fiber for each direct Text node — the reconstructor renders these\n // as escaped JSX text content.\n if (\n tag === \"host\" &&\n children.length === 0 &&\n node.domId &&\n options.iframeDocument\n ) {\n const element = options.iframeDocument.querySelector(\n `[data-dom-id=\"${cssEscape(node.domId)}\"]`,\n );\n if (element) {\n let textIndex = 0;\n for (const childNode of Array.from(element.childNodes)) {\n if (childNode.nodeType === 3 /* Text */) {\n const text = childNode.textContent ?? \"\";\n if (text.length === 0) continue;\n children.push({\n fiber_id: `${node.fiberId}:text-${textIndex++}`,\n name: \"#text\",\n tag: \"text\",\n owner_fiber_id: ownerId,\n props: { text },\n children: [],\n });\n }\n }\n }\n }\n\n const result: DetachSerializedFiber = {\n fiber_id: node.fiberId,\n name,\n tag,\n owner_fiber_id: ownerFiberId,\n props,\n children,\n };\n if (node.hasContextDependencies) {\n result.has_context_dependencies = true;\n }\n\n if (options.preserveSourceAnnotations) {\n const source = detachSourceFromProps(node.props);\n if (source) result.source = source;\n }\n\n return result;\n}\n\nexport function detachTagFromFiberTag(\n tag: FiberTagValue,\n): DetachFiberTag | string {\n switch (tag) {\n case FiberTag.HostComponent:\n return \"host\";\n case FiberTag.HostText:\n return \"text\";\n case FiberTag.FunctionComponent:\n case FiberTag.IndeterminateComponent:\n return \"function\";\n case FiberTag.ClassComponent:\n return \"class\";\n case FiberTag.Fragment:\n return \"fragment\";\n case FiberTag.HostPortal:\n return \"portal\";\n case FiberTag.MemoComponent:\n case FiberTag.SimpleMemoComponent:\n return \"memo\";\n case FiberTag.ForwardRef:\n return \"forward-ref\";\n default:\n return String(tag);\n }\n}\n\nconst SANITIZED_MARKER_PATTERNS: {\n match: RegExp;\n reason: (raw: string) => string;\n value_type?: DetachUnsupportedValue[\"value_type\"];\n}[] = [\n {\n match: /^\\[Function\\]$/,\n reason: () => \"Functions cannot be serialized to JSX\",\n value_type: \"function\",\n },\n {\n match: /^\\[Symbol:.*\\]$/,\n reason: (raw) => `Symbols cannot be serialized to JSX: ${raw}`,\n },\n {\n match: /^\\[Element:.*\\]$/,\n reason: (raw) => `DOM elements cannot be serialized to JSX: ${raw}`,\n },\n {\n match: /^\\[Node:.*\\]$/,\n reason: (raw) => `DOM nodes cannot be serialized to JSX: ${raw}`,\n },\n {\n match: /^\\[Object\\]$/,\n reason: () => \"Object could not be JSON-serialized\",\n },\n {\n match: /^\\[Array\\(\\d+\\)\\]$/,\n reason: (raw) => `Large array cannot be serialized: ${raw}`,\n },\n {\n match: /^\\[ReactElement\\]$/,\n reason: () => \"Inline React elements in props cannot be reconstructed\",\n },\n];\n\nfunction classifyMaybeMarker(raw: string): DetachUnsupportedValue | null {\n for (const { match, reason, value_type } of SANITIZED_MARKER_PATTERNS) {\n if (match.test(raw)) {\n const marker: DetachUnsupportedValue = {\n __type: \"unsupported\",\n reason: reason(raw),\n };\n if (value_type) marker.value_type = value_type;\n return marker;\n }\n }\n return null;\n}\n\nconst TEMPO_DATA_PROP_PREFIX = \"data-tempo-\";\n\nexport function detachPropsFromSanitized(\n source: Record<string, unknown>,\n): Record<string, DetachSerializableValue> {\n const out: Record<string, DetachSerializableValue> = {};\n for (const [key, value] of Object.entries(source)) {\n if (key === \"children\") continue;\n // `data-tempo-*` props are Tempo's source-annotation channel and aren't\n // part of the user's authored JSX; stripping them keeps detached output\n // clean (the canvas will re-stamp them on the next HMR cycle).\n if (key.startsWith(TEMPO_DATA_PROP_PREFIX)) continue;\n out[key] = convertValue(value);\n }\n return out;\n}\n\nfunction convertValue(value: unknown): DetachSerializableValue {\n if (value === null || value === undefined) return null;\n if (typeof value === \"string\") {\n const marker = classifyMaybeMarker(value);\n if (marker) return marker;\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") return value;\n\n if (Array.isArray(value)) {\n return value.map((entry) => convertValue(entry));\n }\n\n if (typeof value === \"object\") {\n const out: Record<string, DetachSerializableValue> = {};\n for (const [key, entry] of Object.entries(\n value as Record<string, unknown>,\n )) {\n out[key] = convertValue(entry);\n }\n return out;\n }\n\n // Functions, symbols, etc. shouldn't survive sanitizeValue on the source\n // side, but guard defensively so the converter never produces a non-JSON\n // primitive type.\n return {\n __type: \"unsupported\",\n reason: `Unsupported runtime type: ${typeof value}`,\n };\n}\n\nexport function detachSourceFromProps(\n props: Record<string, unknown> | undefined,\n): { file: string; position: number } | null {\n if (!props) return null;\n const file = props[\"data-tempo-filepath\"];\n const position = props[\"data-tempo-position\"];\n if (typeof file !== \"string\" || file.length === 0) return null;\n const pos = typeof position === \"number\" ? position : Number(position);\n if (!Number.isFinite(pos)) return null;\n return { file, position: pos };\n}\n","/**\n * Cold, operation-scoped React semantic capture.\n *\n * The hot projection stream intentionally carries only destination-ready\n * layer facts. Copy, duplicate, drag, and detach occasionally need runtime\n * props for one selected branch. This serializer performs that richer walk\n * only when one of those operations explicitly asks for it, and returns only\n * the selected Fiber subtree rather than retaining or transporting a full\n * document Fiber tree.\n */\n\nimport type { Fiber, FiberProps } from \"../fiber/react-types\";\nimport { FiberTag } from \"../fiber/react-types\";\nimport { getDisplayName, getProps, sanitizeProps } from \"../fiber/serialize\";\nimport {\n detachPropsFromSanitized,\n detachSourceFromProps,\n detachTagFromFiberTag,\n type DetachSerializedFiber,\n} from \"./enriched-to-serialized-fiber\";\nimport { isProjectionLayerFiber } from \"./projection-layer-snapshot\";\n\nexport interface ProjectionSemanticFiberIdentity {\n /** Return the already-published identity without allocating a new one. */\n knownFiberId(fiber: Fiber): string | null;\n /** Allocate/recover the stable identity for a node inside the result. */\n fiberId(fiber: Fiber): string;\n}\n\n/** Structural guard used at transport boundaries. Runtime prop values are\n * already structured-cloned by the bridge, so the protocol only needs to pin\n * the closed tree envelope here. */\nexport function isProjectionSemanticSubtree(\n value: unknown,\n): value is DetachSerializedFiber {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const node = value as Record<string, unknown>;\n if (\n typeof node.fiber_id !== \"string\" ||\n typeof node.name !== \"string\" ||\n typeof node.tag !== \"string\" ||\n (node.owner_fiber_id !== null && typeof node.owner_fiber_id !== \"string\") ||\n !node.props ||\n typeof node.props !== \"object\" ||\n Array.isArray(node.props) ||\n !Array.isArray(node.children)\n ) {\n return false;\n }\n if (\n node.source !== undefined &&\n (!node.source ||\n typeof node.source !== \"object\" ||\n Array.isArray(node.source) ||\n typeof (node.source as Record<string, unknown>).file !== \"string\" ||\n typeof (node.source as Record<string, unknown>).position !== \"number\")\n ) {\n return false;\n }\n return node.children.every(isProjectionSemanticSubtree);\n}\n\n/**\n * Resolve one currently committed, previously published semantic node and\n * serialize only that node and its rendered descendants.\n */\nexport function captureProjectionSemanticSubtree(\n committedRoot: Fiber,\n targetFiberId: string,\n identity: ProjectionSemanticFiberIdentity,\n): DetachSerializedFiber | null {\n const target = findCurrentFiberByPublishedId(\n committedRoot,\n targetFiberId,\n identity.knownFiberId,\n );\n if (!target || !isProjectionLayerFiber(target)) return null;\n return serializeIncludedFiber(target, null, identity);\n}\n\nfunction findCurrentFiberByPublishedId(\n root: Fiber,\n targetFiberId: string,\n knownFiberId: (fiber: Fiber) => string | null,\n): Fiber | null {\n if (knownFiberId(root) === targetFiberId) return root;\n for (let child = root.child; child; child = child.sibling) {\n const found = findCurrentFiberByPublishedId(\n child,\n targetFiberId,\n knownFiberId,\n );\n if (found) return found;\n }\n return null;\n}\n\nfunction serializeIncludedFiber(\n fiber: Fiber,\n ownerFiberId: string | null,\n identity: ProjectionSemanticFiberIdentity,\n): DetachSerializedFiber {\n const fiberId = identity.fiberId(fiber);\n const normalizedProps = normalizeTempoDataSet(getProps(fiber));\n const sanitized = sanitizeProps(normalizedProps) ?? {};\n const children = serializeChildren(fiber, fiberId, identity);\n // React omits a HostText Fiber for the common single-primitive-child fast\n // path (`<button>Save</button>`). `sanitizeProps` correctly removes the\n // structural `children` prop, so preserve that authored output as the same\n // synthetic text leaf the old DOM-assisted detach capture produced. This\n // stays local to the selected host node and avoids a document/tree query.\n if (fiber.tag === FiberTag.HostComponent && children.length === 0) {\n const text = directPrimitiveChild(normalizedProps?.children);\n if (text !== null) {\n children.push({\n fiber_id: `${fiberId}:text-0`,\n name: \"#text\",\n tag: \"text\",\n owner_fiber_id: fiberId,\n props: { text },\n children: [],\n });\n }\n }\n const result: DetachSerializedFiber = {\n fiber_id: fiberId,\n name: getDisplayName(fiber),\n tag: detachTagFromFiberTag(fiber.tag),\n owner_fiber_id: ownerFiberId,\n props:\n fiber.tag === FiberTag.HostText\n ? { text: readHostText(fiber) }\n : detachPropsFromSanitized(sanitized),\n children,\n };\n if (fiber.key !== null) result.key = fiber.key;\n if (hasContextDependencies(fiber)) {\n result.has_context_dependencies = true;\n }\n const source = detachSourceFromProps(normalizedProps ?? undefined);\n if (source) result.source = source;\n return result;\n}\n\nfunction directPrimitiveChild(value: unknown): string | null {\n if (typeof value === \"string\") return value.length > 0 ? value : null;\n return typeof value === \"number\" ? String(value) : null;\n}\n\nfunction serializeChildren(\n parent: Fiber,\n ownerFiberId: string,\n identity: ProjectionSemanticFiberIdentity,\n): DetachSerializedFiber[] {\n const children: DetachSerializedFiber[] = [];\n for (let child = parent.child; child; child = child.sibling) {\n children.push(...serializeBranch(child, ownerFiberId, identity));\n }\n return children;\n}\n\n/**\n * Mirror the layer stream's include filter: non-layer React wrappers are\n * transparent and promote their descendants. HostText is the one deliberate\n * addition because edit operations need authored text even though the layer\n * panel does not model text as a standalone layer.\n */\nfunction serializeBranch(\n fiber: Fiber,\n ownerFiberId: string,\n identity: ProjectionSemanticFiberIdentity,\n): DetachSerializedFiber[] {\n if (isProjectionLayerFiber(fiber) || fiber.tag === FiberTag.HostText) {\n return [serializeIncludedFiber(fiber, ownerFiberId, identity)];\n }\n\n const promoted: DetachSerializedFiber[] = [];\n for (let child = fiber.child; child; child = child.sibling) {\n promoted.push(...serializeBranch(child, ownerFiberId, identity));\n }\n return promoted;\n}\n\nfunction readHostText(fiber: Fiber): string {\n if (typeof fiber.memoizedProps === \"string\") return fiber.memoizedProps;\n return fiber.stateNode instanceof Text ? fiber.stateNode.textContent : \"\";\n}\n\nfunction hasContextDependencies(fiber: Fiber): boolean {\n const dependencies = fiber.dependencies;\n return Boolean(\n dependencies &&\n typeof dependencies === \"object\" &&\n (dependencies as { firstContext?: unknown }).firstContext,\n );\n}\n\n/** Lift react-native-web's dataSet annotation carrier into the same flat keys\n * used by DOM and ordinary React fibers before source extraction. */\nfunction normalizeTempoDataSet(props: FiberProps | null): FiberProps | null {\n const dataSet = props?.dataSet;\n if (!props || !dataSet || typeof dataSet !== \"object\") return props;\n\n let extracted: Record<string, unknown> | null = null;\n let remaining: Record<string, unknown> | null = null;\n for (const [key, value] of Object.entries(\n dataSet as Record<string, unknown>,\n )) {\n if (key.startsWith(\"tempo\")) {\n (extracted ??= {})[\n `data-${key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}`\n ] = value;\n } else {\n (remaining ??= {})[key] = value;\n }\n }\n if (!extracted) return props;\n\n const normalized = { ...props, ...extracted };\n if (remaining) normalized.dataSet = remaining;\n else delete normalized.dataSet;\n return normalized;\n}\n","/**\n * Narrow reader for Svelte 5's development-only element metadata.\n *\n * Keep every access to `__svelte_meta` in this file. It is an intentionally\n * isolated compatibility boundary: callers receive validated records and do\n * not depend on Svelte runtime object shapes directly.\n */\n\nexport const TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE =\n \"data-tempo-svelte-source-registry\";\n\nexport interface SvelteDevStackEntry {\n readonly type: string;\n readonly file: string;\n readonly line: number;\n readonly column: number;\n readonly componentTag?: string;\n readonly parent: SvelteDevStackEntry | null;\n}\n\nexport interface SvelteElementMetadata {\n readonly loc: {\n readonly file: string;\n readonly line: number;\n readonly column: number;\n };\n readonly parent: SvelteDevStackEntry | null;\n}\n\nexport interface SvelteComponentSourceRecord {\n readonly kind: \"component\";\n readonly name: string;\n readonly line: number;\n readonly column: number;\n readonly position: number;\n readonly className?: string;\n readonly style?: string;\n readonly supportsClassName: boolean;\n readonly supportsStyle: boolean;\n}\n\nexport interface SvelteHostSourceRecord {\n readonly kind: \"host\";\n readonly name: string;\n readonly line: number;\n readonly column: number;\n readonly position: number;\n readonly className?: string;\n readonly style?: string;\n readonly supportsClassName: boolean;\n readonly supportsStyle: boolean;\n}\n\nexport interface SvelteSourceRegistryRecord {\n readonly filename: string;\n readonly filepath: string;\n readonly modifiedTs: number;\n readonly sourceVersion: string;\n readonly components: readonly SvelteComponentSourceRecord[];\n readonly hosts: readonly SvelteHostSourceRecord[];\n}\n\nexport interface SvelteSourceRegistry {\n resolveComponent(\n entry: SvelteDevStackEntry,\n ): { source: SvelteSourceRegistryRecord; component: SvelteComponentSourceRecord } | null;\n resolveHost(\n metadata: SvelteElementMetadata,\n ): { source: SvelteSourceRegistryRecord; host: SvelteHostSourceRecord } | null;\n}\n\nexport type SvelteRuntimeMetadataValidation =\n | { readonly kind: \"supported\" }\n | { readonly kind: \"unavailable\"; readonly message: string };\n\nexport function validateSvelteRuntimeMetadata(\n root: Element,\n): SvelteRuntimeMetadataValidation {\n if (\n !root.querySelector(\n `template[${TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE}]`,\n )\n ) {\n return {\n kind: \"unavailable\",\n message:\n \"Svelte Canvas layers require a supported Svelte 5 development build with Tempo's Svelte preprocessor enabled. No source registry was found in the rendered root; confirm apps[0].uiFramework is set to svelte and the app is not serving a production/minified build.\",\n };\n }\n const renderedElements = [root, ...Array.from(root.querySelectorAll<Element>(\"*\"))]\n .filter(\n (element) =>\n !element.hasAttribute(TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE),\n );\n const authoredHosts = renderedElements.filter(\n (element) =>\n element.hasAttribute(\"data-tempo-filepath\") &&\n element.hasAttribute(\"data-tempo-position\"),\n );\n for (const host of authoredHosts) {\n if (readSvelteElementMetadata(host) === null) {\n return {\n kind: \"unavailable\",\n message:\n \"Svelte Canvas layers require a supported Svelte 5 development build with runtime source metadata. Confirm the app uses Tempo's Svelte preprocessor before its other preprocessors and is not serving a production/minified build.\",\n };\n }\n }\n if (\n renderedElements.length > 1 &&\n renderedElements.every(\n (element) => readSvelteElementMetadata(element) === null,\n )\n ) {\n return {\n kind: \"unavailable\",\n message:\n \"Svelte Canvas layers require a supported Svelte 5 development build with runtime source metadata. The rendered root contains source registry data but no Svelte element metadata; confirm the app is not serving a production/minified build.\",\n };\n }\n return { kind: \"supported\" };\n}\n\nexport function readSvelteElementMetadata(\n element: Element,\n): SvelteElementMetadata | null {\n const value = (element as Element & { __svelte_meta?: unknown })\n .__svelte_meta;\n if (!isRecord(value) || !isLocation(value.loc)) return null;\n const parent = readStackEntry(value.parent, new Set());\n if (value.parent != null && parent === null) return null;\n return { loc: value.loc, parent };\n}\n\nexport function readSvelteComponentChain(\n element: Element,\n): readonly SvelteDevStackEntry[] {\n const metadata = readSvelteElementMetadata(element);\n const chain: SvelteDevStackEntry[] = [];\n for (let entry = metadata?.parent ?? null; entry; entry = entry.parent) {\n if (entry.type === \"component\") chain.push(entry);\n }\n chain.reverse();\n return chain;\n}\n\nexport function collectSvelteSourceRegistry(root: Element): SvelteSourceRegistry {\n const records: SvelteSourceRegistryRecord[] = [];\n for (const element of root.querySelectorAll(\n `template[${TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE}]`,\n )) {\n const raw = element.getAttribute(TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE);\n if (!raw) continue;\n const parsed = parseRegistryRecord(raw);\n if (parsed) records.push(parsed);\n }\n\n return {\n resolveComponent(entry) {\n const file = normalizeFile(entry.file);\n for (let index = records.length - 1; index >= 0; index -= 1) {\n const source = records[index]!;\n if (!sameRuntimeFile(file, normalizeFile(source.filename))) continue;\n const component = source.components.find(\n (candidate) =>\n candidate.line === entry.line &&\n candidate.column === entry.column &&\n (entry.componentTag === undefined ||\n candidate.name === entry.componentTag),\n );\n if (component) return { source, component };\n }\n return null;\n },\n resolveHost(metadata) {\n const file = normalizeFile(metadata.loc.file);\n for (let index = records.length - 1; index >= 0; index -= 1) {\n const source = records[index]!;\n if (!sameRuntimeFile(file, normalizeFile(source.filename))) continue;\n const host = source.hosts.find(\n (candidate) =>\n candidate.line === metadata.loc.line &&\n candidate.column === metadata.loc.column,\n );\n if (host) return { source, host };\n }\n return null;\n },\n };\n}\n\nfunction parseRegistryRecord(value: string): SvelteSourceRegistryRecord | null {\n try {\n const parsed: unknown = JSON.parse(value);\n if (\n !isRecord(parsed) ||\n typeof parsed.filename !== \"string\" ||\n typeof parsed.filepath !== \"string\" ||\n !isNonNegativeInteger(parsed.modifiedTs) ||\n typeof parsed.sourceVersion !== \"string\" ||\n parsed.sourceVersion.length === 0 ||\n !Array.isArray(parsed.components) ||\n !Array.isArray(parsed.hosts)\n ) {\n return null;\n }\n const components = parsed.components\n .map(parseComponentRecord)\n .filter(\n (record): record is SvelteComponentSourceRecord => record !== null,\n );\n const hosts = parsed.hosts\n .map(parseHostRecord)\n .filter((record): record is SvelteHostSourceRecord => record !== null);\n return {\n filename: parsed.filename,\n filepath: parsed.filepath,\n modifiedTs: parsed.modifiedTs,\n sourceVersion: parsed.sourceVersion,\n components,\n hosts,\n };\n } catch {\n return null;\n }\n}\n\nfunction parseHostRecord(value: unknown): SvelteHostSourceRecord | null {\n const common = parseSourceTargetRecord(value, \"host\");\n return common ? { kind: \"host\", ...common } : null;\n}\n\nfunction parseComponentRecord(value: unknown): SvelteComponentSourceRecord | null {\n const common = parseSourceTargetRecord(value, \"component\");\n return common ? { kind: \"component\", ...common } : null;\n}\n\nfunction parseSourceTargetRecord(\n value: unknown,\n kind: \"component\" | \"host\",\n): Omit<SvelteComponentSourceRecord, \"kind\"> | null {\n if (\n !isRecord(value) ||\n value.kind !== kind ||\n typeof value.name !== \"string\" ||\n !isPositiveInteger(value.line) ||\n !isNonNegativeInteger(value.column) ||\n !isNonNegativeInteger(value.position) ||\n typeof value.supportsClassName !== \"boolean\" ||\n typeof value.supportsStyle !== \"boolean\"\n ) {\n return null;\n }\n return {\n name: value.name,\n line: value.line,\n column: value.column,\n position: value.position,\n ...(typeof value.className === \"string\"\n ? { className: value.className }\n : {}),\n ...(typeof value.style === \"string\" ? { style: value.style } : {}),\n supportsClassName: value.supportsClassName,\n supportsStyle: value.supportsStyle,\n };\n}\n\nfunction readStackEntry(\n value: unknown,\n seen: Set<object>,\n depth = 0,\n): SvelteDevStackEntry | null {\n if (!isRecord(value)) return value == null ? null : null;\n if (seen.has(value) || depth >= 512) return null;\n seen.add(value);\n if (\n typeof value.type !== \"string\" ||\n typeof value.file !== \"string\" ||\n !isPositiveInteger(value.line) ||\n !isNonNegativeInteger(value.column) ||\n (value.componentTag !== undefined && typeof value.componentTag !== \"string\")\n ) {\n return null;\n }\n const parent = readStackEntry(value.parent, seen, depth + 1);\n if (value.parent != null && parent === null) return null;\n // Preserve the runtime object's identity. Descendant host elements from one\n // component invocation share this exact stack entry, which is how the layer\n // serializer interns a multi-root component once instead of duplicating it.\n return value as unknown as SvelteDevStackEntry;\n}\n\nfunction normalizeFile(value: string): string {\n return value.replace(/^file:\\/\\//, \"\").replace(/\\\\/g, \"/\");\n}\n\nfunction sameRuntimeFile(left: string, right: string): boolean {\n return left === right || left.endsWith(`/${right}`) || right.endsWith(`/${left}`);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isLocation(value: unknown): value is SvelteElementMetadata[\"loc\"] {\n return (\n isRecord(value) &&\n typeof value.file === \"string\" &&\n isPositiveInteger(value.line) &&\n isNonNegativeInteger(value.column)\n );\n}\n\nfunction isNonNegativeInteger(value: unknown): value is number {\n return Number.isInteger(value) && (value as number) >= 0;\n}\n\nfunction isPositiveInteger(value: unknown): value is number {\n return Number.isInteger(value) && (value as number) > 0;\n}\n","import { FiberTag } from \"../fiber/react-types\";\nimport { ensureProjectionDomId } from \"../html/watch-dom\";\nimport {\n captureProjectionDomLayerProps,\n type ProjectionDomLayerSerializer,\n type ProjectionDomLayerTargets,\n} from \"./projection-dom-layers\";\nimport type {\n ProjectionLayerNode,\n ProjectionLayerProps,\n ProjectionLayerRootSnapshot,\n} from \"./projection-layer-snapshot\";\nimport {\n collectSvelteSourceRegistry,\n readSvelteComponentChain,\n readSvelteElementMetadata,\n TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE,\n type SvelteComponentSourceRecord,\n type SvelteDevStackEntry,\n type SvelteHostSourceRecord,\n type SvelteSourceRegistryRecord,\n} from \"./projection-svelte-metadata\";\nimport {\n ProjectionObservedFileAccumulator,\n type ProjectionObservedFileMap,\n} from \"./projection-observed-files\";\nimport type { ProjectionLayerPatch } from \"./projection-root-accumulator\";\n\nexport const SVELTE_LAYER_ROOT_ID = \"svelte:$projection-root\";\n\ninterface ResolvedComponent {\n readonly runtime: SvelteDevStackEntry;\n readonly source: SvelteSourceRegistryRecord;\n readonly component: SvelteComponentSourceRecord;\n}\n\ninterface ResolvedHost {\n readonly source: SvelteSourceRegistryRecord;\n readonly host: SvelteHostSourceRecord;\n}\n\n/**\n * Svelte's adapter deliberately implements the DOM serializer contract: DOM\n * mutations remain the observation authority, while Svelte's development\n * parent stack supplies the component nodes missing from DOM ancestry.\n */\nexport function createProjectionSvelteLayerSerializer(): ProjectionDomLayerSerializer {\n let nextHostId = 1;\n let nextComponentId = 1;\n const hostIds = new WeakMap<Element, string>();\n const componentIds = new WeakMap<object, string>();\n\n const hostId = (element: Element): string => {\n const existing = hostIds.get(element);\n if (existing) return existing;\n const id = `svelte:host:${nextHostId++}`;\n hostIds.set(element, id);\n return id;\n };\n const componentId = (entry: SvelteDevStackEntry): string => {\n const key = entry as object;\n const existing = componentIds.get(key);\n if (existing) return existing;\n const id = `svelte:component:${nextComponentId++}`;\n componentIds.set(key, id);\n return id;\n };\n\n const createSession = (\n root: Element,\n observedFiles: ProjectionObservedFileMap,\n ) => {\n const registry = collectSvelteSourceRegistry(root);\n const observed = new ProjectionObservedFileAccumulator();\n observed.merge(observedFiles);\n const resolveChain = (element: Element): readonly ResolvedComponent[] =>\n readSvelteComponentChain(element).flatMap((runtime) => {\n const resolved = registry.resolveComponent(runtime);\n if (resolved) {\n observed.add(\n resolved.source.filepath,\n resolved.source.modifiedTs,\n resolved.source.sourceVersion,\n );\n }\n return resolved ? [{ runtime, ...resolved }] : [];\n });\n const resolveHost = (element: Element): ResolvedHost | null => {\n const metadata = readSvelteElementMetadata(element);\n if (!metadata) return null;\n const resolved = registry.resolveHost(metadata);\n if (resolved) {\n observed.add(\n resolved.source.filepath,\n resolved.source.modifiedTs,\n resolved.source.sourceVersion,\n );\n }\n return resolved;\n };\n const isSourceHost = (element: Element): boolean =>\n isAnnotatedSvelteSourceHost(element) || resolveHost(element) !== null;\n const occurrencePlan = planStableOccurrenceIds(\n root,\n resolveChain,\n resolveHost,\n isSourceHost,\n );\n const occurrenceHostId = (element: Element): string => {\n const stable = occurrencePlan.hostIds.get(element);\n if (stable) {\n hostIds.set(element, stable);\n return stable;\n }\n return hostId(element);\n };\n const occurrenceComponentId = (entry: SvelteDevStackEntry): string => {\n const stable = occurrencePlan.componentIds.get(entry as object);\n if (stable) {\n componentIds.set(entry as object, stable);\n return stable;\n }\n return componentId(entry);\n };\n\n const serializeElementList = (\n elements: readonly Element[],\n activeChain: readonly ResolvedComponent[],\n ): ProjectionLayerNode[] => {\n const nodes: ProjectionLayerNode[] = [];\n let index = 0;\n while (index < elements.length) {\n const element = elements[index]!;\n const chain = resolveChain(element);\n const next = firstNewComponent(chain, activeChain);\n if (next) {\n const grouped: Element[] = [];\n while (index < elements.length) {\n const candidate = elements[index]!;\n const candidateNext = firstNewComponent(\n resolveChain(candidate),\n activeChain,\n );\n if (candidateNext?.runtime !== next.runtime) break;\n grouped.push(candidate);\n index += 1;\n }\n nodes.push(\n serializeComponentNode(\n next,\n serializeElementList(grouped, [...activeChain, next]),\n occurrenceComponentId(next.runtime),\n ),\n );\n continue;\n }\n nodes.push(\n serializeHostNode(\n element,\n chain,\n resolveHost(element),\n isSourceHost,\n serializeElementList,\n occurrenceHostId,\n ),\n );\n index += 1;\n }\n return nodes;\n };\n\n const serializeHost = (\n element: Element,\n activeChain: readonly ResolvedComponent[] = resolveChain(element),\n ): ProjectionLayerNode =>\n serializeHostNode(\n element,\n activeChain,\n resolveHost(element),\n isSourceHost,\n serializeElementList,\n occurrenceHostId,\n );\n\n return {\n isSourceHost,\n resolveChain,\n hostId: occurrenceHostId,\n serializeElementList,\n serializeHost,\n captureHostProps(element: Element): ProjectionLayerProps | undefined {\n return captureSvelteHostProps(element, resolveHost(element));\n },\n observedFiles(): ProjectionObservedFileMap {\n return observed.snapshot();\n },\n };\n };\n\n const serialize = (\n root: Element,\n observedFiles: ProjectionObservedFileMap,\n ): ProjectionLayerRootSnapshot => {\n const session = createSession(root, observedFiles);\n return {\n semantic: {\n kind: \"layers\",\n tree: {\n kind: \"fragment\",\n name: \"svelte-root\",\n domId: null,\n elementTag: null,\n source: {\n kind: \"react-fiber\",\n fiber: {\n tag: FiberTag.HostRoot,\n name: \"svelte-root\",\n id: SVELTE_LAYER_ROOT_ID,\n },\n },\n children: session.serializeElementList(\n visibleChildren(root, session.isSourceHost),\n [],\n ),\n },\n },\n observedFiles: session.observedFiles(),\n };\n };\n\n return {\n serializeRoot: serialize,\n capturePatch(\n root: Element,\n targets: ProjectionDomLayerTargets,\n observedFiles: ProjectionObservedFileMap = {},\n ): ProjectionLayerPatch | undefined {\n if (targets.structural.length === 0 && targets.metadata.length === 0) {\n return undefined;\n }\n const session = createSession(root, observedFiles);\n const sourceHost = session.isSourceHost;\n const structuralTargets = new Set(\n targets.structural\n .filter((target) => target === root || root.contains(target))\n .map((target) => nearestPublishedHost(root, target, sourceHost)),\n );\n const coalesced = Array.from(structuralTargets).filter(\n (candidate) =>\n candidate === root ||\n !Array.from(structuralTargets).some(\n (other) => other !== candidate && other.contains(candidate),\n ),\n );\n const regionTrees = coalesced.map((target) => {\n const targetFiberId =\n target === root ? SVELTE_LAYER_ROOT_ID : session.hostId(target);\n if (target === root) {\n const snapshot = serialize(root, observedFiles);\n return {\n targetFiberId,\n tree:\n snapshot.semantic.kind === \"layers\"\n ? snapshot.semantic.tree\n : null,\n };\n }\n return {\n targetFiberId,\n tree: session.serializeHost(target),\n };\n });\n const metadata = targets.metadata.flatMap((target) => {\n if (\n target === root ||\n !root.contains(target) ||\n !sourceHost(target) ||\n coalesced.some(\n (region) => region === root || region.contains(target),\n )\n ) {\n return [];\n }\n const targetFiberId = session.hostId(target);\n return [\n { targetFiberId, props: session.captureHostProps(target) },\n ];\n });\n if (regionTrees.length === 0 && metadata.length === 0) return undefined;\n const patchObservedFiles = session.observedFiles();\n const regions = regionTrees.map((region) => ({\n ...region,\n observedFiles: patchObservedFiles,\n }));\n return {\n ...(regions.length > 0 ? { regions } : {}),\n ...(metadata.length > 0 ? { metadata } : {}),\n };\n },\n };\n}\n\ninterface StableOccurrenceIdPlan {\n readonly hostIds: WeakMap<Element, string>;\n readonly componentIds: WeakMap<object, string>;\n}\n\n/**\n * HMR replaces Svelte runtime objects and often replaces host elements. Source\n * anchors can still preserve the occurrence when its full authored component\n * ancestry is unique. Repeated loop instances deliberately keep ephemeral\n * IDs: retaining one by ordinal could silently move selection to a different\n * item after insertion or removal.\n */\nfunction planStableOccurrenceIds(\n root: Element,\n resolveChain: (element: Element) => readonly ResolvedComponent[],\n resolveHost: (element: Element) => ResolvedHost | null,\n isSourceHost: (element: Element) => boolean,\n): StableOccurrenceIdPlan {\n const hostIds = new WeakMap<Element, string>();\n const componentIds = new WeakMap<object, string>();\n const hostSignatures = new Map<string, Element[]>();\n const componentSignatures = new Map<\n string,\n Array<SvelteDevStackEntry>\n >();\n const seenComponents = new Set<object>();\n\n for (const element of authoredDescendants(root, isSourceHost)) {\n const chain = resolveChain(element);\n const host = resolveHost(element);\n if (host) {\n const signature = sourceOccurrenceSignature(chain, host);\n const matches = hostSignatures.get(signature) ?? [];\n matches.push(element);\n hostSignatures.set(signature, matches);\n }\n for (let index = 0; index < chain.length; index += 1) {\n const resolved = chain[index]!;\n const runtime = resolved.runtime as object;\n if (seenComponents.has(runtime)) continue;\n seenComponents.add(runtime);\n const signature = sourceOccurrenceSignature(\n chain.slice(0, index),\n resolved,\n );\n const matches = componentSignatures.get(signature) ?? [];\n matches.push(resolved.runtime);\n componentSignatures.set(signature, matches);\n }\n }\n\n for (const [signature, matches] of hostSignatures) {\n if (matches.length === 1) {\n hostIds.set(matches[0]!, stableOccurrenceId(\"host\", signature));\n }\n }\n for (const [signature, matches] of componentSignatures) {\n if (matches.length === 1) {\n componentIds.set(\n matches[0] as object,\n stableOccurrenceId(\"component\", signature),\n );\n }\n }\n return { hostIds, componentIds };\n}\n\nfunction authoredDescendants(\n root: Element,\n isSourceHost: (element: Element) => boolean,\n): Element[] {\n return [root, ...Array.from(root.querySelectorAll<Element>(\"*\"))].filter(\n (element) =>\n !element.hasAttribute(TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE) &&\n isSourceHost(element),\n );\n}\n\nfunction sourceOccurrenceSignature(\n chain: readonly ResolvedComponent[],\n target: ResolvedComponent | ResolvedHost,\n): string {\n const anchors = chain.map(\n ({ source, component }) =>\n `${source.filepath}:${component.position}:${component.name}`,\n );\n if (\"component\" in target) {\n anchors.push(\n `${target.source.filepath}:${target.component.position}:${target.component.name}`,\n );\n } else {\n anchors.push(\n `${target.source.filepath}:${target.host.position}:${target.host.name}`,\n );\n }\n return anchors.join(\">\");\n}\n\nfunction stableOccurrenceId(\n kind: \"host\" | \"component\",\n signature: string,\n): string {\n return `svelte:${kind}:source:${encodeURIComponent(signature)}`;\n}\n\nfunction nearestPublishedHost(\n root: Element,\n target: Element,\n isSourceHost: (element: Element) => boolean,\n): Element {\n for (let current: Element | null = target; current; current = current.parentElement) {\n if (current === root) return root;\n if (isSourceHost(current)) return current;\n if (!root.contains(current)) break;\n }\n return root;\n}\n\nfunction serializeHostNode(\n element: Element,\n chain: readonly ResolvedComponent[],\n resolvedHost: ResolvedHost | null,\n isSourceHost: (element: Element) => boolean,\n serializeElementList: (\n elements: readonly Element[],\n activeChain: readonly ResolvedComponent[],\n ) => ProjectionLayerNode[],\n hostId: (element: Element) => string,\n): ProjectionLayerNode {\n const name = element.tagName.toLowerCase();\n const isSemanticLeaf =\n name === \"svg\" || element.hasAttribute(\"contenteditable\");\n return {\n kind: \"host\",\n name,\n domId: ensureProjectionDomId(element),\n elementTag: name,\n props: captureSvelteHostProps(element, resolvedHost),\n source: {\n kind: \"react-fiber\",\n fiber: { tag: FiberTag.HostComponent, name, id: hostId(element) },\n },\n children: isSemanticLeaf\n ? []\n : serializeElementList(visibleChildren(element, isSourceHost), chain),\n };\n}\n\nfunction serializeComponentNode(\n resolved: ResolvedComponent,\n children: readonly ProjectionLayerNode[],\n id: string,\n): ProjectionLayerNode {\n const { source, component } = resolved;\n const props: ProjectionLayerProps = {\n ...(component.className ? { className: component.className } : {}),\n ...(component.style ? { style: parseInlineStyle(component.style) } : {}),\n \"data-tempo-filepath\": source.filepath,\n \"data-tempo-position\": component.position,\n \"data-tempo-modifiedts\": source.modifiedTs,\n \"data-tempo-source-version\": source.sourceVersion,\n };\n return {\n kind: \"component\",\n name: component.name,\n domId: null,\n elementTag: null,\n props,\n source: {\n kind: \"react-fiber\",\n fiber: {\n tag: FiberTag.FunctionComponent,\n name: component.name,\n id,\n },\n },\n children,\n };\n}\n\nfunction visibleChildren(\n parent: Element,\n isSourceHost: (element: Element) => boolean,\n): Element[] {\n const visible: Element[] = [];\n for (const child of Array.from(parent.children)) {\n if (child.hasAttribute(TEMPO_SVELTE_SOURCE_REGISTRY_ATTRIBUTE)) continue;\n if (isSourceHost(child)) visible.push(child);\n else visible.push(...visibleChildren(child, isSourceHost));\n }\n return visible;\n}\n\nfunction isAnnotatedSvelteSourceHost(element: Element): boolean {\n return (\n element.hasAttribute(\"data-tempo-filepath\") &&\n element.hasAttribute(\"data-tempo-position\")\n );\n}\n\nfunction captureSvelteHostProps(\n element: Element,\n resolved: ResolvedHost | null,\n): ProjectionLayerProps | undefined {\n const live = captureProjectionDomLayerProps(element);\n if (!resolved) return live;\n const { source, host } = resolved;\n return {\n ...live,\n ...(host.className && live?.className === undefined\n ? { className: host.className }\n : {}),\n ...(host.style && live?.style === undefined\n ? { style: parseInlineStyle(host.style) }\n : {}),\n \"data-tempo-filepath\": source.filepath,\n \"data-tempo-position\": host.position,\n \"data-tempo-modifiedts\": source.modifiedTs,\n \"data-tempo-source-version\": source.sourceVersion,\n \"data-tempo-supports-classname\": host.supportsClassName,\n \"data-tempo-supports-style\": host.supportsStyle,\n };\n}\n\nfunction firstNewComponent(\n chain: readonly ResolvedComponent[],\n active: readonly ResolvedComponent[],\n): ResolvedComponent | null {\n for (const component of chain) {\n if (!active.some((candidate) => candidate.runtime === component.runtime)) {\n return component;\n }\n }\n return null;\n}\n\nfunction parseInlineStyle(value: string): Readonly<Record<string, string>> {\n const style: Record<string, string> = {};\n for (const declaration of value.split(\";\")) {\n const separator = declaration.indexOf(\":\");\n if (separator < 0) continue;\n const property = declaration.slice(0, separator).trim();\n const propertyValue = declaration.slice(separator + 1).trim();\n if (property && propertyValue) style[property] = propertyValue;\n }\n return style;\n}\n","import { getFiberFromElement } from \"../fiber/capture\";\nimport type { Fiber, FiberRoot } from \"../fiber/react-types\";\nimport {\n isTransientFiberResolutionError,\n resolveCommittedFiber,\n} from \"../fiber/serialize\";\nimport type { DetachSerializedFiber } from \"./enriched-to-serialized-fiber\";\nimport type { LayerFramework } from \"./layer-framework\";\nimport type { CombinedProjectionProblem } from \"./projection-batch\";\nimport {\n createProjectionDomLayerSerializer,\n type ProjectionDomLayerTargets,\n} from \"./projection-dom-layers\";\nimport {\n ascendToAnnotatedComponentRoot,\n createProjectionLayerSerializer,\n isProjectionLayerFiber,\n type ProjectionLayerMetadataSnapshot,\n type ProjectionLayerRegionSerializationResult,\n type ProjectionLayerRootSnapshot,\n} from \"./projection-layer-snapshot\";\nimport type { ProjectionObservedFileMap } from \"./projection-observed-files\";\nimport type { ProjectionLayerPatch } from \"./projection-root-accumulator\";\nimport { captureProjectionSemanticSubtree } from \"./projection-semantic-subtree\";\nimport { createProjectionSvelteLayerSerializer } from \"./projection-svelte-layers\";\nimport { validateSvelteRuntimeMetadata } from \"./projection-svelte-metadata\";\n\nexport interface ProjectionLayerTarget {\n readonly element: Element;\n readonly fiberSelector?: string;\n}\n\nexport interface ProjectionLayerFullCapture {\n readonly snapshot: ProjectionLayerRootSnapshot;\n readonly fiberNodesVisited: number;\n readonly semanticNodesSerialized: number;\n}\n\n/**\n * The sole framework-specific seam in combined projection. The producer owns\n * scheduling and the common DOM transaction; an adapter owns only the source\n * of semantic layers and their identity.\n */\nexport interface ProjectionLayerAdapter {\n readonly layerFramework: LayerFramework;\n readonly retainDomMutationTargets: boolean;\n readProblem(root: Element): CombinedProjectionProblem | null;\n captureFull(\n root: Element,\n fiberTarget: Element | null,\n observedFiles: ProjectionObservedFileMap,\n ): ProjectionLayerFullCapture;\n capturePatch(\n root: Element,\n targets: ProjectionDomLayerTargets,\n observedFiles: ProjectionObservedFileMap,\n ): ProjectionLayerPatch | undefined;\n resolveCommittedRoot(\n fiberRoot: FiberRoot | undefined,\n target: ProjectionLayerTarget,\n ): Fiber | null;\n resolveElementCandidate(element: Element): Fiber | null;\n layerSourceId(fiber: Fiber): string | null;\n captureRegion(fiber: Fiber): ProjectionLayerRegionSerializationResult | null;\n captureMetadata(\n fiber: Fiber,\n options?: { readonly sourceAnnotations?: \"fiber\" | \"live-host\" },\n ): ProjectionLayerMetadataSnapshot | null;\n captureSemanticSubtree(\n target: ProjectionLayerTarget,\n targetLayerSourceId: string,\n ): DetachSerializedFiber | null;\n}\n\nexport function createProjectionLayerAdapter(\n layerFramework: LayerFramework,\n): ProjectionLayerAdapter {\n switch (layerFramework) {\n case \"react\":\n return createReactLayerAdapter();\n case \"svelte\":\n return createDomBackedLayerAdapter(\n \"svelte\",\n createProjectionSvelteLayerSerializer(),\n (root) => {\n const validation = validateSvelteRuntimeMetadata(root);\n return validation.kind === \"unavailable\"\n ? {\n reason: \"svelte-layer-metadata-unavailable\",\n message: validation.message,\n }\n : null;\n },\n );\n case \"dom\":\n return createDomBackedLayerAdapter(\n \"dom\",\n createProjectionDomLayerSerializer(),\n () => null,\n );\n }\n}\n\nfunction createReactLayerAdapter(): ProjectionLayerAdapter {\n const serializer = createProjectionLayerSerializer();\n const missingFiberFallback = createProjectionDomLayerSerializer();\n return {\n layerFramework: \"react\",\n retainDomMutationTargets: false,\n readProblem: () => null,\n captureFull(root, fiberTarget, observedFiles) {\n const rawFiber = fiberTarget ? getFiberFromElement(fiberTarget) : null;\n if (!rawFiber) {\n const snapshot = missingFiberFallback.serializeRoot(root, observedFiles);\n return {\n snapshot,\n fiberNodesVisited: 0,\n semanticNodesSerialized: countLayerNodes(snapshot),\n };\n }\n const serialized = serializer.serialize(\n ascendToAnnotatedComponentRoot(resolveCommittedFiber(rawFiber)),\n );\n return {\n snapshot: serialized.snapshot,\n fiberNodesVisited: serialized.fiberNodesVisited,\n semanticNodesSerialized: serialized.semanticNodesSerialized,\n };\n },\n capturePatch: () => undefined,\n resolveCommittedRoot: resolveWatchedCommittedFiber,\n resolveElementCandidate(element) {\n const raw = getFiberFromElement(element);\n if (!raw) return null;\n const committed = resolveCommittedFiberOrNull(raw);\n if (!committed) return null;\n let current: Fiber | null = committed;\n while (current && !isProjectionLayerFiber(current)) {\n current = current.return;\n }\n return current;\n },\n layerSourceId: serializer.fiberId,\n captureRegion: serializer.serializeRegion,\n captureMetadata: serializer.captureMetadata,\n captureSemanticSubtree(target, targetLayerSourceId) {\n const current = resolveWatchedCommittedFiber(undefined, target);\n if (!current) return null;\n return captureProjectionSemanticSubtree(current, targetLayerSourceId, {\n fiberId: serializer.fiberId,\n knownFiberId: serializer.knownFiberId,\n });\n },\n };\n}\n\nfunction createDomBackedLayerAdapter(\n layerFramework: \"svelte\" | \"dom\",\n serializer: ReturnType<typeof createProjectionDomLayerSerializer>,\n readProblem: (root: Element) => CombinedProjectionProblem | null,\n): ProjectionLayerAdapter {\n return {\n layerFramework,\n retainDomMutationTargets: true,\n readProblem,\n captureFull(root, _fiberTarget, observedFiles) {\n const snapshot = serializer.serializeRoot(root, observedFiles);\n return {\n snapshot,\n fiberNodesVisited: 0,\n semanticNodesSerialized: countLayerNodes(snapshot),\n };\n },\n capturePatch: serializer.capturePatch,\n resolveCommittedRoot: () => null,\n resolveElementCandidate: () => null,\n layerSourceId: () => null,\n captureRegion: () => null,\n captureMetadata: () => null,\n captureSemanticSubtree: () => null,\n };\n}\n\nfunction countLayerNodes(snapshot: ProjectionLayerRootSnapshot): number {\n if (snapshot.semantic.kind !== \"layers\" || !snapshot.semantic.tree) return 0;\n const visit = (node: typeof snapshot.semantic.tree): number =>\n 1 + node.children.reduce((total, child) => total + visit(child), 0);\n return visit(snapshot.semantic.tree);\n}\n\nfunction resolveWatchedCommittedFiber(\n fiberRoot: FiberRoot | undefined,\n target: ProjectionLayerTarget,\n): Fiber | null {\n const element = target.fiberSelector\n ? target.element.ownerDocument.querySelector(target.fiberSelector)\n : (target.element.firstElementChild ?? target.element);\n if (!element) return null;\n if (\n fiberRoot &&\n (fiberRoot.containerInfo === element || element.contains(fiberRoot.containerInfo))\n ) {\n return fiberRoot.current;\n }\n const rawFiber = getFiberFromElement(element);\n if (!rawFiber) return null;\n const rawCommitted = resolveCommittedFiberOrNull(rawFiber);\n if (!rawCommitted) return null;\n const committed = ascendToAnnotatedComponentRoot(rawCommitted);\n if (!fiberRoot) return committed;\n let root = committed;\n while (root.return) root = root.return;\n return root === fiberRoot.current || root === fiberRoot.current.alternate\n ? committed\n : null;\n}\n\nexport function resolveCommittedFiberOrNull(fiber: Fiber): Fiber | null {\n try {\n return resolveCommittedFiber(fiber);\n } catch (error) {\n if (!isTransientFiberResolutionError(error)) throw error;\n return null;\n }\n}\n","import type {\n CombinedProjectionBatch,\n CombinedProjectionProblem,\n} from \"./projection-batch\";\nimport type { ProjectionFullSnapshot } from \"./projection-full-snapshot\";\nimport type { ProjectionRootPatch } from \"./projection-root-accumulator\";\n\nexport const PROJECTION_FLUSH_WINDOW_MS = 500;\n\ntype Stop = () => void;\n\nexport interface ProjectionFlushTiming {\n readonly flushStartedAt: number;\n readonly flushIntervalMs: number | null;\n readonly fixedWindowTimersOpened: number;\n readonly maxSimultaneousTimers: number;\n}\n\nexport interface ProjectionProducerFlushContext extends ProjectionFlushTiming {\n readonly candidateRootCount: number;\n readonly initialForSession: boolean;\n readonly fullRequested: boolean;\n}\n\nexport interface ProjectionProducerScheduler {\n now(): number;\n schedule(callback: () => void, delayMs: number): Stop;\n}\n\ntype CapturedRoot =\n | { readonly kind: \"full\"; readonly snapshot: ProjectionFullSnapshot }\n | { readonly kind: \"patch\"; readonly patch: ProjectionRootPatch }\n | { readonly kind: \"problem\"; readonly problem: CombinedProjectionProblem }\n | null;\n\ninterface OutboxOptions {\n readonly scheduler?: ProjectionProducerScheduler;\n readonly flushWindowMs?: number;\n readonly onError?: (error: unknown) => void;\n captureRoot(\n rootId: string,\n context: ProjectionProducerFlushContext,\n ): CapturedRoot;\n captureHead(context: ProjectionProducerFlushContext): string | undefined;\n emit(batch: CombinedProjectionBatch): void;\n}\n\nexport interface ProjectionOutbox {\n bindSession(sessionId: string): void;\n addRoot(rootId: string): void;\n removeRoot(rootId: string): void;\n record(activity: {\n readonly rootIds?: readonly string[];\n readonly head?: boolean;\n }): void;\n /** One current self-contained baseline for one root. */\n requestFull(rootId: string): void;\n stop(): void;\n}\n\nconst defaultScheduler: ProjectionProducerScheduler = {\n now: () =>\n typeof performance === \"undefined\" ? Date.now() : performance.now(),\n schedule(callback, delayMs) {\n const timer = setTimeout(callback, delayMs);\n return () => clearTimeout(timer);\n },\n};\n\nexport interface ProjectionFixedWindow {\n schedule(): void;\n flushNow(): void;\n cancel(): void;\n reset(): void;\n stop(): void;\n}\n\n/** @internal One non-resetting timer shared by live and static source owners. */\nexport function createProjectionFixedWindow(options: {\n readonly scheduler?: ProjectionProducerScheduler;\n readonly flushWindowMs?: number;\n hasPending(): boolean;\n flush(timing: ProjectionFlushTiming): void;\n}): ProjectionFixedWindow {\n const scheduler = options.scheduler ?? defaultScheduler;\n const windowMs = options.flushWindowMs ?? PROJECTION_FLUSH_WINDOW_MS;\n if (windowMs < 0) throw new Error(\"flushWindowMs must be non-negative\");\n let cancelTimer: Stop | undefined;\n let stopped = false;\n let flushing = false;\n let flushAgain = false;\n let timersOpened = 0;\n let lastFlushAt: number | null = null;\n\n const cancel = () => {\n cancelTimer?.();\n cancelTimer = undefined;\n };\n const schedule = () => {\n if (stopped || !options.hasPending() || cancelTimer) return;\n timersOpened += 1;\n cancelTimer = scheduler.schedule(() => {\n cancelTimer = undefined;\n flushNow();\n }, windowMs);\n };\n function flushNow(): void {\n cancel();\n if (stopped || !options.hasPending()) return;\n if (flushing) {\n flushAgain = true;\n return;\n }\n flushing = true;\n do {\n flushAgain = false;\n const now = scheduler.now();\n const timing: ProjectionFlushTiming = {\n flushStartedAt: Date.now(),\n flushIntervalMs: lastFlushAt === null ? null : now - lastFlushAt,\n fixedWindowTimersOpened: timersOpened,\n maxSimultaneousTimers: timersOpened > 0 ? 1 : 0,\n };\n lastFlushAt = now;\n timersOpened = 0;\n options.flush(timing);\n } while (flushAgain && !stopped && options.hasPending());\n flushing = false;\n }\n\n return {\n schedule,\n flushNow,\n cancel,\n reset() {\n cancel();\n timersOpened = 0;\n lastFlushAt = null;\n },\n stop() {\n stopped = true;\n cancel();\n },\n };\n}\n\n/** @internal Ordered outbox for the one live-document producer. */\nexport function createProjectionOutbox(\n options: OutboxOptions,\n): ProjectionOutbox {\n const roots = new Set<string>();\n const dirty = new Set<string>();\n const full = new Set<string>();\n let dirtyHead = false;\n let sessionId: string | undefined;\n let sequence = 0;\n let stopped = false;\n let fixedWindow: ProjectionFixedWindow;\n\n const hasWork = () => dirtyHead || dirty.size > 0;\n const report = (error: unknown) => {\n try {\n options.onError?.(error);\n } catch {\n // Reporting cannot break recovery or cleanup.\n }\n };\n const assertActive = () => {\n if (stopped) throw new Error(\"Projection producer has been stopped\");\n };\n\n const restore = (\n failedSession: string,\n rootIds: readonly string[],\n includeHead: boolean,\n ) => {\n if (stopped || sessionId !== failedSession) return;\n for (const rootId of rootIds) {\n if (!roots.has(rootId)) continue;\n dirty.add(rootId);\n // Capture drains source-local candidates, so an unsent patch can only be\n // retried honestly as a current baseline.\n full.add(rootId);\n }\n dirtyHead ||= includeHead;\n fixedWindow.schedule();\n };\n\n const flushOnce = (timing: ProjectionFlushTiming) => {\n const activeSession = sessionId;\n if (stopped || !activeSession || !hasWork()) return;\n const rootIds = [...dirty];\n const fullRootIds = new Set(full);\n const includeHead = dirtyHead;\n const context: ProjectionProducerFlushContext = {\n ...timing,\n candidateRootCount: rootIds.length,\n initialForSession: sequence === 0,\n fullRequested: false,\n };\n dirty.clear();\n full.clear();\n dirtyHead = false;\n\n try {\n const changes: CombinedProjectionBatch[\"roots\"][number][] = [];\n for (const rootId of rootIds) {\n if (!roots.has(rootId)) continue;\n const captured = options.captureRoot(rootId, {\n ...context,\n fullRequested: fullRootIds.has(rootId),\n });\n if (!roots.has(rootId) || !captured) continue;\n changes.push({ rootId, ...captured });\n }\n if (stopped || sessionId !== activeSession) return;\n const head = includeHead ? options.captureHead(context) : undefined;\n if (stopped || sessionId !== activeSession) return;\n if (changes.length === 0 && head === undefined) return;\n const emittedSequence = sequence;\n options.emit({\n sessionId: activeSession,\n sequence: emittedSequence,\n ...(head === undefined ? {} : { head }),\n roots: changes,\n });\n if (sessionId === activeSession && sequence === emittedSequence) {\n sequence += 1;\n }\n } catch (error) {\n report(error);\n restore(activeSession, rootIds, includeHead);\n }\n };\n\n fixedWindow = createProjectionFixedWindow({\n scheduler: options.scheduler,\n flushWindowMs: options.flushWindowMs,\n hasPending: hasWork,\n flush: flushOnce,\n });\n\n return {\n bindSession(nextSessionId) {\n assertActive();\n if (!nextSessionId)\n throw new Error(\"Projection session ID must not be empty\");\n if (sessionId === nextSessionId) return;\n fixedWindow.reset();\n dirty.clear();\n full.clear();\n dirtyHead = true;\n sessionId = nextSessionId;\n sequence = 0;\n for (const rootId of roots.keys()) {\n dirty.add(rootId);\n full.add(rootId);\n }\n fixedWindow.schedule();\n },\n addRoot(rootId) {\n assertActive();\n if (!rootId) throw new Error(\"Projection root ID must not be empty\");\n if (roots.has(rootId)) return;\n roots.add(rootId);\n if (!sessionId) return;\n dirty.add(rootId);\n full.add(rootId);\n // A root that joined after the last head emission holds no copy of the\n // document head, and every later emission reaches every lane, so this is\n // the only moment a lane can be missing it.\n dirtyHead = true;\n if (sequence === 0) fixedWindow.schedule();\n else fixedWindow.flushNow();\n },\n removeRoot(rootId) {\n if (stopped || !roots.delete(rootId)) return;\n dirty.delete(rootId);\n full.delete(rootId);\n if (!hasWork()) fixedWindow.cancel();\n },\n record(activity) {\n if (stopped || !sessionId) return;\n dirtyHead ||= activity.head === true;\n for (const rootId of activity.rootIds ?? []) {\n if (roots.has(rootId)) dirty.add(rootId);\n }\n fixedWindow.schedule();\n },\n requestFull(rootId) {\n assertActive();\n if (!sessionId || !roots.has(rootId)) return;\n dirty.add(rootId);\n full.add(rootId);\n fixedWindow.flushNow();\n },\n stop() {\n if (stopped) return;\n stopped = true;\n fixedWindow.stop();\n roots.clear();\n dirty.clear();\n full.clear();\n dirtyHead = false;\n sessionId = undefined;\n },\n };\n}\n","/**\n * Portal Tracker\n *\n * Watches document.body for new subtrees and determines which watched element\n * (if any) they belong to by walking up the React fiber ancestry.\n *\n * ## How it works\n *\n * React portals render content outside their component's DOM location, but the\n * fiber tree maintains the logical parent-child relationship. When a new element\n * appears in body:\n *\n * 1. Get its fiber via getFiberFromElement\n * 2. Walk up fiber.return chain, collecting DOM nodes from stateNode\n * 3. Check if any collected DOM node is within a registered watcher's element\n * 4. If yes, notify that watcher\n *\n * ## Usage\n *\n * ```ts\n * const tracker = getPortalTracker();\n * const unregister = tracker.register({\n * element: myWatchedElement,\n * onPortalFound: (portalRoot) => startWatchingPortal(portalRoot),\n * onPortalRemoved: (portalRoot) => stopWatchingPortal(portalRoot),\n * });\n * ```\n */\n\nimport { getFiberFromElement } from \"../fiber/capture\";\nimport type { Fiber } from \"../fiber/react-types\";\n\n// Note: This module depends on the fiber module for React fiber tree traversal.\n// Both modules are at the same level (siblings in the module structure).\n\nexport interface PortalWatcher {\n /** The DOM element being watched for HTML projection */\n element: Element;\n /** Called when a portal belonging to this element is detected */\n onPortalFound: (portalRoot: Element) => void;\n /** Called when a tracked portal is removed from the DOM */\n onPortalRemoved: (portalRoot: Element) => void;\n}\n\nexport interface PortalTracker {\n /**\n * Register a watcher. Immediately scans existing body children for matches.\n * @returns Unregister function\n */\n register(watcher: PortalWatcher): () => void;\n\n /** Stop tracking and clean up. Call when done with all watching. */\n destroy(): void;\n}\n\n/** Module-level singleton */\nlet instance: PortalTrackerImpl | null = null;\n\n/**\n * Get the singleton PortalTracker instance.\n * Creates one if it doesn't exist.\n */\nexport function getPortalTracker(): PortalTracker {\n if (!instance) {\n instance = new PortalTrackerImpl();\n }\n return instance;\n}\n\n/**\n * Reset the singleton. For testing only.\n * @internal\n */\nexport function _resetPortalTrackerForTesting(): void {\n instance?.destroy();\n instance = null;\n}\n\n/** Whether React logically owns `candidate` below `root`, across portals. */\nexport function isElementOwnedByRoot(\n candidate: Element,\n root: Element,\n): boolean {\n const fiber = getFiberFromElement(candidate);\n if (!fiber) return false;\n\n let current: Fiber | null = fiber.return;\n while (current) {\n if (\n current.stateNode instanceof Element &&\n (current.stateNode === root || root.contains(current.stateNode))\n ) {\n return true;\n }\n current = current.return;\n }\n\n return false;\n}\n\n/**\n * Finds the topmost portal roots owned by `root`. Portal targets may be nested\n * below arbitrary non-React containers, so body-child-only scans are not\n * sufficient.\n */\nexport function findOwnedPortalRoots(root: Element): Element[] {\n const body = root.ownerDocument?.body;\n if (!body) return [];\n\n const portals: Element[] = [];\n const visit = (candidate: Element): void => {\n if (candidate === root || root.contains(candidate)) return;\n if (isElementOwnedByRoot(candidate, root)) {\n portals.push(candidate);\n return;\n }\n for (const child of Array.from(candidate.children)) visit(child);\n };\n\n for (const child of Array.from(body.children)) visit(child);\n return portals;\n}\n\nclass PortalTrackerImpl implements PortalTracker {\n private watchers = new Set<PortalWatcher>();\n private trackedPortals = new Map<Element, Set<PortalWatcher>>(); // portal element -> subscribed watchers\n private observer: MutationObserver | null = null;\n private pendingScanRoots = new Set<Element>();\n private scanScheduled = false;\n\n register(watcher: PortalWatcher): () => void {\n this.watchers.add(watcher);\n\n // Start observing if this is the first watcher\n if (this.watchers.size === 1) {\n this.startObserving();\n }\n\n // Initial scan: custom portal targets may be nested below body children.\n for (const child of Array.from(document.body.children)) {\n this.scanElementTree(child, watcher);\n }\n\n return () => this.unregister(watcher);\n }\n\n private unregister(watcher: PortalWatcher): void {\n this.watchers.delete(watcher);\n\n // Remove this watcher from all tracked portal subscriptions\n for (const [portal, owners] of this.trackedPortals) {\n owners.delete(watcher);\n if (owners.size === 0) {\n this.trackedPortals.delete(portal);\n }\n }\n\n // Stop observing if no watchers remain\n if (this.watchers.size === 0) {\n this.stopObserving();\n }\n }\n\n destroy(): void {\n this.stopObserving();\n this.watchers.clear();\n this.trackedPortals.clear();\n this.pendingScanRoots.clear();\n }\n\n private startObserving(): void {\n if (this.observer) return;\n\n this.observer = new MutationObserver(this.handleMutations);\n this.observer.observe(document.body, { childList: true, subtree: true });\n }\n\n private stopObserving(): void {\n this.observer?.disconnect();\n this.observer = null;\n }\n\n private handleMutations = (mutations: MutationRecord[]): void => {\n for (const mutation of mutations) {\n // Handle added nodes\n for (const node of mutation.addedNodes) {\n if (node instanceof Element) {\n // React attaches __reactFiber$* keys after DOM insertion. Coalesce a\n // mutation batch so nested additions are scanned only once.\n this.scheduleScan(node);\n }\n }\n\n // Handle removed nodes\n for (const node of mutation.removedNodes) {\n if (node instanceof Element) {\n for (const [portal, owners] of this.trackedPortals) {\n if (portal !== node && !node.contains(portal)) continue;\n for (const owner of owners) {\n owner.onPortalRemoved(portal);\n }\n this.trackedPortals.delete(portal);\n }\n }\n }\n }\n };\n\n private scheduleScan(element: Element): void {\n this.pendingScanRoots.add(element);\n if (this.scanScheduled) return;\n\n this.scanScheduled = true;\n queueMicrotask(() => {\n this.scanScheduled = false;\n const roots = Array.from(this.pendingScanRoots);\n this.pendingScanRoots.clear();\n\n for (const root of roots) {\n // An add+remove in one observer batch must not create a detached ghost.\n if (!root.isConnected) continue;\n if (roots.some((other) => other !== root && other.contains(root))) {\n continue;\n }\n this.scanElementTree(root);\n }\n });\n }\n\n /**\n * Scan until a topmost owned portal is found. Mutations inside an already\n * tracked portal are handled by that portal's own watcher.\n */\n private scanElementTree(element: Element, onlyWatcher?: PortalWatcher): void {\n const requestedWatchers = onlyWatcher\n ? this.watchers.has(onlyWatcher)\n ? [onlyWatcher]\n : []\n : Array.from(this.watchers);\n this.scanElementTreeForWatchers(element, requestedWatchers);\n }\n\n private scanElementTreeForWatchers(\n element: Element,\n requestedWatchers: readonly PortalWatcher[],\n ): void {\n const eligibleWatchers = requestedWatchers.filter(\n (watcher) =>\n watcher.element !== element &&\n !watcher.element.contains(element) &&\n !this.isInsidePortalOwnedByWatcher(element, watcher),\n );\n if (eligibleWatchers.length === 0) return;\n\n const matchedWatchers = this.checkElement(element, eligibleWatchers);\n const descendantWatchers = eligibleWatchers.filter(\n (watcher) => !matchedWatchers.has(watcher),\n );\n if (descendantWatchers.length === 0) return;\n\n for (const child of Array.from(element.children)) {\n this.scanElementTreeForWatchers(child, descendantWatchers);\n }\n }\n\n private isInsidePortalOwnedByWatcher(\n element: Element,\n watcher: PortalWatcher,\n ): boolean {\n for (const [portal, owners] of this.trackedPortals) {\n if (\n owners.has(watcher) &&\n (portal === element || portal.contains(element))\n ) {\n return true;\n }\n }\n return false;\n }\n\n /** Check ownership with one fiber walk, even when many roots are watched. */\n private checkElement(\n element: Element,\n watchers: readonly PortalWatcher[],\n ): Set<PortalWatcher> {\n const matched = new Set<PortalWatcher>();\n const fiber = getFiberFromElement(element);\n if (!fiber) return matched;\n\n let current: Fiber | null = fiber.return;\n while (current && matched.size < watchers.length) {\n if (current.stateNode instanceof Element) {\n for (const watcher of watchers) {\n if (\n !matched.has(watcher) &&\n (current.stateNode === watcher.element ||\n watcher.element.contains(current.stateNode))\n ) {\n matched.add(watcher);\n }\n }\n }\n current = current.return;\n }\n\n if (matched.size === 0) return matched;\n let owners = this.trackedPortals.get(element);\n if (!owners) {\n owners = new Set<PortalWatcher>();\n this.trackedPortals.set(element, owners);\n }\n for (const watcher of matched) {\n if (!this.watchers.has(watcher) || owners.has(watcher)) continue;\n owners.add(watcher);\n watcher.onPortalFound(element);\n }\n\n return matched;\n }\n}\n","import {\n type DomWatcher,\n drainProjectionDomMutations,\n type ProjectionDomMutation,\n watchDom,\n} from \"../html/watch-dom\";\nimport { type PortalWatcherHandle, watchPortal } from \"../html/watch-portal\";\nimport {\n drainProjectionStateEvents,\n type StateWatcher,\n watchState,\n} from \"../html/watch-state\";\nimport { getPortalTracker } from \"../shared/portal-tracker\";\nimport type {\n ProjectionLayerMetadataSnapshot,\n ProjectionLayerRegionSnapshot,\n} from \"./projection-layer-snapshot\";\nimport {\n ProjectionObservedFileAccumulator,\n type ProjectionObservedFileMap,\n} from \"./projection-observed-files\";\nimport {\n captureProjectionMutationPatch,\n captureProjectionPortalCoordinates,\n captureProjectionPortalRegion,\n captureProjectionStatePatch,\n type ProjectionAnnotationPatch,\n type ProjectionDomPatch,\n type ProjectionPortalPatch,\n type ProjectionStatePatch,\n} from \"./projection-patch\";\n\nexport interface ProjectionLayerPatch {\n readonly regions?: readonly ProjectionLayerRegionSnapshot[];\n readonly metadata?: readonly ProjectionLayerMetadataSnapshot[];\n}\n\nexport interface ProjectionRootPatch {\n readonly dom?: readonly ProjectionDomPatch[];\n readonly annotations?: readonly ProjectionAnnotationPatch[];\n readonly state?: readonly ProjectionStatePatch[];\n readonly portals?: readonly ProjectionPortalPatch[];\n readonly layers?: ProjectionLayerPatch;\n readonly observedFiles?: ProjectionObservedFileMap;\n}\n\nexport type ProjectionRootPatchResult =\n | {\n readonly kind: \"patch\";\n readonly patch: ProjectionRootPatch;\n /** DOM-derived metadata targets retained only for local Fiber capture. */\n readonly localMetadataTargets: readonly Element[];\n /** Exact source-realm targets for synthetic DOM Layers. They never\n * cross transport, so duplicate DOM ids remain unambiguous. */\n readonly localDomLayerTargets?: {\n readonly structural: readonly Element[];\n readonly metadata: readonly Element[];\n };\n }\n | { readonly kind: \"empty\" };\n\nexport interface ProjectionPortalRegistration {\n readonly onPortalFound: (portal: Element) => void;\n readonly onPortalRemoved: (portal: Element) => void;\n}\n\nexport interface CreateProjectionRootAccumulatorOptions {\n readonly root: Element;\n readonly onChange: () => void;\n /** Injection seam; the default delegates to the document portal tracker. */\n readonly registerPortals?: (\n registration: ProjectionPortalRegistration,\n ) => () => void;\n}\n\nexport interface ProjectionRootAccumulator {\n capturePatch(options?: {\n readonly regionalChildLists?: boolean;\n readonly retainDomLayerTargets?: boolean;\n }): ProjectionRootPatchResult;\n /**\n * Retain DOM records already queued for this root and return their count.\n * This is called synchronously at React's commit boundary; the caller owns\n * the scheduling signal for those records.\n */\n takePendingDomRecords(): number;\n /** Whether this root currently owns any portal. Document-wide changes that\n * can move a portal without mutating it (new styling) only need to schedule\n * the roots that answer yes. */\n hasPortals(): boolean;\n /** Current live portal roots for an explicit full baseline. */\n portalElements(): readonly Element[];\n /** Counters already maintained by observers; performs no discovery work. */\n perfSnapshot(): {\n readonly rawMutationRecords: number;\n readonly rawStateRecords: number;\n readonly rawPortalRecords: number;\n readonly candidateTargets: number;\n };\n stop(): void;\n}\n\n/**\n * One root-local final-state accumulator. Observer callbacks only retain exact\n * source targets and signal the document scheduler; serialization happens once\n * when the scheduler flushes.\n */\nexport function createProjectionRootAccumulator(\n options: CreateProjectionRootAccumulatorOptions,\n): ProjectionRootAccumulator {\n const dom: DomWatcher = watchDom(options.root, options.onChange);\n const state: StateWatcher = watchState(options.root, options.onChange);\n const portals = new Map<Element, PortalWatcherHandle>();\n const dirtyPortals = new Set<Element>();\n const removedPortals = new Map<string, ProjectionPortalPatch>();\n /** The coordinate space the destination last received per live portal,\n * serialized. Both sides of the comparison are built by the same capture\n * routine, so key order is fixed and the string is a sound identity — and\n * one that stays exhaustive if the coordinate space grows a field. */\n const sentPortalCoordinates = new Map<Element, string>();\n let stopped = false;\n\n // A host positions the watched root by styling an ANCESTOR of it (a\n // storyboard's frame carries the layout position), so the root can move in\n // its viewport without one mutation inside the watched subtree. Every\n // portal's coordinate space moves with it, and nothing else would notice.\n const ancestorsOf = (element: Element): Element[] => {\n const chain: Element[] = [];\n for (\n let ancestor = element.parentElement;\n ancestor;\n ancestor = ancestor.parentElement\n ) {\n chain.push(ancestor);\n }\n return chain;\n };\n const sameChain = (chain: Element[], other: Element[]): boolean =>\n chain.length === other.length &&\n chain.every((element, index) => element === other[index]);\n let observedAncestors: Element[] = [];\n const frameWatcher = new MutationObserver((records) => {\n if (stopped) return;\n // childList is observed only to notice the root being re-parented, which\n // moves it under ancestors this observer has never seen. Sibling churn\n // under an unchanged chain is not a coordinate signal, so it must not\n // become one — the chain is compared before anything is reported.\n let reparented = false;\n if (records.some((record) => record.type === \"childList\")) {\n const chain = ancestorsOf(options.root);\n reparented = !sameChain(chain, observedAncestors);\n if (reparented) observeAncestors(chain);\n }\n const restyled = records.some((record) => record.type === \"attributes\");\n if (!reparented && !restyled) return;\n if (portals.size === 0) return;\n options.onChange();\n });\n function observeAncestors(chain: Element[]): void {\n frameWatcher.disconnect();\n observedAncestors = chain;\n for (const ancestor of chain) {\n frameWatcher.observe(ancestor, {\n attributes: true,\n attributeFilter: [\"style\", \"class\"],\n childList: true,\n });\n }\n }\n observeAncestors(ancestorsOf(options.root));\n\n const registerPortals =\n options.registerPortals ??\n ((registration: ProjectionPortalRegistration) =>\n getPortalTracker().register({\n element: options.root,\n ...registration,\n }));\n const unregisterPortals = registerPortals({\n onPortalFound(portal) {\n if (stopped || portals.has(portal)) return;\n // No coordinate root: this lane captures a portal's frame with its\n // body, from the patch builder, rather than through the handle's own\n // legacy-envelope flush.\n const handle = watchPortal(portal, () => {\n dirtyPortals.add(portal);\n options.onChange();\n });\n portals.set(portal, handle);\n dirtyPortals.add(portal);\n options.onChange();\n },\n onPortalRemoved(portal) {\n const handle = portals.get(portal);\n if (!handle) return;\n removedPortals.set(handle.id, {\n kind: \"remove\",\n portalId: handle.id,\n });\n dirtyPortals.delete(portal);\n portals.delete(portal);\n sentPortalCoordinates.delete(portal);\n handle.stop();\n options.onChange();\n },\n });\n\n return {\n takePendingDomRecords() {\n if (stopped) return 0;\n return dom.takePendingRecords();\n },\n hasPortals() {\n return !stopped && portals.size > 0;\n },\n capturePatch(captureOptions) {\n if (stopped) throw new Error(\"Projection root accumulator has stopped\");\n const domMutations = drainProjectionDomMutations(dom);\n const localDomLayerTargets = captureOptions?.retainDomLayerTargets\n ? collectDomLayerTargets(options.root, domMutations)\n : undefined;\n const mutationPatch = captureProjectionMutationPatch(\n options.root,\n domMutations,\n captureOptions,\n );\n\n const states: ProjectionStatePatch[] = [];\n for (const event of drainProjectionStateEvents(state)) {\n const captured = captureProjectionStatePatch(\n options.root,\n event.element,\n event.eventKind,\n );\n if (captured) states.push(captured);\n }\n\n const portalPatches = Array.from(removedPortals.values());\n const portalAnnotations: ProjectionAnnotationPatch[] = [];\n const observedFiles = new ProjectionObservedFileAccumulator();\n observedFiles.merge(mutationPatch.observedFiles);\n removedPortals.clear();\n const resentPortals = new Set<Element>();\n for (const portal of dirtyPortals) {\n const handle = portals.get(portal);\n if (!handle) continue;\n const captured = captureProjectionPortalRegion(\n portal,\n false,\n options.root,\n );\n if (!captured) continue;\n resentPortals.add(portal);\n if (\n captured.portal.kind === \"replace\" &&\n captured.portal.coordinateSpace\n ) {\n sentPortalCoordinates.set(\n portal,\n JSON.stringify(captured.portal.coordinateSpace),\n );\n }\n portalPatches.push(captured.portal);\n portalAnnotations.push(...captured.annotations);\n observedFiles.merge(captured.observedFiles);\n for (const event of handle.clearPendingChanges()) {\n const statePatch = captureProjectionStatePatch(\n portal,\n event.element,\n event.eventKind,\n );\n if (statePatch) states.push(statePatch);\n }\n }\n dirtyPortals.clear();\n\n // The root can move, and new styling can move a portal, without either\n // one mutating the portal. Portals whose body this patch already carries\n // are current; the rest are worth a coordinate refresh, but only when\n // the frame actually moved — re-sending a body would cost destination\n // focus and edit state, and re-sending an unchanged frame is noise.\n for (const portal of portals.keys()) {\n if (resentPortals.has(portal)) continue;\n const coordinates = captureProjectionPortalCoordinates(\n options.root,\n portal,\n );\n if (!coordinates) continue;\n const measured = JSON.stringify(coordinates.coordinateSpace);\n if (sentPortalCoordinates.get(portal) === measured) continue;\n sentPortalCoordinates.set(portal, measured);\n portalPatches.push(coordinates);\n }\n\n const observedSnapshot = observedFiles.snapshot();\n const patch: ProjectionRootPatch = {\n ...(mutationPatch.dom.length > 0 ? { dom: mutationPatch.dom } : {}),\n ...(mutationPatch.annotations.length + portalAnnotations.length > 0\n ? {\n annotations: [...mutationPatch.annotations, ...portalAnnotations],\n }\n : {}),\n ...(states.length > 0 ? { state: states } : {}),\n ...(portalPatches.length > 0 ? { portals: portalPatches } : {}),\n ...(Object.keys(observedSnapshot).length > 0\n ? { observedFiles: observedSnapshot }\n : {}),\n };\n const hasLocalDomLayerTargets =\n localDomLayerTargets !== undefined &&\n (localDomLayerTargets.structural.length > 0 ||\n localDomLayerTargets.metadata.length > 0);\n return Object.keys(patch).length === 0 && !hasLocalDomLayerTargets\n ? { kind: \"empty\" }\n : {\n kind: \"patch\",\n patch,\n localMetadataTargets: mutationPatch.localMetadataTargets,\n ...(hasLocalDomLayerTargets ? { localDomLayerTargets } : {}),\n };\n },\n portalElements() {\n return Array.from(portals.keys());\n },\n perfSnapshot() {\n return {\n rawMutationRecords: dom.mutationRecordCount,\n rawStateRecords: state.stateRecordCount,\n rawPortalRecords:\n removedPortals.size +\n Array.from(portals.values()).reduce(\n (count, portal) => count + portal.pendingRecordCount(),\n 0,\n ),\n candidateTargets:\n dom.mutatedElements.size + dom.addedElementCount + dirtyPortals.size,\n };\n },\n stop() {\n if (stopped) return;\n stopped = true;\n unregisterPortals();\n frameWatcher.disconnect();\n dom.stop();\n state.stop();\n for (const portal of portals.values()) portal.stop();\n portals.clear();\n dirtyPortals.clear();\n removedPortals.clear();\n sentPortalCoordinates.clear();\n },\n };\n}\n\nfunction collectDomLayerTargets(\n root: Element,\n mutations: readonly ProjectionDomMutation[],\n): {\n readonly structural: readonly Element[];\n readonly metadata: readonly Element[];\n} {\n const structural = new Set<Element>();\n const metadata = new Set<Element>();\n for (const mutation of mutations) {\n const target =\n mutation.target instanceof Element\n ? mutation.target\n : mutation.target.parentElement;\n if (!target || (target !== root && !root.contains(target))) continue;\n if (mutation.type === \"childList\") structural.add(target);\n else if (mutation.type === \"attributes\") metadata.add(target);\n }\n return {\n structural: Array.from(structural),\n metadata: Array.from(metadata),\n };\n}\n","import type { Fiber, FiberRoot } from \"../fiber/react-types\";\nimport { resolveCommittedFiber } from \"../fiber/serialize\";\nimport type { FiberTagValue, SerializeFn } from \"../fiber/types\";\nimport { initHook } from \"../fiber/watch\";\nimport { captureHead, getHeadTracker } from \"../html/watch-head\";\nimport {\n registerCaptureRootObserver,\n registerDocumentCaptureProducer,\n resetCaptureFlushCounters,\n} from \"../shared/capture-perf\";\nimport type { DetachSerializedFiber } from \"./enriched-to-serialized-fiber\";\nimport type {\n CombinedProjectionBatch,\n CombinedProjectionProblem,\n ProjectionRenderErrorProblem,\n} from \"./projection-batch\";\nimport { buildProjectionCapturePerf } from \"./projection-capture-perf\";\nimport {\n captureProjectionFullSnapshot,\n captureProjectionRegion,\n type ProjectionRegionCapture,\n} from \"./projection-full-snapshot\";\nimport {\n isProjectionLayerFiber,\n type ProjectionLayerMetadataSnapshot,\n type ProjectionLayerProps,\n type ProjectionLayerRegionSnapshot,\n} from \"./projection-layer-snapshot\";\nimport {\n createProjectionLayerAdapter,\n type ProjectionLayerAdapter,\n resolveCommittedFiberOrNull,\n} from \"./projection-layer-adapter\";\nimport { ProjectionObservedFileAccumulator } from \"./projection-observed-files\";\nimport { isProjectionPendingOnly } from \"./projection-pending\";\nimport {\n createProjectionOutbox,\n type ProjectionProducerFlushContext,\n type ProjectionProducerScheduler,\n} from \"./projection-producer\";\nimport {\n createProjectionRootAccumulator,\n type ProjectionRootAccumulator,\n type ProjectionRootPatch,\n} from \"./projection-root-accumulator\";\nimport type {\n CaptureProducerPerf,\n EnrichedFiberConstraint,\n EnrichedFiberNode,\n} from \"./types\";\nimport type { LayerFramework } from \"./layer-framework\";\n\n/** The old customization fields remain accepted at the public SDK boundary,\n * but the document producer deliberately emits one closed DTO. */\nexport interface CombinedProjectionRootOptions<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n> {\n rootId: string;\n element: Element;\n /** Fixed semantic-layer authority for this watcher lifetime. */\n layerFramework: LayerFramework;\n selector?: string;\n serialize?: SerializeFn<T>;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n hideFiberProp?: string;\n}\n\nexport type {\n CombinedProjectionBatch,\n CombinedProjectionProblem,\n ProjectionRenderErrorProblem,\n} from \"./projection-batch\";\n\nexport interface CreateCombinedDocumentProducerOptions {\n document: Document;\n /** Return only after the batch has been synchronously handed to transport. */\n emit(batch: CombinedProjectionBatch): void;\n scheduler?: ProjectionProducerScheduler;\n flushWindowMs?: number;\n onError?: (error: unknown) => void;\n}\n\nexport interface CombinedDocumentProducer<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n> {\n bindSession(sessionId: string): void;\n watchRoot(options: CombinedProjectionRootOptions<T>): void;\n unwatchRoot(rootId: string): void;\n /** One current self-contained baseline for one root. Every baseline names\n * its root: a document-wide baseline would make one root's mount or\n * recovery re-serialize its healthy siblings. */\n requestFull(rootId: string): void;\n /** Cold query for one selected branch; never enters the hot batch stream. */\n captureSemanticSubtree(\n rootId: string,\n targetFiberId: string,\n ): DetachSerializedFiber | null;\n /** Cold scoped-repair query: one element's exact current children-region\n * final state, or null when the id no longer exists. Never enters the hot\n * batch stream. */\n captureRegion(\n rootId: string,\n targetId: string,\n ): ProjectionRegionCapture | null;\n stop(): void;\n}\n\ninterface RootRuntime<T extends EnrichedFiberConstraint> {\n readonly options: CombinedProjectionRootOptions<T>;\n readonly layerAdapter: ProjectionLayerAdapter;\n dormant: boolean;\n accumulator: ProjectionRootAccumulator | null;\n stopObserver: (() => void) | null;\n references: number;\n committedFiber: Fiber | null;\n renderError: ProjectionRenderErrorProblem | null;\n layerProblem: CombinedProjectionProblem | null;\n readonly pendingRegions: Map<string, Fiber>;\n readonly pendingMetadata: Map<\n string,\n { readonly fiber: Fiber; readonly sourceAnnotations: \"fiber\" | \"live-host\" }\n >;\n semanticDiscoveryNodesVisited: number;\n /** True from the drain that reported `suspended` until the one that finds\n * content again, so one pending episode costs exactly one problem. */\n suspendedEpisode: boolean;\n /** A full asked for while suspended, carried to the drain that can serve it.\n * The flush consumes its request set before capture, so without this a\n * baseline requested mid-episode would be dropped. */\n deferredFullRequest: boolean;\n}\n\ninterface RootCaptureStats {\n readonly perf: CaptureProducerPerf;\n}\n\n/**\n * One producer for one source document. Observer callbacks retain source-realm\n * targets; the fixed scheduler asks for their current final state once. Full\n * snapshots exist only for initial registration, explicit synchronization,\n * reload, and recovery.\n */\nexport function createCombinedDocumentProducer<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n>(options: CreateCombinedDocumentProducerOptions): CombinedDocumentProducer<T> {\n const reactHook = initHook();\n const roots = new Map<string, RootRuntime<T>>();\n const captureStats = new WeakMap<object, RootCaptureStats>();\n let stopped = false;\n let rootLifecycleObserver: MutationObserver | null = null;\n let headPerfContext: ProjectionProducerFlushContext | null = null;\n let headSnapshotMs = 0;\n\n const core = createProjectionOutbox({\n emit(batch) {\n const rootPerf = batch.roots.flatMap((change) => {\n const payload =\n change.kind === \"full\"\n ? change.snapshot\n : change.kind === \"patch\"\n ? change.patch\n : change.problem;\n return typeof payload === \"object\" && payload !== null\n ? [captureStats.get(payload)?.perf].filter(\n (perf): perf is CaptureProducerPerf => perf !== undefined,\n )\n : [];\n });\n const perf = aggregateBatchPerf(\n rootPerf,\n batch.head,\n headPerfContext,\n headSnapshotMs,\n batch.roots.length,\n );\n headPerfContext = null;\n headSnapshotMs = 0;\n const emitted: CombinedProjectionBatch = {\n sessionId: batch.sessionId,\n sequence: batch.sequence,\n ...(batch.head === undefined ? {} : { head: batch.head }),\n ...(perf ? { perf } : {}),\n roots: batch.roots,\n };\n options.emit(emitted);\n },\n scheduler: options.scheduler,\n flushWindowMs: options.flushWindowMs,\n onError: options.onError,\n captureRoot(rootId, flushContext) {\n const runtime = roots.get(rootId);\n if (runtime && !runtime.options.element.isConnected) {\n makeRootDormant(runtime);\n }\n if (runtime?.dormant) return null;\n if (!runtime?.accumulator) {\n return {\n kind: \"problem\",\n problem: { reason: \"missing-fiber-target\" },\n };\n }\n const observation = runtime.accumulator.perfSnapshot();\n resetCaptureFlushCounters();\n const captureStartedAt = Date.now();\n const renderError = readProjectionRenderError(runtime.options.element);\n if (renderError) {\n runtime.renderError = renderError;\n // Consume all pre-error candidates. They describe a DOM state that is\n // intentionally never published, and the eventual full baseline\n // supersedes them.\n runtime.accumulator.capturePatch();\n runtime.pendingRegions.clear();\n runtime.pendingMetadata.clear();\n runtime.semanticDiscoveryNodesVisited = 0;\n captureStats.set(renderError, {\n perf: makePerf({\n flushContext,\n observation,\n snapshotMs: Date.now() - captureStartedAt,\n semanticNodes: 0,\n domNodes: 0,\n htmlChars: 0,\n annotations: 0,\n states: 0,\n portals: 0,\n observedFiles: 0,\n candidatesAfter: 0,\n fullReason: fullReason(flushContext),\n }),\n });\n return { kind: \"problem\", problem: renderError };\n }\n\n const layerProblem = runtime.layerAdapter.readProblem(\n runtime.options.element,\n );\n if (layerProblem) {\n runtime.layerProblem = layerProblem;\n runtime.accumulator.capturePatch();\n runtime.pendingRegions.clear();\n runtime.pendingMetadata.clear();\n runtime.semanticDiscoveryNodesVisited = 0;\n captureStats.set(layerProblem, {\n perf: makePerf({\n flushContext,\n observation,\n snapshotMs: Date.now() - captureStartedAt,\n semanticNodes: 0,\n domNodes: 0,\n htmlChars: 0,\n annotations: 0,\n states: 0,\n portals: 0,\n observedFiles: 0,\n candidatesAfter: 0,\n fullReason: null,\n }),\n });\n return { kind: \"problem\", problem: layerProblem };\n }\n const recoveredFromLayerProblem = runtime.layerProblem !== null;\n runtime.layerProblem = null;\n\n // A Tempo Suspense boundary showing only its pending marker has no\n // representable state: the content it will show is still loading. Report\n // that and HOLD this flush's work — leaving the accumulator undrained is\n // what re-queues it, so the next drain sees these records alongside the\n // content commit. Because the episode ends by serving a full baseline,\n // the held records are then consumed and superseded wholesale — and a\n // root-element attribute mutated during the episode is lost with them,\n // since document-lane fulls carry no rootAttributes (the recorded\n // bounded edge of this design). Retained semantic candidates need no\n // special handling: `captureSemanticRegions` already drops any fiber\n // the committed root no longer contains.\n if (isProjectionPendingOnly(runtime.options.element)) {\n runtime.deferredFullRequest ||= flushContext.fullRequested;\n if (runtime.suspendedEpisode) return null;\n runtime.suspendedEpisode = true;\n const problem = { reason: \"suspended\" } as const;\n captureStats.set(problem, {\n perf: makePerf({\n flushContext,\n observation,\n snapshotMs: Date.now() - captureStartedAt,\n semanticNodes: 0,\n domNodes: 0,\n htmlChars: 0,\n annotations: 0,\n states: 0,\n portals: 0,\n observedFiles: 0,\n candidatesAfter: 0,\n fullReason: null,\n }),\n });\n return { kind: \"problem\", problem };\n }\n\n // Ending an episode means the subtree was just rebuilt from nothing, so\n // every fiber in it is new. A patch would carry semantic regions naming\n // ids the destination has never published, which it can only answer with\n // a resync baseline — one wasted round trip per suspense resolution.\n // Serve the baseline directly instead.\n const endedSuspendedEpisode = runtime.suspendedEpisode;\n runtime.suspendedEpisode = false;\n\n runtime.committedFiber = runtime.layerAdapter.resolveCommittedRoot(\n undefined,\n runtime.options,\n );\n\n const fullRequested =\n flushContext.fullRequested ||\n runtime.deferredFullRequest ||\n endedSuspendedEpisode ||\n recoveredFromLayerProblem;\n if (fullRequested) {\n runtime.deferredFullRequest = false;\n // Consume observer-local candidates because this baseline supersedes\n // them with one current self-contained state.\n runtime.accumulator.capturePatch();\n runtime.pendingRegions.clear();\n runtime.pendingMetadata.clear();\n runtime.semanticDiscoveryNodesVisited = 0;\n const fiberTarget = resolveFiberTarget(runtime.options);\n const captured = captureProjectionFullSnapshot({\n root: runtime.options.element,\n fiberTarget,\n portals: runtime.accumulator.portalElements(),\n layerAdapter: runtime.layerAdapter,\n });\n const { snapshot } = captured;\n captureStats.set(snapshot, {\n perf: makePerf({\n flushContext,\n observation,\n snapshotMs: Date.now() - captureStartedAt,\n semanticNodes: captured.semanticNodesSerialized,\n domNodes: captured.hostDomIdCount,\n htmlChars:\n snapshot.dom.html.length +\n snapshot.dom.portals.reduce(\n (sum, portal) =>\n sum + (portal.kind === \"replace\" ? portal.html.length : 0),\n 0,\n ),\n annotations: snapshot.dom.annotations.length,\n states: snapshot.dom.state.length,\n portals: snapshot.dom.portals.length,\n observedFiles: Object.keys(snapshot.observedFiles).length,\n candidatesAfter: 1,\n fullReason: fullReason(flushContext),\n }),\n });\n return { kind: \"full\", snapshot };\n }\n\n const accumulated = runtime.accumulator.capturePatch({\n // MutationObserver's parent is stable across a React commit. The\n // unkeyed child ids React may reuse within that parent are not.\n regionalChildLists: true,\n retainDomLayerTargets: runtime.layerAdapter.retainDomMutationTargets,\n });\n if (accumulated.kind === \"patch\") {\n for (const element of accumulated.localMetadataTargets) {\n runtime.semanticDiscoveryNodesVisited += addElementFiberCandidate(\n runtime,\n element,\n );\n }\n }\n\n const regions = captureSemanticRegions(runtime);\n const metadata = captureSemanticMetadata(runtime, regions.coveredFibers);\n runtime.pendingRegions.clear();\n runtime.pendingMetadata.clear();\n\n const basePatch =\n accumulated.kind === \"patch\" ? accumulated.patch : ({} as const);\n const observedFiles = new ProjectionObservedFileAccumulator();\n observedFiles.merge(basePatch.observedFiles);\n for (const region of regions.snapshots) {\n observedFiles.merge(region.observedFiles);\n }\n const observedSnapshot = observedFiles.snapshot();\n const adapterLayerPatch = runtime.layerAdapter.capturePatch(\n runtime.options.element,\n accumulated.kind === \"patch\"\n ? (accumulated.localDomLayerTargets ?? {\n structural: [],\n metadata: [],\n })\n : { structural: [], metadata: [] },\n observedSnapshot,\n );\n const patch: ProjectionRootPatch = {\n ...basePatch,\n ...(adapterLayerPatch\n ? { layers: adapterLayerPatch }\n : regions.snapshots.length > 0 || metadata.length > 0\n ? {\n layers: {\n ...(regions.snapshots.length > 0\n ? { regions: regions.snapshots }\n : {}),\n ...(metadata.length > 0 ? { metadata } : {}),\n },\n }\n : {}),\n ...(Object.keys(observedSnapshot).length > 0\n ? { observedFiles: observedSnapshot }\n : {}),\n };\n if (Object.keys(patch).length === 0) {\n runtime.semanticDiscoveryNodesVisited = 0;\n return null;\n }\n\n const semanticNodes = regions.semanticNodesSerialized;\n const semanticDiscoveryNodesVisited =\n runtime.semanticDiscoveryNodesVisited;\n runtime.semanticDiscoveryNodesVisited = 0;\n captureStats.set(patch, {\n perf: makePerf({\n flushContext,\n observation,\n snapshotMs: Date.now() - captureStartedAt,\n semanticNodes,\n domNodes: patch.dom?.length ?? 0,\n htmlChars: patchHtmlChars(patch),\n annotations: patch.annotations?.length ?? 0,\n states: patch.state?.length ?? 0,\n portals: patch.portals?.length ?? 0,\n observedFiles: Object.keys(observedSnapshot).length,\n candidatesAfter:\n (patch.dom?.length ?? 0) +\n regions.snapshots.length +\n metadata.length,\n semanticDiscoveryNodesVisited,\n fullReason: null,\n }),\n });\n return { kind: \"patch\", patch };\n },\n captureHead(flushContext) {\n // The head describes the document, not any one root. A root that cannot\n // render still shares the stylesheets its healthy siblings render with.\n if (flushContext.candidateRootCount === 0) resetCaptureFlushCounters();\n const startedAt = Date.now();\n const head = captureHead(options.document);\n headSnapshotMs = Date.now() - startedAt;\n headPerfContext = flushContext;\n return head;\n },\n });\n\n function recordReactCommit(commit: FiberRoot): void {\n if (stopped) return;\n const affectedRootIds: string[] = [];\n for (const [rootId, runtime] of roots) {\n if (runtime.dormant) continue;\n const current = runtime.layerAdapter.resolveCommittedRoot(\n commit,\n runtime.options,\n );\n if (!current || current === runtime.committedFiber) continue;\n if (\n runtime.renderError !== null ||\n readProjectionRenderError(runtime.options.element) !== null\n ) {\n // MutationObserver owns the explicit problem/clear transition. Keep\n // Fiber identity current without racing an ordinary patch against it.\n runtime.committedFiber = current;\n continue;\n }\n if (runtime.committedFiber) {\n runtime.semanticDiscoveryNodesVisited += recordCommitSemanticChanges(\n runtime,\n commit,\n runtime.committedFiber,\n current,\n );\n // React and MutationObserver are independent authorities. Record the\n // commit's semantic regions, then drain already-queued DOM records into\n // the same fixed window. Each stream contributes only its own domain.\n runtime.accumulator?.takePendingDomRecords();\n }\n runtime.committedFiber = current;\n affectedRootIds.push(rootId);\n }\n if (affectedRootIds.length > 0) core.record({ rootIds: affectedRootIds });\n }\n\n function startRootObserver(rootId: string, runtime: RootRuntime<T>): void {\n const unregisterRootObserver = registerCaptureRootObserver();\n try {\n const accumulator = createProjectionRootAccumulator({\n root: runtime.options.element,\n onChange() {\n if (!runtime.options.element.isConnected) {\n makeRootDormant(runtime);\n return;\n }\n const renderError = readProjectionRenderError(\n runtime.options.element,\n );\n if (renderError) {\n if (runtime.renderError === null) {\n runtime.renderError = renderError;\n // Problems are ordered events but do not wait for the hot window.\n core.requestFull(rootId);\n }\n return;\n }\n if (runtime.renderError !== null) {\n runtime.renderError = null;\n // This root's stream resumes on its own baseline. A sibling still\n // in a problem state owns its own recovery and never delays this\n // one.\n core.requestFull(rootId);\n return;\n }\n core.record({ rootIds: [rootId] });\n },\n });\n runtime.accumulator = accumulator;\n runtime.stopObserver = () => {\n try {\n accumulator.stop();\n } finally {\n unregisterRootObserver();\n if (runtime.accumulator === accumulator) runtime.accumulator = null;\n runtime.stopObserver = null;\n }\n };\n } catch (error) {\n unregisterRootObserver();\n throw error;\n }\n }\n\n function createRootRuntime(\n rootOptions: CombinedProjectionRootOptions<T>,\n references: number,\n ): RootRuntime<T> {\n const layerAdapter = createProjectionLayerAdapter(\n rootOptions.layerFramework,\n );\n return {\n options: rootOptions,\n layerAdapter,\n dormant: false,\n accumulator: null,\n stopObserver: null,\n references,\n committedFiber: layerAdapter.resolveCommittedRoot(\n undefined,\n rootOptions,\n ),\n renderError: readProjectionRenderError(rootOptions.element),\n layerProblem: null,\n pendingRegions: new Map(),\n pendingMetadata: new Map(),\n semanticDiscoveryNodesVisited: 0,\n suspendedEpisode: false,\n deferredFullRequest: false,\n };\n }\n\n function makeRootDormant(runtime: RootRuntime<T>): void {\n if (runtime.dormant) return;\n runCleanup(runtime.stopObserver ?? (() => {}));\n runtime.dormant = true;\n runtime.committedFiber = null;\n runtime.renderError = null;\n runtime.layerProblem = null;\n runtime.pendingRegions.clear();\n runtime.pendingMetadata.clear();\n runtime.semanticDiscoveryNodesVisited = 0;\n runtime.suspendedEpisode = false;\n runtime.deferredFullRequest = false;\n }\n\n function rebindRoot(\n rootId: string,\n previous: RootRuntime<T>,\n rootOptions: CombinedProjectionRootOptions<T>,\n references: number,\n ): RootRuntime<T> {\n // A hot-swap can replace the selector's element wholesale. Treat that as\n // element succession: the logical root survives, but Fiber identity must\n // restart from a fresh serializer and a fresh full baseline.\n makeRootDormant(previous);\n const runtime = createRootRuntime(rootOptions, references);\n roots.set(rootId, runtime);\n try {\n startRootObserver(rootId, runtime);\n } catch (error) {\n roots.set(rootId, previous);\n throw error;\n }\n core.requestFull(rootId);\n return runtime;\n }\n\n function reconcileSelectorRoots(): void {\n if (stopped) return;\n for (const [rootId, runtime] of roots) {\n const selector = runtime.options.selector;\n if (selector === undefined) continue;\n if (!runtime.dormant && !runtime.options.element.isConnected) {\n makeRootDormant(runtime);\n }\n if (!runtime.dormant) continue;\n const element = options.document.querySelector(selector);\n if (!element?.isConnected) continue;\n rebindRoot(\n rootId,\n runtime,\n { ...runtime.options, element },\n runtime.references,\n );\n }\n }\n\n function syncRootLifecycleObserver(): void {\n const hasSelectorRoots = Array.from(roots.values()).some(\n (runtime) => runtime.options.selector !== undefined,\n );\n if (hasSelectorRoots && !rootLifecycleObserver) {\n rootLifecycleObserver = new MutationObserver(reconcileSelectorRoots);\n rootLifecycleObserver.observe(options.document, {\n childList: true,\n subtree: true,\n });\n } else if (!hasSelectorRoots && rootLifecycleObserver) {\n rootLifecycleObserver.disconnect();\n rootLifecycleObserver = null;\n }\n }\n\n function resolveOwnedRootOptions(\n rootOptions: CombinedProjectionRootOptions<T>,\n ): CombinedProjectionRootOptions<T> {\n if (rootOptions.selector === undefined) return rootOptions;\n const element = options.document.querySelector(rootOptions.selector);\n if (!element) {\n throw new Error(\n `Projection root selector ${JSON.stringify(rootOptions.selector)} did not match`,\n );\n }\n return element === rootOptions.element\n ? rootOptions\n : { ...rootOptions, element };\n }\n\n function runCleanup(cleanup: () => void): void {\n try {\n cleanup();\n } catch (error) {\n try {\n options.onError?.(error);\n } catch {\n // Cleanup must continue when error reporting itself fails.\n }\n }\n }\n\n let stopReactCommits: () => void = () => {};\n let stopHeadChanges: () => void = () => {};\n try {\n stopReactCommits = reactHook.onCommit(recordReactCommit);\n const headSubscription = getHeadTracker().subscribe(\n options.document,\n () => {\n if (stopped) return;\n // New styling can move a portal without mutating it, so the roots that\n // own portals ride in the same batch as the head that moved them —\n // their capture refreshes any portal frame the styling changed.\n const rootIds: string[] = [];\n for (const [rootId, runtime] of roots) {\n if (runtime.accumulator?.hasPortals()) rootIds.push(rootId);\n }\n core.record({ head: true, rootIds });\n },\n );\n stopHeadChanges = () => headSubscription.unsubscribe();\n } catch (error) {\n runCleanup(stopReactCommits);\n core.stop();\n throw error;\n }\n const unregisterDocumentProducer = registerDocumentCaptureProducer(\n options.document,\n );\n\n return {\n bindSession: (sessionId) => core.bindSession(sessionId),\n watchRoot(requestedRootOptions) {\n if (stopped) throw new Error(\"Projection producer has been stopped\");\n const rootOptions = resolveOwnedRootOptions(requestedRootOptions);\n const existing = roots.get(rootOptions.rootId);\n if (existing) {\n if (\n existing.options.element === rootOptions.element &&\n existing.options.fiberSelector === rootOptions.fiberSelector &&\n existing.options.selector === rootOptions.selector\n ) {\n existing.references += 1;\n return;\n }\n if (\n existing.options.element !== rootOptions.element &&\n !existing.options.element.isConnected\n ) {\n rebindRoot(\n rootOptions.rootId,\n existing,\n rootOptions,\n existing.references + 1,\n );\n syncRootLifecycleObserver();\n return;\n }\n throw new Error(\n `Projection root ${JSON.stringify(rootOptions.rootId)} has conflicting options`,\n );\n }\n const runtime = createRootRuntime(rootOptions, 1);\n roots.set(rootOptions.rootId, runtime);\n try {\n startRootObserver(rootOptions.rootId, runtime);\n core.addRoot(rootOptions.rootId);\n syncRootLifecycleObserver();\n } catch (error) {\n roots.delete(rootOptions.rootId);\n runCleanup(runtime.stopObserver ?? (() => {}));\n syncRootLifecycleObserver();\n throw error;\n }\n },\n unwatchRoot(rootId) {\n const runtime = roots.get(rootId);\n if (!runtime) return;\n runtime.references -= 1;\n if (runtime.references > 0) return;\n roots.delete(rootId);\n core.removeRoot(rootId);\n runCleanup(runtime.stopObserver ?? (() => {}));\n syncRootLifecycleObserver();\n },\n requestFull: (rootId) => core.requestFull(rootId),\n captureSemanticSubtree(rootId, targetFiberId) {\n if (stopped) throw new Error(\"Projection producer has been stopped\");\n const runtime = roots.get(rootId);\n if (!runtime || runtime.dormant || !runtime.options.element.isConnected) {\n return null;\n }\n const current = runtime.layerAdapter.resolveCommittedRoot(\n undefined,\n runtime.options,\n );\n if (!current) return null;\n runtime.committedFiber = current;\n return runtime.layerAdapter.captureSemanticSubtree(\n runtime.options,\n targetFiberId,\n );\n },\n captureRegion(rootId, targetId) {\n if (stopped) throw new Error(\"Projection producer has been stopped\");\n const runtime = roots.get(rootId);\n if (!runtime || runtime.dormant || !runtime.options.element.isConnected) {\n return null;\n }\n return captureProjectionRegion(\n runtime.options.element,\n targetId,\n runtime.accumulator?.portalElements() ?? [],\n );\n },\n stop() {\n if (stopped) return;\n stopped = true;\n core.stop();\n for (const runtime of roots.values()) {\n runCleanup(runtime.stopObserver ?? (() => {}));\n }\n rootLifecycleObserver?.disconnect();\n rootLifecycleObserver = null;\n runCleanup(stopReactCommits);\n runCleanup(stopHeadChanges);\n unregisterDocumentProducer();\n roots.clear();\n },\n };\n}\n\nfunction readProjectionRenderError(\n root: Element,\n): ProjectionRenderErrorProblem | null {\n const sentinel = root.matches('[data-render-error=\"true\"]')\n ? root\n : root.querySelector('[data-render-error=\"true\"]');\n if (!sentinel) return null;\n return {\n reason: \"render-error\",\n message: sentinel.getAttribute(\"data-render-error-message\"),\n };\n}\n\nfunction resolveFiberTarget<T extends EnrichedFiberConstraint>(\n options: CombinedProjectionRootOptions<T>,\n): Element | null {\n return options.fiberSelector\n ? options.element.ownerDocument.querySelector(options.fiberSelector)\n : (options.element.firstElementChild ?? options.element);\n}\n\n/**\n * React's development FiberRoot exposes both the exact scheduling Fibers and\n * their valid before/after generations only while `onCommitFiberRoot` is\n * executing. Discover the affected semantic regions at that boundary, then\n * defer serialization of those regions until the fixed final-state window\n * closes. Later commits can reuse both Fiber generations, so deferring the\n * comparison itself would lose the earlier change.\n *\n * The fallback is the changed watched endpoint itself. It preserves\n * correctness for renderers that do not expose updater tracking, while Tempo's\n * normal development renderer takes the exact K-candidate path.\n */\nfunction recordCommitSemanticChanges<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n commit: FiberRoot,\n previousRoot: Fiber,\n currentRoot: Fiber,\n): number {\n const candidates: Fiber[] = [];\n for (const scheduled of commit.memoizedUpdaters ?? []) {\n const candidate = resolveCommittedFiberOrNull(scheduled);\n if (!candidate) {\n // The commit unmounted its own scheduling component, so there is no\n // representable candidate for it. Its removal still changed the watched\n // tree: fall back to the whole watched root rather than dropping it.\n retainSemanticCandidate(candidates, currentRoot);\n continue;\n }\n if (fiberContains(currentRoot, candidate)) {\n retainSemanticCandidate(candidates, candidate);\n } else if (\n fiberContains(candidate, currentRoot) ||\n fiberContains(scheduled, previousRoot)\n ) {\n // The scheduling component wraps the selected projection boundary. Its\n // exact representable candidate is the watched root, never that outside\n // owner or any of its siblings.\n retainSemanticCandidate(candidates, currentRoot);\n }\n }\n if (candidates.length === 0) retainSemanticCandidate(candidates, currentRoot);\n\n let nodesVisited = 0;\n for (const candidate of candidates) {\n const currentCandidate = resolveCommittedFiberOrNull(candidate);\n if (!currentCandidate) {\n const rootBoundary = nearestProjectionBoundary(runtime, currentRoot);\n if (rootBoundary) addRegion(runtime, rootBoundary);\n continue;\n }\n const previousCandidate = currentCandidate.alternate;\n if (!previousCandidate) {\n const boundary = nearestProjectionBoundary(runtime, currentCandidate);\n if (boundary) addRegion(runtime, boundary);\n continue;\n }\n nodesVisited += collectChangedSemanticFibers(\n previousCandidate,\n currentCandidate,\n runtime,\n );\n }\n return nodesVisited;\n}\n\nfunction retainSemanticCandidate(candidates: Fiber[], candidate: Fiber): void {\n for (const existing of candidates) {\n if (fiberPair(existing, candidate) || fiberContains(existing, candidate)) {\n return;\n }\n }\n for (let index = candidates.length - 1; index >= 0; index -= 1) {\n const existing = candidates[index];\n if (existing && fiberContains(candidate, existing)) {\n candidates.splice(index, 1);\n }\n }\n candidates.push(candidate);\n}\n\nfunction collectChangedSemanticFibers<T extends EnrichedFiberConstraint>(\n previous: Fiber,\n current: Fiber,\n runtime: RootRuntime<T>,\n): number {\n let nodesVisited = 0;\n const visit = (before: Fiber, after: Fiber, boundary: Fiber): void => {\n nodesVisited += 1;\n if (before === after) return;\n const nextBoundary = isProjectionLayerFiber(after) ? after : boundary;\n if (!fiberPair(before, after)) {\n addRegion(runtime, nextBoundary);\n return;\n }\n if (!projectionPropsEqual(before, after, runtime.layerAdapter)) {\n addMetadata(runtime, after, \"fiber\");\n }\n if (before.child === after.child) return;\n\n let oldChild = before.child;\n let newChild = after.child;\n while (oldChild && newChild) {\n if (!fiberPair(oldChild, newChild)) {\n addRegion(runtime, nextBoundary);\n return;\n }\n visit(oldChild, newChild, nextBoundary);\n oldChild = oldChild.sibling;\n newChild = newChild.sibling;\n }\n if (oldChild || newChild) addRegion(runtime, nextBoundary);\n };\n\n const boundary = nearestProjectionBoundary(runtime, current);\n if (boundary) visit(previous, current, boundary);\n return nodesVisited;\n}\n\nfunction fiberPair(left: Fiber, right: Fiber): boolean {\n return left === right || left.alternate === right || right.alternate === left;\n}\n\nfunction nearestProjectionBoundary<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n fiber: Fiber,\n): Fiber | null {\n let current: Fiber | null = fiber;\n while (current) {\n if (isProjectionLayerFiber(current)) return current;\n if (runtime.committedFiber && fiberPair(current, runtime.committedFiber)) {\n return current;\n }\n current = current.return;\n }\n return null;\n}\n\nfunction addElementFiberCandidate<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n element: Element,\n): number {\n const candidate = runtime.layerAdapter.resolveElementCandidate(element);\n if (!candidate) return 0;\n // DOM observation is not evidence that the Fiber tree changed. React's\n // commit stream owns semantic regions. The only intentional crossover is a\n // source annotation stamped directly on a host element, whose exact live\n // value must update that one already-published semantic node.\n addMetadata(runtime, candidate, \"live-host\");\n return 1;\n}\n\nfunction addRegion<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n fiber: Fiber,\n): void {\n const id = runtime.layerAdapter.layerSourceId(fiber);\n if (id === null) return;\n for (const existing of runtime.pendingRegions.values()) {\n if (fiberContains(existing, fiber)) return;\n }\n for (const [existingId, existing] of runtime.pendingRegions) {\n if (fiberContains(fiber, existing))\n runtime.pendingRegions.delete(existingId);\n }\n runtime.pendingRegions.set(id, fiber);\n}\n\nfunction addMetadata<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n fiber: Fiber,\n sourceAnnotations: \"fiber\" | \"live-host\",\n): void {\n if (!isProjectionLayerFiber(fiber)) return;\n const id = runtime.layerAdapter.layerSourceId(fiber);\n if (id === null) return;\n const existing = runtime.pendingMetadata.get(id);\n runtime.pendingMetadata.set(id, {\n fiber,\n sourceAnnotations:\n existing?.sourceAnnotations === \"live-host\" ||\n sourceAnnotations === \"live-host\"\n ? \"live-host\"\n : \"fiber\",\n });\n}\n\nfunction fiberContains(ancestor: Fiber, candidate: Fiber): boolean {\n for (\n let current: Fiber | null = candidate;\n current;\n current = current.return\n ) {\n if (current === ancestor || current.alternate === ancestor) return true;\n }\n return false;\n}\n\nfunction projectionPropsEqual(\n before: Fiber,\n after: Fiber,\n adapter: ProjectionLayerAdapter,\n): boolean {\n const left = adapter.captureMetadata(before)?.props;\n const right = adapter.captureMetadata(after)?.props;\n return layerPropsEqual(left, right);\n}\n\nfunction layerPropsEqual(\n left: ProjectionLayerProps | undefined,\n right: ProjectionLayerProps | undefined,\n): boolean {\n if (left === right) return true;\n if (!left || !right) return left === right;\n const leftEntries = Object.entries(left);\n const rightEntries = Object.entries(right);\n if (leftEntries.length !== rightEntries.length) return false;\n for (const [key, value] of leftEntries) {\n const other = right[key as keyof ProjectionLayerProps];\n if (key === \"style\") {\n if (\n !recordEqual(\n value as Record<string, string>,\n other as Record<string, string>,\n )\n ) {\n return false;\n }\n } else if (value !== other) return false;\n }\n return true;\n}\n\nfunction recordEqual(\n left: Readonly<Record<string, string>> | undefined,\n right: Readonly<Record<string, string>> | undefined,\n): boolean {\n if (left === right) return true;\n if (!left || !right) return left === right;\n const keys = Object.keys(left);\n return (\n keys.length === Object.keys(right).length &&\n keys.every((key) => left[key] === right[key])\n );\n}\n\nfunction captureSemanticRegions<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n): {\n readonly snapshots: ProjectionLayerRegionSnapshot[];\n readonly coveredFibers: ReadonlySet<Fiber>;\n readonly semanticNodesSerialized: number;\n} {\n const snapshots: ProjectionLayerRegionSnapshot[] = [];\n const coveredFibers = new Set<Fiber>();\n let semanticNodesSerialized = 0;\n for (const retainedFiber of runtime.pendingRegions.values()) {\n const fiber = resolveCommittedFiber(retainedFiber);\n if (\n runtime.committedFiber &&\n !fiberContains(runtime.committedFiber, fiber)\n ) {\n continue;\n }\n const serialized = runtime.layerAdapter.captureRegion(fiber);\n if (!serialized) continue;\n snapshots.push(serialized.region);\n coveredFibers.add(fiber);\n semanticNodesSerialized += serialized.semanticNodesSerialized;\n }\n return { snapshots, coveredFibers, semanticNodesSerialized };\n}\n\nfunction captureSemanticMetadata<T extends EnrichedFiberConstraint>(\n runtime: RootRuntime<T>,\n coveredFibers: ReadonlySet<Fiber>,\n): ProjectionLayerMetadataSnapshot[] {\n const snapshots: ProjectionLayerMetadataSnapshot[] = [];\n for (const retained of runtime.pendingMetadata.values()) {\n if (\n Array.from(coveredFibers).some((region) =>\n fiberContains(region, retained.fiber),\n )\n ) {\n continue;\n }\n const fiber = resolveCommittedFiber(retained.fiber);\n if (\n runtime.committedFiber &&\n !fiberContains(runtime.committedFiber, fiber)\n ) {\n continue;\n }\n const metadata = runtime.layerAdapter.captureMetadata(fiber, {\n sourceAnnotations: retained.sourceAnnotations,\n });\n if (metadata) snapshots.push(metadata);\n }\n return snapshots;\n}\n\nfunction patchHtmlChars(patch: ProjectionRootPatch): number {\n let chars = 0;\n for (const change of patch.dom ?? []) {\n if (\n change.kind === \"children\" ||\n change.kind === \"place\" ||\n change.kind === \"text\"\n ) {\n chars += change.html.length;\n }\n }\n for (const portal of patch.portals ?? []) {\n if (portal.kind === \"replace\") chars += portal.html.length;\n }\n return chars;\n}\n\nfunction fullReason(context: ProjectionProducerFlushContext): string {\n return context.initialForSession ? \"initial\" : \"explicit-full\";\n}\n\nfunction makePerf(input: {\n readonly flushContext: ProjectionProducerFlushContext;\n readonly observation: ReturnType<ProjectionRootAccumulator[\"perfSnapshot\"]>;\n readonly snapshotMs: number;\n readonly semanticNodes: number;\n readonly domNodes: number;\n readonly htmlChars: number;\n readonly annotations: number;\n readonly states: number;\n readonly portals: number;\n readonly observedFiles: number;\n readonly candidatesAfter: number;\n readonly semanticDiscoveryNodesVisited?: number;\n readonly fullReason: string | null;\n}): CaptureProducerPerf {\n return buildProjectionCapturePerf({\n flushStartedAt: input.flushContext.flushStartedAt,\n snapshotMs: input.snapshotMs,\n identityMs: 0,\n html: undefined,\n fiberNodeCount: input.semanticNodes,\n changedNodeEstimate: input.observation.candidateTargets,\n fixedWindowTimersOpened: input.flushContext.fixedWindowTimersOpened,\n maxSimultaneousTimers: input.flushContext.maxSimultaneousTimers,\n flushIntervalMs: input.flushContext.flushIntervalMs,\n rawMutationRecords: input.observation.rawMutationRecords,\n rawStateRecords: input.observation.rawStateRecords,\n rawPortalRecords: input.observation.rawPortalRecords,\n candidateTargetsBeforeCoalescing: input.observation.candidateTargets,\n candidateTargetsAfterCoalescing: input.candidatesAfter,\n semanticDiscoveryNodesVisited: input.semanticDiscoveryNodesVisited ?? 0,\n rootsPerBatch: input.flushContext.candidateRootCount,\n fullSnapshotReason: input.fullReason,\n htmlChars: input.htmlChars,\n domNodesSerialized: input.domNodes,\n semanticNodesSerialized: input.semanticNodes,\n annotationTargetsSerialized: input.annotations,\n stateTargetsSerialized: input.states,\n portalTargetsSerialized: input.portals,\n observedFileEntries: input.observedFiles,\n });\n}\n\nfunction aggregateBatchPerf(\n roots: readonly CaptureProducerPerf[],\n head: string | undefined,\n context: ProjectionProducerFlushContext | null,\n capturedHeadMs: number,\n rootsPerBatch: number,\n): CaptureProducerPerf | undefined {\n if (roots.length === 0) {\n if (!context) return undefined;\n return buildProjectionCapturePerf({\n flushStartedAt: context.flushStartedAt,\n snapshotMs: capturedHeadMs,\n identityMs: 0,\n html: undefined,\n head,\n fiberNodeCount: 0,\n changedNodeEstimate: 0,\n fixedWindowTimersOpened: context.fixedWindowTimersOpened,\n maxSimultaneousTimers: context.maxSimultaneousTimers,\n flushIntervalMs: context.flushIntervalMs,\n rawMutationRecords: 0,\n rawStateRecords: 0,\n rawPortalRecords: 0,\n candidateTargetsBeforeCoalescing: 0,\n candidateTargetsAfterCoalescing: 0,\n rootsPerBatch: 0,\n fullSnapshotReason: null,\n domNodesSerialized: 0,\n semanticNodesSerialized: 0,\n annotationTargetsSerialized: 0,\n stateTargetsSerialized: 0,\n portalTargetsSerialized: 0,\n observedFileEntries: 0,\n });\n }\n const sum = (read: (perf: CaptureProducerPerf) => number): number =>\n roots.reduce((total, perf) => total + read(perf), 0);\n const max = (read: (perf: CaptureProducerPerf) => number): number =>\n Math.max(...roots.map(read));\n const first = roots[0];\n if (!first) return undefined;\n const flushStartedAt = context?.flushStartedAt ?? first.flushStartedAt;\n const reasons = new Set(roots.map((perf) => perf.fullSnapshotReason));\n return {\n flushStartedAt,\n flushMs: Date.now() - flushStartedAt,\n snapshotMs: sum((perf) => perf.snapshotMs) + capturedHeadMs,\n identityMs: sum((perf) => perf.identityMs),\n identityNodesVisited: sum((perf) => perf.identityNodesVisited),\n sourceVersionDomScanNodes: sum((perf) => perf.sourceVersionDomScanNodes),\n sourceVersionFiberSerializeNodes: sum(\n (perf) => perf.sourceVersionFiberSerializeNodes,\n ),\n sourceVersionFiberReductionNodes: sum(\n (perf) => perf.sourceVersionFiberReductionNodes,\n ),\n sourceVersionFallbackScanNodes: sum(\n (perf) => perf.sourceVersionFallbackScanNodes,\n ),\n sourceVersionScanNodes: sum((perf) => perf.sourceVersionScanNodes),\n styleReadCount: sum((perf) => perf.styleReadCount),\n htmlChars: sum((perf) => perf.htmlChars),\n headChars: head?.length ?? 0,\n fiberNodeCount: sum((perf) => perf.fiberNodeCount),\n changedNodeEstimate: sum((perf) => perf.changedNodeEstimate),\n activeDocumentProducers: max((perf) => perf.activeDocumentProducers),\n activeRootObservers: max((perf) => perf.activeRootObservers),\n headObservers: max((perf) => perf.headObservers),\n headSubscriptions: max((perf) => perf.headSubscriptions),\n reactCommitSubscriptions: max((perf) => perf.reactCommitSubscriptions),\n fixedWindowTimersOpened:\n context?.fixedWindowTimersOpened ?? first.fixedWindowTimersOpened,\n maxSimultaneousTimers:\n context?.maxSimultaneousTimers ?? first.maxSimultaneousTimers,\n flushIntervalMs: context?.flushIntervalMs ?? first.flushIntervalMs,\n rawMutationRecords: sum((perf) => perf.rawMutationRecords),\n rawStateRecords: sum((perf) => perf.rawStateRecords),\n rawPortalRecords: sum((perf) => perf.rawPortalRecords),\n producerCandidateNodes: sum((perf) => perf.producerCandidateNodes),\n producerVisitedNodes: sum((perf) => perf.producerVisitedNodes),\n candidateTargetsBeforeCoalescing: sum(\n (perf) => perf.candidateTargetsBeforeCoalescing,\n ),\n candidateTargetsAfterCoalescing: sum(\n (perf) => perf.candidateTargetsAfterCoalescing,\n ),\n semanticDiscoveryNodesVisited: sum(\n (perf) => perf.semanticDiscoveryNodesVisited ?? 0,\n ),\n domNodesSerialized: roots.some((perf) => perf.domNodesSerialized === null)\n ? null\n : sum((perf) => perf.domNodesSerialized ?? 0),\n semanticNodesSerialized: sum((perf) => perf.semanticNodesSerialized),\n annotationTargetsSerialized: sum(\n (perf) => perf.annotationTargetsSerialized,\n ),\n stateTargetsSerialized: sum((perf) => perf.stateTargetsSerialized),\n portalTargetsSerialized: sum((perf) => perf.portalTargetsSerialized),\n headSerializations: head === undefined ? 0 : 1,\n observedFileEntries: sum((perf) => perf.observedFileEntries),\n batchesEmitted: 1,\n rootsPerBatch,\n fullSnapshotReason:\n reasons.size === 1 ? first.fullSnapshotReason : \"mixed-full\",\n };\n}\n","/**\n * The semantic-layer authority selected for one projection watcher lifetime.\n *\n * This is deliberately distinct from project-level `uiFramework`: callers\n * resolve product configuration and storyboard kind before entering the\n * projection module. The producer never infers a framework from the DOM or\n * installed runtimes.\n */\nexport type LayerFramework = \"react\" | \"svelte\" | \"dom\";\n\nexport function isLayerFramework(value: unknown): value is LayerFramework {\n return value === \"react\" || value === \"svelte\" || value === \"dom\";\n}\n","/**\n * Projection Snapshot\n *\n * Shared one-shot snapshot used by:\n * - capture APIs (single event)\n * - watch initial emission (first event in stream)\n */\n\nimport { findOwnedPortalRoots } from \"../shared/portal-tracker\";\nimport {\n captureWithSupplementalRoots,\n collectElementStates,\n removeScriptTags,\n} from \"./capture\";\nimport type { DomCapture, PortalUpdate } from \"./types\";\nimport { captureHead } from \"./watch-head\";\nimport {\n capturePortalCoordinateSpace,\n getOrAssignPortalId,\n} from \"./watch-portal\";\n\nexport function captureProjectionSnapshot(\n element: Element,\n supplementalRoots?: readonly Element[],\n): DomCapture {\n return {\n ...captureProjectionBodySnapshot(element, supplementalRoots),\n head: captureHead(element.ownerDocument ?? document),\n };\n}\n\n/**\n * Capture one complete root without re-reading document-scoped head state.\n *\n * A document producer calls this once per dirty root and captures the head at\n * most once for the enclosing batch. The legacy one-shot API above remains\n * self-contained for callers that truly need a single root plus head.\n */\nexport function captureProjectionBodySnapshot(\n element: Element,\n supplementalRoots?: readonly Element[],\n): Omit<DomCapture, \"head\"> {\n const { updates: portals, elements: portalElements } = supplementalRoots\n ? captureKnownPortals(supplementalRoots, element)\n : capturePortals(element);\n const baseCapture = captureWithSupplementalRoots(element, portalElements);\n\n return {\n ...baseCapture,\n portalsComplete: true,\n ...(portals.length > 0 ? { portals } : {}),\n };\n}\n\nexport function collectProjectionPortalElements(root: Element): Element[] {\n return capturePortals(root).elements;\n}\n\nfunction captureKnownPortals(\n roots: readonly Element[],\n ownerRoot: Element,\n): CapturedPortals {\n const updates: PortalUpdate[] = [];\n const elements: Element[] = [];\n for (const root of roots) {\n if (!root.isConnected) continue;\n const id = getOrAssignPortalId(root);\n const coordinateSpace = capturePortalCoordinateSpace(ownerRoot, root);\n updates.push({\n id,\n selector: \"\",\n html: removeScriptTags(root.outerHTML),\n states: collectElementStates(root, { includeDocumentScroll: false }),\n ...(coordinateSpace && { coordinateSpace }),\n });\n elements.push(root);\n }\n return { updates, elements };\n}\n\ninterface CapturedPortals {\n updates: PortalUpdate[];\n /** Live portal root elements, for declared-facts computation. */\n elements: Element[];\n}\n\nfunction capturePortals(root: Element): CapturedPortals {\n return captureKnownPortals(findOwnedPortalRoots(root), root);\n}\n","import { getFiberFromElement } from \"../fiber/capture\";\nimport { FiberTag } from \"../fiber/react-types\";\nimport {\n isTransientFiberResolutionError,\n resolveCommittedFiber,\n} from \"../fiber/serialize\";\nimport { countIdentityNodeVisited } from \"../shared/capture-perf\";\nimport type {\n EnrichedFiberConstraint,\n RenderHostIdentity,\n RenderHostIdentityDeclaration,\n} from \"./types\";\n\nconst SOURCE_IDENTITY_KEYS = [\n \"data-tempo-filepath\",\n \"data-tempo-position\",\n \"data-tempo-modifiedts\",\n \"data-tempo-source-version\",\n \"data-tempo-html-filepath\",\n \"data-tempo-html-offset\",\n \"data-tempo-html-modifiedts\",\n \"data-tempo-html-source-version\",\n] as const;\n\ntype SourceIdentityKey = (typeof SOURCE_IDENTITY_KEYS)[number];\n\nfunction normalizeIdentityValue(value: unknown): string | undefined {\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return String(value);\n }\n return undefined;\n}\n\nfunction sourceIdentityFromProps(\n props: Readonly<Record<string, unknown>> | undefined,\n): Partial<Record<SourceIdentityKey, string>> | undefined {\n if (!props) return undefined;\n const source: Partial<Record<SourceIdentityKey, string>> = {};\n for (const key of SOURCE_IDENTITY_KEYS) {\n const value = normalizeIdentityValue(props[key]);\n if (value !== undefined) source[key] = value;\n }\n return Object.keys(source).length > 0 ? source : undefined;\n}\n\nfunction sourceIdentityFromElement(\n element: Element,\n): Partial<Record<SourceIdentityKey, string>> | undefined {\n const source: Partial<Record<SourceIdentityKey, string>> = {};\n for (const key of SOURCE_IDENTITY_KEYS) {\n const value = element.getAttribute(key);\n if (value !== null) source[key] = value;\n }\n return Object.keys(source).length > 0 ? source : undefined;\n}\n\nfunction isContentEditableBoundary(\n props: Readonly<Record<string, unknown>> | undefined,\n): boolean {\n if (!props) return false;\n return (\n (props.contentEditable !== null && props.contentEditable !== undefined) ||\n (props.contenteditable !== null && props.contenteditable !== undefined)\n );\n}\n\nfunction finalizeDeclaration(\n hosts: RenderHostIdentity[],\n missingDomIdCount: number,\n): RenderHostIdentityDeclaration {\n const counts = new Map<string, number>();\n for (const host of hosts) {\n counts.set(host.domId, (counts.get(host.domId) ?? 0) + 1);\n }\n const duplicateDomIds = [...counts]\n .filter(([, count]) => count > 1)\n .map(([domId]) => domId)\n .sort();\n hosts.sort((left, right) => left.domId.localeCompare(right.domId));\n return { hosts, missingDomIdCount, duplicateDomIds };\n}\n\nexport function declareFiberHostIdentity<T extends EnrichedFiberConstraint>(\n tree: T,\n): RenderHostIdentityDeclaration {\n const hosts: RenderHostIdentity[] = [];\n let missingDomIdCount = 0;\n const visit = (node: EnrichedFiberConstraint): void => {\n countIdentityNodeVisited();\n if (node.insideContentEditable) return;\n const renderNode = node as EnrichedFiberConstraint & {\n tag?: number;\n name?: string;\n };\n if (renderNode.tag === FiberTag.HostComponent) {\n if (!node.domId) {\n missingDomIdCount += 1;\n } else {\n hosts.push({\n domId: node.domId,\n tag: renderNode.name?.toLowerCase() ?? \"\",\n source: sourceIdentityFromProps(node.props),\n });\n }\n if (isContentEditableBoundary(node.props)) return;\n }\n for (const child of node.children) {\n visit(child as EnrichedFiberConstraint);\n }\n };\n visit(tree);\n return finalizeDeclaration(hosts, missingDomIdCount);\n}\n\nexport function declareDomHostIdentity(\n captureRoot: Element,\n supplementalRoots: readonly Element[],\n): RenderHostIdentityDeclaration {\n const hosts: RenderHostIdentity[] = [];\n let missingDomIdCount = 0;\n const seenElements = new Set<Element>();\n const visit = (element: Element): void => {\n if (seenElements.has(element)) return;\n seenElements.add(element);\n countIdentityNodeVisited();\n const rawFiber = getFiberFromElement(element);\n if (rawFiber) {\n try {\n const fiber = resolveCommittedFiber(rawFiber);\n if (\n fiber.tag === FiberTag.HostComponent &&\n fiber.stateNode === element\n ) {\n const domId = element.getAttribute(\"data-dom-id\");\n if (!domId) {\n missingDomIdCount += 1;\n } else {\n hosts.push({\n domId,\n tag: element.localName.toLowerCase(),\n source: sourceIdentityFromElement(element),\n });\n }\n }\n } catch (error) {\n if (!isTransientFiberResolutionError(error)) throw error;\n // React can detach an alternate between DOM enumeration and this\n // identity read. Make the atomic candidate incomplete instead of\n // surfacing capture internals as an application runtime error.\n missingDomIdCount += 1;\n }\n }\n if (element.getAttribute(\"contenteditable\") !== null) return;\n for (const child of element.children) visit(child);\n };\n // The root snapshot serializes `captureRoot.innerHTML`, so the root itself\n // is outside the HTML arm even when it is a React-owned CanvasHost wrapper.\n // Portal snapshots use `outerHTML` and therefore include their roots.\n for (const child of captureRoot.children) visit(child);\n for (const root of supplementalRoots) visit(root);\n return finalizeDeclaration(hosts, missingDomIdCount);\n}\n\nexport function hostIdentityDeclarationsMatch(\n left: RenderHostIdentityDeclaration,\n right: RenderHostIdentityDeclaration,\n): boolean {\n if (\n left.missingDomIdCount !== 0 ||\n right.missingDomIdCount !== 0 ||\n left.duplicateDomIds.length !== 0 ||\n right.duplicateDomIds.length !== 0 ||\n left.hosts.length !== right.hosts.length\n ) {\n return false;\n }\n for (let index = 0; index < left.hosts.length; index += 1) {\n const leftHost = left.hosts[index];\n const rightHost = right.hosts[index];\n if (\n !leftHost ||\n !rightHost ||\n leftHost.domId !== rightHost.domId ||\n leftHost.tag !== rightHost.tag ||\n JSON.stringify(leftHost.source ?? {}) !==\n JSON.stringify(rightHost.source ?? {})\n ) {\n return false;\n }\n }\n return true;\n}\n","/**\n * Declared Capture Facts — fiber half\n *\n * The layers half of a combined capture declares its own observed source\n * versions, computed by walking the enriched fiber tree's annotated props\n * (the same props the DOM half reads as attributes). See\n * specs/canvas-determinism.md §4.\n */\n\nimport type { DomCapture } from \"../html/types\";\nimport type { CombinedCapture, EnrichedFiberConstraint } from \"./types\";\nimport {\n declareDomHostIdentity,\n declareFiberHostIdentity,\n hostIdentityDeclarationsMatch,\n} from \"./render-identity\";\n\n/** Both per-file version signals a fiber walk observes, mirroring\n * `computeDeclaredFacts` on the DOM side: the numeric mtime (`observedVersions`)\n * and the content-version token (`observedSourceVersions`, co-located with the\n * MAX-mtime element). Keys in both are the raw stamped filepath spellings\n * (consumers canonicalize on read). */\nexport interface FiberObservedVersions {\n observedVersions: Record<string, number>;\n observedSourceVersions: Record<string, string>;\n}\n\nexport interface RenderDeclarationScope {\n captureRoot: Element;\n supplementalRoots: readonly Element[];\n renderMode?: \"static-dom\";\n}\n\nexport function createRenderDeclarationScope(\n captureRoot: Element,\n supplementalRoots: readonly Element[],\n): RenderDeclarationScope {\n return {\n captureRoot,\n supplementalRoots,\n ...(captureRoot.getAttribute(\"data-tempo-render-mode\") === \"static-dom\" && {\n renderMode: \"static-dom\" as const,\n }),\n };\n}\n\n/**\n * Per-file MAX `data-tempo-modifiedts` / `data-tempo-html-modifiedts` among\n * a walked fiber tree's annotated props, across BOTH namespaces, plus the\n * `data-tempo-source-version` / `data-tempo-html-source-version` token\n * co-located with each file's newest (MAX-mtime) node. Keys are the raw\n * stamped filepath spellings (consumers canonicalize on read), mirroring\n * `computeDeclaredFacts` on the DOM side.\n */\nexport function computeObservedVersionsFromFiber<\n T extends EnrichedFiberConstraint,\n>(tree: T): FiberObservedVersions {\n const observedVersions: Record<string, number> = {};\n const observedSourceVersions: Record<string, string> = {};\n\n const record = (\n filepath: unknown,\n modifiedTsRaw: unknown,\n sourceVersionRaw: unknown,\n ): void => {\n if (typeof filepath !== \"string\" || filepath.length === 0) return;\n const modifiedTs =\n typeof modifiedTsRaw === \"number\"\n ? modifiedTsRaw\n : typeof modifiedTsRaw === \"string\"\n ? Number(modifiedTsRaw)\n : NaN;\n if (Number.isNaN(modifiedTs)) return;\n const existing = observedVersions[filepath];\n if (existing === undefined || modifiedTs > existing) {\n observedVersions[filepath] = modifiedTs;\n // The token rides the file's newest render — same co-location rule the\n // DOM-side walker uses. A newest node without a token clears any stale\n // token from an older render (old-SDK / mid-HMR mixed tree).\n if (typeof sourceVersionRaw === \"string\" && sourceVersionRaw.length > 0) {\n observedSourceVersions[filepath] = sourceVersionRaw;\n } else {\n delete observedSourceVersions[filepath];\n }\n }\n };\n\n const visit = (node: EnrichedFiberConstraint): void => {\n const props = node.props;\n record(\n props?.[\"data-tempo-filepath\"],\n props?.[\"data-tempo-modifiedts\"],\n props?.[\"data-tempo-source-version\"],\n );\n record(\n props?.[\"data-tempo-html-filepath\"],\n props?.[\"data-tempo-html-modifiedts\"],\n props?.[\"data-tempo-html-source-version\"],\n );\n for (const child of node.children) {\n visit(child as EnrichedFiberConstraint);\n }\n };\n\n visit(tree);\n return { observedVersions, observedSourceVersions };\n}\n\n/** Build the completeness facts shared by standing and one-shot captures.\n * `undefined` means the fiber arm was not sampled; `null` means it was sampled\n * and no root existed. Static DOM is authoritative only for a full HTML scope\n * in a document where React never registered a renderer. */\nexport function computeRenderDeclarations<T extends EnrichedFiberConstraint>(\n fiber: T | null | undefined,\n html: DomCapture | undefined,\n hasReactRenderer: boolean,\n document?: Document | null,\n identityScope?: RenderDeclarationScope,\n): Pick<\n CombinedCapture<T>,\n \"fiberDeclared\" | \"renderDeclared\" | \"renderIdentity\"\n> {\n const domIdentity = identityScope\n ? declareDomHostIdentity(\n identityScope.captureRoot,\n identityScope.supplementalRoots,\n )\n : undefined;\n const fiberIdentity = fiber ? declareFiberHostIdentity(fiber) : undefined;\n const identityMatching =\n domIdentity && fiberIdentity\n ? hostIdentityDeclarationsMatch(domIdentity, fiberIdentity)\n : undefined;\n return {\n ...(fiber !== undefined && {\n fiberDeclared: fiber\n ? {\n complete: true as const,\n ...(document && {\n domConsistent:\n identityMatching ??\n fiberHostIdentitiesAreLive(fiber, document),\n }),\n ...(fiberIdentity && { hostIdentity: fiberIdentity }),\n ...computeObservedVersionsFromFiber(fiber),\n }\n : null,\n }),\n ...(fiber\n ? { renderDeclared: { complete: true, kind: \"fiber\" } as const }\n : (identityScope?.renderMode === \"static-dom\" || !hasReactRenderer) &&\n html?.declared.complete === true\n ? {\n renderDeclared: {\n complete: true,\n kind: \"static-dom\",\n } as const,\n }\n : {}),\n ...(domIdentity && {\n renderIdentity: {\n dom: domIdentity,\n ...(fiberIdentity && { fiber: fiberIdentity }),\n ...(identityMatching !== undefined && {\n matching: identityMatching,\n }),\n },\n }),\n };\n}\n\n/** A React commit can leave `FiberRoot.current` describing host nodes that\n * have already been detached. A fiber arm is visible proof only when every\n * host identity it serialized still exists in the producer's live document. */\nexport function fiberHostIdentitiesAreLive<T extends EnrichedFiberConstraint>(\n fiber: T,\n document: Document,\n): boolean {\n const liveDomIds = new Set(\n Array.from(document.querySelectorAll<HTMLElement>(\"[data-dom-id]\"))\n .filter((element) => element.isConnected)\n .map((element) => element.getAttribute(\"data-dom-id\"))\n .filter((domId): domId is string => domId !== null),\n );\n const seenFiberDomIds = new Set<string>();\n const visit = (node: EnrichedFiberConstraint): boolean => {\n if (node.domId) {\n if (seenFiberDomIds.has(node.domId) || !liveDomIds.has(node.domId)) {\n return false;\n }\n seenFiberDomIds.add(node.domId);\n }\n return node.children.every((child) =>\n visit(child as EnrichedFiberConstraint),\n );\n };\n return visit(fiber);\n}\n","/**\n * Layout Kind\n *\n * Classifies a DOM element's container layout based on its computed styles,\n * and provides matching SVG icon markup for each kind.\n *\n * The four kinds mirror the \"draw\" tools in a typical design canvas:\n * - grid → display: grid\n * - row → flex stacking children vertically (flex-direction: column)\n * - column → flex stacking children horizontally (flex-direction: row)\n * - div → any other element that still counts as a layout parent\n * (position: relative|sticky|absolute)\n *\n * Plain statically positioned non-flex/non-grid elements are NOT layout\n * parents — drawing a child into them has no meaningful placement behavior,\n * so they return null.\n *\n * Naming follows the stacking metaphor: a \"row\" is one of a set of rows stacked\n * vertically, and a \"column\" is one of a set of columns placed side-by-side.\n */\n\nexport type ElementLayoutKind = \"row\" | \"column\" | \"grid\" | \"div\";\n\nexport function getElementLayoutKind(\n el: Element,\n style: CSSStyleDeclaration = getComputedStyle(el),\n): ElementLayoutKind | null {\n if (/grid/.test(style.display)) return \"grid\";\n if (/flex/.test(style.display)) {\n return /^column/.test(style.flexDirection) ? \"row\" : \"column\";\n }\n if (\n style.position === \"relative\" ||\n style.position === \"sticky\" ||\n style.position === \"absolute\"\n ) {\n return \"div\";\n }\n return null;\n}\n\n/** Static 12×12 SVG markup for each layout kind, stroked with `currentColor`\n * so the pill's text color drives the icon color. Shapes mirror the canvas\n * draw-tool icons (div / row / column / grid) — a filled rectangle split\n * into one, two stacked, two side-by-side, or four quadrants. */\nexport const LAYOUT_KIND_SVG: Record<ElementLayoutKind, string> = {\n div:\n '<svg width=\"12\" height=\"12\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">' +\n '<rect x=\"1.5\" y=\"1.5\" width=\"13\" height=\"13\" rx=\"3\" stroke=\"currentColor\"/>' +\n \"</svg>\",\n row:\n '<svg width=\"12\" height=\"12\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">' +\n '<rect x=\"1.5\" y=\"1.5\" width=\"13\" height=\"5.75\" rx=\"2\" stroke=\"currentColor\"/>' +\n '<rect x=\"1.5\" y=\"8.75\" width=\"13\" height=\"5.75\" rx=\"2\" stroke=\"currentColor\"/>' +\n \"</svg>\",\n column:\n '<svg width=\"12\" height=\"12\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">' +\n '<rect x=\"1.5\" y=\"1.5\" width=\"5.75\" height=\"13\" rx=\"2\" stroke=\"currentColor\"/>' +\n '<rect x=\"8.75\" y=\"1.5\" width=\"5.75\" height=\"13\" rx=\"2\" stroke=\"currentColor\"/>' +\n \"</svg>\",\n grid:\n '<svg width=\"12\" height=\"12\" viewBox=\"0 0 16 16\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">' +\n '<rect x=\"1.5\" y=\"1.5\" width=\"5.75\" height=\"5.75\" rx=\"1.5\" stroke=\"currentColor\"/>' +\n '<rect x=\"8.75\" y=\"1.5\" width=\"5.75\" height=\"5.75\" rx=\"1.5\" stroke=\"currentColor\"/>' +\n '<rect x=\"1.5\" y=\"8.75\" width=\"5.75\" height=\"5.75\" rx=\"1.5\" stroke=\"currentColor\"/>' +\n '<rect x=\"8.75\" y=\"8.75\" width=\"5.75\" height=\"5.75\" rx=\"1.5\" stroke=\"currentColor\"/>' +\n \"</svg>\",\n};\n","/**\n * Enriched Fiber Serializer\n *\n * Extends the default serializer with domId extraction from HostComponent\n * fibers and sanitized props from all component fibers.\n *\n * The domId comes from the `data-dom-id` attribute that the HTML watcher's\n * MutationObserver assigns to all DOM elements. By the time the debounce\n * fires and captureTree calls this serializer, the MutationObserver has\n * already assigned IDs (MutationObserver fires as microtask, debounce fires\n * as macrotask via setTimeout).\n */\n\nimport { getElementLayoutKind } from \"../../element-overlay/render/layout-kind\";\nimport { countCaptureStyleRead } from \"../shared/capture-perf\";\nimport type { SerializeFn } from \"../fiber/types\";\nimport type { Fiber } from \"../fiber/react-types\";\nimport type { EnrichedFiberNode } from \"./types\";\nimport {\n getDisplayName,\n getTag,\n getDomElement,\n sanitizeProps,\n getProps,\n} from \"../fiber/serialize\";\nimport { DOM_ID_ATTR } from \"../html/watch-dom\";\n\nlet nextFiberId = 1;\nlet fiberIdMap = new WeakMap<Fiber, string>();\n\n/**\n * Returns a stable ID for a fiber across re-renders.\n * React alternates current/work-in-progress fibers, so both alternates share one ID.\n */\nexport function getFiberId(fiber: Fiber): string {\n let id = fiberIdMap.get(fiber);\n if (id) return id;\n\n if (fiber.alternate) {\n id = fiberIdMap.get(fiber.alternate);\n if (id) {\n fiberIdMap.set(fiber, id);\n return id;\n }\n }\n\n id = String(nextFiberId++);\n fiberIdMap.set(fiber, id);\n if (fiber.alternate) {\n fiberIdMap.set(fiber.alternate, id);\n }\n return id;\n}\n\n/**\n * Test-only state reset for deterministic fiberId assertions.\n */\nexport function _resetFiberIdStateForTesting(): void {\n nextFiberId = 1;\n fiberIdMap = new WeakMap<Fiber, string>();\n}\n\n/**\n * Default enriched serializer for the combined module.\n *\n * Produces nodes with name, tag, domId (for HostComponents), and sanitized props.\n *\n * @example\n * ```ts\n * // Extend with additional fields:\n * interface MyNode extends EnrichedFiberNode { key?: string; }\n * const mySerialize: SerializeFn<MyNode> = (fiber) => ({\n * ...enrichedSerialize(fiber),\n * key: fiber.key ?? undefined,\n * });\n * ```\n */\n/**\n * react-native-web View/Text host components carry Tempo's source annotations in\n * a `dataSet` object instead of flat `data-*` props — RNW only flattens\n * dataSet→data-* onto the host DOM node, so the component fiber still reports\n * `dataSet`. Lift the `tempo*` keys out to flat `data-tempo-*` here, at capture,\n * so every downstream consumer (source extraction, modifiedts tracking, layer\n * building) sees one uniform shape and never has to know about `dataSet`. User\n * dataSet keys are preserved.\n */\nfunction normalizeTempoDataSet(\n props: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n const dataSet = props?.dataSet;\n if (!props || !dataSet || typeof dataSet !== \"object\") return props;\n\n let extracted: Record<string, unknown> | null = null;\n let remaining: Record<string, unknown> | null = null;\n for (const [key, value] of Object.entries(\n dataSet as Record<string, unknown>,\n )) {\n if (key.startsWith(\"tempo\")) {\n // \"tempoFilepath\" -> \"data-tempo-filepath\" (matches RNW's hyphenation).\n (extracted ??= {})[\n `data-${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`\n ] = value;\n } else {\n (remaining ??= {})[key] = value;\n }\n }\n if (!extracted) return props;\n\n const out = { ...props, ...extracted };\n if (remaining) out.dataSet = remaining;\n else delete out.dataSet;\n return out;\n}\n\nexport const enrichedSerialize: SerializeFn<EnrichedFiberNode> = (fiber) => {\n const domElement = getDomElement(fiber);\n return {\n fiberId: getFiberId(fiber),\n name: getDisplayName(fiber),\n tag: getTag(fiber),\n ...(hasContextDependencies(fiber) && { hasContextDependencies: true }),\n ...(domElement && {\n domId: domElement.getAttribute(DOM_ID_ATTR) ?? undefined,\n ...(hasContentEditableAncestor(domElement) && {\n insideContentEditable: true,\n }),\n layoutKind: layoutKindWithCountedStyleRead(domElement),\n }),\n props: normalizeTempoDataSet(sanitizeProps(getProps(fiber))),\n };\n};\n\n/** getElementLayoutKind's default style parameter is one getComputedStyle\n * call per host element — counted as a capture-path style read. */\nfunction layoutKindWithCountedStyleRead(element: Element) {\n countCaptureStyleRead();\n return getElementLayoutKind(element) ?? undefined;\n}\n\nfunction hasContentEditableAncestor(element: Element): boolean {\n let current = element.parentElement;\n while (current) {\n if (current.getAttribute(\"contenteditable\") !== null) return true;\n current = current.parentElement;\n }\n return false;\n}\n\nfunction hasContextDependencies(fiber: Fiber): boolean {\n const dependencies = fiber.dependencies;\n if (!dependencies || typeof dependencies !== \"object\") {\n return false;\n }\n\n return Boolean(\n (dependencies as { firstContext?: unknown }).firstContext,\n );\n}\n","import type { FiberRoot } from \"../fiber/react-types\";\nimport { serializeTree } from \"../fiber/serialize\";\nimport type { FiberTagValue, SerializeFn } from \"../fiber/types\";\nimport { captureTree, getCommittedFiberRoots } from \"../fiber/watch\";\nimport type { EnrichedFiberConstraint } from \"./types\";\n\nconst shouldHideFiberNode = (\n node: { props?: Record<string, unknown> },\n hideFiberProp: string | undefined,\n): boolean => {\n if (!hideFiberProp) {\n return false;\n }\n\n const value = node.props?.[hideFiberProp];\n return value === true || value === \"true\";\n};\n\nconst filterHiddenFiberNode = <T extends EnrichedFiberConstraint>(\n node: T,\n hideFiberProp: string,\n): T[] => {\n const children = node.children.flatMap((child) =>\n filterHiddenFiberNode(child as T, hideFiberProp),\n );\n return shouldHideFiberNode(node, hideFiberProp)\n ? children\n : [{ ...node, children } as T];\n};\n\nexport const filterHiddenFiberTree = <T extends EnrichedFiberConstraint>(\n tree: T | null,\n hideFiberProp?: string,\n): T | null => {\n if (!tree || !hideFiberProp) {\n return tree;\n }\n\n return filterHiddenFiberNode(tree, hideFiberProp)[0] ?? null;\n};\n\nexport const captureCombinedFiberTree = <\n T extends EnrichedFiberConstraint,\n>(options: {\n serialize: SerializeFn<T>;\n selector?: string;\n /** DOM scope whose contained React roots make up one document-level render. */\n rootElement?: Element;\n tags?: FiberTagValue[];\n hideFiberProp?: string;\n}): T | null => {\n const rootElement = options.rootElement;\n if (options.selector || !rootElement) {\n const tree = captureTree<T>({\n serialize: options.serialize,\n selector: options.selector,\n tags: options.tags,\n });\n return filterHiddenFiberTree(tree, options.hideFiberProp);\n }\n\n const roots = getCommittedFiberRoots().filter((root) =>\n rootBelongsToElement(root, rootElement),\n );\n const firstRoot = roots[0];\n if (!firstRoot) return null;\n const trees = roots\n .flatMap((root) =>\n serializeRootBranches(root, options.serialize, options.tags),\n )\n .flatMap((tree) =>\n options.hideFiberProp\n ? filterHiddenFiberNode(tree, options.hideFiberProp)\n : [tree],\n );\n\n if (trees.length === 0) {\n return {\n ...options.serialize(firstRoot.current),\n domId: undefined,\n props: undefined,\n children: [],\n } as unknown as T;\n }\n if (trees.length === 1) return trees[0] ?? null;\n\n // CombinedCapture has one tree-shaped layers arm. Use a real serialized\n // HostRoot as its fragment-like aggregate and place each independent root\n // below it. Consumers therefore see every root without inventing an opaque\n // second wire shape or falsely declaring one root to be the whole document.\n return {\n ...options.serialize(firstRoot.current),\n fiberId: \"__tempo_document_fiber_roots__\",\n domId: undefined,\n props: undefined,\n children: trees,\n } as unknown as T;\n};\n\nfunction rootBelongsToElement(root: FiberRoot, element: Element): boolean {\n const container = root.containerInfo;\n return container === element || element.contains(container);\n}\n\nfunction serializeRootBranches<T extends EnrichedFiberConstraint>(\n root: FiberRoot,\n serialize: SerializeFn<T>,\n tags: FiberTagValue[] | undefined,\n): T[] {\n const tagSet = tags && tags.length > 0 ? new Set(tags) : null;\n const branches: T[] = [];\n for (let fiber = root.current.child; fiber; fiber = fiber.sibling) {\n const tree = serializeTree(fiber, serialize);\n if (!tree) continue;\n branches.push(...filterTreeBranches(tree, tagSet));\n }\n return branches;\n}\n\n/** Filter one serialized branch while preserving every promoted child. The\n * generic fiber utility returns a single tree and therefore cannot represent\n * an excluded Fragment/HostRoot with multiple included children. */\nfunction filterTreeBranches<T extends EnrichedFiberConstraint>(\n tree: T,\n tags: ReadonlySet<FiberTagValue> | null,\n): T[] {\n if (!tags || !(\"tag\" in tree)) return [tree];\n const children = tree.children.flatMap((child) =>\n filterTreeBranches(child as T, tags),\n );\n return tags.has((tree as T & { tag: FiberTagValue }).tag)\n ? [{ ...tree, children } as T]\n : children;\n}\n","/**\n * Identity of this JS realm (one document evaluation), stamped on every\n * emitted capture. A consumer seeing the epoch change across captures of the\n * same logical watch has OBSERVED a document replacement — the signal is\n * carried by the capture itself, so it survives watch re-creation, relay\n * coalescing, and frame discards that strip replay-time markers like\n * `producerReset`.\n */\nexport const REALM_DOCUMENT_EPOCH = `${Date.now().toString(36)}-${Math.random()\n .toString(36)\n .slice(2, 10)}`;\n\nlet nextCaptureSequence = 0;\n\n/** Monotonic across every combined watcher and one-shot capture in this realm.\n * Watch restarts must not reset ordering: a delayed capture from the retired\n * watcher can otherwise arrive after and overwrite newer visible pixels. */\nexport function nextRealmCaptureSequence(): number {\n return nextCaptureSequence++;\n}\n","/**\n * Reverse-skew adapter for pre-projection-batch interact frames.\n *\n * Current Tempo clients consume the document producer's closed, regional\n * ProjectionBatch stream directly. Deployed older clients still ask the\n * newest workspace SDK for `start-combined-watcher`, so this adapter uses the\n * document producer only as a change clock and materializes the old complete\n * CombinedCapture envelope at that one compatibility boundary.\n */\n\nimport type { FiberTagValue, SerializeFn } from \"../fiber/types\";\nimport { initHook } from \"../fiber/watch\";\nimport {\n captureProjectionSnapshot,\n collectProjectionPortalElements,\n} from \"../html/snapshot\";\nimport type { DomCapture } from \"../html/types\";\nimport {\n computeRenderDeclarations,\n createRenderDeclarationScope,\n} from \"./declared-facts\";\nimport {\n createCombinedDocumentProducer,\n type CombinedProjectionBatch,\n} from \"./document-producer\";\nimport { enrichedSerialize } from \"./enriched-serialize\";\nimport { captureCombinedFiberTree } from \"./hide-fiber-tree\";\nimport { nextRealmCaptureSequence, REALM_DOCUMENT_EPOCH } from \"./realm-epoch\";\nimport type {\n CombinedCapture,\n CombinedCaptureProvenance,\n CombinedWatchTrigger,\n EnrichedFiberConstraint,\n EnrichedFiberNode,\n} from \"./types\";\n\nconst LEGACY_FLUSH_WINDOW_MS = 50;\nlet nextLegacyWatchId = 1;\n\nexport interface CombinedWatchOptions<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n> {\n debounceDelay?: number;\n /** Retained on the old wire; the fixed document scheduler supersedes it. */\n maxWait?: number;\n serialize?: SerializeFn<T>;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n hideFiberProp?: string;\n}\n\nexport type ResumeFlushPolicy = \"if-dirty\" | \"always\" | \"never\";\n\nexport interface CombinedWatchResumeOptions {\n flush?: ResumeFlushPolicy;\n triggers?: readonly CombinedWatchTrigger[];\n}\n\nexport type CombinedWatchHandle = (() => void) & {\n stop: () => void;\n pause: () => void;\n resume: (options?: CombinedWatchResumeOptions) => void;\n setPaused: (paused: boolean, options?: CombinedWatchResumeOptions) => void;\n};\n\nfunction realmHasReactRenderer(\n element: Element,\n localHook: ReturnType<typeof initHook>,\n): boolean {\n const view = element.ownerDocument.defaultView as\n | (Window & {\n __REACT_DEVTOOLS_GLOBAL_HOOK__?: { renderers?: Map<unknown, unknown> };\n })\n | null;\n return view && view !== window\n ? (view.__REACT_DEVTOOLS_GLOBAL_HOOK__?.renderers?.size ?? 0) > 0\n : localHook.hook.renderers.size > 0;\n}\n\nfunction captureLegacyEnvelope<T extends EnrichedFiberConstraint>(\n element: Element,\n hook: ReturnType<typeof initHook>,\n options: CombinedWatchOptions<T>,\n provenance: CombinedCaptureProvenance,\n coordinateOnlyPortalIds: ReadonlySet<string>,\n): CombinedCapture<T> {\n const supplementalRoots = collectProjectionPortalElements(element);\n const html = withCoordinateOnlyPortals(\n captureProjectionSnapshot(element, supplementalRoots),\n coordinateOnlyPortalIds,\n );\n const fiber = captureCombinedFiberTree<T>({\n rootElement: element,\n selector: options.fiberSelector,\n tags: options.fiberTags,\n hideFiberProp: options.hideFiberProp,\n serialize:\n options.serialize ?? (enrichedSerialize as unknown as SerializeFn<T>),\n });\n return {\n html,\n fiber,\n ...computeRenderDeclarations(\n fiber,\n html,\n realmHasReactRenderer(element, hook),\n element.ownerDocument,\n createRenderDeclarationScope(element, supplementalRoots),\n ),\n provenance,\n documentEpoch: REALM_DOCUMENT_EPOCH,\n sequence: nextRealmCaptureSequence(),\n };\n}\n\nfunction triggersForBatch(\n batch: CombinedProjectionBatch,\n): CombinedWatchTrigger[] {\n const triggers = new Set<CombinedWatchTrigger>();\n if (batch.head !== undefined) triggers.add(\"head\");\n for (const change of batch.roots) {\n if (change.kind !== \"patch\") {\n triggers.add(\"dom\");\n triggers.add(\"fiber\");\n continue;\n }\n const patch = change.patch;\n if (patch.dom?.length || patch.annotations?.length) triggers.add(\"dom\");\n if (patch.state?.length) triggers.add(\"state\");\n for (const portal of patch.portals ?? []) {\n // A portal moved by new styling is the head's doing, and this envelope\n // reports it as one refreshed coordinate space, not as portal content.\n if (portal.kind === \"replace\" && portal.coordinatesOnly) continue;\n // A portal is an arm of the same Fiber tree this envelope re-serializes\n // whole, so its content always arrives with a current fiber.\n triggers.add(\"portal\");\n triggers.add(\"fiber\");\n }\n if (patch.layers) triggers.add(\"fiber\");\n }\n return triggers.size > 0 ? [...triggers] : [\"dom\", \"fiber\"];\n}\n\n/** Portal ids this batch refreshed coordinates for without resending their\n * bodies. The old envelope always re-serializes every portal, so those are\n * downgraded back to coordinate-only updates to keep the destination's focus\n * and edit state inside an unchanged portal. */\nfunction coordinateOnlyPortalIds(batch: CombinedProjectionBatch): Set<string> {\n const ids = new Set<string>();\n for (const change of batch.roots) {\n if (change.kind !== \"patch\") continue;\n for (const portal of change.patch.portals ?? []) {\n if (portal.kind === \"replace\" && portal.coordinatesOnly) {\n ids.add(portal.portalId);\n }\n }\n }\n return ids;\n}\n\nfunction withCoordinateOnlyPortals(\n capture: DomCapture,\n portalIds: ReadonlySet<string>,\n): DomCapture {\n if (portalIds.size === 0 || !capture.portals) return capture;\n return {\n ...capture,\n portals: capture.portals.map((portal) =>\n portalIds.has(portal.id)\n ? { ...portal, html: \"\", states: [], coordinatesOnly: true }\n : portal,\n ),\n };\n}\n\n/** @deprecated Retained only for old clients talking to a new interact frame. */\nexport function watchCombined<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n>(\n element: Element,\n onChange: (capture: CombinedCapture<T>) => void,\n options: CombinedWatchOptions<T> = {},\n): CombinedWatchHandle {\n const rootId = `legacy-combined-root-${nextLegacyWatchId++}`;\n const sessionId = `legacy-combined-session-${nextLegacyWatchId++}`;\n const hook = initHook();\n let stopped = false;\n let paused = false;\n let dirtyWhilePaused = false;\n let resumeTriggers: readonly CombinedWatchTrigger[] | undefined;\n\n const producer = createCombinedDocumentProducer<T>({\n document: element.ownerDocument,\n flushWindowMs: options.debounceDelay ?? LEGACY_FLUSH_WINDOW_MS,\n emit(batch) {\n if (stopped) return;\n if (paused) {\n dirtyWhilePaused = true;\n return;\n }\n const provenance: CombinedCaptureProvenance =\n batch.sequence === 0\n ? { kind: \"initial\" }\n : {\n kind: \"watch\",\n triggers: resumeTriggers\n ? [...resumeTriggers]\n : triggersForBatch(batch),\n };\n resumeTriggers = undefined;\n onChange(\n captureLegacyEnvelope(\n element,\n hook,\n options,\n provenance,\n coordinateOnlyPortalIds(batch),\n ),\n );\n },\n });\n producer.bindSession(sessionId);\n producer.watchRoot({\n rootId,\n element,\n layerFramework: realmHasReactRenderer(element, hook) ? \"react\" : \"dom\",\n fiberSelector: options.fiberSelector,\n });\n // Preserve the legacy API's synchronous initial emission while keeping the\n // document producer as the sole observer/scheduler owner.\n producer.requestFull(rootId);\n\n const stop = () => {\n if (stopped) return;\n stopped = true;\n producer.stop();\n };\n const pause = () => {\n if (stopped || paused) return;\n paused = true;\n // The producer may have retained observer records that have not reached\n // its fixed-window callback yet. Conservatively rebuild once on resume;\n // the old destination values correctness over compatibility-path work.\n dirtyWhilePaused = true;\n };\n const resume = (resumeOptions?: CombinedWatchResumeOptions) => {\n if (stopped || !paused) return;\n paused = false;\n const policy = resumeOptions?.flush ?? \"if-dirty\";\n const shouldFlush =\n policy === \"always\" || (policy === \"if-dirty\" && dirtyWhilePaused);\n dirtyWhilePaused = false;\n if (shouldFlush) {\n resumeTriggers = [\"dom\", ...(resumeOptions?.triggers ?? [])];\n producer.requestFull(rootId);\n }\n };\n const setPaused = (\n nextPaused: boolean,\n resumeOptions?: CombinedWatchResumeOptions,\n ) => (nextPaused ? pause() : resume(resumeOptions));\n\n return Object.assign(stop, { stop, pause, resume, setPaused });\n}\n\n/**\n * Selector lifecycle for the old interact command. HMR may replace the target\n * element without replacing the document, so the binding is re-resolved and\n * the replacement begins with one complete legacy envelope.\n */\nexport function watchCombinedSelector<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n>(\n root: Document | Element,\n selector: string | undefined,\n onChange: (capture: CombinedCapture<T>) => void,\n options: CombinedWatchOptions<T> = {},\n): CombinedWatchHandle {\n const documentRoot = root.nodeType === 9;\n let activeElement: Element | null = null;\n let activeWatcher: CombinedWatchHandle | null = null;\n let targetObserver: MutationObserver | null = null;\n let stopped = false;\n let paused = false;\n let dirtyWhilePaused = false;\n let hasBound = false;\n\n const getTarget = () =>\n selector\n ? root.querySelector(selector)\n : documentRoot\n ? (root as Document).body\n : (root as Element);\n const disconnect = () => {\n targetObserver?.disconnect();\n targetObserver = null;\n };\n const stopActive = () => {\n activeWatcher?.stop();\n activeWatcher = null;\n activeElement = null;\n };\n // Observe the selector scope, not only the target's current parent: Vite\n // HMR can replace both the target and its parent in one mutation. Every\n // reconcile disconnects first, so each path that keeps watching must re-arm.\n const armSelectorObserver = () => {\n if (!selector) return;\n targetObserver = new MutationObserver(reconcile);\n targetObserver.observe(root, { childList: true, subtree: true });\n };\n\n const reconcile = () => {\n if (stopped) return;\n const target = getTarget();\n if (\n activeElement &&\n (!activeElement.isConnected || activeElement !== target)\n ) {\n stopActive();\n dirtyWhilePaused = true;\n }\n disconnect();\n if (!target || paused) {\n if (!paused && selector) {\n targetObserver = new MutationObserver(reconcile);\n targetObserver.observe(root, {\n attributes: true,\n childList: true,\n subtree: true,\n });\n }\n return;\n }\n // Still watching the same target: nothing to rebind, but `disconnect()`\n // above dropped the selector observer, and every capture ends in a\n // reconcile — leaving it dropped blinds the watcher to the first target\n // swap after the first change.\n if (activeWatcher) {\n armSelectorObserver();\n return;\n }\n\n const rebind = hasBound;\n hasBound = true;\n activeElement = target;\n activeWatcher = watchCombined(\n target,\n (capture) => {\n if (!target.isConnected || target !== getTarget()) {\n reconcile();\n return;\n }\n onChange(\n rebind && capture.provenance?.kind === \"initial\"\n ? {\n ...capture,\n provenance: {\n kind: \"watch\",\n triggers: [\"selector-rebind\"],\n },\n }\n : capture,\n );\n queueMicrotask(reconcile);\n },\n options,\n );\n armSelectorObserver();\n };\n\n reconcile();\n const stop = () => {\n if (stopped) return;\n stopped = true;\n disconnect();\n stopActive();\n };\n const pause = () => {\n if (stopped || paused) return;\n paused = true;\n dirtyWhilePaused = true;\n disconnect();\n activeWatcher?.pause();\n };\n const resume = (resumeOptions?: CombinedWatchResumeOptions) => {\n if (stopped || !paused) return;\n paused = false;\n if (activeWatcher) {\n activeWatcher.resume(resumeOptions);\n dirtyWhilePaused = false;\n } else if (\n (resumeOptions?.flush ?? \"if-dirty\") === \"always\" ||\n dirtyWhilePaused\n ) {\n dirtyWhilePaused = false;\n reconcile();\n }\n queueMicrotask(reconcile);\n };\n const setPaused = (\n nextPaused: boolean,\n resumeOptions?: CombinedWatchResumeOptions,\n ) => (nextPaused ? pause() : resume(resumeOptions));\n return Object.assign(stop, { stop, pause, resume, setPaused });\n}\n","/**\n * Document Projection PostMessage Interface\n *\n * Provides one ordered ProjectionBatch stream carrying exact DOM, head, and\n * semantic-layer changes from a source iframe to its destination.\n *\n * ## Usage\n *\n * ### Source Side (in iframe)\n * ```ts\n * import { initHook } from '@modules/iframe-projection/fiber';\n * initHook(); // Before React loads\n *\n * import { startCombinedSourceInterface } from '@modules/iframe-projection/combined/postmessage';\n * startCombinedSourceInterface();\n * ```\n *\n * ### Dest Side (parent window)\n * ```ts\n * import { watchProjectionBatchesIframe } from '@modules/iframe-projection/combined/postmessage';\n *\n * const watcher = await watchProjectionBatchesIframe(iframe, {\n * sessionId: 'source-document-1',\n * rootId: 'storyboard-1',\n * selector: '#root',\n * onBatch: (batch) => destination.enqueue(batch),\n * });\n *\n * watcher.stop();\n * ```\n */\n\nimport type { FiberTagValue, SerializeFn } from \"../fiber/types\";\nimport {\n type CombinedDocumentProducer,\n type CombinedProjectionBatch,\n createCombinedDocumentProducer,\n} from \"./document-producer\";\nimport type { DetachSerializedFiber } from \"./enriched-to-serialized-fiber\";\nimport {\n isLayerFramework,\n type LayerFramework,\n} from \"./layer-framework\";\nimport { decodeCombinedProjectionBatch } from \"./projection-batch\";\nimport {\n isProjectionRegionCapture,\n type ProjectionRegionCapture,\n} from \"./projection-full-snapshot\";\nimport { isProjectionSemanticSubtree } from \"./projection-semantic-subtree\";\nimport type {\n CombinedCapture,\n EnrichedFiberConstraint,\n EnrichedFiberNode,\n} from \"./types\";\nimport { type CombinedWatchHandle, watchCombinedSelector } from \"./watch\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Message Types\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Marker to identify our messages (shared across all iframe-projection protocols) */\nconst MESSAGE_MARKER = \"__iframeProjection\" as const;\n\ninterface BaseMessage {\n [MESSAGE_MARKER]: true;\n}\n\n// Handshake\ninterface CombinedSourceReadyMessage extends BaseMessage {\n type: \"combined-source-ready\";\n}\ninterface CombinedPingCommand extends BaseMessage {\n type: \"combined-ping\";\n}\ninterface CombinedPongResponse extends BaseMessage {\n type: \"combined-pong\";\n}\n\n// Watcher lifecycle\ninterface StartCombinedWatcherCommand extends BaseMessage {\n type: \"start-combined-watcher\";\n requestId: string;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n debounceDelay?: number;\n maxWait?: number;\n}\ninterface CombinedWatcherStartedResponse extends BaseMessage {\n type: \"combined-watcher-started\";\n requestId: string;\n watcherId: string;\n}\ninterface StopCombinedWatcherCommand extends BaseMessage {\n type: \"stop-combined-watcher\";\n watcherId: string;\n}\ninterface SetCombinedWatcherPausedCommand extends BaseMessage {\n type: \"set-combined-watcher-paused\";\n watcherId: string;\n paused: boolean;\n}\ninterface CombinedWatcherStoppedResponse extends BaseMessage {\n type: \"combined-watcher-stopped\";\n watcherId: string;\n}\n\n// Exact document projection lifecycle. The same command names are used by the\n// iframe and Electron page bridges; only their delivery mechanism differs.\ninterface StartProjectionWatcherCommand extends BaseMessage {\n type: \"start-projection-watcher\";\n requestId: string;\n sessionId: string;\n rootId: string;\n layerFramework: LayerFramework;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n}\ninterface ProjectionWatcherStartedResponse extends BaseMessage {\n type: \"projection-watcher-started\";\n requestId: string;\n watcherId: string;\n}\ninterface RequestProjectionFullCommand extends BaseMessage {\n type: \"request-projection-full\";\n watcherId: string;\n}\ninterface CaptureProjectionSemanticSubtreeCommand extends BaseMessage {\n type: \"capture-projection-semantic-subtree\";\n requestId: string;\n watcherId: string;\n targetFiberId: string;\n}\ninterface ProjectionSemanticSubtreeResponse extends BaseMessage {\n type: \"projection-semantic-subtree-response\";\n requestId: string;\n subtree: DetachSerializedFiber | null;\n error?: string;\n}\ninterface CaptureProjectionRegionCommand extends BaseMessage {\n type: \"capture-projection-region\";\n requestId: string;\n watcherId: string;\n targetId: string;\n}\ninterface ProjectionRegionResponse extends BaseMessage {\n type: \"projection-region-response\";\n requestId: string;\n region: ProjectionRegionCapture | null;\n error?: string;\n}\ninterface StopProjectionWatcherCommand extends BaseMessage {\n type: \"stop-projection-watcher\";\n watcherId: string;\n}\ninterface CancelProjectionWatcherCommand extends BaseMessage {\n type: \"cancel-projection-watcher\";\n requestId: string;\n}\ninterface ProjectionWatcherStoppedResponse extends BaseMessage {\n type: \"projection-watcher-stopped\";\n watcherId: string;\n}\n\n// Data\ninterface CombinedUpdateMessage extends BaseMessage {\n type: \"combined-update\";\n watcherId: string;\n capture: CombinedCapture;\n}\ninterface ProjectionBatchUpdateMessage extends BaseMessage {\n type: \"projection-batch\";\n batch: CombinedProjectionBatch;\n}\n\n// Error\ninterface CombinedErrorMessage extends BaseMessage {\n type: \"combined-error\";\n error: string;\n requestId?: string;\n watcherId?: string;\n}\n\ntype CombinedMessage =\n | CombinedSourceReadyMessage\n | CombinedPingCommand\n | CombinedPongResponse\n | StartCombinedWatcherCommand\n | CombinedWatcherStartedResponse\n | StopCombinedWatcherCommand\n | SetCombinedWatcherPausedCommand\n | CombinedWatcherStoppedResponse\n | CombinedUpdateMessage\n | StartProjectionWatcherCommand\n | ProjectionWatcherStartedResponse\n | RequestProjectionFullCommand\n | CaptureProjectionSemanticSubtreeCommand\n | ProjectionSemanticSubtreeResponse\n | CaptureProjectionRegionCommand\n | ProjectionRegionResponse\n | StopProjectionWatcherCommand\n | CancelProjectionWatcherCommand\n | ProjectionWatcherStoppedResponse\n | ProjectionBatchUpdateMessage\n | CombinedErrorMessage;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Type Guards\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction isMessage(data: unknown): data is CombinedMessage {\n return (\n typeof data === \"object\" &&\n data !== null &&\n MESSAGE_MARKER in data &&\n (data as any)[MESSAGE_MARKER] === true\n );\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Source Side (iframe)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Active watchers by ID */\nconst combinedWatchers = new Map<string, CombinedWatchHandle>();\n\nlet nextCombinedWatcherId = 1;\nlet combinedSourceInitialized = false;\nlet combinedSourceCleanup: (() => void) | null = null;\n\nfunction installWhenDocumentBodyReady(install: () => () => void): () => void {\n let cancelled = false;\n let installedCleanup: (() => void) | null = null;\n let animationFrameId: number | null = null;\n let listeningForDomReady = false;\n\n const init = () => {\n listeningForDomReady = false;\n animationFrameId = null;\n if (cancelled) return;\n if (document.body) {\n installedCleanup = install();\n return;\n }\n animationFrameId = requestAnimationFrame(init);\n };\n\n if (document.readyState === \"loading\") {\n listeningForDomReady = true;\n document.addEventListener(\"DOMContentLoaded\", init);\n } else {\n init();\n }\n\n return () => {\n if (cancelled) return;\n cancelled = true;\n if (listeningForDomReady) {\n document.removeEventListener(\"DOMContentLoaded\", init);\n listeningForDomReady = false;\n }\n if (animationFrameId !== null) {\n cancelAnimationFrame(animationFrameId);\n animationFrameId = null;\n }\n installedCleanup?.();\n installedCleanup = null;\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\ntype ProjectionSourceEventType =\n | \"projection-watcher-started\"\n | \"projection-watcher-stopped\"\n | \"projection-batch\"\n | \"projection-semantic-subtree-response\"\n | \"projection-region-response\"\n | \"error\";\n\ninterface ProjectionSourceController {\n /** Returns true when the payload belongs to the exact projection protocol. */\n handleCommand(payload: unknown): boolean;\n stop(): void;\n}\n\n/**\n * Source-side ownership shared by postMessage iframes and Electron pages.\n * There is one producer per live source document; the transports only forward\n * its closed ProjectionBatch DTO and lifecycle commands.\n */\nfunction createProjectionSourceController<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n>(options: {\n document: Document;\n watcherIdPrefix: string;\n serialize?: SerializeFn<T>;\n hideFiberProp?: string;\n send(type: ProjectionSourceEventType, payload: Record<string, unknown>): void;\n}): ProjectionSourceController {\n type WatcherRegistration = {\n readonly rootId: string;\n readonly sessionId: string;\n readonly requestId: string;\n };\n\n const watchers = new Map<string, WatcherRegistration>();\n const pendingBatches: CombinedProjectionBatch[] = [];\n let nextWatcherId = 1;\n let producer: CombinedDocumentProducer<T> | null = null;\n let sessionId: string | null = null;\n let watchesEstablishing = 0;\n let stopped = false;\n\n const sendError = (\n error: unknown,\n scope: { requestId?: string; watcherId?: string } = {},\n ): void => {\n options.send(\"error\", {\n ...scope,\n error: error instanceof Error ? error.message : String(error),\n });\n };\n\n const publishBatch = (batch: CombinedProjectionBatch): void => {\n if (stopped) return;\n // A newly registered root can request an immediate full after sequence\n // zero. Keep acknowledgement ahead of any batch that registration causes.\n if (watchesEstablishing > 0) {\n pendingBatches.push(batch);\n return;\n }\n options.send(\"projection-batch\", { batch });\n };\n\n const flushPendingBatches = (): void => {\n if (stopped || watchesEstablishing > 0) return;\n for (const batch of pendingBatches.splice(0)) {\n options.send(\"projection-batch\", { batch });\n }\n };\n\n const getProducer = (\n requestedSessionId: string,\n ): CombinedDocumentProducer<T> => {\n if (sessionId !== null && sessionId !== requestedSessionId) {\n if (watchers.size > 0) {\n throw new Error(\n \"A source document cannot bind two projection sessions at once\",\n );\n }\n producer?.stop();\n producer = null;\n sessionId = null;\n pendingBatches.length = 0;\n }\n producer ??= createCombinedDocumentProducer<T>({\n document: options.document,\n emit: publishBatch,\n onError: (error) => sendError(error),\n });\n return producer;\n };\n\n const stopWatcher = (watcherId: string): void => {\n const registration = watchers.get(watcherId);\n if (!registration) return;\n producer?.unwatchRoot(registration.rootId);\n watchers.delete(watcherId);\n if (watchers.size === 0) {\n // An iframe or pooled page can remain alive after its destination\n // detaches. No observer, React subscription, or timer survives idle.\n producer?.stop();\n producer = null;\n sessionId = null;\n pendingBatches.length = 0;\n }\n options.send(\"projection-watcher-stopped\", { watcherId });\n };\n\n return {\n handleCommand(payload) {\n if (stopped || !isRecord(payload) || typeof payload.type !== \"string\") {\n return false;\n }\n\n if (payload.type === \"start-projection-watcher\") {\n const requestId =\n typeof payload.requestId === \"string\" ? payload.requestId : undefined;\n const requestedSessionId =\n typeof payload.sessionId === \"string\" ? payload.sessionId.trim() : \"\";\n const rootId =\n typeof payload.rootId === \"string\" ? payload.rootId.trim() : \"\";\n const layerFramework = isLayerFramework(payload.layerFramework)\n ? payload.layerFramework\n : null;\n if (!requestId || !requestedSessionId || !rootId || !layerFramework) {\n sendError(\n new Error(\n \"Exact projection watch requires requestId, sessionId, rootId, and layerFramework\",\n ),\n requestId ? { requestId } : {},\n );\n return true;\n }\n\n const selector =\n typeof payload.selector === \"string\" ? payload.selector : undefined;\n const fiberSelector =\n typeof payload.fiberSelector === \"string\"\n ? payload.fiberSelector\n : undefined;\n const fiberTags = Array.isArray(payload.fiberTags)\n ? (payload.fiberTags as FiberTagValue[])\n : undefined;\n const watcherId = `${options.watcherIdPrefix}-${nextWatcherId++}`;\n watchesEstablishing += 1;\n let watched = false;\n try {\n const element = selector\n ? options.document.querySelector(selector)\n : options.document.body;\n if (!element) {\n throw new Error(`Element not found: ${selector ?? \"body\"}`);\n }\n const activeProducer = getProducer(requestedSessionId);\n activeProducer.watchRoot({\n rootId,\n element,\n layerFramework,\n serialize: options.serialize,\n fiberSelector,\n fiberTags,\n hideFiberProp: options.hideFiberProp,\n });\n watched = true;\n if (sessionId !== requestedSessionId) {\n activeProducer.bindSession(requestedSessionId);\n sessionId = requestedSessionId;\n }\n watchers.set(watcherId, {\n rootId,\n sessionId: requestedSessionId,\n requestId,\n });\n options.send(\"projection-watcher-started\", {\n requestId,\n watcherId,\n });\n } catch (error) {\n if (watched) producer?.unwatchRoot(rootId);\n sendError(error, { requestId });\n } finally {\n watchesEstablishing -= 1;\n flushPendingBatches();\n }\n return true;\n }\n\n if (payload.type === \"request-projection-full\") {\n const watcherId =\n typeof payload.watcherId === \"string\" ? payload.watcherId : undefined;\n const registration = watcherId ? watchers.get(watcherId) : undefined;\n if (!registration || registration.sessionId !== sessionId) {\n if (watcherId) {\n sendError(new Error(\"Projection watcher is not active\"), {\n watcherId,\n });\n }\n return true;\n }\n producer?.requestFull(registration.rootId);\n return true;\n }\n\n if (payload.type === \"capture-projection-semantic-subtree\") {\n const requestId =\n typeof payload.requestId === \"string\" ? payload.requestId : undefined;\n const watcherId =\n typeof payload.watcherId === \"string\" ? payload.watcherId : undefined;\n const targetFiberId =\n typeof payload.targetFiberId === \"string\"\n ? payload.targetFiberId.trim()\n : \"\";\n const registration = watcherId ? watchers.get(watcherId) : undefined;\n if (!requestId || !registration || !targetFiberId) {\n if (requestId) {\n options.send(\"projection-semantic-subtree-response\", {\n requestId,\n subtree: null,\n error:\n \"Semantic subtree capture requires an active watcher and targetFiberId\",\n });\n }\n return true;\n }\n try {\n const subtree = producer?.captureSemanticSubtree(\n registration.rootId,\n targetFiberId,\n );\n options.send(\"projection-semantic-subtree-response\", {\n requestId,\n subtree: subtree ?? null,\n });\n } catch (error) {\n options.send(\"projection-semantic-subtree-response\", {\n requestId,\n subtree: null,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n return true;\n }\n\n if (payload.type === \"capture-projection-region\") {\n const requestId =\n typeof payload.requestId === \"string\" ? payload.requestId : undefined;\n const watcherId =\n typeof payload.watcherId === \"string\" ? payload.watcherId : undefined;\n const targetId =\n typeof payload.targetId === \"string\" ? payload.targetId.trim() : \"\";\n const registration = watcherId ? watchers.get(watcherId) : undefined;\n if (!requestId || !registration || !targetId) {\n if (requestId) {\n options.send(\"projection-region-response\", {\n requestId,\n region: null,\n error:\n \"Region capture requires an active watcher and targetId\",\n });\n }\n return true;\n }\n try {\n const region = producer?.captureRegion(\n registration.rootId,\n targetId,\n );\n options.send(\"projection-region-response\", {\n requestId,\n region: region ?? null,\n });\n } catch (error) {\n options.send(\"projection-region-response\", {\n requestId,\n region: null,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n return true;\n }\n\n if (payload.type === \"stop-projection-watcher\") {\n const watcherId =\n typeof payload.watcherId === \"string\" ? payload.watcherId : undefined;\n if (watcherId) stopWatcher(watcherId);\n return true;\n }\n\n if (payload.type === \"cancel-projection-watcher\") {\n const requestId =\n typeof payload.requestId === \"string\" ? payload.requestId : undefined;\n if (!requestId) return true;\n const entry = Array.from(watchers).find(\n ([, registration]) => registration.requestId === requestId,\n );\n if (entry) stopWatcher(entry[0]);\n return true;\n }\n\n return false;\n },\n stop() {\n if (stopped) return;\n stopped = true;\n producer?.stop();\n producer = null;\n sessionId = null;\n watchers.clear();\n pendingBatches.length = 0;\n },\n };\n}\n\nexport interface CombinedSourceOptions<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n> {\n targetOrigin?: string;\n /** Custom fiber serializer used for all watchers started via postMessage */\n serialize?: SerializeFn<T>;\n /** Hide fibers whose serialized props contain this truthy prop */\n hideFiberProp?: string;\n}\n\n/**\n * Starts the combined source-side postMessage interface.\n *\n * IMPORTANT: Call initHook() BEFORE React loads, then call this after DOM is ready.\n *\n * @param options - Source options\n * @returns Cleanup function\n */\nexport function startCombinedSourceInterface<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n>(options: CombinedSourceOptions<T> = {}): () => void {\n const { targetOrigin = \"*\", serialize, hideFiberProp } = options;\n\n if (combinedSourceInitialized) {\n console.warn(\"[combined-postmessage:source] Already initialized\");\n return combinedSourceCleanup || (() => {});\n }\n\n if (typeof window === \"undefined\" || window.parent === window) {\n console.log(\"[combined-postmessage:source] Not in iframe, skipping\");\n return () => {};\n }\n\n combinedSourceInitialized = true;\n let disposeDeferredInstall = () => {};\n let disposed = false;\n const cleanup = () => {\n if (disposed) return;\n disposed = true;\n disposeDeferredInstall();\n if (combinedSourceCleanup === cleanup) {\n combinedSourceCleanup = null;\n combinedSourceInitialized = false;\n }\n };\n combinedSourceCleanup = cleanup;\n const deferredInstall = installWhenDocumentBodyReady(() =>\n initCombinedSourceInterface(targetOrigin, serialize, hideFiberProp),\n );\n if (disposed) deferredInstall();\n else disposeDeferredInstall = deferredInstall;\n return cleanup;\n}\n\nfunction initCombinedSourceInterface<T extends EnrichedFiberConstraint>(\n targetOrigin: string,\n serialize?: SerializeFn<T>,\n hideFiberProp?: string,\n): () => void {\n (window as any).__IFRAME_PROJECTION_COMBINED_INTERFACE_ACTIVE__ = true;\n\n const send = (msg: CombinedMessage) => {\n window.parent.postMessage({ ...msg, [MESSAGE_MARKER]: true }, targetOrigin);\n };\n const projectionSource = createProjectionSourceController<T>({\n document,\n watcherIdPrefix: \"iframe-projection-watcher\",\n serialize,\n hideFiberProp,\n send(type, payload) {\n if (type === \"error\") {\n send({\n type: \"combined-error\",\n [MESSAGE_MARKER]: true,\n ...(payload as Omit<\n CombinedErrorMessage,\n typeof MESSAGE_MARKER | \"type\"\n >),\n });\n return;\n }\n send({\n type,\n [MESSAGE_MARKER]: true,\n ...payload,\n } as CombinedMessage);\n },\n });\n\n const handleMessage = (event: MessageEvent) => {\n const data = event.data;\n if (!isMessage(data)) return;\n if (projectionSource.handleCommand(data)) return;\n\n switch (data.type) {\n case \"combined-ping\":\n send({ type: \"combined-pong\", [MESSAGE_MARKER]: true });\n break;\n\n case \"start-combined-watcher\": {\n const {\n requestId,\n selector,\n fiberSelector,\n fiberTags,\n debounceDelay,\n maxWait,\n } = data;\n const watcherId = `combined-watcher-${nextCombinedWatcherId++}`;\n\n try {\n const pendingCaptures: CombinedCapture[] = [];\n let established = false;\n const watcher = watchCombinedSelector(\n document,\n selector,\n (capture) => {\n if (!established) {\n pendingCaptures.push(capture);\n return;\n }\n send({\n type: \"combined-update\",\n [MESSAGE_MARKER]: true,\n watcherId,\n capture,\n });\n },\n {\n debounceDelay,\n maxWait,\n ...(serialize && {\n serialize: serialize as unknown as SerializeFn<any>,\n }),\n fiberSelector,\n fiberTags,\n hideFiberProp,\n },\n );\n\n combinedWatchers.set(watcherId, watcher);\n send({\n type: \"combined-watcher-started\",\n [MESSAGE_MARKER]: true,\n requestId,\n watcherId,\n });\n established = true;\n for (const capture of pendingCaptures) {\n send({\n type: \"combined-update\",\n [MESSAGE_MARKER]: true,\n watcherId,\n capture,\n });\n }\n console.log(\n `[combined-postmessage:source] Started ${watcherId} on ${selector || \"body\"}`,\n );\n } catch (err) {\n send({\n type: \"combined-error\",\n [MESSAGE_MARKER]: true,\n requestId,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n break;\n }\n\n case \"stop-combined-watcher\": {\n const { watcherId } = data;\n const watcher = combinedWatchers.get(watcherId);\n\n if (watcher) {\n watcher.stop();\n combinedWatchers.delete(watcherId);\n send({\n type: \"combined-watcher-stopped\",\n [MESSAGE_MARKER]: true,\n watcherId,\n });\n console.log(`[combined-postmessage:source] Stopped ${watcherId}`);\n }\n break;\n }\n\n case \"set-combined-watcher-paused\": {\n const watcher = combinedWatchers.get(data.watcherId);\n watcher?.setPaused(data.paused);\n break;\n }\n }\n };\n\n window.addEventListener(\"message\", handleMessage);\n\n send({ type: \"combined-source-ready\", [MESSAGE_MARKER]: true });\n console.log(\n \"[combined-postmessage:source] Ready, sent combined-source-ready\",\n );\n\n return () => {\n window.removeEventListener(\"message\", handleMessage);\n projectionSource.stop();\n for (const [id, watcher] of combinedWatchers) {\n watcher.stop();\n console.log(`[combined-postmessage:source] Stopped ${id}`);\n }\n combinedWatchers.clear();\n delete (window as any).__IFRAME_PROJECTION_COMBINED_INTERFACE_ACTIVE__;\n console.log(\"[combined-postmessage:source] Cleaned up\");\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Deprecated CombinedCapture destination compatibility\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Handle for the pre-ProjectionBatch combined transport.\n *\n * @deprecated New projection consumers should use {@link ProjectionBatchWatcher}.\n * This remains an opt-in transport adapter for independent library consumers\n * and deployed destinations; it is not used by the Canvas hot path.\n */\nexport interface CombinedWatcher {\n id: string;\n stop: () => void;\n pause: () => void;\n resume: () => void;\n setPaused: (paused: boolean) => void;\n}\n\n/** @deprecated Use {@link WatchProjectionBatchesIframeOptions}. */\nexport interface WatchCombinedIframeOptions {\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n debounceDelay?: number;\n maxWait?: number;\n timeout?: number;\n targetOrigin?: string;\n onUpdate: (capture: CombinedCapture) => void;\n onError?: (error: Error) => void;\n}\n\n/** @deprecated Use {@link WatchProjectionBatchesPageOptions}. */\nexport interface WatchCombinedPageOptions {\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n debounceDelay?: number;\n maxWait?: number;\n timeout?: number;\n /** Cancels source-readiness and watcher establishment. */\n signal?: AbortSignal;\n onUpdate: (capture: CombinedCapture) => void;\n onError?: (error: Error) => void;\n}\n\n/**\n * Options for a cold, one-shot complete DOM + Fiber capture.\n *\n * @deprecated Exact live projection should use ProjectionBatch. This cold\n * query remains useful when a complete compatibility envelope is the result.\n */\nexport interface CaptureCombinedPageOptions {\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n timeout?: number;\n}\n\ntype LegacyCombinedChannelCommand =\n | { type: \"ping\" }\n | {\n type: \"start-watcher\";\n requestId: string;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n debounceDelay?: number;\n maxWait?: number;\n }\n | { type: \"set-watcher-paused\"; watcherId: string; paused: boolean }\n | { type: \"stop-watcher\"; watcherId: string }\n | {\n type: \"capture\";\n requestId: string;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n };\n\ntype LegacyCombinedChannelEvent =\n | { type: \"ready\" }\n | { type: \"watcher-started\"; requestId: string; watcherId: string }\n | { type: \"update\"; watcherId: string; capture: CombinedCapture }\n | {\n type: \"capture-response\";\n requestId: string;\n capture: CombinedCapture | null;\n }\n | {\n type: \"error\";\n error: string;\n requestId: unknown;\n watcherId: unknown;\n };\n\ninterface LegacyCombinedChannel {\n readonly readinessTimeoutMessage: string;\n nextWatcherRequestId(): string;\n nextCaptureRequestId(): string;\n send(command: LegacyCombinedChannelCommand): void;\n listen(listener: (event: LegacyCombinedChannelEvent) => void): () => void;\n}\n\nfunction normalizeLegacyCombinedChannelEvent(\n value: unknown,\n): LegacyCombinedChannelEvent | null {\n if (!isRecord(value) || typeof value.type !== \"string\") return null;\n switch (value.type) {\n case \"combined-source-ready\":\n case \"combined-pong\":\n case \"source-ready\":\n case \"pong\":\n return { type: \"ready\" };\n case \"combined-watcher-started\":\n case \"watcher-started\":\n return typeof value.requestId === \"string\" &&\n typeof value.watcherId === \"string\"\n ? {\n type: \"watcher-started\",\n requestId: value.requestId,\n watcherId: value.watcherId,\n }\n : null;\n case \"combined-update\":\n return typeof value.watcherId === \"string\" && isRecord(value.capture)\n ? {\n type: \"update\",\n watcherId: value.watcherId,\n capture: value.capture as unknown as CombinedCapture,\n }\n : null;\n case \"capture-response\":\n return typeof value.requestId === \"string\"\n ? {\n type: \"capture-response\",\n requestId: value.requestId,\n capture: isRecord(value.capture)\n ? (value.capture as unknown as CombinedCapture)\n : null,\n }\n : null;\n case \"combined-error\":\n case \"error\":\n return typeof value.error === \"string\"\n ? {\n type: \"error\",\n error: value.error,\n requestId: value.requestId,\n watcherId: value.watcherId,\n }\n : null;\n default:\n return null;\n }\n}\n\ntype ChannelResolution<T> =\n | { status: \"success\"; value: T }\n | { status: \"failure\"; error: Error }\n | undefined;\n\n/** The only thing a request/response wait needs of its transport. */\ninterface ListenableChannel<TEvent> {\n listen(listener: (event: TEvent) => void): () => void;\n}\n\n/**\n * Resolve one request against a channel: send, then settle on the first event\n * `receive` recognises. Without `retryInterval` the send happens once and\n * `timeout` bounds the wait; with it the send repeats until `timeout` elapses,\n * which is how a listener that may not exist yet is reached.\n *\n * The listener is registered before the first send so a synchronous reply\n * cannot be missed, and is removed on every exit path including one that\n * settles during registration.\n */\nfunction waitForChannelEvent<TEvent, T>(\n channel: ListenableChannel<TEvent>,\n options: {\n timeout: number;\n timeoutError: string;\n abortError: () => Error;\n signal?: AbortSignal;\n retryInterval?: number;\n send(): void;\n onAbort?: () => void;\n receive(event: TEvent): ChannelResolution<T>;\n },\n): Promise<T> {\n return new Promise((resolve, reject) => {\n if (options.signal?.aborted) {\n reject(options.abortError());\n return;\n }\n\n const startedAt = Date.now();\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let removeListener: (() => void) | null = null;\n let cleanupPending = false;\n\n const cleanup = (): void => {\n if (timer !== null) clearTimeout(timer);\n timer = null;\n options.signal?.removeEventListener(\"abort\", onAbort);\n if (removeListener) {\n bestEffort(removeListener);\n removeListener = null;\n } else {\n cleanupPending = true;\n }\n };\n const fail = (error: Error): void => {\n if (settled) return;\n settled = true;\n cleanup();\n reject(error);\n };\n const succeed = (value: T): void => {\n if (settled) return;\n settled = true;\n cleanup();\n resolve(value);\n };\n const onAbort = (): void => {\n bestEffort(() => options.onAbort?.());\n fail(options.abortError());\n };\n const receive = (event: TEvent): void => {\n if (settled) return;\n let resolution: ChannelResolution<T>;\n try {\n resolution = options.receive(event);\n } catch (error) {\n fail(errorFromUnknown(error));\n return;\n }\n if (resolution?.status === \"failure\") fail(resolution.error);\n else if (resolution?.status === \"success\") succeed(resolution.value);\n };\n\n options.signal?.addEventListener(\"abort\", onAbort, { once: true });\n try {\n const registeredListener = channel.listen(receive);\n if (cleanupPending) bestEffort(registeredListener);\n else removeListener = registeredListener;\n } catch (error) {\n fail(errorFromUnknown(error));\n return;\n }\n if (settled) return;\n\n const send = (): void => {\n if (settled) return;\n if (\n options.retryInterval !== undefined &&\n Date.now() - startedAt > options.timeout\n ) {\n fail(new Error(options.timeoutError));\n return;\n }\n try {\n options.send();\n } catch (error) {\n fail(errorFromUnknown(error));\n return;\n }\n if (!settled && options.retryInterval !== undefined) {\n timer = setTimeout(send, options.retryInterval);\n }\n };\n\n if (options.retryInterval === undefined) {\n timer = setTimeout(\n () => fail(new Error(options.timeoutError)),\n options.timeout,\n );\n }\n send();\n });\n}\n\nfunction waitForLegacyCombinedSourceReady(\n channel: LegacyCombinedChannel,\n timeout: number,\n signal?: AbortSignal,\n): Promise<void> {\n return waitForChannelEvent(channel, {\n timeout,\n signal,\n timeoutError: channel.readinessTimeoutMessage,\n abortError: combinedSetupAbortError,\n retryInterval: 100,\n send: () => channel.send({ type: \"ping\" }),\n receive: (event) =>\n event.type === \"ready\"\n ? { status: \"success\", value: undefined }\n : undefined,\n });\n}\n\nfunction requestLegacyCombinedWatcher(\n channel: LegacyCombinedChannel,\n options: Omit<\n Extract<LegacyCombinedChannelCommand, { type: \"start-watcher\" }>,\n \"type\" | \"requestId\"\n >,\n timeout: number,\n signal?: AbortSignal,\n): Promise<string> {\n const requestId = channel.nextWatcherRequestId();\n return waitForChannelEvent(channel, {\n timeout,\n signal,\n timeoutError: \"Timeout waiting for combined watcher to start\",\n abortError: combinedSetupAbortError,\n send: () => channel.send({ type: \"start-watcher\", requestId, ...options }),\n receive: (event) => {\n if (event.type === \"watcher-started\" && event.requestId === requestId) {\n return { status: \"success\", value: event.watcherId };\n }\n if (\n event.type === \"error\" &&\n (event.requestId === undefined || event.requestId === requestId)\n ) {\n return { status: \"failure\", error: new Error(event.error) };\n }\n return undefined;\n },\n });\n}\n\nasync function watchLegacyCombinedChannel(\n channel: LegacyCombinedChannel,\n options: {\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n debounceDelay?: number;\n maxWait?: number;\n timeout?: number;\n signal?: AbortSignal;\n onUpdate(capture: CombinedCapture): void;\n onError?(error: Error): void;\n },\n): Promise<CombinedWatcher> {\n const timeout = options.timeout ?? 10000;\n await waitForLegacyCombinedSourceReady(channel, timeout, options.signal);\n\n let stopped = false;\n let watcherId: string | null = null;\n const pendingUpdates = new Map<string, CombinedCapture[]>();\n const removeListener = channel.listen((event) => {\n if (stopped) return;\n if (event.type === \"update\") {\n if (watcherId === null) {\n const updates = pendingUpdates.get(event.watcherId) ?? [];\n updates.push(event.capture);\n pendingUpdates.set(event.watcherId, updates);\n } else if (event.watcherId === watcherId) {\n options.onUpdate(event.capture);\n }\n return;\n }\n if (\n watcherId !== null &&\n event.type === \"error\" &&\n (event.watcherId === undefined || event.watcherId === watcherId)\n ) {\n options.onError?.(new Error(event.error));\n }\n });\n\n try {\n watcherId = await requestLegacyCombinedWatcher(\n channel,\n {\n selector: options.selector,\n fiberSelector: options.fiberSelector,\n fiberTags: options.fiberTags,\n debounceDelay: options.debounceDelay,\n maxWait: options.maxWait,\n },\n timeout,\n options.signal,\n );\n } catch (error) {\n stopped = true;\n bestEffort(removeListener);\n throw error;\n }\n\n const activeWatcherId = watcherId;\n if (options.signal?.aborted) {\n stopped = true;\n bestEffort(removeListener);\n bestEffort(() =>\n channel.send({ type: \"stop-watcher\", watcherId: activeWatcherId }),\n );\n throw combinedSetupAbortError();\n }\n\n for (const capture of pendingUpdates.get(activeWatcherId) ?? []) {\n options.onUpdate(capture);\n }\n pendingUpdates.clear();\n\n const setPaused = (paused: boolean): void => {\n if (stopped) return;\n bestEffort(() =>\n channel.send({\n type: \"set-watcher-paused\",\n watcherId: activeWatcherId,\n paused,\n }),\n );\n };\n return {\n id: activeWatcherId,\n pause: () => setPaused(true),\n resume: () => setPaused(false),\n setPaused,\n stop() {\n if (stopped) return;\n stopped = true;\n bestEffort(removeListener);\n bestEffort(() =>\n channel.send({ type: \"stop-watcher\", watcherId: activeWatcherId }),\n );\n },\n };\n}\n\nasync function captureLegacyCombinedChannel(\n channel: LegacyCombinedChannel,\n options: CaptureCombinedPageOptions,\n): Promise<CombinedCapture | null> {\n const timeout = options.timeout ?? 10000;\n await waitForLegacyCombinedSourceReady(channel, timeout);\n const requestId = channel.nextCaptureRequestId();\n return waitForChannelEvent(channel, {\n timeout,\n timeoutError: \"Timeout waiting for combined capture response\",\n abortError: combinedSetupAbortError,\n send: () =>\n channel.send({\n type: \"capture\",\n requestId,\n selector: options.selector,\n fiberSelector: options.fiberSelector,\n fiberTags: options.fiberTags,\n }),\n receive: (event) => {\n if (event.type === \"capture-response\" && event.requestId === requestId) {\n return { status: \"success\", value: event.capture };\n }\n if (\n event.type === \"error\" &&\n (event.requestId === undefined || event.requestId === requestId)\n ) {\n return { status: \"failure\", error: new Error(event.error) };\n }\n return undefined;\n },\n });\n}\n\ntype ProjectionChannelCommand =\n | { type: \"ping\" }\n | {\n type: \"start-projection-watcher\";\n requestId: string;\n sessionId: string;\n rootId: string;\n layerFramework: LayerFramework;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n }\n | { type: \"cancel-projection-watcher\"; requestId: string }\n | { type: \"request-projection-full\"; watcherId: string }\n | {\n type: \"capture-projection-semantic-subtree\";\n requestId: string;\n watcherId: string;\n targetFiberId: string;\n }\n | {\n type: \"capture-projection-region\";\n requestId: string;\n watcherId: string;\n targetId: string;\n }\n | { type: \"stop-projection-watcher\"; watcherId: string };\n\ntype ProjectionChannelEvent =\n | { type: \"ready\" }\n | { type: \"watcher-started\"; requestId: string; watcherId: string }\n | { type: \"batch\"; batch: unknown }\n | {\n type: \"semantic-subtree\";\n requestId: string;\n subtree: unknown;\n error?: string;\n }\n | {\n type: \"region\";\n requestId: string;\n region: unknown;\n error?: string;\n }\n | {\n type: \"error\";\n error: string;\n requestId: unknown;\n watcherId: unknown;\n };\n\ninterface ProjectionChannel {\n readonly readinessTimeoutMessage: string;\n nextWatcherRequestId(): string;\n send(command: ProjectionChannelCommand): void;\n listen(listener: (event: ProjectionChannelEvent) => void): () => void;\n}\n\ninterface ProjectionChannelWatchOptions {\n sessionId: string;\n rootId: string;\n layerFramework: LayerFramework;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n timeout?: number;\n signal?: AbortSignal;\n onBatch(batch: CombinedProjectionBatch): void;\n onError?(error: Error): void;\n}\n\nfunction normalizeProjectionChannelEvent(\n value: unknown,\n): ProjectionChannelEvent | null {\n if (!isRecord(value) || typeof value.type !== \"string\") return null;\n switch (value.type) {\n case \"combined-source-ready\":\n case \"combined-pong\":\n case \"source-ready\":\n case \"pong\":\n return { type: \"ready\" };\n case \"projection-watcher-started\":\n return typeof value.requestId === \"string\" &&\n typeof value.watcherId === \"string\"\n ? {\n type: \"watcher-started\",\n requestId: value.requestId,\n watcherId: value.watcherId,\n }\n : null;\n case \"projection-batch\":\n return { type: \"batch\", batch: value.batch };\n case \"projection-semantic-subtree-response\":\n return typeof value.requestId === \"string\"\n ? {\n type: \"semantic-subtree\",\n requestId: value.requestId,\n subtree: value.subtree,\n error: typeof value.error === \"string\" ? value.error : undefined,\n }\n : null;\n case \"projection-region-response\":\n return typeof value.requestId === \"string\"\n ? {\n type: \"region\",\n requestId: value.requestId,\n region: value.region,\n error: typeof value.error === \"string\" ? value.error : undefined,\n }\n : null;\n case \"combined-error\":\n case \"error\":\n return typeof value.error === \"string\"\n ? {\n type: \"error\",\n error: value.error,\n requestId: value.requestId,\n watcherId: value.watcherId,\n }\n : null;\n default:\n return null;\n }\n}\n\nfunction errorFromUnknown(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\nfunction bestEffort(action: () => void): void {\n try {\n action();\n } catch {\n // Reload and destruction are normal transport teardown boundaries.\n }\n}\n\nasync function waitForProjectionChannelReady(\n channel: ProjectionChannel,\n timeout: number,\n signal?: AbortSignal,\n): Promise<void> {\n await waitForChannelEvent(channel, {\n signal,\n timeout,\n timeoutError: channel.readinessTimeoutMessage,\n abortError: combinedSetupAbortError,\n retryInterval: 100,\n send: () => channel.send({ type: \"ping\" }),\n receive: (event) =>\n event.type === \"ready\"\n ? { status: \"success\", value: undefined }\n : undefined,\n });\n}\n\nfunction requestProjectionChannelWatcher(\n channel: ProjectionChannel,\n options: {\n sessionId: string;\n rootId: string;\n layerFramework: LayerFramework;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n },\n timeout: number,\n signal?: AbortSignal,\n): Promise<string> {\n const requestId = channel.nextWatcherRequestId();\n return waitForChannelEvent(channel, {\n signal,\n timeout,\n timeoutError: \"Timeout waiting for projection watcher to start\",\n abortError: combinedSetupAbortError,\n onAbort: () =>\n channel.send({ type: \"cancel-projection-watcher\", requestId }),\n send: () =>\n channel.send({\n type: \"start-projection-watcher\",\n requestId,\n ...options,\n }),\n receive: (event) => {\n if (event.type === \"watcher-started\" && event.requestId === requestId) {\n return { status: \"success\", value: event.watcherId };\n }\n if (\n event.type === \"error\" &&\n (event.requestId === undefined || event.requestId === requestId)\n ) {\n return { status: \"failure\", error: new Error(event.error) };\n }\n return undefined;\n },\n });\n}\n\nlet nextProjectionSemanticQueryRequestId = 1;\n\nfunction requestProjectionChannelSemanticSubtree(\n channel: ProjectionChannel,\n watcherId: string,\n targetFiberId: string,\n timeout: number,\n signal: AbortSignal,\n): Promise<DetachSerializedFiber | null> {\n const requestId = `projection-semantic-query-${nextProjectionSemanticQueryRequestId++}`;\n return waitForChannelEvent(channel, {\n signal,\n timeout,\n timeoutError: \"Timeout waiting for projection semantic subtree\",\n abortError: () => new Error(\"Projection semantic query was cancelled\"),\n send: () =>\n channel.send({\n type: \"capture-projection-semantic-subtree\",\n requestId,\n watcherId,\n targetFiberId,\n }),\n receive: (event) => {\n if (event.type !== \"semantic-subtree\" || event.requestId !== requestId) {\n return undefined;\n }\n if (event.error) {\n return { status: \"failure\", error: new Error(event.error) };\n }\n if (\n event.subtree !== null &&\n !isProjectionSemanticSubtree(event.subtree)\n ) {\n return {\n status: \"failure\",\n error: new Error(\n \"Projection source returned an invalid semantic subtree\",\n ),\n };\n }\n return { status: \"success\", value: event.subtree };\n },\n });\n}\n\nlet nextProjectionRegionQueryRequestId = 1;\n\nfunction requestProjectionChannelRegion(\n channel: ProjectionChannel,\n watcherId: string,\n targetId: string,\n timeout: number,\n signal: AbortSignal,\n): Promise<ProjectionRegionCapture | null> {\n const requestId = `projection-region-query-${nextProjectionRegionQueryRequestId++}`;\n return waitForChannelEvent(channel, {\n signal,\n timeout,\n timeoutError: \"Timeout waiting for projection region capture\",\n abortError: () => new Error(\"Projection region query was cancelled\"),\n send: () =>\n channel.send({\n type: \"capture-projection-region\",\n requestId,\n watcherId,\n targetId,\n }),\n receive: (event) => {\n if (event.type !== \"region\" || event.requestId !== requestId) {\n return undefined;\n }\n if (event.error) {\n return { status: \"failure\", error: new Error(event.error) };\n }\n if (event.region !== null && !isProjectionRegionCapture(event.region)) {\n return {\n status: \"failure\",\n error: new Error(\n \"Projection source returned an invalid region capture\",\n ),\n };\n }\n return { status: \"success\", value: event.region };\n },\n });\n}\n\nasync function watchProjectionChannel(\n channel: ProjectionChannel,\n options: ProjectionChannelWatchOptions,\n): Promise<ProjectionBatchWatcher> {\n const {\n sessionId,\n rootId,\n layerFramework,\n selector,\n fiberSelector,\n fiberTags,\n timeout = 10000,\n signal,\n onBatch,\n onError,\n } = options;\n const normalizedSessionId = sessionId.trim();\n const normalizedRootId = rootId.trim();\n if (!normalizedSessionId) {\n throw new Error(\"Projection session ID must not be empty\");\n }\n if (!normalizedRootId) {\n throw new Error(\"Projection root ID must not be empty\");\n }\n\n await waitForProjectionChannelReady(channel, timeout, signal);\n\n let stopped = false;\n let watcherId: string | null = null;\n const pendingBatches: CombinedProjectionBatch[] = [];\n const removeListener = channel.listen((event) => {\n if (stopped) return;\n if (event.type === \"batch\") {\n const batch = decodeCombinedProjectionBatch(event.batch);\n if (!batch || batch.sessionId !== normalizedSessionId) return;\n if (watcherId === null) pendingBatches.push(batch);\n else onBatch(batch);\n return;\n }\n if (\n watcherId !== null &&\n event.type === \"error\" &&\n (event.watcherId === undefined || event.watcherId === watcherId)\n ) {\n onError?.(new Error(event.error));\n }\n });\n\n try {\n watcherId = await requestProjectionChannelWatcher(\n channel,\n {\n sessionId: normalizedSessionId,\n rootId: normalizedRootId,\n layerFramework,\n selector,\n fiberSelector,\n fiberTags,\n },\n timeout,\n signal,\n );\n } catch (error) {\n stopped = true;\n bestEffort(removeListener);\n throw error;\n }\n\n const activeWatcherId = watcherId;\n if (signal?.aborted) {\n stopped = true;\n bestEffort(removeListener);\n bestEffort(() =>\n channel.send({\n type: \"stop-projection-watcher\",\n watcherId: activeWatcherId,\n }),\n );\n throw combinedSetupAbortError();\n }\n\n for (const batch of pendingBatches) onBatch(batch);\n pendingBatches.length = 0;\n // Every in-flight on-demand query (semantic subtree and region capture),\n // so stopping the watcher cancels them instead of leaving them to time out.\n const pendingQueryControllers = new Set<AbortController>();\n\n return {\n id: activeWatcherId,\n requestFull() {\n if (stopped) return;\n bestEffort(() =>\n channel.send({\n type: \"request-projection-full\",\n watcherId: activeWatcherId,\n }),\n );\n },\n captureSemanticSubtree(targetFiberId) {\n if (stopped) {\n return Promise.reject(new Error(\"Projection watcher has been stopped\"));\n }\n const normalizedTargetFiberId = targetFiberId.trim();\n if (!normalizedTargetFiberId) {\n return Promise.reject(\n new Error(\"Projection semantic target ID must not be empty\"),\n );\n }\n const controller = new AbortController();\n pendingQueryControllers.add(controller);\n return requestProjectionChannelSemanticSubtree(\n channel,\n activeWatcherId,\n normalizedTargetFiberId,\n timeout,\n controller.signal,\n ).finally(() => pendingQueryControllers.delete(controller));\n },\n captureRegion(targetId) {\n if (stopped) {\n return Promise.reject(new Error(\"Projection watcher has been stopped\"));\n }\n const normalizedTargetId = targetId.trim();\n if (!normalizedTargetId) {\n return Promise.reject(\n new Error(\"Projection region target ID must not be empty\"),\n );\n }\n const controller = new AbortController();\n pendingQueryControllers.add(controller);\n return requestProjectionChannelRegion(\n channel,\n activeWatcherId,\n normalizedTargetId,\n timeout,\n controller.signal,\n ).finally(() => pendingQueryControllers.delete(controller));\n },\n stop() {\n if (stopped) return;\n stopped = true;\n for (const controller of pendingQueryControllers) controller.abort();\n pendingQueryControllers.clear();\n bestEffort(removeListener);\n bestEffort(() =>\n channel.send({\n type: \"stop-projection-watcher\",\n watcherId: activeWatcherId,\n }),\n );\n },\n };\n}\n\nlet nextLegacyIframeWatcherRequestId = 1;\n\nfunction createIframeLegacyCombinedChannel(\n contentWindow: Window,\n targetOrigin: string,\n): LegacyCombinedChannel {\n return {\n readinessTimeoutMessage:\n \"Timeout waiting for combined iframe source - did you call startCombinedSourceInterface()?\",\n nextWatcherRequestId: () =>\n `combined-watch-req-${nextLegacyIframeWatcherRequestId++}`,\n nextCaptureRequestId: () => {\n throw new Error(\"The legacy iframe transport has no one-shot capture\");\n },\n send(command) {\n let wireCommand: Record<string, unknown>;\n switch (command.type) {\n case \"ping\":\n wireCommand = { type: \"combined-ping\" };\n break;\n case \"start-watcher\":\n wireCommand = { ...command, type: \"start-combined-watcher\" };\n break;\n case \"set-watcher-paused\":\n wireCommand = {\n ...command,\n type: \"set-combined-watcher-paused\",\n };\n break;\n case \"stop-watcher\":\n wireCommand = { ...command, type: \"stop-combined-watcher\" };\n break;\n case \"capture\":\n throw new Error(\n \"The legacy iframe transport has no one-shot capture\",\n );\n }\n contentWindow.postMessage(\n { ...wireCommand, [MESSAGE_MARKER]: true },\n targetOrigin,\n );\n },\n listen(listener) {\n const handleMessage = (event: MessageEvent): void => {\n if (event.source !== contentWindow || !isMessage(event.data)) return;\n const normalized = normalizeLegacyCombinedChannelEvent(event.data);\n if (normalized) listener(normalized);\n };\n window.addEventListener(\"message\", handleMessage);\n return () => window.removeEventListener(\"message\", handleMessage);\n },\n };\n}\n\n/**\n * Watch an iframe through the pre-ProjectionBatch complete-capture protocol.\n *\n * @deprecated Use {@link watchProjectionBatchesIframe}. This adapter is\n * intentionally isolated from the exact Canvas projection path.\n */\nexport function watchCombinedIframe(\n iframe: HTMLIFrameElement,\n options: WatchCombinedIframeOptions,\n): Promise<CombinedWatcher> {\n const contentWindow = iframe.contentWindow;\n if (!contentWindow) {\n return Promise.reject(new Error(\"Cannot access iframe contentWindow\"));\n }\n return watchLegacyCombinedChannel(\n createIframeLegacyCombinedChannel(\n contentWindow,\n options.targetOrigin ?? \"*\",\n ),\n options,\n );\n}\n\nlet nextProjectionIframeWatcherRequestId = 1;\n\nfunction createIframeProjectionChannel(\n contentWindow: Window,\n targetOrigin: string,\n): ProjectionChannel {\n return {\n readinessTimeoutMessage:\n \"Timeout waiting for combined iframe source - did you call startCombinedSourceInterface()?\",\n nextWatcherRequestId: () =>\n `projection-iframe-watch-${nextProjectionIframeWatcherRequestId++}`,\n send(command) {\n const wireCommand =\n command.type === \"ping\"\n ? { type: \"combined-ping\", [MESSAGE_MARKER]: true }\n : { ...command, [MESSAGE_MARKER]: true };\n contentWindow.postMessage(wireCommand, targetOrigin);\n },\n listen(listener) {\n const handleMessage = (event: MessageEvent): void => {\n if (event.source !== contentWindow || !isMessage(event.data)) return;\n const normalized = normalizeProjectionChannelEvent(event.data);\n if (normalized) listener(normalized);\n };\n window.addEventListener(\"message\", handleMessage);\n return () => window.removeEventListener(\"message\", handleMessage);\n },\n };\n}\n\n/**\n * Subscribe directly to the iframe document's ordered ProjectionBatch stream.\n * Source capture remains live during destination previews; the watcher exposes\n * only explicit full recovery and teardown, never source-side pause/resume.\n */\nexport function watchProjectionBatchesIframe(\n iframe: HTMLIFrameElement,\n options: WatchProjectionBatchesIframeOptions,\n): Promise<ProjectionBatchWatcher> {\n const contentWindow = iframe.contentWindow;\n if (!contentWindow) {\n return Promise.reject(new Error(\"Cannot access iframe contentWindow\"));\n }\n return watchProjectionChannel(\n createIframeProjectionChannel(contentWindow, options.targetOrigin ?? \"*\"),\n options,\n );\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Webview Support (Electron IPC instead of postMessage)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface PageMessageHandle {\n send: (channel: string, ...args: unknown[]) => void;\n on: (channel: string, callback: (...args: unknown[]) => void) => () => void;\n}\n\nexport interface CombinedWebviewBridge {\n sendToHost: (channel: string, payload: unknown) => void;\n onCommand: (handler: (payload: unknown) => void) => () => void;\n}\n\nexport interface CombinedWebviewSourceOptions<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n> {\n serialize?: SerializeFn<T>;\n hideFiberProp?: string;\n}\n\n/**\n * One exact document-projection subscription over the frame-pool page bridge.\n * Source observation remains current while destination-local preview queues\n * pause; the transport itself has no pause operation.\n */\nexport interface ProjectionBatchWatcher {\n readonly id: string;\n requestFull(): void;\n /** Cold source-side capture of exactly one selected semantic branch. */\n captureSemanticSubtree(\n targetFiberId: string,\n ): Promise<DetachSerializedFiber | null>;\n /** Cold scoped-repair capture of one element's exact children region; null\n * when the id no longer exists at the source. */\n captureRegion(targetId: string): Promise<ProjectionRegionCapture | null>;\n stop(): void;\n}\n\nexport interface WatchProjectionBatchesIframeOptions {\n /** Lifecycle-owned identity. A reloaded iframe receives a new session. */\n sessionId: string;\n /** Stable identity used by the Canvas destination to route root-local work. */\n rootId: string;\n layerFramework: LayerFramework;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n timeout?: number;\n targetOrigin?: string;\n /** Cancels source-readiness and watcher establishment. */\n signal?: AbortSignal;\n onBatch(batch: CombinedProjectionBatch): void;\n onError?(error: Error): void;\n}\n\nexport interface WatchProjectionBatchesPageOptions {\n /** Lifecycle-owned identity. A reloaded document receives a new session. */\n sessionId: string;\n /** Stable identity used by the Canvas destination to route root-local work. */\n rootId: string;\n layerFramework: LayerFramework;\n selector?: string;\n fiberSelector?: string;\n fiberTags?: FiberTagValue[];\n timeout?: number;\n /** Cancels source-readiness and watcher establishment. */\n signal?: AbortSignal;\n onBatch(batch: CombinedProjectionBatch): void;\n onError?(error: Error): void;\n}\n\nlet webviewCombinedSourceInitialized = false;\nlet webviewCombinedSourceCleanup: (() => void) | null = null;\n\nexport function startCombinedSourceWebviewInterface<\n T extends EnrichedFiberConstraint = EnrichedFiberNode,\n>(\n bridge: CombinedWebviewBridge,\n options: CombinedWebviewSourceOptions<T> = {},\n): () => void {\n if (webviewCombinedSourceInitialized) {\n console.warn(\"[combined-postmessage:webview-source] Already initialized\");\n return webviewCombinedSourceCleanup || (() => {});\n }\n\n webviewCombinedSourceInitialized = true;\n let disposeDeferredInstall = () => {};\n let disposed = false;\n const cleanup = () => {\n if (disposed) return;\n disposed = true;\n disposeDeferredInstall();\n if (webviewCombinedSourceCleanup === cleanup) {\n webviewCombinedSourceCleanup = null;\n webviewCombinedSourceInitialized = false;\n }\n };\n webviewCombinedSourceCleanup = cleanup;\n const deferredInstall = installWhenDocumentBodyReady(() =>\n initCombinedWebviewSourceInterface(bridge, options),\n );\n if (disposed) deferredInstall();\n else disposeDeferredInstall = deferredInstall;\n return cleanup;\n}\n\nfunction initCombinedWebviewSourceInterface<T extends EnrichedFiberConstraint>(\n bridge: CombinedWebviewBridge,\n options: CombinedWebviewSourceOptions<T>,\n): () => void {\n (window as any).__IFRAME_PROJECTION_COMBINED_WEBVIEW_INTERFACE_ACTIVE__ =\n true;\n\n const send = (type: string, payload: Record<string, unknown>) => {\n bridge.sendToHost(\"combined-projection:update\", { type, ...payload });\n };\n\n const projectionSource = createProjectionSourceController<T>({\n document,\n watcherIdPrefix: \"webview-projection-watcher\",\n serialize: options.serialize,\n hideFiberProp: options.hideFiberProp,\n send,\n });\n const legacyWatchers = new Map<string, CombinedWatchHandle>();\n let nextLegacyWatcherId = 1;\n\n const handleCommand = (payload: unknown) => {\n if (!isRecord(payload) || typeof payload.type !== \"string\") {\n return;\n }\n if (projectionSource.handleCommand(payload)) return;\n\n switch (payload.type) {\n case \"ping\": {\n send(\"pong\", {});\n break;\n }\n\n // Deprecated compatibility commands are deliberately handled after the\n // exact projection controller. They instantiate their own compatibility\n // envelope only when an old destination explicitly requests one.\n case \"start-watcher\": {\n const requestId =\n typeof payload.requestId === \"string\" ? payload.requestId : undefined;\n const selector =\n typeof payload.selector === \"string\" ? payload.selector : undefined;\n const fiberSelector =\n typeof payload.fiberSelector === \"string\"\n ? payload.fiberSelector\n : undefined;\n const fiberTags = Array.isArray(payload.fiberTags)\n ? (payload.fiberTags as FiberTagValue[])\n : undefined;\n const debounceDelay =\n typeof payload.debounceDelay === \"number\"\n ? payload.debounceDelay\n : undefined;\n const maxWait =\n typeof payload.maxWait === \"number\" ? payload.maxWait : undefined;\n const watcherId = `webview-combined-watcher-${nextLegacyWatcherId++}`;\n\n try {\n const pendingCaptures: CombinedCapture<T>[] = [];\n let established = false;\n const watcher = watchCombinedSelector<T>(\n document,\n selector,\n (capture) => {\n if (!established) {\n pendingCaptures.push(capture);\n return;\n }\n send(\"combined-update\", { watcherId, capture });\n },\n {\n debounceDelay,\n maxWait,\n fiberSelector,\n fiberTags,\n serialize: options.serialize,\n hideFiberProp: options.hideFiberProp,\n },\n );\n legacyWatchers.set(watcherId, watcher);\n send(\"watcher-started\", {\n watcherId,\n ...(requestId ? { requestId } : {}),\n });\n established = true;\n for (const capture of pendingCaptures) {\n send(\"combined-update\", { watcherId, capture });\n }\n } catch (error) {\n send(\"error\", {\n ...(requestId ? { requestId } : {}),\n error: error instanceof Error ? error.message : String(error),\n });\n }\n break;\n }\n\n case \"stop-watcher\": {\n const watcherId =\n typeof payload.watcherId === \"string\" ? payload.watcherId : undefined;\n if (!watcherId) break;\n const watcher = legacyWatchers.get(watcherId);\n if (!watcher) break;\n watcher.stop();\n legacyWatchers.delete(watcherId);\n send(\"watcher-stopped\", { watcherId });\n break;\n }\n\n case \"set-watcher-paused\": {\n const watcherId =\n typeof payload.watcherId === \"string\" ? payload.watcherId : undefined;\n if (!watcherId) break;\n legacyWatchers.get(watcherId)?.setPaused(payload.paused === true);\n break;\n }\n\n case \"capture\": {\n const requestId =\n typeof payload.requestId === \"string\" ? payload.requestId : undefined;\n if (!requestId) break;\n const selector =\n typeof payload.selector === \"string\" ? payload.selector : undefined;\n const fiberSelector =\n typeof payload.fiberSelector === \"string\"\n ? payload.fiberSelector\n : undefined;\n const fiberTags = Array.isArray(payload.fiberTags)\n ? (payload.fiberTags as FiberTagValue[])\n : undefined;\n\n try {\n let capture: CombinedCapture<T> | null = null;\n const watcher = watchCombinedSelector<T>(\n document,\n selector,\n (nextCapture) => {\n capture ??= nextCapture;\n },\n {\n fiberSelector,\n fiberTags,\n serialize: options.serialize,\n hideFiberProp: options.hideFiberProp,\n },\n );\n watcher.stop();\n send(\"capture-response\", { requestId, capture });\n } catch (error) {\n send(\"capture-response\", {\n requestId,\n capture: null,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n break;\n }\n }\n };\n\n const removeListener = bridge.onCommand(handleCommand);\n send(\"source-ready\", {});\n\n return () => {\n removeListener();\n projectionSource.stop();\n for (const watcher of legacyWatchers.values()) watcher.stop();\n legacyWatchers.clear();\n delete (window as any)\n .__IFRAME_PROJECTION_COMBINED_WEBVIEW_INTERFACE_ACTIVE__;\n };\n}\n\nlet nextLegacyPageWatcherRequestId = 1;\nlet nextLegacyPageCaptureRequestId = 1;\n\nfunction createPageLegacyCombinedChannel(\n page: PageMessageHandle,\n): LegacyCombinedChannel {\n return {\n readinessTimeoutMessage:\n \"Timeout waiting for combined source - did you call startCombinedSourceWebviewInterface()?\",\n nextWatcherRequestId: () =>\n `combined-page-watch-${nextLegacyPageWatcherRequestId++}`,\n nextCaptureRequestId: () =>\n `combined-capture-${nextLegacyPageCaptureRequestId++}`,\n send(command) {\n page.send(\"combined-projection:command\", command);\n },\n listen(listener) {\n return page.on(\"combined-projection:update\", (message) => {\n const normalized = normalizeLegacyCombinedChannelEvent(message);\n if (normalized) listener(normalized);\n });\n },\n };\n}\n\n/**\n * Watch a frame-pool page through the pre-ProjectionBatch complete-capture\n * protocol.\n *\n * @deprecated Use {@link watchProjectionBatchesPage}. This adapter is opt-in\n * and does not participate in the Canvas projection stream.\n */\nexport function watchCombinedPage(\n page: PageMessageHandle,\n options: WatchCombinedPageOptions,\n): Promise<CombinedWatcher> {\n return watchLegacyCombinedChannel(\n createPageLegacyCombinedChannel(page),\n options,\n );\n}\n\n/**\n * Capture one complete compatibility envelope from a frame-pool page.\n *\n * @deprecated Prefer exact ProjectionBatch streaming for live projection.\n * This remains a cold query and creates no persistent destination model.\n */\nexport function captureCombinedPage(\n page: PageMessageHandle,\n options: CaptureCombinedPageOptions = {},\n): Promise<CombinedCapture | null> {\n return captureLegacyCombinedChannel(\n createPageLegacyCombinedChannel(page),\n options,\n );\n}\n\n/**\n * Subscribe to the exact document producer owned by a frame-pool page.\n * Transport stays structural: it forwards ProjectionBatch and never rebuilds\n * a CombinedCapture compatibility envelope in the Canvas renderer.\n */\nexport function watchProjectionBatchesPage(\n page: PageMessageHandle,\n options: WatchProjectionBatchesPageOptions,\n): Promise<ProjectionBatchWatcher> {\n return watchProjectionChannel(createPageProjectionChannel(page), options);\n}\n\nlet nextProjectionPageWatcherRequestId = 1;\n\nfunction createPageProjectionChannel(\n page: PageMessageHandle,\n): ProjectionChannel {\n return {\n readinessTimeoutMessage:\n \"Timeout waiting for combined source - did you call startCombinedSourceWebviewInterface()?\",\n nextWatcherRequestId: () =>\n `projection-page-watch-${nextProjectionPageWatcherRequestId++}`,\n send(command) {\n page.send(\"combined-projection:command\", command);\n },\n listen(listener) {\n return page.on(\"combined-projection:update\", (message) => {\n const normalized = normalizeProjectionChannelEvent(message);\n if (normalized) listener(normalized);\n });\n },\n };\n}\n\nfunction combinedSetupAbortError(): Error {\n const error = new Error(\"Combined watcher setup aborted\");\n error.name = \"AbortError\";\n return error;\n}\n","import { startCombinedSourceInterface } from \"../../../modules/iframe-projection/combined/postmessage.ts\";\nimport type { FiberRoot } from \"../../../modules/iframe-projection/fiber/react-types.ts\";\nimport { initHook } from \"../../../modules/iframe-projection/fiber/watch.ts\";\nimport { isTempoInteractFrameName } from \"./interact-frame.ts\";\n\nconst PENDING_ROOTS_KEY = \"__tempoPendingFiberRoots\";\n\ntype BootstrapHook = ReturnType<typeof initHook>[\"hook\"] & {\n [PENDING_ROOTS_KEY]?: Map<number, FiberRoot>;\n};\n\n/**\n * Starts the combined DOM + React source used by Tempo's direct interact iframe.\n * The Vite plugin installs a synchronous hook first; replaying its latest roots\n * here closes the small gap while this lazy client module is loading.\n */\nexport function installTempoInteractProjectionSource(): () => void {\n if (\n typeof window === \"undefined\" ||\n window.parent === window ||\n !isTempoInteractFrameName(window.name)\n ) {\n return () => {};\n }\n\n const hookInterface = initHook();\n const hook = hookInterface.hook as BootstrapHook;\n const pendingRoots = hook[PENDING_ROOTS_KEY];\n if (pendingRoots) {\n hookInterface.seedCommittedRoots(pendingRoots);\n pendingRoots.clear();\n delete hook[PENDING_ROOTS_KEY];\n }\n\n return startCombinedSourceInterface();\n}\n"],"mappings":";;;;;;;;AAiCO,IAAM,WAAW;AAAA;AAAA,EAEtB,mBAAmB;AAAA;AAAA,EAGnB,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMhB,wBAAwB;AAAA;AAAA,EAGxB,UAAU;AAAA;AAAA,EAGV,YAAY;AAAA;AAAA,EAGZ,eAAe;AAAA;AAAA,EAGf,UAAU;AAAA;AAAA,EAGV,UAAU;AAAA;AAAA,EAGV,MAAM;AA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OAAO,WAAW,UAClB,CAAC,yBAAyB,OAAO,IAAI,GACrC;AACA,WAAO,MAAM;AAAA,IAAC;AAAA,EAChB;AAEA,QAAM,gBAAgB,SAAS;AAC/B,QAAM,OAAO,cAAc;AAC3B,QAAM,eAAe,KAAK,iBAAiB;AAC3C,MAAI,cAAc;AAChB,kBAAc,mBAAmB,YAAY;AAC7C,iBAAa,MAAM;AACnB,WAAO,KAAK,iBAAiB;AAAA,EAC/B;AAEA,SAAO,6BAA6B;AACtC;","names":["document","nextFiberId","isContentEditableBoundary","parseInlineStyle","parseInlineStyle","instance","perf","boundary","document","normalizeTempoDataSet","hasContextDependencies","hasContentEditableAncestor","coordinateOnlyPortalIds","isRecord"]}