tempo-sdk 0.0.60 → 0.0.66

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.
Files changed (108) hide show
  1. package/astro/client.d.ts +4 -0
  2. package/dist/assets/editor.js +1 -1
  3. package/dist/assets/index.d.ts +10 -63
  4. package/dist/assets/index.js +12 -32
  5. package/dist/assets/index.js.map +1 -1
  6. package/dist/assets/parser.js +1 -1
  7. package/dist/astro/asset-preview-client.d.ts +4 -0
  8. package/dist/astro/asset-preview-client.js +93 -0
  9. package/dist/astro/asset-preview-client.js.map +1 -0
  10. package/dist/astro/controls.d.ts +7 -0
  11. package/dist/astro/controls.js +7 -0
  12. package/dist/astro/controls.js.map +1 -0
  13. package/dist/astro/document-client.d.ts +10 -0
  14. package/dist/astro/document-client.js +78 -0
  15. package/dist/astro/document-client.js.map +1 -0
  16. package/dist/astro/runtime.d.ts +15 -0
  17. package/dist/astro/runtime.js +86 -0
  18. package/dist/astro/runtime.js.map +1 -0
  19. package/dist/astro.d.ts +21 -0
  20. package/dist/astro.js +749 -0
  21. package/dist/astro.js.map +1 -0
  22. package/dist/canvas/astro-contract.d.ts +21 -0
  23. package/dist/canvas/astro-contract.js +9 -0
  24. package/dist/canvas/astro-contract.js.map +1 -0
  25. package/dist/canvas/astro.d.ts +18 -0
  26. package/dist/canvas/astro.js +42 -0
  27. package/dist/canvas/astro.js.map +1 -0
  28. package/dist/canvas/editor.d.ts +1 -1
  29. package/dist/canvas/editor.js +3 -2
  30. package/dist/canvas/editor.js.map +1 -1
  31. package/dist/canvas/index.d.ts +1 -1
  32. package/dist/canvas/index.js +40 -16
  33. package/dist/canvas/index.js.map +1 -1
  34. package/dist/canvas/interact-projection.js +4 -4
  35. package/dist/canvas/parser.d.ts +3 -1
  36. package/dist/canvas/parser.js +1 -1
  37. package/dist/canvas/svelte.d.ts +1 -1
  38. package/dist/canvas/svelte.js +3 -3
  39. package/dist/{chunk-5BHIHP25.js → chunk-2JRAG36X.js} +37 -11
  40. package/dist/chunk-2JRAG36X.js.map +1 -0
  41. package/dist/{chunk-N2TYN3RB.js → chunk-6AAE4LYV.js} +123 -123
  42. package/dist/chunk-6AAE4LYV.js.map +1 -0
  43. package/dist/{chunk-7DT5DDSH.js → chunk-6IR5JY6W.js} +106 -7
  44. package/dist/chunk-6IR5JY6W.js.map +1 -0
  45. package/dist/{chunk-FQSZRVSL.js → chunk-6W6UKDSY.js} +45 -4
  46. package/dist/chunk-6W6UKDSY.js.map +1 -0
  47. package/dist/chunk-77DZCV5Z.js +38 -0
  48. package/dist/chunk-77DZCV5Z.js.map +1 -0
  49. package/dist/chunk-DELFOKU3.js +2495 -0
  50. package/dist/chunk-DELFOKU3.js.map +1 -0
  51. package/dist/{chunk-MXKZZOLM.js → chunk-EYKOOLPL.js} +368 -32
  52. package/dist/chunk-EYKOOLPL.js.map +1 -0
  53. package/dist/chunk-F23JGM4U.js +107 -0
  54. package/dist/chunk-F23JGM4U.js.map +1 -0
  55. package/dist/chunk-FE6TYCLF.js +1514 -0
  56. package/dist/chunk-FE6TYCLF.js.map +1 -0
  57. package/dist/chunk-H6OZIX2U.js +133 -0
  58. package/dist/chunk-H6OZIX2U.js.map +1 -0
  59. package/dist/chunk-JVVHU3A7.js +1077 -0
  60. package/dist/chunk-JVVHU3A7.js.map +1 -0
  61. package/dist/{chunk-2IQD2KPS.js → chunk-KOSJXE4G.js} +3 -102
  62. package/dist/chunk-KOSJXE4G.js.map +1 -0
  63. package/dist/{chunk-TL4MGN7E.js → chunk-NSKYOKG5.js} +254 -10
  64. package/dist/chunk-NSKYOKG5.js.map +1 -0
  65. package/dist/chunk-OX2YKYSL.js +13 -0
  66. package/dist/chunk-OX2YKYSL.js.map +1 -0
  67. package/dist/{chunk-VMTQDG4U.js → chunk-PXDTH36X.js} +12 -10
  68. package/dist/chunk-PXDTH36X.js.map +1 -0
  69. package/dist/{chunk-XLEKCOB7.js → chunk-PYAJHLXO.js} +56 -1
  70. package/dist/chunk-PYAJHLXO.js.map +1 -0
  71. package/dist/{chunk-OTVBSF7U.js → chunk-Q2A46HHW.js} +17 -12
  72. package/dist/chunk-Q2A46HHW.js.map +1 -0
  73. package/dist/controls-reader-SNMI2UY7.js +191 -0
  74. package/dist/controls-reader-SNMI2UY7.js.map +1 -0
  75. package/dist/controls-uCaQ3CNX.d.ts +61 -0
  76. package/dist/expo/plugin.cjs +16 -11
  77. package/dist/expo/plugin.cjs.map +1 -1
  78. package/dist/expo/plugin.js +1 -1
  79. package/dist/expo-babel-plugin.cjs +16 -11
  80. package/dist/expo-babel-plugin.cjs.map +1 -1
  81. package/dist/expo-babel-plugin.js +1 -1
  82. package/dist/index.d.ts +4 -0
  83. package/dist/index.js +10 -2465
  84. package/dist/index.js.map +1 -1
  85. package/dist/nextjs/plugin.cjs +44 -3
  86. package/dist/nextjs/plugin.cjs.map +1 -1
  87. package/dist/nextjs/plugin.js +1 -1
  88. package/dist/nextjs-loader.cjs +60 -14
  89. package/dist/nextjs-loader.cjs.map +1 -1
  90. package/dist/nextjs.cjs +44 -3
  91. package/dist/nextjs.cjs.map +1 -1
  92. package/dist/nextjs.d.cts +4 -4
  93. package/dist/nextjs.d.ts +4 -4
  94. package/dist/nextjs.js +1 -1
  95. package/dist/{storyboard-DjOF61B_.d.ts → storyboard-4YdTYq_e.d.ts} +1 -1
  96. package/dist/svelte.js +7 -1075
  97. package/dist/svelte.js.map +1 -1
  98. package/package.json +44 -3
  99. package/dist/chunk-2IQD2KPS.js.map +0 -1
  100. package/dist/chunk-5BHIHP25.js.map +0 -1
  101. package/dist/chunk-7DT5DDSH.js.map +0 -1
  102. package/dist/chunk-FQSZRVSL.js.map +0 -1
  103. package/dist/chunk-MXKZZOLM.js.map +0 -1
  104. package/dist/chunk-N2TYN3RB.js.map +0 -1
  105. package/dist/chunk-OTVBSF7U.js.map +0 -1
  106. package/dist/chunk-TL4MGN7E.js.map +0 -1
  107. package/dist/chunk-VMTQDG4U.js.map +0 -1
  108. package/dist/chunk-XLEKCOB7.js.map +0 -1
@@ -1 +0,0 @@
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/fiber/projection-scope.ts","../../../modules/iframe-projection/combined/realm-epoch.ts","../../../modules/iframe-projection/html/watch-dom.ts","../../../modules/iframe-projection/combined/projection-observed-files.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-patch.ts","../../../modules/iframe-projection/combined/projection-dom-layers.ts","../../../modules/iframe-projection/combined/projection-layer-snapshot.ts","../../../modules/iframe-projection/combined/projection-pending.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 (a hook may have none: a cleared DevTools hook)\n if (callbacks.onInject && typeof hook.inject === \"function\") {\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) > 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) > 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","import { type Fiber, FiberTag } from \"./react-types\";\n\n/** Generic renderer metadata. It never travels through user component props. */\nexport const PROJECTION_SCOPE_ROLE = \"__tempoProjectionScopeRole\";\nexport type ProjectionScopeRole = \"transparent\" | \"output\";\nfunction role(fiber: Fiber | null): ProjectionScopeRole | undefined {\n const type = fiber?.type as {\n [PROJECTION_SCOPE_ROLE]?: ProjectionScopeRole;\n } | null;\n return type?.[PROJECTION_SCOPE_ROLE];\n}\n/** The output marker owns one invocation. React's memo wrapper may add a\n * second invocation fiber for it; neither is an authored content layer. */\nfunction isOutputInvocation(fiber: Fiber): boolean {\n const parent = fiber.return;\n return (\n role(parent) === \"output\" ||\n (parent?.tag === FiberTag.MemoComponent && isOutputInvocation(parent))\n );\n}\nexport function isProjectionScopePlumbing(fiber: Fiber): boolean {\n return role(fiber) !== undefined || isOutputInvocation(fiber);\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 * 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 { REALM_DOCUMENT_EPOCH } from \"../combined/realm-epoch\";\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\nexport const HOST_LAYER_ID_ATTR = \"data-host-layer-id\";\n\n/** Stamped by the host on an element that is a projection root of its own\n * (the SDK's storyboard content slot). What lies below it is that root's:\n * a root above it publishes the element itself, never its content. */\nexport const PROJECTION_ROOT_ATTRIBUTE = \"data-tempo-projection-root\";\n\n// Every id minted in this realm is `${prefix}-${counter}`. The prefix is the\n// bound session id, which the canvas mints unique per document generation,\n// so an id from another document or an earlier generation can only miss,\n// never collide. Until a session is bound the realm epoch stands in.\nlet idPrefix = REALM_DOCUMENT_EPOCH;\nlet idCounter = 0;\nlet liveElementIds = new WeakMap<Node, string>();\n\nexport function getSessionHash(): string {\n return idPrefix;\n}\n\nexport function nextProjectionId(): string {\n return `${idPrefix}-${idCounter++}`;\n}\n\n/** Ids minted from now on carry `sessionId`. Ids already assigned keep their\n * prefix: the WeakMap is the authority and an id never changes under an\n * element the destination may already know. */\nexport function seedProjectionIds(sessionId: string): void {\n idPrefix = sessionId;\n}\n\n/**\n * Resets the session state. Primarily for testing.\n * @internal\n */\nexport function _resetSessionState(): void {\n idPrefix = REALM_DOCUMENT_EPOCH;\n idCounter = 0;\n liveElementIds = new WeakMap();\n}\n\n/**\n * True when another projection root's element lies on the path from `element`\n * (inclusive) up to `root` (exclusive): the element is that root's content,\n * not `root`'s. A root's own element carrying the attribute is never foreign\n * to itself.\n */\nexport function underForeignProjectionRoot(\n element: Element,\n root: Element,\n): boolean {\n for (\n let current: Element | null = element;\n current && current !== root;\n current = current.parentElement\n ) {\n if (current.hasAttribute(PROJECTION_ROOT_ATTRIBUTE)) return true;\n }\n return false;\n}\n\n/**\n * `scope` and every element below it that `scope`'s watcher publishes.\n * Another projection root's element below `scope` is listed (it is part of\n * this tree) but nothing under it is: that content is the other root's.\n * Scripts never cross the wire and are left out.\n */\nexport function projectedElements(scope: Element): Element[] {\n const elements: Element[] = [];\n const stack: Element[] = [scope];\n while (stack.length > 0) {\n const element = stack.pop()!;\n if (element.tagName.toLowerCase() === \"script\") continue;\n elements.push(element);\n if (element !== scope && element.hasAttribute(PROJECTION_ROOT_ATTRIBUTE))\n continue;\n for (let index = element.children.length - 1; index >= 0; index -= 1) {\n stack.push(element.children[index]!);\n }\n }\n return elements;\n}\n\n/**\n * Assigns a unique projection id to one live source element. The attribute is\n * the transport carrier, not the identity authority: application code can\n * copy it with cloneNode(true), while object identity cannot be copied.\n */\nfunction assignDomId(element: Element): string {\n let id = liveElementIds.get(element);\n if (!id) {\n id = nextProjectionId();\n liveElementIds.set(element, id);\n }\n if (element.getAttribute(DOM_ID_ATTR) !== id) {\n element.setAttribute(DOM_ID_ATTR, id);\n }\n if (element.getAttribute(HOST_LAYER_ID_ATTR) !== id) {\n element.setAttribute(HOST_LAYER_ID_ATTR, id);\n }\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(\n element: Node,\n root?: Element,\n): string | null {\n if (element.nodeType === 3 || element.nodeType === 8) {\n let parent = element.parentElement;\n if (!parent) return readProjectionDomId(element);\n // Registry templates are producer metadata, stripped from the mirror.\n // Positional bindings count only nodes carried by the projection.\n const position = [\n Array.from(parent.childNodes)\n .filter(\n (child) =>\n !(child instanceof Element) ||\n (child.localName !== \"script\" &&\n !child.hasAttribute(\"data-tempo-svelte-source-registry\")),\n )\n .indexOf(element as ChildNode),\n ];\n // The destination container stands in for the watched root, so text\n // under the root is addressed through the root sentinel. The root's own\n // seeded id scopes the sentinel: like every host id, it never repeats on\n // another board or in another document generation.\n const rootDomId = root ? ensureProjectionDomId(root) : null;\n const rootParentId = rootDomId && `$projection-root:${rootDomId}`;\n let parentId =\n parent === root ? rootParentId : ensureProjectionDomId(parent);\n // Editor-owned elements stay unstamped; their text still has an exact\n // child path from the nearest stamped ancestor.\n while (!parentId && parent !== root && parent.parentElement) {\n position.unshift(\n Array.from(parent.parentElement.childNodes)\n .filter(\n (child) =>\n !(child instanceof Element) ||\n (child.localName !== \"script\" &&\n !child.hasAttribute(\"data-tempo-svelte-source-registry\")),\n )\n .indexOf(parent),\n );\n parent = parent.parentElement;\n parentId =\n parent === root ? rootParentId : ensureProjectionDomId(parent);\n }\n if (!parentId) return null;\n const kind = element.nodeType === 3 ? \"text\" : \"comment\";\n const id = `${parentId}/${kind}/${position.join(\"/\")}`;\n liveElementIds.set(element, id);\n return id;\n }\n if (!(element instanceof Element)) return null;\n if (hasContentEditableAncestor(element)) return null;\n return assignDomId(element);\n}\n\n/** Read an identity already allocated for an exact source reference. */\nexport function readProjectionDomId(element: Node): string | null {\n return liveElementIds.get(element) ?? null;\n}\n\n/**\n * Register the stable carrier selected by a producer-owned detached document.\n *\n * Static HTML projection reparses source into a new detached document for each\n * revision, then transfers carriers between corresponding model elements. Its\n * parsed elements are the producer's reference authority rather than live app\n * DOM, so registering the transferred carrier preserves patch addressing\n * without teaching `ensureProjectionDomId` to trust application attributes.\n */\nexport function registerDetachedProjectionDomId(\n element: Node,\n id: string,\n): string {\n liveElementIds.set(element, id);\n return element instanceof Element ? assignDomId(element) : id;\n}\n\n/**\n * Copy the allocator's authoritative ids into a detached transport clone.\n * `cloneNode(true)` also copies application-provided identity attributes, so\n * serializers reconcile the clone against live element references before\n * publishing it. Editor-owned descendants remain unstamped even when their\n * authored DOM contains copied carrier attributes.\n */\nexport function syncProjectionDomIdsToClone(\n liveRoot: Element,\n cloneRoot: Element,\n includeRoot = true,\n): void {\n const pending: Array<readonly [Element, Element]> = includeRoot\n ? [[liveRoot, cloneRoot]]\n : Array.from(\n liveRoot.children,\n (liveChild, index) => [liveChild, cloneRoot.children[index]!] as const,\n );\n while (pending.length > 0) {\n const [live, clone] = pending.pop()!;\n const id =\n live.tagName.toLowerCase() === \"script\"\n ? null\n : ensureProjectionDomId(live);\n if (id) {\n clone.setAttribute(DOM_ID_ATTR, id);\n clone.setAttribute(HOST_LAYER_ID_ATTR, id);\n } else {\n clone.removeAttribute(DOM_ID_ATTR);\n clone.removeAttribute(HOST_LAYER_ID_ATTR);\n }\n // The clone carries another root's element as an empty shell: its content\n // is published by that root, so the destination never receives it twice.\n if (live !== liveRoot && live.hasAttribute(PROJECTION_ROOT_ATTRIBUTE)) {\n clone.replaceChildren();\n continue;\n }\n for (let index = 0; index < live.children.length; index += 1) {\n const liveChild = live.children[index];\n const cloneChild = clone.children[index];\n if (liveChild && cloneChild) pending.push([liveChild, cloneChild]);\n }\n }\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, watchedRoot: Element): void {\n if (hasContentEditableAncestor(root)) {\n return;\n }\n ensureProjectionDomId(root);\n if (isContentEditableRoot(root)) {\n return;\n }\n if (root !== watchedRoot && root.hasAttribute(PROJECTION_ROOT_ATTRIBUTE)) {\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 // Another root's content is stamped by that root's watcher.\n if (element.hasAttribute(PROJECTION_ROOT_ATTRIBUTE)) {\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, root);\n\n const retainMutations = (mutations: readonly MutationRecord[]): 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 // A record under another projection root's element is that root's\n // content: its watcher retains it, this one never sees it. The\n // element's own attributes still belong to the watcher above it, so\n // the walk starts at the element whose children the record concerns.\n const concernedParent =\n mutation.type === \"attributes\"\n ? (mutation.target as Element).parentElement\n : mutation.target instanceof Element\n ? mutation.target\n : mutation.target.parentElement;\n if (concernedParent && underForeignProjectionRoot(concernedParent, root))\n continue;\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 const isProjectionId =\n mutation.attributeName === DOM_ID_ATTR ||\n mutation.attributeName === HOST_LAYER_ID_ATTR;\n if (isProjectionId) 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, root);\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","import type { ProjectionLayerProps } from \"./projection-layer-snapshot\";\n\nexport interface ProjectionObservedFile {\n /** Minimum timestamp across every serialized target from this file. */\n readonly modifiedTs: number;\n /** The content of the stamps at that minimum timestamp: present only when\n * every one of them reports the same 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. It carries the content of\n * the stamps at that oldest timestamp, retained only when they agree: the\n * region is no newer than those (V-a, catch-up 2026-09-26).\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 if (modifiedTs > current.modifiedTs) return;\n if (modifiedTs < current.modifiedTs) {\n current.modifiedTs = modifiedTs;\n current.sourceVersion = sourceVersion;\n return;\n }\n if (current.sourceVersion !== sourceVersion)\n current.sourceVersion = undefined;\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 addLayerProps(props: ProjectionLayerProps | undefined): void {\n if (!props) return;\n this.add(\n props[\"data-tempo-filepath\"],\n props[\"data-tempo-modifiedts\"],\n props[\"data-tempo-source-version\"],\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 }\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","/**\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\";\nimport {\n FORM_RUNTIME_MUTATION,\n observeRuntimeMutations,\n} from \"./runtime-mutations\";\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 const stopRuntimeMutations = observeRuntimeMutations(root.ownerDocument);\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 document.addEventListener(FORM_RUNTIME_MUTATION, 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 document.removeEventListener(\n FORM_RUNTIME_MUTATION,\n handleFormChange,\n true,\n );\n stopRuntimeMutations();\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 type ProjectionDomMutation,\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 /** Retain already queued DOM records before a synchronous baseline. */\n takePendingDomRecords(): number;\n\n /** Clear retained regional candidates after a caller captured final state. */\n clearPendingChanges(): {\n dom: ProjectionDomMutation[];\n state: ProjectionStateEvent[];\n };\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 takePendingDomRecords: () => domWatcher.takePendingRecords(),\n\n clearPendingChanges() {\n return {\n dom: drainProjectionDomMutations(domWatcher),\n state: drainProjectionStateEvents(stateWatcher),\n };\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","import { removeScriptTags } from \"../html/capture\";\nimport type { PortalCoordinateSpace } from \"../html/types\";\nimport {\n DOM_ID_ATTR,\n ensureProjectionDomId,\n projectedElements,\n readProjectionDomId,\n syncProjectionDomIdsToClone,\n} 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 // Expression facts describe the same callsite, so they travel, update and\n // are distrusted exactly like the location stamps.\n \"data-tempo-expr\",\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 type ProjectionDomPatch =\n | ProjectionAttributePatch\n | ProjectionRegionPatch\n | ProjectionRemovePatch\n | ProjectionPlacePatch;\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 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 layers?: import(\"./projection-root-accumulator\").ProjectionLayerPatch;\n readonly pointerEventsNone?: readonly string[];\n readonly dom: readonly ProjectionDomPatch[];\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 readonly observedFiles: ProjectionObservedFileMap;\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 observedFiles = new ProjectionObservedFileAccumulator();\n const fallbackRegions = new Set<Element>();\n const childListMutations: ProjectionMutationInput[] = [];\n const characterDataTargets: Node[] = [];\n const attributes = new Map<Element, Set<string>>();\n const metadataTargets = new Set<Element>();\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 isSourceMetadata = SOURCE_ANNOTATION_ATTRIBUTES.has(\n mutation.attributeName,\n );\n if (isSourceMetadata) {\n metadataTargets.add(element);\n continue;\n }\n const names = attributes.get(element) ?? new Set<string>();\n names.add(mutation.attributeName);\n attributes.set(element, names);\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 metadata: import(\"./projection-layer-snapshot\").ProjectionLayerMetadataSnapshot[] =\n [];\n\n for (const removed of removedElements) {\n const targetId = readProjectionDomId(removed);\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(\n added,\n observedFiles,\n );\n placements.push({\n kind: \"place\",\n parentId,\n targetId,\n beforeId,\n html: captured.html,\n ancestorIds: captureProjectionAncestorIds(root, added),\n });\n }\n\n for (const target of characterDataTargets) {\n const parent = target.parentElement;\n if (!parent || coveredByAddedElement(parent)) continue;\n const targetId = ensureProjectionDomId(target, root);\n if (targetId)\n metadata.push({\n targetId,\n targetFiberId: targetId,\n content: target.textContent ?? \"\",\n ancestorIds: [\n ensureProjectionDomId(parent, root)!,\n ...captureProjectionAncestorIds(root, parent),\n ],\n });\n }\n for (const mutation of childListMutations) {\n const nodes = [\n ...(mutation.addedNodes ?? []),\n ...(mutation.removedNodes ?? []),\n ];\n if (nodes.some((node) => !(node instanceof Element))) {\n const parent =\n mutation.target instanceof Element\n ? mutation.target\n : mutation.target.parentElement;\n if (parent && !coveredByAddedElement(parent)) fallbackRegions.add(parent);\n }\n }\n\n // Unaddressable work widens to the nearest identifiable ancestor region;\n // its presentation rides in the region HTML instead of a separate 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 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, observedFiles);\n regionCaptures.set(region, captured);\n }\n\n const allTargets = new Set<Element>([\n ...survivingRegions,\n ...attributes.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 const pointerEventsNone = new Set<string>();\n for (const element of addedElements) {\n if (\n element.tagName.toLowerCase() === \"script\" ||\n survivingRegions.some(\n (region) => region === element || region.contains(element),\n )\n )\n continue;\n for (const target of projectedElements(element)) {\n const id = target.getAttribute(DOM_ID_ATTR);\n if (\n id &&\n target.ownerDocument.defaultView?.getComputedStyle(target)\n .pointerEvents === \"none\"\n ) {\n pointerEventsNone.add(id);\n }\n }\n }\n for (const element of attributes.keys()) {\n const id = ids.get(element);\n if (\n id &&\n element.ownerDocument.defaultView?.getComputedStyle(element)\n .pointerEvents === \"none\"\n ) {\n pointerEventsNone.add(id);\n }\n }\n return {\n ...(metadata.length ? { layers: { metadata } } : {}),\n ...(pointerEventsNone.size > 0\n ? { pointerEventsNone: [...pointerEventsNone] }\n : {}),\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 ...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 localMetadataTargets: Array.from(metadataTargets),\n observedFiles: observedFiles.snapshot(),\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 = ensureProjectionDomId(element);\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 {\n targetId,\n kind: \"checked\",\n checked: element.checked,\n ancestorIds,\n };\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 observedFiles: {},\n };\n }\n\n for (const live of projectedElements(element)) ensureProjectionDomId(live);\n const clone = element.cloneNode(true) as Element;\n syncProjectionDomIdsToClone(element, clone);\n for (const script of clone.querySelectorAll(\"script\")) script.remove();\n const observedFiles = new ProjectionObservedFileAccumulator();\n stripSourceAnnotations(clone, observedFiles, true);\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 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 : ensureProjectionDomId(element);\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 capturePlacedElementWithoutAnnotations(\n element: Element,\n observedFiles: ProjectionObservedFileAccumulator,\n): CapturedRegion {\n for (const live of projectedElements(element)) ensureProjectionDomId(live);\n const clone = element.cloneNode(true) as Element;\n syncProjectionDomIdsToClone(element, clone);\n if (clone.tagName.toLowerCase() === \"script\") {\n return { html: \"\" };\n }\n for (const script of clone.querySelectorAll(\"script\")) script.remove();\n stripSourceAnnotations(clone, observedFiles, true);\n return { html: clone.outerHTML };\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\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/** Observe before stripping so fiber-less HTML also constrains file freshness.\n * Clone identity survives stripping and supplies the producer's perf receipt. */\nexport function stripSourceAnnotations(\n cloneRoot: Element,\n observedFiles: ProjectionObservedFileAccumulator,\n includeRoot: boolean,\n): Set<string> {\n // Svelte's registry is needed only while capturing source-side layers.\n // Leaving unrecorded templates in the mirror changes insertion boundaries.\n for (const registry of cloneRoot.querySelectorAll(\n \"template[data-tempo-svelte-source-registry]\",\n ))\n registry.remove();\n const hostDomIds = new Set<string>();\n const walker = cloneRoot.ownerDocument.createTreeWalker(\n cloneRoot,\n NodeFilter.SHOW_ELEMENT,\n );\n let copy = (includeRoot ? cloneRoot : walker.nextNode()) as Element | null;\n while (copy) {\n observedFiles.add(\n copy.getAttribute(\"data-tempo-filepath\"),\n copy.getAttribute(\"data-tempo-modifiedts\"),\n copy.getAttribute(\"data-tempo-source-version\"),\n );\n const domId = copy.getAttribute(DOM_ID_ATTR);\n if (domId) hostDomIds.add(domId);\n for (const name of SOURCE_ANNOTATION_ATTRIBUTES) copy.removeAttribute(name);\n copy = walker.nextNode() as Element | null;\n }\n return hostDomIds;\n}\n\nexport interface CapturedRegion {\n readonly html: string;\n}\n\nexport function captureRegionWithoutAnnotations(\n element: Element,\n observedFiles: ProjectionObservedFileAccumulator,\n): CapturedRegion {\n for (const live of projectedElements(element)) ensureProjectionDomId(live);\n const clone = element.cloneNode(true) as Element;\n syncProjectionDomIdsToClone(element, clone, false);\n for (const script of clone.querySelectorAll(\"script\")) script.remove();\n stripSourceAnnotations(clone, observedFiles, false);\n return { html: clone.innerHTML };\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 (readProjectionDomId(current)) 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 if (element === root) return [];\n const ids: string[] = [];\n for (\n let current = element.parentElement;\n current && current !== root;\n current = current.parentElement\n ) {\n const id = readProjectionDomId(current);\n if (id) {\n ensureProjectionDomId(current);\n ids.push(id);\n }\n }\n return ids;\n}\n","import { FiberTag } from \"../fiber/react-types\";\nimport {\n DOM_ID_ATTR,\n ensureProjectionDomId,\n nextProjectionId,\n PROJECTION_ROOT_ATTRIBUTE,\n} from \"../html/watch-dom\";\nimport {\n layoutModeOf,\n type ProjectionLayerMetadataSnapshot,\n type ProjectionLayerNode,\n type ProjectionLayerProps,\n type ProjectionLayerRegionSnapshot,\n type ProjectionLayerRootSnapshot,\n} from \"./projection-layer-snapshot\";\nimport {\n ProjectionObservedFileAccumulator,\n type ProjectionObservedFileMap,\n} 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 id: new WeakMap(),\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 id: WeakMap<Element, string>;\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 id: new WeakMap(),\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 const observed = new ProjectionObservedFileAccumulator();\n observed.merge(observedFiles);\n const tree = serializeDomLayerRootNode(root, identity, observed);\n return {\n semantic: { kind: \"layers\", tree },\n observedFiles: observed.snapshot(),\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 const observed = new ProjectionObservedFileAccumulator();\n observed.merge(observedFiles);\n const tree =\n target === root\n ? serializeDomLayerRootNode(root, identity, observed)\n : serializeDomLayerNode(root, target, identity, observed);\n return {\n targetFiberId: layerIdForTarget(root, target, identity),\n targetId: id(root, target, identity),\n tree,\n observedFiles: observed.snapshot(),\n };\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 targetId: id(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 const observed = new ProjectionObservedFileAccumulator();\n observed.merge(observedFiles);\n const tree =\n target === root\n ? serializeDomLayerRootNode(root, dataDomLayerIdentity, observed)\n : serializeDomLayerNode(root, target, dataDomLayerIdentity, observed);\n return {\n targetFiberId: layerIdForTarget(root, target, dataDomLayerIdentity),\n targetId: id(root, target, dataDomLayerIdentity),\n tree,\n observedFiles: observed.snapshot(),\n };\n}\n\nexport function captureProjectionDomLayerMetadata(\n element: Element,\n): ProjectionLayerMetadataSnapshot | null {\n const domId = ensureProjectionDomId(element);\n if (!domId) return null;\n return {\n targetFiberId: projectionDomLayerId(domId),\n targetId: domId,\n props: captureProjectionDomLayerProps(element),\n };\n}\n\nfunction serializeDomLayerRootNode(\n root: Element,\n identity: DomLayerIdentity,\n observedFiles?: ProjectionObservedFileAccumulator,\n children?: readonly ProjectionLayerNode[],\n): ProjectionLayerNode {\n const name = root.tagName.toLowerCase();\n // The watched root is the document's own element (an HTML board's\n // <body>); when the source stamped it, its stamps travel on the root so\n // text and structure directly under it have a source site, and the\n // document counts as observed even with no stamped child left. Only the\n // four stamps are read, straight off the attributes: the root is a\n // fragment, not a subject, and a computed-style read per capture on\n // every DOM root is a cost the adapter budget forbids.\n const stamps = rootSourceStamps(root);\n observedFiles?.addLayerProps(stamps);\n return {\n kind: \"fragment\",\n runtime: \"dom\",\n id: id(root, root, identity),\n key: null,\n name,\n domId: null,\n elementTag: null,\n ...(stamps ? { props: stamps } : {}),\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.childNodes)\n .filter(\n (child) =>\n !(child instanceof Element) ||\n (child.localName !== \"script\" &&\n !child.hasAttribute(PROJECTION_ROOT_ATTRIBUTE)),\n )\n .flatMap(\n (child) =>\n serializeDomLayerNode(root, child, identity, observedFiles) ?? [],\n ),\n };\n}\n\n/** The props without the source annotation attributes. */\nfunction withoutSourceStamps(\n props: ProjectionLayerProps | undefined,\n): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(props ?? {}).filter(\n ([key]) => !SOURCE_ANNOTATION_ATTRIBUTES.has(key),\n ),\n );\n}\n\n/** Whether `element` is the first element under `root` (document order,\n * the root excluded) carrying its own (filepath, position) stamp pair. An\n * unstamped element is trivially first. Read from the live document, so a\n * patch of one subtree judges its elements against the whole document. The\n * root never competes: it is serialized as its own site, and an HTML\n * document with no <body> tag gets an implied body stamped at its first\n * element's position, so root and first child share a pair by design. */\nfunction firstStampCarrier(root: Element, element: Element): boolean {\n const filepath = element.getAttribute(\"data-tempo-filepath\");\n const position = element.getAttribute(\"data-tempo-position\");\n if (filepath === null || position === null) return true;\n const quote = (value: string) => `\"${value.replace(/[\"\\\\]/g, \"\\\\$&\")}\"`;\n const selector = `[data-tempo-filepath=${quote(filepath)}][data-tempo-position=${quote(position)}]`;\n return root.querySelector(selector) === element;\n}\n\nfunction rootSourceStamps(root: Element): ProjectionLayerProps | undefined {\n const stamps: Record<string, string | number> = {};\n for (const name of SOURCE_ANNOTATION_ATTRIBUTES) {\n const value = root.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)) stamps[name] = numeric;\n } else stamps[name] = value;\n }\n return Object.keys(stamps).length\n ? (stamps as unknown as ProjectionLayerProps)\n : undefined;\n}\n\nexport function serializeDomLayerNode(\n root: Element | null,\n element: Node,\n identity: DomLayerIdentity = dataDomLayerIdentity,\n observedFiles?: ProjectionObservedFileAccumulator,\n children?: readonly ProjectionLayerNode[],\n): ProjectionLayerNode | null {\n if (element.nodeType === 3 || element.nodeType === 8) {\n const kind = element.nodeType === 3 ? \"text\" : \"comment\";\n // Null only under editor-owned content with no stamped ancestor up to the\n // root (a root inside a contenteditable): such text has no address.\n const domId = ensureProjectionDomId(element, root ?? undefined);\n if (domId === null) return null;\n return {\n kind,\n id: domId,\n content: element.textContent ?? \"\",\n };\n }\n if (!(element instanceof Element))\n throw new Error(\"Invalid projection child\");\n const domId = identity.bindableDomIdForElement(root ?? element, element);\n const name = element.tagName.toLowerCase();\n const props = captureProjectionDomLayerProps(element, observedFiles);\n // A React descendant without a Fiber has no authored callsite. Raw HTML\n // or cloneNode may copy stamps, but those cannot authorize source writes.\n // Under a document root a location is attached only when proven\n // (V2-214): the annotator stamps each source element once, so the first\n // element of the document carrying a (filepath, position) pair is that\n // source element, and a later carrier is a runtime copy (a script's\n // cloneNode), a host with no location. DOM observation still owns its\n // existence.\n const hostProps =\n root && firstStampCarrier(root, element)\n ? props\n : withoutSourceStamps(props);\n return {\n kind: \"host\",\n runtime: \"dom\",\n id: domId ?? id(root ?? element, element, identity),\n key: null,\n name,\n domId,\n elementTag: name,\n props: hostProps && Object.keys(hostProps).length ? hostProps : undefined,\n source: {\n kind: \"react-fiber\",\n fiber: {\n tag: FiberTag.HostComponent,\n name,\n id: identity.layerIdForElement(root ?? element, element),\n },\n },\n // Another root's element ends this root's tree, as the React lane's\n // serializer does: what it holds is that root's to publish.\n children:\n children ??\n Array.from(element.childNodes)\n .filter(\n (child) =>\n !(child instanceof Element) ||\n (child.localName !== \"script\" &&\n !child.hasAttribute(PROJECTION_ROOT_ATTRIBUTE)),\n )\n .flatMap(\n (child) =>\n serializeDomLayerNode(root, child, identity, observedFiles) ?? [],\n ),\n };\n}\n\n// Synthetic roots and unbound hosts need stable ids without changing V1 bindings.\nfunction id(\n root: Element,\n element: Element,\n identity: DomLayerIdentity,\n): string {\n const domId =\n element === root ? null : identity.bindableDomIdForElement(root, element);\n if (domId !== null) return domId;\n const existing = identity.id.get(element);\n if (existing) return existing;\n const value = nextProjectionId();\n identity.id.set(element, value);\n return value;\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 observedFiles?: ProjectionObservedFileAccumulator,\n): ProjectionLayerProps | undefined {\n const props: Record<string, unknown> = {};\n const locked = element.getAttribute(\"data-tempo-locked\");\n if (locked === \"true\" || locked === \"\") props[\"data-tempo-locked\"] = true;\n else if (locked === \"false\") props[\"data-tempo-locked\"] = false;\n const layoutMode = layoutModeOf(getComputedStyle(element));\n if (layoutMode) props.layoutMode = layoutMode;\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 for (const name of [\"data-tempo-storyboard-root\", \"data-tempo-hide-fiber\"]) {\n const value = element.getAttribute(name);\n if (value !== null) props[name] = value !== \"false\";\n }\n observedFiles?.addLayerProps(props);\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 or copy an\n * arbitrary component prop bag. Computed layout is reduced to one host fact.\n * Source annotations and exact observed-file facts are collected during the\n * same Fiber enumeration that creates the semantic tree.\n */\n\nimport { getFiberFromElement } from \"../fiber/capture\";\nimport { isProjectionScopePlumbing } from \"../fiber/projection-scope\";\nimport { type Fiber, FiberTag, type FiberTagValue } from \"../fiber/react-types\";\nimport {\n getDisplayName,\n getDomElement,\n getProps,\n resolveCommittedFiber,\n} from \"../fiber/serialize\";\nimport { getCommittedFiberRoots } from \"../fiber/watch\";\nimport {\n ensureProjectionDomId,\n nextProjectionId,\n PROJECTION_ROOT_ATTRIBUTE,\n} from \"../html/watch-dom\";\nimport { serializeDomLayerNode } from \"./projection-dom-layers\";\nimport {\n ProjectionObservedFileAccumulator,\n type ProjectionObservedFileMap,\n} from \"./projection-observed-files\";\n\nexport type ProjectionLayerKind =\n | \"host\"\n | \"component\"\n | \"fragment\"\n | \"text\"\n | \"comment\";\n\n/** The complete top-level prop allowlist consumed by LayerSnapshot today. */\nexport interface ProjectionLayerProps {\n readonly \"data-tempo-locked\"?: boolean;\n readonly className?: string;\n readonly layoutMode?: \"grid\" | \"flex-row\" | \"flex-column\";\n readonly points?: 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 /** The SDK's compile step stamps a Storyboard callsite with what its\n * `component` prop resolves to; the canvas folds it into source identity. */\n readonly \"data-tempo-component-reference\"?: string;\n readonly \"data-tempo-external-component\"?: string;\n readonly \"data-tempo-storyboard-root\"?: boolean;\n readonly \"data-tempo-hide-fiber\"?: boolean;\n /** The SDK's Canvas element and each Storyboard shell stamp their\n * declaration as one JSON attribute; the canvas reads them off the page\n * root's layers. */\n readonly \"data-tempo-canvas-declaration\"?: string;\n readonly \"data-tempo-storyboard-declaration\"?: string;\n /** The storyboard's id, stamped on its shell beside the declaration so the\n * canvas registers roots without parsing the declaration JSON. */\n readonly \"data-tempo-storyboard-id\"?: string;\n readonly \"data-tempo-supports-style\"?: boolean;\n readonly \"data-tempo-supports-classname\"?: boolean;\n readonly \"data-tempo-supports-children\"?: boolean;\n /** Expression facts the SDK transform stamps: space-separated tokens\n * (`#slot`, attribute names, `style.<key>`). The canvas reads them to\n * route an edit to AI before the writer is asked. */\n readonly \"data-tempo-expr\"?: string;\n}\n\n// V1 lets grid win, collapses inline variants and reverse directions, and ignores wrap.\n// Positioned divs have no layout mode.\nexport function layoutModeOf(\n style: CSSStyleDeclaration,\n): ProjectionLayerProps[\"layoutMode\"] | undefined {\n if (/grid/.test(style.display)) return \"grid\";\n if (!/flex/.test(style.display)) return undefined;\n return /^column/.test(style.flexDirection) ? \"flex-column\" : \"flex-row\";\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\n/** Evidence from committed React objects, scoped by the receiver to its\n * document session and watched root. Keys and source positions are not proof. */\nexport interface ProjectionPortalRuntime {\n /** Unowned physical target, absent from the transported owned DOM roots. */\n readonly target?: true;\n readonly nodeId?: string;\n readonly fiberId?: string;\n readonly ownerFiberId: string;\n}\n\ninterface ProjectionLayerNodeBase {\n readonly portal?: ProjectionPortalRuntime;\n /** Actual observation adapter for this node; not the project framework. */\n readonly runtime?: \"react\" | \"svelte\" | \"dom\";\n /** This is the HostLayerId, the id the host reports for this layer this time.\n * It is the same string the element carries as data-host-layer-id when there\n * is an element. The canvas never uses it as identity over time, React reuses\n * fibers and elements by position across a reorder. It uses it as evidence. */\n readonly id: string;\n readonly key: string | null;\n readonly name: string;\n readonly content?: 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: string | null;\n readonly elementTag: null;\n}\n\nexport type ProjectionLayerNode =\n | ProjectionHostLayerNode\n | ProjectionElementlessLayerNode\n | {\n readonly kind: \"text\" | \"comment\";\n readonly portal?: ProjectionPortalRuntime;\n /** The positional id is also the receiver's DOM binding. */\n readonly id: string;\n readonly content: string;\n readonly runtime?: never;\n readonly key?: never;\n readonly name?: never;\n readonly elementTag?: never;\n readonly domId?: never;\n readonly props?: never;\n readonly source?: never;\n readonly children?: never;\n };\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 */\n/** An observation container, never an editable layer or a React identity. */\nexport interface ProjectionScopeFragment {\n readonly kind: \"fragment\";\n readonly children: readonly ProjectionLayerNode[];\n}\nexport const PROJECTION_SCOPE_TARGET = \"$projection-scope\";\nexport function projectionLayerRoots(\n snapshot: ProjectionLayerRootSnapshot,\n): readonly ProjectionLayerNode[] {\n const semantic = snapshot.semantic;\n return semantic.kind === \"scope\"\n ? semantic.fragment.children\n : semantic.kind === \"layers\" && semantic.tree\n ? [semantic.tree]\n : [];\n}\nexport interface ProjectionLayerRootSnapshot {\n readonly semantic:\n | { readonly kind: \"layers\"; readonly tree: ProjectionLayerNode | null }\n | { readonly kind: \"scope\"; readonly fragment: ProjectionScopeFragment }\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 /** Replaces the watched scope contents; never inserts a wrapper layer. */\n readonly scope?: ProjectionScopeFragment;\n readonly targetFiberId: string;\n readonly targetId: 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 /** Nearest-first DOM ancestors for text/comment application repair. */\n readonly ancestorIds?: readonly string[];\n readonly content?: string;\n readonly targetFiberId: string;\n readonly targetId: 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 portalClosure(root: Fiber): { required: boolean; nodesVisited: number };\n /** Serialize one committed Fiber root in one synchronous enumeration. */\n serialize(root: Fiber): ProjectionLayerSerializationResult;\n /** A DOM scope may contain several independent React roots. */\n serializeContents(): 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?: {\n readonly sourceAnnotations?: \"fiber\" | \"live-host\";\n /** Reuse this pass's host read; null avoids rereading a known none. */\n readonly layoutMode?: ProjectionLayerProps[\"layoutMode\"] | null;\n },\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(\n /** The element this serializer's root is watched from. Text directly under\n * it is named through the scoped root sentinel, as in the DOM lane: the\n * destination container stands in for this element. */\n watchedRoot?: Element,\n contentsScope = false,\n includeRoot = false,\n): ProjectionLayerSerializer {\n const fiberIds = new WeakMap<Fiber, string>();\n const portalNodeIds = new WeakMap<Node, string>();\n let publishedPortalAncestors = new WeakSet<Fiber>();\n let publishedTargetAncestors = new Set<Node>();\n let observedRoot: Fiber | null = null;\n const physicalAggregations = new WeakSet<Fiber>();\n const aggregatesPhysicalTargets = (fiber: Fiber) =>\n physicalAggregations.has(fiber) ||\n (fiber.alternate !== null && physicalAggregations.has(fiber.alternate));\n const portalNodeId = (node: Node): string => {\n const known = portalNodeIds.get(node);\n if (known) return known;\n const value = nextProjectionId();\n portalNodeIds.set(node, value);\n return value;\n };\n const ids = new WeakMap<Fiber, string>();\n\n function id(fiber: Fiber): string {\n // Text under editor-owned content with no stamped ancestor has no DOM\n // address; like a DOM-less fiber it takes a minted id below.\n const node =\n fiber.tag === FiberTag.HostText && fiber.stateNode instanceof Node\n ? fiber.stateNode\n : fiber.tag === FiberTag.HostComponent\n ? getDomElement(fiber)\n : null;\n const domId = node ? ensureProjectionDomId(node, watchedRoot) : null;\n if (domId !== null) return domId;\n const direct = ids.get(fiber);\n if (direct) return direct;\n const alternate = fiber.alternate ? ids.get(fiber.alternate) : null;\n if (alternate) {\n ids.set(fiber, alternate);\n return alternate;\n }\n const value = nextProjectionId();\n ids.set(fiber, value);\n if (fiber.alternate) ids.set(fiber.alternate, value);\n return value;\n }\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 // Same seeded realm counter as every DOM id: nothing on the wire is\n // unprefixed, so a fiber id from another document can only miss.\n const id = nextProjectionId();\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 = (\n root: Fiber | null,\n observation = false,\n ): ProjectionLayerSerializationResult => {\n const observedFiles = new ProjectionObservedFileAccumulator();\n let fiberNodesVisited = 0;\n let semanticNodesSerialized = 0;\n const portalOwners = new Map<Fiber, Fiber>();\n const portalTargets = new Map<Element, Fiber[]>();\n const emittedNodes = new Set<Node>();\n // The committed tree establishes ownership before a physical DOM walk\n // can encounter the same portal through its target and its React caller.\n const collectOwnership = (fiber: Fiber, portal?: Fiber) => {\n if (fiber !== root && isProjectionRootFiber(fiber)) return;\n fiberNodesVisited += 1;\n if (fiber.tag === FiberTag.HostPortal) {\n portal = fiber;\n const target = (fiber.stateNode as { containerInfo?: unknown })\n ?.containerInfo;\n if (target instanceof Element) {\n const entries = portalTargets.get(target) ?? [];\n entries.push(fiber);\n portalTargets.set(target, entries);\n }\n }\n if (portal) portalOwners.set(fiber, portal);\n for (let child = fiber.child; child; child = child.sibling)\n collectOwnership(child, portal);\n };\n if (root) collectOwnership(root);\n else if (watchedRoot) {\n for (const committed of getCommittedFiberRoots()) {\n const container = committed.containerInfo;\n if (!(container instanceof Element) || !watchedRoot.contains(container))\n continue;\n let boundary: Element | null = container;\n while (\n boundary &&\n boundary !== watchedRoot &&\n !boundary.hasAttribute(PROJECTION_ROOT_ATTRIBUTE)\n )\n boundary = boundary.parentElement;\n if (boundary === watchedRoot) collectOwnership(committed.current);\n }\n }\n if (observation) observedRoot = root;\n if (\n root === observedRoot ||\n root?.alternate === observedRoot ||\n observedRoot?.alternate === root\n ) {\n publishedPortalAncestors = new WeakSet();\n // React may detach a deleted Fiber's return chain after the commit.\n // Retain the observed ancestors themselves, not a later walk of that\n // mutable deleted chain, so portal removal still closes publication.\n for (const portals of portalTargets.values())\n for (const portal of portals)\n for (\n let ancestor: Fiber | null = portal;\n ancestor;\n ancestor = ancestor.return\n )\n publishedPortalAncestors.add(ancestor);\n publishedTargetAncestors = new Set();\n for (const target of portalTargets.keys())\n for (let node: Node | null = target; node; node = node.parentNode)\n publishedTargetAncestors.add(node);\n }\n const portalOf = (fiber: Fiber): Fiber | undefined => {\n const known = portalOwners.get(fiber);\n if (known) return known;\n for (let owner = fiber.return; owner; owner = owner.return) {\n if (owner.tag === FiberTag.HostPortal) return owner;\n if (isProjectionRootFiber(owner)) break;\n }\n };\n const portalRuntime = (fiber: Fiber, node?: Node) => {\n const portal = portalOf(fiber);\n return portal\n ? {\n ...(node ? { nodeId: portalNodeId(node) } : {}),\n fiberId: fiberId(fiber),\n ownerFiberId: fiberId(portal.return ?? portal),\n }\n : undefined;\n };\n const domChildren = (\n element: Element,\n parent?: Fiber,\n allowed?: ReadonlySet<Node>,\n inheritedPortal?: Fiber,\n ): ProjectionLayerNode[] => {\n const physicalPortal = (parent && portalOf(parent)) ?? inheritedPortal;\n const annotations = new Map<Node, { fiber: Fiber; chain: Fiber[] }>();\n const extras: { fiber: Fiber; chain: Fiber[]; before?: Node }[] = [];\n const pending: typeof extras = [];\n const collect = (fiber: Fiber, chain: Fiber[]): boolean => {\n if (isProjectionRootFiber(fiber)) return false;\n if (fiber.tag === FiberTag.HostPortal) {\n // Its physical target owns emission. The caller may still be an\n // empty component, but it cannot add a second physical child.\n return false;\n }\n const node =\n fiber.tag === FiberTag.HostText\n ? fiber.stateNode\n : fiber.tag === FiberTag.HostComponent\n ? getDomElement(fiber)\n : null;\n if (node instanceof Node) {\n annotations.set(node, { fiber, chain });\n for (const extra of pending.splice(0)) extra.before = node;\n return true;\n }\n fiberNodesVisited += 1;\n const included = isProjectionLayerFiber(fiber);\n const next = included ? [...chain, fiber] : chain;\n let hasChildren = false;\n for (let child = fiber.child; child; child = child.sibling)\n hasChildren = collect(child, next) || hasChildren;\n if (!hasChildren && included) {\n const extra = { fiber, chain };\n extras.push(extra);\n pending.push(extra);\n return true;\n }\n return hasChildren;\n };\n if (parent)\n for (let child = parent.child; child; child = child.sibling)\n collect(child, []);\n for (const portal of portalTargets.get(element) ?? [])\n for (let child = portal.child; child; child = child.sibling)\n collect(child, []);\n\n const extrasByNode = new Map<Node, typeof extras>();\n const trailing: typeof extras = [];\n for (const extra of extras) {\n if (!extra.before || extra.before.parentNode !== element)\n trailing.push(extra);\n else {\n const group = extrasByNode.get(extra.before) ?? [];\n group.push(extra);\n extrasByNode.set(extra.before, group);\n }\n }\n const children: ProjectionLayerNode[] = [];\n const components = new Map<Fiber, ProjectionLayerNode[]>();\n const seen = new Set<Fiber>();\n const destinationOf = (chain: readonly Fiber[], node?: Node) => {\n // A component can own disjoint host roots. Reopening an earlier group\n // would move its later roots ahead of intervening DOM siblings.\n for (const component of components.keys()) {\n if (!chain.includes(component)) components.delete(component);\n }\n let destination = children;\n for (const component of chain) {\n let nested = components.get(component);\n if (!nested) {\n nested = [];\n components.set(component, nested);\n const branches = visit(component, nested);\n if (seen.has(component)) {\n const suffix =\n (node && ensureProjectionDomId(node, watchedRoot)) ||\n nextProjectionId();\n for (const branch of branches) {\n // The component source remains an annotation on each run;\n // each logical record still needs its own host-layer id.\n destination.push({ ...branch, id: `${branch.id}/${suffix}` });\n }\n } else destination.push(...branches);\n seen.add(component);\n }\n destination = nested;\n }\n return destination;\n };\n const appendExtra = (extra: (typeof extras)[number]) => {\n // Empty components and portals are logical branches, not extra DOM\n // children. A portal's elements live in its separately captured slot.\n destinationOf(extra.chain, extra.before).push(\n ...visit(\n extra.fiber,\n extra.fiber.tag === FiberTag.HostPortal ? undefined : [],\n ),\n );\n };\n // The live DOM owns membership and order. Fibers attach annotations and\n // component ancestry to those nodes, never contribute an extra child.\n for (const child of Array.from(element.childNodes)) {\n if (allowed && !allowed.has(child)) continue;\n if (\n child instanceof Element &&\n (child.localName === \"script\" ||\n child.hasAttribute(PROJECTION_ROOT_ATTRIBUTE))\n )\n continue;\n for (const extra of extrasByNode.get(child) ?? []) appendExtra(extra);\n const annotation = annotations.get(child);\n const destination = destinationOf(annotation?.chain ?? [], child);\n let fiber = annotation?.fiber;\n if (!fiber && child instanceof Element) {\n const candidate = getFiberFromElement(child);\n if (candidate) fiber = resolveCommittedFiber(candidate) ?? undefined;\n }\n if (fiber?.tag === FiberTag.HostRoot && child instanceof Element) {\n // An independently mounted React tree annotates this DOM container's\n // children. The container remains a real physical content node.\n const serialized = serializeDomLayerNode(\n null,\n child,\n undefined,\n undefined,\n domChildren(child, fiber),\n );\n if (serialized) destination.push(serialized);\n } else if (fiber) destination.push(...visit(fiber));\n else {\n // A fiber-less element's stamps cannot authorize source writes, so\n // it serializes without a root; the root only scopes a text id.\n const isElement = child instanceof Element;\n if (emittedNodes.has(child)) continue;\n emittedNodes.add(child);\n const serialized = serializeDomLayerNode(\n isElement ? null : (watchedRoot ?? null),\n child,\n undefined,\n undefined,\n isElement\n ? domChildren(child, undefined, undefined, physicalPortal)\n : undefined,\n );\n if (serialized) {\n const portal = physicalPortal;\n destination.push(\n portal\n ? {\n ...serialized,\n portal: {\n nodeId: portalNodeId(child),\n ownerFiberId: fiberId(portal.return ?? portal),\n },\n }\n : serialized,\n );\n semanticNodesSerialized += 1;\n }\n }\n }\n for (const extra of trailing) appendExtra(extra);\n return children;\n };\n\n const visit = (\n fiber: Fiber,\n suppliedChildren?: ProjectionLayerNode[],\n ): ProjectionLayerNode[] => {\n if (!suppliedChildren) fiberNodesVisited += 1;\n // Another root's element ends this root's subtree: what it holds is\n // published by that root (a storyboard's content slot under the page\n // root), never traversed here.\n if (fiber !== root && isProjectionRootFiber(fiber)) return [];\n if (fiber.tag === FiberTag.HostPortal) return [];\n if (\n fiber.tag === FiberTag.HostText &&\n fiber.stateNode instanceof Node &&\n fiber.stateNode.parentElement\n ) {\n if (emittedNodes.has(fiber.stateNode)) return [];\n emittedNodes.add(fiber.stateNode);\n // For a text node the root argument only scopes its id.\n const text = serializeDomLayerNode(\n watchedRoot ?? null,\n fiber.stateNode,\n );\n if (!text) return [];\n semanticNodesSerialized += 1;\n const portal = portalRuntime(fiber, fiber.stateNode);\n return [portal ? { ...text, portal } : text];\n }\n const name = getDisplayName(fiber);\n const kind = projectionKindForTag(fiber.tag);\n const included =\n isProjectionLayerFiber(fiber) &&\n !(\n contentsScope &&\n !includeRoot &&\n fiber === root &&\n getDomElement(fiber) === watchedRoot\n );\n const element = kind === \"host\" ? getDomElement(fiber) : null;\n if (element?.localName === \"script\") return [];\n if (element) {\n if (emittedNodes.has(element)) return [];\n emittedNodes.add(element);\n }\n const domId = element ? ensureProjectionDomId(element) : null;\n\n const props = included\n ? captureProjectionLayerProps(fiber, element)\n : undefined;\n observedFiles.addLayerProps(props);\n if (element) {\n // Imperative instrumentation may update the host without a React\n // render. Both authorities still constrain the conservative receipt.\n observedFiles.addLayerProps(\n captureProjectionLayerProps(\n fiber,\n element,\n \"live-host\",\n props?.layoutMode ?? null,\n ),\n );\n }\n\n const children =\n suppliedChildren ?? (element ? domChildren(element, fiber) : []);\n if (!suppliedChildren && !element)\n for (let child = fiber.child; child; child = child.sibling)\n children.push(...visit(child));\n\n if (!included) return children;\n if (kind === null || kind === \"text\" || kind === \"comment\")\n return children;\n\n const source: ProjectionLayerSource = {\n kind: \"react-fiber\",\n fiber: { tag: fiber.tag, name, id: fiberId(fiber) },\n };\n const portal = portalRuntime(fiber, element ?? undefined);\n let node: ProjectionLayerNode;\n if (kind === \"host\") {\n node = {\n runtime: \"react\",\n kind,\n id: domId ?? id(fiber),\n key: fiber.key == null ? null : String(fiber.key),\n name,\n domId,\n elementTag: name,\n props,\n source,\n ...(portal ? { portal } : {}),\n children,\n };\n } else {\n node = {\n runtime: \"react\",\n kind,\n id: id(fiber),\n key: fiber.key == null ? null : String(fiber.key),\n name,\n domId: null,\n elementTag: null,\n props,\n source,\n ...(portal ? { portal } : {}),\n children,\n };\n }\n semanticNodesSerialized += 1;\n return [node];\n };\n\n const isScope =\n contentsScope &&\n (!root ||\n root === observedRoot ||\n root?.alternate === observedRoot ||\n observation);\n const branches =\n isScope && (!root || root.tag === FiberTag.HostRoot) && watchedRoot\n ? domChildren(watchedRoot, root ?? undefined)\n : root\n ? visit(root)\n : [];\n if (\n isScope &&\n includeRoot &&\n (!root || root.tag === FiberTag.HostRoot) &&\n watchedRoot\n ) {\n const node = serializeDomLayerNode(\n null,\n watchedRoot,\n undefined,\n observedFiles,\n [...branches],\n );\n branches.splice(0, branches.length, ...(node ? [node] : []));\n }\n for (const [target, portals] of portalTargets) {\n if (\n emittedNodes.has(target) ||\n !target.isConnected ||\n target.ownerDocument !== watchedRoot?.ownerDocument\n )\n continue;\n const allowed = new Set<Node>();\n for (const [fiber, portal] of portalOwners) {\n if (!portals.includes(portal)) continue;\n const node =\n fiber.tag === FiberTag.HostText\n ? fiber.stateNode\n : fiber.tag === FiberTag.HostComponent\n ? getDomElement(fiber)\n : null;\n if (node instanceof Node && node.parentNode === target)\n allowed.add(node);\n }\n const portal = portals[0]!;\n // The DOM lane transports owned portal roots, not an arbitrary target\n // wrapper. Keep its actual physical parent fact opaque and unbound:\n // a fragment would incorrectly redirect placement to the board/caller.\n branches.push({\n runtime: \"dom\",\n kind: \"host\",\n id: portalNodeId(target),\n name: target.localName,\n key: null,\n domId: null,\n elementTag: target.localName,\n props: {\n \"data-tempo-hide-fiber\": true,\n \"data-tempo-supports-style\": false,\n \"data-tempo-supports-classname\": false,\n \"data-tempo-supports-children\": false,\n layoutMode: target.ownerDocument.defaultView\n ? layoutModeOf(\n target.ownerDocument.defaultView.getComputedStyle(target),\n )\n : undefined,\n },\n source: {\n kind: \"react-fiber\",\n fiber: {\n tag: FiberTag.HostPortal,\n name: \"\",\n id: fiberId(portal),\n },\n },\n portal: {\n target: true,\n nodeId: portalNodeId(target),\n ownerFiberId: fiberId(portal.return ?? portal),\n },\n children: domChildren(target, undefined, allowed),\n });\n semanticNodesSerialized += 1;\n emittedNodes.add(target);\n }\n\n let tree: ProjectionLayerNode | null;\n // Portal aggregations retain their physical-target identity policy; a\n // hidden slot alone does not force a cardinality fragment.\n const hiddenWatchedSlot =\n root !== null &&\n isTempoHiddenFiber(root) &&\n getDomElement(root) === watchedRoot;\n if (root && branches.some((branch) => branch.portal?.target))\n physicalAggregations.add(root);\n if (isScope || !root) {\n tree = null;\n } else if (branches.length === 1 && !aggregatesPhysicalTargets(root)) {\n tree = branches[0] ?? null;\n } else if (\n root.tag === FiberTag.HostRoot ||\n branches.length > 1 ||\n aggregatesPhysicalTargets(root)\n ) {\n const name = getDisplayName(root);\n tree = {\n runtime: \"react\",\n kind: \"fragment\",\n // A nonhidden root already contributes its own physical branch.\n // This transparent aggregation belongs to the watched observation,\n // and must not alias that branch's host address.\n id:\n root.tag === FiberTag.HostRoot ||\n hiddenWatchedSlot ||\n !aggregatesPhysicalTargets(root)\n ? id(root)\n : `${fiberId(root)}/physical`,\n key: root.key == null ? null : String(root.key),\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: isScope\n ? {\n kind: \"scope\",\n fragment: { kind: \"fragment\", children: branches },\n }\n : { kind: \"layers\", tree },\n observedFiles: observedFiles.snapshot(),\n },\n fiberNodesVisited,\n semanticNodesSerialized,\n };\n };\n\n return {\n portalClosure(candidate) {\n // Previous committed ownership detects removals too. These facts only\n // widen publication; they never authorize descendant correspondence.\n if (\n publishedPortalAncestors.has(candidate) ||\n (candidate.alternate &&\n publishedPortalAncestors.has(candidate.alternate))\n )\n return { required: true, nodesVisited: 0 };\n const element = getDomElement(candidate);\n if (element && publishedTargetAncestors.has(element))\n return { required: true, nodesVisited: 0 };\n let nodesVisited = 0;\n const pending = [candidate];\n while (pending.length) {\n const fiber = pending.pop()!;\n nodesVisited += 1;\n if (fiber !== candidate && isProjectionRootFiber(fiber)) continue;\n if (fiber.tag === FiberTag.HostPortal)\n return { required: true, nodesVisited };\n for (let child = fiber.child; child; child = child.sibling)\n pending.push(child);\n }\n return { required: false, nodesVisited };\n },\n serialize: (root) => serialize(root, true),\n serializeContents: () => serialize(null, true),\n fiberId,\n knownFiberId,\n serializeRegion(root) {\n const targetFiberId = fiberId(root);\n const serialized = serialize(root);\n const semantic = serialized.snapshot.semantic;\n return {\n region: {\n targetFiberId,\n ...(semantic.kind === \"scope\" ? { scope: semantic.fragment } : {}),\n targetId:\n semantic.kind === \"scope\"\n ? PROJECTION_SCOPE_TARGET\n : aggregatesPhysicalTargets(root) &&\n root.tag !== FiberTag.HostRoot &&\n !(\n isTempoHiddenFiber(root) &&\n getDomElement(root) === watchedRoot\n )\n ? `${fiberId(root)}/physical`\n : id(root),\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 targetId: id(root),\n props: captureProjectionLayerProps(\n root,\n root.tag === FiberTag.HostComponent ? getDomElement(root) : null,\n options?.sourceAnnotations ?? \"fiber\",\n options?.layoutMode,\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 (tag === FiberTag.HostText) return \"text\";\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\nexport { PROJECTION_ROOT_ATTRIBUTE };\n\n/** The fiber whose element is another projection root's (the SDK's\n * storyboard content slot). A root above it stops there. */\nexport function isProjectionRootFiber(fiber: Fiber): boolean {\n const props = getProps(fiber);\n const dataSet = props?.dataSet;\n const native =\n dataSet && typeof dataSet === \"object\"\n ? (dataSet as Record<string, unknown>).tempoProjectionRoot\n : undefined;\n const value = native ?? props?.[PROJECTION_ROOT_ATTRIBUTE];\n return value === true || value === \"true\";\n}\n\nfunction isTempoHiddenFiber(fiber: Fiber): boolean {\n if (isProjectionScopePlumbing(fiber)) return true;\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 layoutMode?: ProjectionLayerProps[\"layoutMode\"] | null,\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 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 const putPresence = (flatKey: string, dataSetKey: string): void => {\n const present =\n (dataSet != null && Object.hasOwn(dataSet, dataSetKey)) ||\n (raw != null && Object.hasOwn(raw, flatKey));\n if (present)\n props[flatKey] = read(flatKey, dataSetKey, \"fiber\") !== \"false\";\n };\n\n putString(\"data-tempo-filepath\", \"tempoFilepath\");\n const locked = read(\"data-tempo-locked\", \"tempoLocked\");\n if (locked === true || locked === \"true\" || locked === \"\")\n props[\"data-tempo-locked\"] = true;\n else if (locked === false || locked === \"false\")\n props[\"data-tempo-locked\"] = false;\n putFiniteNumber(\"data-tempo-position\", \"tempoPosition\");\n putFiniteNumber(\"data-tempo-modifiedts\", \"tempoModifiedts\");\n putString(\"data-tempo-source-version\", \"tempoSourceVersion\");\n putBoolean(\"data-tempo-supports-style\", \"tempoSupportsStyle\");\n putBoolean(\"data-tempo-supports-classname\", \"tempoSupportsClassname\");\n putBoolean(\"data-tempo-supports-children\", \"tempoSupportsChildren\");\n putString(\"data-tempo-expr\", \"tempoExpr\");\n\n putPresence(\"data-tempo-storyboard-root\", \"tempoStoryboardRoot\");\n putString(\"data-tempo-component-reference\", \"tempoComponentReference\");\n putString(\"data-tempo-external-component\", \"tempoExternalComponent\");\n putString(\"data-tempo-canvas-declaration\", \"tempoCanvasDeclaration\");\n putString(\"data-tempo-storyboard-declaration\", \"tempoStoryboardDeclaration\");\n putString(\"data-tempo-storyboard-id\", \"tempoStoryboardId\");\n\n // Polygon labels distinguish triangles and stars by their authored points.\n // Other geometry stays out of the layer stream.\n if (\n fiber.tag === FiberTag.HostComponent &&\n fiber.type === \"polygon\" &&\n typeof raw?.points === \"string\"\n ) {\n props.points = raw.points;\n }\n\n if (element) {\n // Alternate and source-annotation captures reuse the first host read.\n if (layoutMode === undefined) {\n layoutMode = layoutModeOf(getComputedStyle(element));\n }\n if (layoutMode) props.layoutMode = layoutMode;\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 } else if (typeof raw?.className === \"string\") {\n // Component edits own invocation classes, not the implementation's DOM\n // classes. Keep this baseline across HMR for subsequent structural edits.\n props.className = raw.className;\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","/**\n * The pending-marker contract, shared between the source app and the producer.\n *\n * A Tempo-owned admission or Suspense boundary renders a single hidden marker\n * element while waiting instead of `null`. That turns \"this subtree is briefly\n * empty because content is loading\" — which is indistinguishable from \"this\n * subtree is now empty\" once it reaches the DOM — into something the producer can\n * recognise without inspecting React internals.\n *\n * This file is imported directly by tempo-sdk and bundled into it, so it must\n * stay dependency-free: no imports, no DOM globals beyond the element passed in.\n */\n\n/** Marks an element as a Tempo-owned boundary's pending placeholder. */\nexport const PROJECTION_PENDING_ATTRIBUTE = \"data-tempo-projection-pending\";\n\n/**\n * Is this root showing a pending marker and nothing else?\n *\n * The rule is deliberately strict — marker-ONLY. A root that still holds real\n * content alongside a marker is a partially-loaded tree, and partial content is\n * exactly what the mirror should show; only a root whose entire visible output\n * is placeholder has nothing worth publishing. An empty root is likewise not\n * pending: emptiness with no marker is a real state (a conditional unmount, a\n * foreign boundary with `fallback={null}`) and stays a real change.\n */\nexport function isProjectionPendingOnly(rootElement: Element): boolean {\n const children = rootElement.children;\n if (children.length === 0) return false;\n for (let index = 0; index < children.length; index += 1) {\n const child = children[index];\n if (!child || !child.hasAttribute(PROJECTION_PENDING_ATTRIBUTE)) {\n return false;\n }\n }\n return true;\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;AAA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