@fictjs/runtime 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/advanced.cjs +10 -8
  2. package/dist/advanced.cjs.map +1 -1
  3. package/dist/advanced.d.cts +4 -3
  4. package/dist/advanced.d.ts +4 -3
  5. package/dist/advanced.js +10 -8
  6. package/dist/advanced.js.map +1 -1
  7. package/dist/{chunk-TWELIZRY.js → chunk-5AA7HP4S.js} +5 -3
  8. package/dist/{chunk-TWELIZRY.js.map → chunk-5AA7HP4S.js.map} +1 -1
  9. package/dist/chunk-6SOPF5LZ.cjs +2363 -0
  10. package/dist/chunk-6SOPF5LZ.cjs.map +1 -0
  11. package/dist/{chunk-SO6X7G5S.js → chunk-BQG7VEBY.js} +501 -1880
  12. package/dist/chunk-BQG7VEBY.js.map +1 -0
  13. package/dist/chunk-FKDMDAUR.js +2363 -0
  14. package/dist/chunk-FKDMDAUR.js.map +1 -0
  15. package/dist/{chunk-L4DIV3RC.cjs → chunk-GHUV2FLD.cjs} +9 -7
  16. package/dist/chunk-GHUV2FLD.cjs.map +1 -0
  17. package/dist/{chunk-XLIZJMMJ.js → chunk-KKKYW54Z.js} +8 -6
  18. package/dist/{chunk-XLIZJMMJ.js.map → chunk-KKKYW54Z.js.map} +1 -1
  19. package/dist/{chunk-M2TSXZ4C.cjs → chunk-KYLNC4CD.cjs} +18 -16
  20. package/dist/chunk-KYLNC4CD.cjs.map +1 -0
  21. package/dist/chunk-TKWN42TA.cjs +2259 -0
  22. package/dist/chunk-TKWN42TA.cjs.map +1 -0
  23. package/dist/{context-B25xyQrJ.d.cts → context-CTBE00S_.d.cts} +1 -1
  24. package/dist/{context-CGdP7_Jb.d.ts → context-lkLhbkFJ.d.ts} +1 -1
  25. package/dist/{effect-D6kaLM2-.d.cts → effect-BpSNEJJz.d.cts} +7 -67
  26. package/dist/{effect-D6kaLM2-.d.ts → effect-BpSNEJJz.d.ts} +7 -67
  27. package/dist/index.cjs +40 -38
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.cts +5 -4
  30. package/dist/index.d.ts +5 -4
  31. package/dist/index.dev.js +92 -4
  32. package/dist/index.dev.js.map +1 -1
  33. package/dist/index.js +19 -17
  34. package/dist/index.js.map +1 -1
  35. package/dist/internal.cjs +189 -202
  36. package/dist/internal.cjs.map +1 -1
  37. package/dist/internal.d.cts +13 -23
  38. package/dist/internal.d.ts +13 -23
  39. package/dist/internal.js +195 -208
  40. package/dist/internal.js.map +1 -1
  41. package/dist/loader.cjs +280 -0
  42. package/dist/loader.cjs.map +1 -0
  43. package/dist/loader.d.cts +57 -0
  44. package/dist/loader.d.ts +57 -0
  45. package/dist/loader.js +280 -0
  46. package/dist/loader.js.map +1 -0
  47. package/dist/{props-BIfromL0.d.cts → props-XTHYD19o.d.cts} +13 -2
  48. package/dist/{props-BEgIVMRx.d.ts → props-x-HbI-jX.d.ts} +13 -2
  49. package/dist/resume-BrAkmSTY.d.cts +79 -0
  50. package/dist/resume-Dx8_l72o.d.ts +79 -0
  51. package/dist/{scope-CzNkn587.d.ts → scope-CdbGmsFf.d.ts} +1 -1
  52. package/dist/{scope-Cx_3CjIZ.d.cts → scope-DfcP9I-A.d.cts} +1 -1
  53. package/dist/signal-C4ISF17w.d.cts +66 -0
  54. package/dist/signal-C4ISF17w.d.ts +66 -0
  55. package/package.json +8 -3
  56. package/src/binding.ts +254 -5
  57. package/src/dom.ts +103 -5
  58. package/src/hooks.ts +15 -2
  59. package/src/hydration.ts +75 -0
  60. package/src/internal.ts +34 -2
  61. package/src/list-helpers.ts +113 -12
  62. package/src/loader.ts +437 -0
  63. package/src/node-ops.ts +65 -0
  64. package/src/resume.ts +517 -0
  65. package/src/store.ts +8 -0
  66. package/dist/chunk-ID3WBWNO.cjs +0 -3638
  67. package/dist/chunk-ID3WBWNO.cjs.map +0 -1
  68. package/dist/chunk-L4DIV3RC.cjs.map +0 -1
  69. package/dist/chunk-M2TSXZ4C.cjs.map +0 -1
  70. package/dist/chunk-SO6X7G5S.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/store.ts","../src/reconcile.ts","../src/list-helpers.ts"],"sourcesContent":["import { signal, batch, type SignalAccessor } from './signal'\n\nconst PROXY = Symbol('fict:store-proxy')\nconst TARGET = Symbol('fict:store-target')\nconst ITERATE_KEY = Symbol('fict:iterate')\n\n// ============================================================================\n// Store (Deep Proxy)\n// ============================================================================\n\nexport type Store<T> = T\n\n/**\n * Create a Store: a reactive proxy that allows fine-grained access and mutation.\n *\n * @param initialValue - The initial state object\n * @returns [store, setStore]\n */\nexport function createStore<T extends object>(\n initialValue: T,\n): [Store<T>, (fn: (state: T) => void | T) => void] {\n const unwrapped = unwrap(initialValue)\n const wrapped = wrap(unwrapped)\n\n function setStore(fn: (state: T) => void | T) {\n batch(() => {\n const result = fn(wrapped)\n if (result !== undefined) {\n reconcile(wrapped, result)\n }\n })\n }\n\n return [wrapped, setStore]\n}\n\n// Map of target object -> Proxy\nconst proxyCache = new WeakMap<object, unknown>()\n// Map of target object -> Map<key, Signal>\nconst signalCache = new WeakMap<object, Map<string | symbol, SignalAccessor<unknown>>>()\n\nfunction wrap<T>(value: T): T {\n if (value === null || typeof value !== 'object') return value\n if (Reflect.get(value, PROXY)) return value\n\n if (proxyCache.has(value)) return proxyCache.get(value) as T\n\n const handler: ProxyHandler<object> = {\n get(target, prop, receiver) {\n if (prop === PROXY) return true\n if (prop === TARGET) return target\n\n const value = Reflect.get(target, prop, receiver)\n\n // Track property access\n track(target, prop)\n\n // Recursively wrap objects\n return wrap(value)\n },\n has(target, prop) {\n const result = Reflect.has(target, prop)\n track(target, prop)\n return result\n },\n ownKeys(target) {\n track(target, ITERATE_KEY)\n return Reflect.ownKeys(target)\n },\n getOwnPropertyDescriptor(target, prop) {\n track(target, prop)\n return Reflect.getOwnPropertyDescriptor(target, prop)\n },\n set(target, prop, value, receiver) {\n if (prop === PROXY || prop === TARGET) return false\n\n const isArrayLength = Array.isArray(target) && prop === 'length'\n const oldLength = isArrayLength ? target.length : undefined\n const hadKey = Object.prototype.hasOwnProperty.call(target, prop)\n const oldValue = Reflect.get(target, prop, receiver)\n if (oldValue === value) return true\n\n const result = Reflect.set(target, prop, value, receiver)\n if (result) {\n trigger(target, prop)\n if (!hadKey) {\n trigger(target, ITERATE_KEY)\n }\n if (isArrayLength) {\n const nextLength = target.length\n if (typeof oldLength === 'number' && nextLength < oldLength) {\n const signals = signalCache.get(target)\n if (signals) {\n for (const key of signals.keys()) {\n if (typeof key !== 'string') continue\n const index = Number(key)\n if (!Number.isInteger(index) || String(index) !== key) continue\n if (index >= nextLength && index < oldLength) {\n trigger(target, key)\n }\n }\n }\n }\n trigger(target, ITERATE_KEY)\n }\n }\n return result\n },\n deleteProperty(target, prop) {\n const hadKey = Object.prototype.hasOwnProperty.call(target, prop)\n const result = Reflect.deleteProperty(target, prop)\n if (result) {\n trigger(target, prop)\n if (hadKey) {\n trigger(target, ITERATE_KEY)\n }\n }\n return result\n },\n }\n\n const proxy = new Proxy(value, handler)\n proxyCache.set(value, proxy)\n return proxy as T\n}\n\nfunction unwrap<T>(value: T): T {\n if (value && typeof value === 'object' && Reflect.get(value, PROXY)) {\n return Reflect.get(value, TARGET) as T\n }\n return value\n}\n\nfunction track(target: object, prop: string | symbol) {\n let signals = signalCache.get(target)\n if (!signals) {\n signals = new Map()\n signalCache.set(target, signals)\n }\n\n let s = signals.get(prop)\n if (!s) {\n const initial =\n prop === ITERATE_KEY ? (Reflect.ownKeys(target).length as number) : getLastValue(target, prop)\n s = signal(initial)\n signals.set(prop, s)\n }\n s() // subscribe\n}\n\nfunction trigger(target: object, prop: string | symbol) {\n const signals = signalCache.get(target)\n if (signals) {\n const s = signals.get(prop)\n if (s) {\n if (prop === ITERATE_KEY) {\n s(Reflect.ownKeys(target).length)\n } else {\n s(getLastValue(target, prop)) // notify with new value\n }\n }\n }\n}\n\nfunction getLastValue(target: object, prop: string | symbol) {\n return Reflect.get(target, prop)\n}\n\n/**\n * Reconcile a store path with a new value (shallow merge/diff)\n */\nfunction reconcile(target: object, value: unknown) {\n if (target === value) return\n if (value === null || typeof value !== 'object') {\n throw new Error(\n `[Fict] Cannot replace store with primitive value: ${String(\n value,\n )}. setStore should return an object/array to merge.`,\n )\n }\n\n const realTarget = unwrap(target)\n const realValue = unwrap(value)\n\n const keys = new Set([...Object.keys(realTarget), ...Object.keys(realValue)])\n for (const key of keys) {\n const rTarget = realTarget as Record<string, unknown>\n const rValue = realValue as Record<string, unknown>\n\n if (rValue[key] === undefined && rTarget[key] !== undefined) {\n // deleted\n delete (target as Record<string, unknown>)[key] // Triggers proxy trap\n } else if (rTarget[key] !== rValue[key]) {\n ;(target as Record<string, unknown>)[key] = rValue[key] // Triggers proxy trap\n }\n }\n\n // Fix array length if needed\n if (Array.isArray(target) && Array.isArray(realValue) && target.length !== realValue.length) {\n target.length = realValue.length\n }\n}\n\n// ============================================================================\n// Diffing Signal (for List Items)\n// ============================================================================\n\n/**\n * Creates a signal that returns a Stable Proxy.\n * Updates to the signal (via set) will diff the new value against the old value\n * and trigger property-specific updates.\n */\nexport function createDiffingSignal<T extends object>(initialValue: T) {\n let currentValue = unwrap(initialValue)\n const signals = new Map<string | symbol, SignalAccessor<unknown>>()\n let iterateSignal: SignalAccessor<number> | undefined\n\n const getPropSignal = (prop: string | symbol) => {\n let s = signals.get(prop)\n if (!s) {\n s = signal(Reflect.get(currentValue as object, prop))\n signals.set(prop, s)\n }\n return s\n }\n\n const trackIterate = () => {\n if (!iterateSignal) {\n iterateSignal = signal(Reflect.ownKeys(currentValue).length)\n }\n iterateSignal()\n }\n\n const updateIterate = (value: T) => {\n if (iterateSignal) {\n iterateSignal(Reflect.ownKeys(value).length)\n }\n }\n\n // The stable proxy we return\n const proxy = new Proxy({} as T, {\n get(_, prop) {\n if (prop === PROXY) return true\n if (prop === TARGET) return currentValue\n\n // Subscribe to property\n const s = getPropSignal(prop)\n return s()\n },\n ownKeys() {\n trackIterate()\n return Reflect.ownKeys(currentValue)\n },\n has(target, prop) {\n getPropSignal(prop)()\n return Reflect.has(currentValue, prop)\n },\n getOwnPropertyDescriptor(target, prop) {\n getPropSignal(prop)()\n return Reflect.getOwnPropertyDescriptor(currentValue, prop)\n },\n })\n\n const read = () => proxy\n\n const write = (newValue: T) => {\n const next = unwrap(newValue)\n const prev = currentValue\n currentValue = next\n\n if (prev === next) {\n // Same ref update: re-evaluate all tracked signals\n // This is necessary for in-place mutations\n for (const [prop, s] of signals) {\n const newVal = Reflect.get(next as object, prop)\n s(newVal)\n }\n updateIterate(next)\n return\n }\n\n // Diff logic\n // We only trigger signals for properties that exist in our cache (tracked)\n // and have changed.\n for (const [prop, s] of signals) {\n const oldVal = Reflect.get(prev as object, prop)\n const newVal = Reflect.get(next as object, prop)\n if (oldVal !== newVal) {\n s(newVal)\n }\n }\n updateIterate(next)\n\n // Note: If new properties appeared that weren't tracked, we don't care\n // because no one is listening.\n // If we assume shape stability (Keyed List), this is efficient.\n }\n\n return [read, write] as const\n}\n","/**\n * Fict DOM Reconciliation\n *\n * Efficient array reconciliation algorithm based on udomdiff.\n * https://github.com/WebReflection/udomdiff\n *\n * This algorithm uses a 5-step strategy:\n * 1. Common prefix - skip matching nodes at start\n * 2. Common suffix - skip matching nodes at end\n * 3. Append - insert remaining new nodes\n * 4. Remove - remove remaining old nodes\n * 5. Swap/Map fallback - handle complex rearrangements\n *\n * Most real-world updates (95%+) use fast paths without building a Map.\n */\n\n/**\n * Reconcile two arrays of DOM nodes, efficiently updating the DOM.\n *\n * @param parentNode - The parent element containing the nodes\n * @param a - The old array of nodes (currently in DOM)\n * @param b - The new array of nodes (target state)\n *\n * **Note:** This function may mutate the input array `a` during the swap\n * optimization (step 5a). If you need to preserve the original array,\n * pass a shallow copy: `reconcileArrays(parent, [...oldNodes], newNodes)`.\n *\n * @example\n * ```ts\n * const oldNodes = [node1, node2, node3]\n * const newNodes = [node1, node4, node3] // node2 replaced with node4\n * reconcileArrays(parent, oldNodes, newNodes)\n * ```\n */\nexport default function reconcileArrays(parentNode: ParentNode, a: Node[], b: Node[]): void {\n const bLength = b.length\n let aEnd = a.length\n let bEnd = bLength\n let aStart = 0\n let bStart = 0\n const after = aEnd > 0 ? a[aEnd - 1]!.nextSibling : null\n let map: Map<Node, number> | null = null\n\n while (aStart < aEnd || bStart < bEnd) {\n // 1. Common prefix - nodes match at start\n if (a[aStart] === b[bStart]) {\n aStart++\n bStart++\n continue\n }\n\n // 2. Common suffix - nodes match at end\n while (a[aEnd - 1] === b[bEnd - 1]) {\n aEnd--\n bEnd--\n }\n\n // 3. Append - old array exhausted, insert remaining new nodes\n if (aEnd === aStart) {\n const node: Node | null =\n bEnd < bLength ? (bStart ? b[bStart - 1]!.nextSibling : (b[bEnd - bStart] ?? null)) : after\n\n const count = bEnd - bStart\n const doc = (parentNode as Node).ownerDocument\n if (count > 1 && doc) {\n const frag = doc.createDocumentFragment()\n for (let i = bStart; i < bEnd; i++) {\n frag.appendChild(b[i]!)\n }\n parentNode.insertBefore(frag, node)\n bStart = bEnd\n } else {\n while (bStart < bEnd) {\n parentNode.insertBefore(b[bStart++]!, node)\n }\n }\n }\n // 4. Remove - new array exhausted, remove remaining old nodes\n else if (bEnd === bStart) {\n while (aStart < aEnd) {\n const nodeToRemove = a[aStart]!\n if (!map || !map.has(nodeToRemove)) {\n nodeToRemove.parentNode?.removeChild(nodeToRemove)\n }\n aStart++\n }\n }\n // 5a. Swap backward - detect backward swap pattern\n else if (a[aStart] === b[bEnd - 1] && b[bStart] === a[aEnd - 1]) {\n const node = a[--aEnd]!.nextSibling\n parentNode.insertBefore(b[bStart++]!, a[aStart++]!.nextSibling)\n parentNode.insertBefore(b[--bEnd]!, node)\n // Update reference in old array for potential future matches\n a[aEnd] = b[bEnd]!\n }\n // 5b. Map fallback - use Map for complex rearrangements\n else {\n // Build map on first use (lazy initialization)\n if (!map) {\n map = new Map()\n let i = bStart\n while (i < bEnd) {\n map.set(b[i]!, i++)\n }\n }\n\n const index = map.get(a[aStart]!)\n\n if (index != null) {\n if (bStart < index && index < bEnd) {\n // Check for longest increasing subsequence\n let i = aStart\n let sequence = 1\n let t: number | undefined\n\n while (++i < aEnd && i < bEnd) {\n t = map.get(a[i]!)\n if (t == null || t !== index + sequence) break\n sequence++\n }\n\n // Use optimal strategy based on sequence length\n if (sequence > index - bStart) {\n // Sequence is long enough - insert nodes before current\n const node = a[aStart]!\n while (bStart < index) {\n parentNode.insertBefore(b[bStart++]!, node)\n }\n } else {\n // Short sequence - replace\n parentNode.replaceChild(b[bStart++]!, a[aStart++]!)\n }\n } else {\n aStart++\n }\n } else {\n // Node not in new array - remove it\n const nodeToRemove = a[aStart++]!\n nodeToRemove.parentNode?.removeChild(nodeToRemove)\n }\n }\n }\n}\n\n/**\n * Simple reconciliation for keyed lists.\n * Uses the same algorithm but works with keyed blocks.\n *\n * @param parentNode - The parent element\n * @param oldNodes - Old nodes in DOM order\n * @param newNodes - New nodes in target order\n */\nexport function reconcileNodes(parentNode: ParentNode, oldNodes: Node[], newNodes: Node[]): void {\n reconcileArrays(parentNode, oldNodes, newNodes)\n}\n","/**\n * List Helpers for Compiler-Generated Fine-Grained Updates\n *\n * These helpers are used by the compiler to generate efficient keyed list rendering.\n * They provide low-level primitives for DOM node manipulation without rebuilding.\n */\n\nimport { createElement } from './dom'\nimport { createRenderEffect } from './effect'\nimport {\n createRootContext,\n destroyRoot,\n flushOnMount,\n getCurrentRoot,\n popRoot,\n pushRoot,\n type RootContext,\n} from './lifecycle'\nimport { insertNodesBefore, removeNodes, toNodeArray } from './node-ops'\nimport reconcileArrays from './reconcile'\nimport { batch } from './scheduler'\nimport { createSignal, effectScope, flush, setActiveSub, type Signal } from './signal'\nimport type { FictNode } from './types'\n\n// Re-export shared DOM helpers for compiler-generated code\nexport { insertNodesBefore, removeNodes, toNodeArray }\n\nconst isDev =\n typeof __DEV__ !== 'undefined'\n ? __DEV__\n : typeof process === 'undefined' || process.env?.NODE_ENV !== 'production'\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * A keyed block represents a single item in a list with its associated DOM nodes and state\n */\ninterface KeyedBlock<T = unknown> {\n /** Unique key for this block */\n key: string | number\n /** DOM nodes belonging to this block */\n nodes: Node[]\n /** Root context for lifecycle management */\n root: RootContext\n /** Signal containing the current item value */\n item: Signal<T>\n /** Signal containing the current index */\n index: Signal<number>\n /** Last raw item value assigned to this block */\n rawItem: T\n /** Last raw index value assigned to this block */\n rawIndex: number\n}\n\n/**\n * Container for managing keyed list blocks\n */\ninterface KeyedListContainer<T = unknown> {\n /** Start marker comment node */\n startMarker: Comment\n /** End marker comment node */\n endMarker: Comment\n /** Map of key to block */\n blocks: Map<string | number, KeyedBlock<T>>\n /** Scratch map reused for the next render */\n nextBlocks: Map<string | number, KeyedBlock<T>>\n /** Current nodes in DOM order (including markers) */\n currentNodes: Node[]\n /** Next-frame node buffer to avoid reallocations */\n nextNodes: Node[]\n /** Ordered blocks in current DOM order */\n orderedBlocks: KeyedBlock<T>[]\n /** Next-frame ordered block buffer to avoid reallocations */\n nextOrderedBlocks: KeyedBlock<T>[]\n /** Track position of keys in the ordered buffer to handle duplicates */\n orderedIndexByKey: Map<string | number, number>\n /** Cleanup function */\n dispose: () => void\n}\n\n/**\n * Binding handle returned by createKeyedList for compiler-generated code\n */\nexport interface KeyedListBinding {\n /** Document fragment placeholder inserted by the compiler/runtime */\n marker: DocumentFragment\n /** Start marker comment node */\n startMarker: Comment\n /** End marker comment node */\n endMarker: Comment\n /** Flush pending items - call after markers are inserted into DOM */\n flush?: () => void\n /** Cleanup function */\n dispose: () => void\n}\n\ntype FineGrainedRenderItem<T> = (\n itemSig: Signal<T>,\n indexSig: Signal<number>,\n key: string | number,\n) => Node[]\n\n// ============================================================================\n// DOM Manipulation Primitives\n// ============================================================================\n\n/**\n * Move nodes to a position before the anchor node.\n * This is optimized to avoid unnecessary DOM operations.\n *\n * @param parent - Parent node to move nodes within\n * @param nodes - Array of nodes to move\n * @param anchor - Node to insert before (or null for end)\n */\nexport function moveNodesBefore(parent: Node, nodes: Node[], anchor: Node | null): void {\n // Insert in reverse order to maintain correct sequence\n // This way each node becomes the new anchor for the next\n for (let i = nodes.length - 1; i >= 0; i--) {\n const node = nodes[i]!\n if (!node || !(node instanceof Node)) {\n const message = isDev ? 'Invalid node in moveNodesBefore' : 'FICT:E_NODE'\n throw new Error(message)\n }\n // Only move if not already in correct position\n if (node.nextSibling !== anchor) {\n if (node.ownerDocument !== parent.ownerDocument && parent.ownerDocument) {\n parent.ownerDocument.adoptNode(node)\n }\n try {\n parent.insertBefore(node, anchor)\n } catch (e: any) {\n if (parent.ownerDocument) {\n try {\n const clone = parent.ownerDocument.importNode(node, true)\n parent.insertBefore(clone, anchor)\n // Update the nodes array with the clone to maintain correct references.\n // This ensures future operations (like removal or reordering) work correctly.\n nodes[i] = clone\n if (isDev) {\n console.warn(\n `[fict] Node cloning fallback triggered during list reordering. ` +\n `This may indicate cross-document node insertion. ` +\n `The node reference has been updated to the clone.`,\n )\n }\n anchor = clone\n continue\n } catch {\n // Clone fallback failed\n }\n }\n throw e\n }\n }\n anchor = node\n }\n}\n\n/**\n * Remove an array of nodes from the DOM\n *\n * @param nodes - Array of nodes to remove\n */\n// Number.MAX_SAFE_INTEGER is 2^53 - 1, but we reset earlier to avoid any precision issues\nconst MAX_SAFE_VERSION = 0x1fffffffffffff // 2^53 - 1\n\nexport function createVersionedSignalAccessor<T>(initialValue: T): Signal<T> {\n let current = initialValue\n let version = 0\n const track = createSignal(version)\n\n function accessor(value?: T): T | void {\n if (arguments.length === 0) {\n track()\n return current\n }\n current = value as T\n // This is safe because we only care about version changes, not absolute values\n version = version >= MAX_SAFE_VERSION ? 1 : version + 1\n track(version)\n }\n\n return accessor as Signal<T>\n}\n\n// ============================================================================\n// Keyed List Container\n// ============================================================================\n\n/**\n * Create a container for managing a keyed list.\n * This sets up the marker nodes and provides cleanup.\n *\n * @returns Container object with markers, blocks map, and dispose function\n */\nfunction createKeyedListContainer<T = unknown>(): KeyedListContainer<T> {\n const startMarker = document.createComment('fict:list:start')\n const endMarker = document.createComment('fict:list:end')\n\n const dispose = () => {\n // Clean up all blocks\n for (const block of container.blocks.values()) {\n destroyRoot(block.root)\n // Nodes are removed by parent disposal or specific cleanup if needed\n // But for list disposal, we just clear the container\n }\n container.blocks.clear()\n container.nextBlocks.clear()\n\n // Remove nodes (including markers)\n // Check if markers are still in DOM before using Range\n if (!startMarker.parentNode || !endMarker.parentNode) {\n // Markers already removed, nothing to do\n container.currentNodes = []\n container.nextNodes = []\n container.orderedBlocks.length = 0\n container.nextOrderedBlocks.length = 0\n container.orderedIndexByKey.clear()\n return\n }\n const range = document.createRange()\n range.setStartBefore(startMarker)\n range.setEndAfter(endMarker)\n range.deleteContents()\n\n // Clear cache\n container.currentNodes = []\n container.nextNodes = []\n container.nextBlocks.clear()\n container.orderedBlocks.length = 0\n container.nextOrderedBlocks.length = 0\n container.orderedIndexByKey.clear()\n }\n\n const container: KeyedListContainer<T> = {\n startMarker,\n endMarker,\n blocks: new Map<string | number, KeyedBlock<T>>(),\n nextBlocks: new Map<string | number, KeyedBlock<T>>(),\n currentNodes: [startMarker, endMarker],\n nextNodes: [],\n orderedBlocks: [],\n nextOrderedBlocks: [],\n orderedIndexByKey: new Map<string | number, number>(),\n dispose,\n }\n\n return container\n}\n\n// ============================================================================\n// Block Creation Helpers\n// ============================================================================\n\n/**\n * Create a new keyed block with the given render function\n *\n * @param key - Unique key for this block\n * @param item - Initial item value\n * @param index - Initial index\n * @param render - Function that creates the DOM nodes and sets up bindings\n * @returns New KeyedBlock\n */\nfunction createKeyedBlock<T>(\n key: string | number,\n item: T,\n index: number,\n render: (item: Signal<T>, index: Signal<number>, key: string | number) => Node[],\n needsIndex = true,\n hostRoot?: RootContext,\n): KeyedBlock<T> {\n // Use versioned signal for all item types; avoid diffing proxy overhead for objects\n const itemSig = createVersionedSignalAccessor(item)\n\n const indexSig = needsIndex\n ? createSignal<number>(index)\n : (((next?: number) => {\n if (arguments.length === 0) return index\n index = next as number\n return index\n }) as Signal<number>)\n const root = createRootContext(hostRoot)\n const prevRoot = pushRoot(root)\n // maintaining proper cleanup chain. The scope will be disposed when\n // the root is destroyed, ensuring nested effects are properly cleaned up.\n let nodes: Node[] = []\n let scopeDispose: (() => void) | undefined\n\n // First, isolate from parent effect to prevent child effects from being\n // purged when the outer effect (e.g., performDiff) re-runs\n const prevSub = setActiveSub(undefined)\n\n try {\n // Create an effectScope that will track all effects created during render\n scopeDispose = effectScope(() => {\n const rendered = render(itemSig, indexSig, key)\n // If render returns real DOM nodes/arrays, preserve them to avoid\n // reparenting side-effects (tests may pre-insert them).\n if (\n rendered instanceof Node ||\n (Array.isArray(rendered) && rendered.every(n => n instanceof Node))\n ) {\n nodes = toNodeArray(rendered)\n } else {\n const element = createElement(rendered as unknown as FictNode)\n nodes = toNodeArray(element)\n }\n })\n\n // Register the scope cleanup with the root so effects are cleaned up\n // when the block is destroyed\n if (scopeDispose) {\n root.cleanups.push(scopeDispose)\n }\n } finally {\n setActiveSub(prevSub)\n popRoot(prevRoot)\n }\n\n return {\n key,\n nodes,\n root,\n item: itemSig,\n index: indexSig,\n rawItem: item,\n rawIndex: index,\n }\n}\n\n// ============================================================================\n// Utilities\n// ============================================================================\n\n/**\n * Check if a node is between two markers\n */\nexport function isNodeBetweenMarkers(\n node: Node,\n startMarker: Comment,\n endMarker: Comment,\n): boolean {\n let current: Node | null = startMarker.nextSibling\n while (current && current !== endMarker) {\n if (current === node) return true\n current = current.nextSibling\n }\n return false\n}\n\nfunction reorderBySwap<T>(\n parent: ParentNode & Node,\n first: KeyedBlock<T>,\n second: KeyedBlock<T>,\n): boolean {\n if (first === second) return false\n const firstNodes = first.nodes\n const secondNodes = second.nodes\n if (firstNodes.length === 0 || secondNodes.length === 0) return false\n const lastFirst = firstNodes[firstNodes.length - 1]!\n const lastSecond = secondNodes[secondNodes.length - 1]!\n const afterFirst = lastFirst.nextSibling\n const afterSecond = lastSecond.nextSibling\n moveNodesBefore(parent, firstNodes, afterSecond)\n moveNodesBefore(parent, secondNodes, afterFirst)\n return true\n}\n\nfunction getLISIndices(sequence: number[]): number[] {\n const predecessors = new Array<number>(sequence.length)\n const result: number[] = []\n\n for (let i = 0; i < sequence.length; i++) {\n const value = sequence[i]!\n if (value < 0) {\n predecessors[i] = -1\n continue\n }\n\n let low = 0\n let high = result.length\n while (low < high) {\n const mid = (low + high) >> 1\n if (sequence[result[mid]!]! < value) {\n low = mid + 1\n } else {\n high = mid\n }\n }\n\n predecessors[i] = low > 0 ? result[low - 1]! : -1\n if (low === result.length) {\n result.push(i)\n } else {\n result[low] = i\n }\n }\n\n const lis: number[] = new Array(result.length)\n let k = result.length > 0 ? result[result.length - 1]! : -1\n for (let i = result.length - 1; i >= 0; i--) {\n lis[i] = k\n k = predecessors[k]!\n }\n return lis\n}\n\nfunction reorderByLIS<T>(\n parent: ParentNode & Node,\n endMarker: Comment,\n prev: KeyedBlock<T>[],\n next: KeyedBlock<T>[],\n): boolean {\n const positions = new Map<KeyedBlock<T>, number>()\n for (let i = 0; i < prev.length; i++) {\n positions.set(prev[i]!, i)\n }\n\n const sequence = new Array<number>(next.length)\n for (let i = 0; i < next.length; i++) {\n const position = positions.get(next[i]!)\n if (position === undefined) return false\n sequence[i] = position\n }\n\n const lisIndices = getLISIndices(sequence)\n if (lisIndices.length === sequence.length) return true\n\n const inLIS = new Array<boolean>(sequence.length).fill(false)\n for (let i = 0; i < lisIndices.length; i++) {\n inLIS[lisIndices[i]!] = true\n }\n\n let anchor: Node | null = endMarker\n let moved = false\n for (let i = next.length - 1; i >= 0; i--) {\n const block = next[i]!\n const nodes = block.nodes\n if (nodes.length === 0) continue\n if (inLIS[i]) {\n anchor = nodes[0]!\n continue\n }\n moveNodesBefore(parent, nodes, anchor)\n anchor = nodes[0]!\n moved = true\n }\n\n return moved\n}\n\n// ============================================================================\n// High-Level List Binding (for compiler-generated code)\n// ============================================================================\n\n/**\n * Create a keyed list binding with automatic diffing and DOM updates.\n * This is used by compiler-generated code for efficient list rendering.\n *\n * @param getItems - Function that returns the current array of items\n * @param keyFn - Function to extract unique key from each item\n * @param renderItem - Function that creates DOM nodes for each item\n * @returns Binding handle with markers and dispose function\n */\nexport function createKeyedList<T>(\n getItems: () => T[],\n keyFn: (item: T, index: number) => string | number,\n renderItem: FineGrainedRenderItem<T>,\n needsIndex?: boolean,\n): KeyedListBinding {\n const resolvedNeedsIndex =\n arguments.length >= 4 ? !!needsIndex : renderItem.length > 1 /* has index param */\n return createFineGrainedKeyedList(getItems, keyFn, renderItem, resolvedNeedsIndex)\n}\n\nfunction createFineGrainedKeyedList<T>(\n getItems: () => T[],\n keyFn: (item: T, index: number) => string | number,\n renderItem: FineGrainedRenderItem<T>,\n needsIndex: boolean,\n): KeyedListBinding {\n const container = createKeyedListContainer<T>()\n const hostRoot = getCurrentRoot()\n const fragment = document.createDocumentFragment()\n fragment.append(container.startMarker, container.endMarker)\n let disposed = false\n let effectDispose: (() => void) | undefined\n let connectObserver: MutationObserver | null = null\n let effectStarted = false\n let startScheduled = false\n\n const getConnectedParent = (): (ParentNode & Node) | null => {\n const endParent = container.endMarker.parentNode\n const startParent = container.startMarker.parentNode\n if (\n endParent &&\n startParent &&\n endParent === startParent &&\n (endParent as Node).nodeType !== 11\n ) {\n const parentNode = endParent as ParentNode & Node\n if ('isConnected' in parentNode && !parentNode.isConnected) return null\n return parentNode\n }\n return null\n }\n\n const performDiff = () => {\n if (disposed) return\n const parent = getConnectedParent()\n if (!parent) return\n batch(() => {\n const oldBlocks = container.blocks\n const newBlocks = container.nextBlocks\n const prevOrderedBlocks = container.orderedBlocks\n const nextOrderedBlocks = container.nextOrderedBlocks\n const orderedIndexByKey = container.orderedIndexByKey\n const newItems = getItems()\n\n if (newItems.length === 0) {\n if (oldBlocks.size > 0) {\n // Destroy all block roots first\n for (const block of oldBlocks.values()) {\n destroyRoot(block.root)\n }\n // Use Range.deleteContents for efficient bulk DOM removal\n const range = document.createRange()\n range.setStartAfter(container.startMarker)\n range.setEndBefore(container.endMarker)\n range.deleteContents()\n }\n oldBlocks.clear()\n newBlocks.clear()\n prevOrderedBlocks.length = 0\n nextOrderedBlocks.length = 0\n orderedIndexByKey.clear()\n container.currentNodes.length = 0\n container.currentNodes.push(container.startMarker, container.endMarker)\n container.nextNodes.length = 0\n return\n }\n\n const prevCount = prevOrderedBlocks.length\n if (prevCount > 0 && newItems.length === prevCount && orderedIndexByKey.size === prevCount) {\n let stableOrder = true\n const seen = new Set<string | number>()\n for (let i = 0; i < prevCount; i++) {\n const item = newItems[i]!\n const key = keyFn(item, i)\n if (seen.has(key) || prevOrderedBlocks[i]!.key !== key) {\n stableOrder = false\n break\n }\n seen.add(key)\n }\n if (stableOrder) {\n for (let i = 0; i < prevCount; i++) {\n const item = newItems[i]!\n const block = prevOrderedBlocks[i]!\n if (block.rawItem !== item) {\n block.rawItem = item\n block.item(item)\n }\n if (needsIndex && block.rawIndex !== i) {\n block.rawIndex = i\n block.index(i)\n }\n }\n return\n }\n }\n\n newBlocks.clear()\n nextOrderedBlocks.length = 0\n orderedIndexByKey.clear()\n const createdBlocks: KeyedBlock<T>[] = []\n let appendCandidate = prevCount > 0 && newItems.length >= prevCount\n const appendedBlocks: KeyedBlock<T>[] = []\n let mismatchCount = 0\n let mismatchFirst = -1\n let mismatchSecond = -1\n let hasDuplicateKey = false\n\n // Phase 1: Build new blocks map (reuse or create)\n newItems.forEach((item, index) => {\n const key = keyFn(item, index)\n // Micro-optimization: single Map.get instead of has+get\n let block = oldBlocks.get(key)\n const existed = block !== undefined\n\n if (block) {\n if (block.rawItem !== item) {\n block.rawItem = item\n block.item(item)\n }\n if (needsIndex && block.rawIndex !== index) {\n block.rawIndex = index\n block.index(index)\n }\n }\n\n if (block) {\n // Reusing existing block from oldBlocks\n newBlocks.set(key, block)\n oldBlocks.delete(key)\n } else {\n // If newBlocks already has this key (duplicate key case), clean up the previous block\n const existingBlock = newBlocks.get(key)\n if (existingBlock) {\n if (isDev) {\n console.warn(\n `[fict] Duplicate key \"${String(key)}\" detected in list rendering. ` +\n `Each item should have a unique key. The previous item with this key will be replaced.`,\n )\n }\n destroyRoot(existingBlock.root)\n removeNodes(existingBlock.nodes)\n }\n // Create new block\n block = createKeyedBlock(key, item, index, renderItem, needsIndex, hostRoot)\n createdBlocks.push(block)\n }\n\n const resolvedBlock = block\n\n newBlocks.set(key, resolvedBlock)\n\n // Micro-optimization: single Map.get instead of checking position multiple times\n const position = orderedIndexByKey.get(key)\n if (position !== undefined) {\n appendCandidate = false\n hasDuplicateKey = true\n const prior = nextOrderedBlocks[position]\n if (prior && prior !== resolvedBlock) {\n destroyRoot(prior.root)\n removeNodes(prior.nodes)\n }\n nextOrderedBlocks[position] = resolvedBlock\n } else {\n if (appendCandidate) {\n if (index < prevCount) {\n if (!prevOrderedBlocks[index] || prevOrderedBlocks[index]!.key !== key) {\n appendCandidate = false\n }\n } else if (existed) {\n appendCandidate = false\n }\n }\n const nextIndex = nextOrderedBlocks.length\n orderedIndexByKey.set(key, nextIndex)\n nextOrderedBlocks.push(resolvedBlock)\n if (\n mismatchCount < 3 &&\n (nextIndex >= prevCount || prevOrderedBlocks[nextIndex] !== resolvedBlock)\n ) {\n if (mismatchCount === 0) {\n mismatchFirst = nextIndex\n } else if (mismatchCount === 1) {\n mismatchSecond = nextIndex\n }\n mismatchCount++\n }\n }\n\n if (appendCandidate && index >= prevCount) {\n appendedBlocks.push(resolvedBlock)\n }\n })\n\n const canAppend =\n appendCandidate &&\n prevCount > 0 &&\n newItems.length > prevCount &&\n oldBlocks.size === 0 &&\n appendedBlocks.length > 0\n if (canAppend) {\n const appendedNodes: Node[] = []\n for (const block of appendedBlocks) {\n for (let i = 0; i < block.nodes.length; i++) {\n appendedNodes.push(block.nodes[i]!)\n }\n }\n if (appendedNodes.length > 0) {\n insertNodesBefore(parent, appendedNodes, container.endMarker)\n const currentNodes = container.currentNodes\n currentNodes.pop()\n for (let i = 0; i < appendedNodes.length; i++) {\n currentNodes.push(appendedNodes[i]!)\n }\n currentNodes.push(container.endMarker)\n }\n\n container.blocks = newBlocks\n container.nextBlocks = oldBlocks\n container.orderedBlocks = nextOrderedBlocks\n container.nextOrderedBlocks = prevOrderedBlocks\n for (const block of createdBlocks) {\n if (newBlocks.get(block.key) === block) {\n flushOnMount(block.root)\n }\n }\n return\n }\n\n // Phase 2: Remove old blocks that are no longer in the list\n if (oldBlocks.size > 0) {\n for (const block of oldBlocks.values()) {\n destroyRoot(block.root)\n removeNodes(block.nodes)\n }\n oldBlocks.clear()\n }\n\n const canReorderInPlace =\n createdBlocks.length === 0 &&\n oldBlocks.size === 0 &&\n nextOrderedBlocks.length === prevOrderedBlocks.length\n\n let skipReconcile = false\n let updateNodeBuffer = true\n\n if (canReorderInPlace && nextOrderedBlocks.length > 0 && !hasDuplicateKey) {\n if (mismatchCount === 0) {\n skipReconcile = true\n updateNodeBuffer = false\n } else if (\n mismatchCount === 2 &&\n prevOrderedBlocks[mismatchFirst] === nextOrderedBlocks[mismatchSecond] &&\n prevOrderedBlocks[mismatchSecond] === nextOrderedBlocks[mismatchFirst]\n ) {\n if (\n reorderBySwap(\n parent,\n prevOrderedBlocks[mismatchFirst]!,\n prevOrderedBlocks[mismatchSecond]!,\n )\n ) {\n skipReconcile = true\n }\n } else if (\n reorderByLIS(parent, container.endMarker, prevOrderedBlocks, nextOrderedBlocks)\n ) {\n skipReconcile = true\n }\n }\n\n // Phase 3: Reconcile DOM with buffered node arrays\n if (!skipReconcile && (newBlocks.size > 0 || container.currentNodes.length > 0)) {\n const prevNodes = container.currentNodes\n const nextNodes = container.nextNodes\n nextNodes.length = 0\n nextNodes.push(container.startMarker)\n\n for (let i = 0; i < nextOrderedBlocks.length; i++) {\n const nodes = nextOrderedBlocks[i]!.nodes\n for (let j = 0; j < nodes.length; j++) {\n nextNodes.push(nodes[j]!)\n }\n }\n\n nextNodes.push(container.endMarker)\n\n reconcileArrays(parent, prevNodes, nextNodes)\n\n // Swap buffers to reuse arrays on next diff\n container.currentNodes = nextNodes\n container.nextNodes = prevNodes\n } else if (skipReconcile && updateNodeBuffer) {\n const prevNodes = container.currentNodes\n const nextNodes = container.nextNodes\n nextNodes.length = 0\n nextNodes.push(container.startMarker)\n for (let i = 0; i < nextOrderedBlocks.length; i++) {\n const nodes = nextOrderedBlocks[i]!.nodes\n for (let j = 0; j < nodes.length; j++) {\n nextNodes.push(nodes[j]!)\n }\n }\n nextNodes.push(container.endMarker)\n container.currentNodes = nextNodes\n container.nextNodes = prevNodes\n }\n\n // Swap block maps for reuse\n container.blocks = newBlocks\n container.nextBlocks = oldBlocks\n container.orderedBlocks = nextOrderedBlocks\n container.nextOrderedBlocks = prevOrderedBlocks\n for (const block of createdBlocks) {\n if (newBlocks.get(block.key) === block) {\n flushOnMount(block.root)\n }\n }\n })\n }\n\n const disconnectObserver = () => {\n connectObserver?.disconnect()\n connectObserver = null\n }\n\n const ensureEffectStarted = (): boolean => {\n if (disposed || effectStarted) return effectStarted\n const parent = getConnectedParent()\n if (!parent) return false\n const start = () => {\n effectDispose = createRenderEffect(performDiff)\n effectStarted = true\n }\n if (hostRoot) {\n const prev = pushRoot(hostRoot)\n try {\n start()\n } finally {\n popRoot(prev)\n }\n } else {\n start()\n }\n return true\n }\n\n const waitForConnection = () => {\n if (connectObserver || typeof MutationObserver === 'undefined') return\n connectObserver = new MutationObserver(() => {\n if (disposed) return\n if (getConnectedParent()) {\n disconnectObserver()\n if (ensureEffectStarted()) {\n flush()\n }\n }\n })\n connectObserver.observe(document, { childList: true, subtree: true })\n }\n\n const scheduleStart = () => {\n if (startScheduled || disposed || effectStarted) return\n startScheduled = true\n const run = () => {\n startScheduled = false\n if (!ensureEffectStarted()) {\n waitForConnection()\n }\n }\n if (typeof queueMicrotask === 'function') {\n queueMicrotask(run)\n } else {\n Promise.resolve()\n .then(run)\n .catch(() => undefined)\n }\n }\n\n scheduleStart()\n\n return {\n get marker() {\n scheduleStart()\n return fragment\n },\n startMarker: container.startMarker,\n endMarker: container.endMarker,\n // Flush pending items - call after markers are inserted into DOM\n flush: () => {\n if (disposed) return\n scheduleStart()\n if (ensureEffectStarted()) {\n flush()\n } else {\n waitForConnection()\n }\n },\n dispose: () => {\n disposed = true\n effectDispose?.()\n disconnectObserver()\n container.dispose()\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,IAAM,QAAQ,OAAO,kBAAkB;AACvC,IAAM,SAAS,OAAO,mBAAmB;AACzC,IAAM,cAAc,OAAO,cAAc;AAclC,SAAS,YACd,cACkD;AAClD,QAAM,YAAYA,QAAO,YAAY;AACrC,QAAM,UAAU,KAAK,SAAS;AAE9B,WAAS,SAAS,IAA4B;AAC5C,UAAM,MAAM;AACV,YAAM,SAAS,GAAG,OAAO;AACzB,UAAI,WAAW,QAAW;AACxB,kBAAU,SAAS,MAAM;AAAA,MAC3B;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO,CAAC,SAAS,QAAQ;AAC3B;AAGA,IAAM,aAAa,oBAAI,QAAyB;AAEhD,IAAM,cAAc,oBAAI,QAA+D;AAEvF,SAAS,KAAQ,OAAa;AAC5B,MAAI,UAAU,QAAQ,OAAO,UAAU,SAAU,QAAO;AACxD,MAAI,QAAQ,IAAI,OAAO,KAAK,EAAG,QAAO;AAEtC,MAAI,WAAW,IAAI,KAAK,EAAG,QAAO,WAAW,IAAI,KAAK;AAEtD,QAAM,UAAgC;AAAA,IACpC,IAAI,QAAQC,OAAM,UAAU;AAC1B,UAAIA,UAAS,MAAO,QAAO;AAC3B,UAAIA,UAAS,OAAQ,QAAO;AAE5B,YAAMC,SAAQ,QAAQ,IAAI,QAAQD,OAAM,QAAQ;AAGhD,YAAM,QAAQA,KAAI;AAGlB,aAAO,KAAKC,MAAK;AAAA,IACnB;AAAA,IACA,IAAI,QAAQD,OAAM;AAChB,YAAM,SAA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AC;AAAA,EACtE;AAEA,QAAM,gBAAgB,MAAM;AAC1B,QAAI,kBAAkB,YAAY,cAAe;AACjD,qBAAiB;AACjB,UAAM,MAAM,MAAM;AAChB,uBAAiB;AACjB,UAAI,CAAC,oBAAoB,GAAG;AAC1B,0BAAkB;AAAA,MACpB;AAAA,IACF;AACA,QAAI,OAAO,mBAAmB,YAAY;AACxC,qBAAe,GAAG;AAAA,IACpB,OAAO;AACL,cAAQ,QAAQ,EACb,KAAK,GAAG,EACR,MAAM,MAAM,MAAS;AAAA,IAC1B;AAAA,EACF;AAEA,gBAAc;AAEd,SAAO;AAAA,IACL,IAAI,SAAS;AACX,oBAAc;AACd,aAAO;AAAA,IACT;AAAA,IACA,aAAa,UAAU;AAAA,IACvB,WAAW,UAAU;AAAA;AAAA,IAErB,OAAO,MAAM;AACX,UAAI,SAAU;AACd,oBAAc;AACd,UAAI,oBAAoB,GAAG;AACzB,cAAM;AAAA,MACR,OAAO;AACL,0BAAkB;AAAA,MACpB;AAAA,IACF;AAAA,IACA,SAAS,MAAM;AACb,iBAAW;AACX,sBAAgB;AAChB,yBAAmB;AACnB,gBAAU,QAAQ;AAAA,IACpB;AAAA,EACF;AACF;","names":["unwrap","prop","value","track","batch"]}
1
+ {"version":3,"sources":["../src/reconcile.ts","../src/list-helpers.ts"],"sourcesContent":["/**\n * Fict DOM Reconciliation\n *\n * Efficient array reconciliation algorithm based on udomdiff.\n * https://github.com/WebReflection/udomdiff\n *\n * This algorithm uses a 5-step strategy:\n * 1. Common prefix - skip matching nodes at start\n * 2. Common suffix - skip matching nodes at end\n * 3. Append - insert remaining new nodes\n * 4. Remove - remove remaining old nodes\n * 5. Swap/Map fallback - handle complex rearrangements\n *\n * Most real-world updates (95%+) use fast paths without building a Map.\n */\n\n/**\n * Reconcile two arrays of DOM nodes, efficiently updating the DOM.\n *\n * @param parentNode - The parent element containing the nodes\n * @param a - The old array of nodes (currently in DOM)\n * @param b - The new array of nodes (target state)\n *\n * **Note:** This function may mutate the input array `a` during the swap\n * optimization (step 5a). If you need to preserve the original array,\n * pass a shallow copy: `reconcileArrays(parent, [...oldNodes], newNodes)`.\n *\n * @example\n * ```ts\n * const oldNodes = [node1, node2, node3]\n * const newNodes = [node1, node4, node3] // node2 replaced with node4\n * reconcileArrays(parent, oldNodes, newNodes)\n * ```\n */\nexport default function reconcileArrays(parentNode: ParentNode, a: Node[], b: Node[]): void {\n const bLength = b.length\n let aEnd = a.length\n let bEnd = bLength\n let aStart = 0\n let bStart = 0\n const after = aEnd > 0 ? a[aEnd - 1]!.nextSibling : null\n let map: Map<Node, number> | null = null\n\n while (aStart < aEnd || bStart < bEnd) {\n // 1. Common prefix - nodes match at start\n if (a[aStart] === b[bStart]) {\n aStart++\n bStart++\n continue\n }\n\n // 2. Common suffix - nodes match at end\n while (a[aEnd - 1] === b[bEnd - 1]) {\n aEnd--\n bEnd--\n }\n\n // 3. Append - old array exhausted, insert remaining new nodes\n if (aEnd === aStart) {\n const node: Node | null =\n bEnd < bLength ? (bStart ? b[bStart - 1]!.nextSibling : (b[bEnd - bStart] ?? null)) : after\n\n const count = bEnd - bStart\n const doc = (parentNode as Node).ownerDocument\n if (count > 1 && doc) {\n const frag = doc.createDocumentFragment()\n for (let i = bStart; i < bEnd; i++) {\n frag.appendChild(b[i]!)\n }\n parentNode.insertBefore(frag, node)\n bStart = bEnd\n } else {\n while (bStart < bEnd) {\n parentNode.insertBefore(b[bStart++]!, node)\n }\n }\n }\n // 4. Remove - new array exhausted, remove remaining old nodes\n else if (bEnd === bStart) {\n while (aStart < aEnd) {\n const nodeToRemove = a[aStart]!\n if (!map || !map.has(nodeToRemove)) {\n nodeToRemove.parentNode?.removeChild(nodeToRemove)\n }\n aStart++\n }\n }\n // 5a. Swap backward - detect backward swap pattern\n else if (a[aStart] === b[bEnd - 1] && b[bStart] === a[aEnd - 1]) {\n const node = a[--aEnd]!.nextSibling\n parentNode.insertBefore(b[bStart++]!, a[aStart++]!.nextSibling)\n parentNode.insertBefore(b[--bEnd]!, node)\n // Update reference in old array for potential future matches\n a[aEnd] = b[bEnd]!\n }\n // 5b. Map fallback - use Map for complex rearrangements\n else {\n // Build map on first use (lazy initialization)\n if (!map) {\n map = new Map()\n let i = bStart\n while (i < bEnd) {\n map.set(b[i]!, i++)\n }\n }\n\n const index = map.get(a[aStart]!)\n\n if (index != null) {\n if (bStart < index && index < bEnd) {\n // Check for longest increasing subsequence\n let i = aStart\n let sequence = 1\n let t: number | undefined\n\n while (++i < aEnd && i < bEnd) {\n t = map.get(a[i]!)\n if (t == null || t !== index + sequence) break\n sequence++\n }\n\n // Use optimal strategy based on sequence length\n if (sequence > index - bStart) {\n // Sequence is long enough - insert nodes before current\n const node = a[aStart]!\n while (bStart < index) {\n parentNode.insertBefore(b[bStart++]!, node)\n }\n } else {\n // Short sequence - replace\n parentNode.replaceChild(b[bStart++]!, a[aStart++]!)\n }\n } else {\n aStart++\n }\n } else {\n // Node not in new array - remove it\n const nodeToRemove = a[aStart++]!\n nodeToRemove.parentNode?.removeChild(nodeToRemove)\n }\n }\n }\n}\n\n/**\n * Simple reconciliation for keyed lists.\n * Uses the same algorithm but works with keyed blocks.\n *\n * @param parentNode - The parent element\n * @param oldNodes - Old nodes in DOM order\n * @param newNodes - New nodes in target order\n */\nexport function reconcileNodes(parentNode: ParentNode, oldNodes: Node[], newNodes: Node[]): void {\n reconcileArrays(parentNode, oldNodes, newNodes)\n}\n","/**\n * List Helpers for Compiler-Generated Fine-Grained Updates\n *\n * These helpers are used by the compiler to generate efficient keyed list rendering.\n * They provide low-level primitives for DOM node manipulation without rebuilding.\n */\n\nimport { createElement } from './dom'\nimport { createRenderEffect } from './effect'\nimport { isHydratingActive, withHydrationRange } from './hydration'\nimport {\n createRootContext,\n destroyRoot,\n flushOnMount,\n getCurrentRoot,\n popRoot,\n pushRoot,\n type RootContext,\n} from './lifecycle'\nimport { insertNodesBefore, removeNodes, toNodeArray } from './node-ops'\nimport reconcileArrays from './reconcile'\nimport { __fictIsHydrating, __fictIsSSR } from './resume'\nimport { batch } from './scheduler'\nimport { createSignal, effectScope, flush, setActiveSub, type Signal } from './signal'\nimport type { FictNode } from './types'\n\n// Re-export shared DOM helpers for compiler-generated code\nexport { insertNodesBefore, removeNodes, toNodeArray }\n\nconst isDev =\n typeof __DEV__ !== 'undefined'\n ? __DEV__\n : typeof process === 'undefined' || process.env?.NODE_ENV !== 'production'\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * A keyed block represents a single item in a list with its associated DOM nodes and state\n */\ninterface KeyedBlock<T = unknown> {\n /** Unique key for this block */\n key: string | number\n /** DOM nodes belonging to this block */\n nodes: Node[]\n /** Root context for lifecycle management */\n root: RootContext\n /** Signal containing the current item value */\n item: Signal<T>\n /** Signal containing the current index */\n index: Signal<number>\n /** Last raw item value assigned to this block */\n rawItem: T\n /** Last raw index value assigned to this block */\n rawIndex: number\n}\n\n/**\n * Container for managing keyed list blocks\n */\ninterface KeyedListContainer<T = unknown> {\n /** Start marker comment node */\n startMarker: Comment\n /** End marker comment node */\n endMarker: Comment\n /** Map of key to block */\n blocks: Map<string | number, KeyedBlock<T>>\n /** Scratch map reused for the next render */\n nextBlocks: Map<string | number, KeyedBlock<T>>\n /** Current nodes in DOM order (including markers) */\n currentNodes: Node[]\n /** Next-frame node buffer to avoid reallocations */\n nextNodes: Node[]\n /** Ordered blocks in current DOM order */\n orderedBlocks: KeyedBlock<T>[]\n /** Next-frame ordered block buffer to avoid reallocations */\n nextOrderedBlocks: KeyedBlock<T>[]\n /** Track position of keys in the ordered buffer to handle duplicates */\n orderedIndexByKey: Map<string | number, number>\n /** Cleanup function */\n dispose: () => void\n}\n\n/**\n * Binding handle returned by createKeyedList for compiler-generated code\n */\nexport interface KeyedListBinding {\n /** Document fragment placeholder inserted by the compiler/runtime */\n marker: Comment | DocumentFragment\n /** Start marker comment node */\n startMarker: Comment\n /** End marker comment node */\n endMarker: Comment\n /** Flush pending items - call after markers are inserted into DOM */\n flush?: () => void\n /** Cleanup function */\n dispose: () => void\n}\n\ntype FineGrainedRenderItem<T> = (\n itemSig: Signal<T>,\n indexSig: Signal<number>,\n key: string | number,\n) => Node[]\n\n// ============================================================================\n// DOM Manipulation Primitives\n// ============================================================================\n\n/**\n * Move nodes to a position before the anchor node.\n * This is optimized to avoid unnecessary DOM operations.\n *\n * @param parent - Parent node to move nodes within\n * @param nodes - Array of nodes to move\n * @param anchor - Node to insert before (or null for end)\n */\nexport function moveNodesBefore(parent: Node, nodes: Node[], anchor: Node | null): void {\n // Insert in reverse order to maintain correct sequence\n // This way each node becomes the new anchor for the next\n for (let i = nodes.length - 1; i >= 0; i--) {\n const node = nodes[i]!\n if (!node || !(node instanceof Node)) {\n const message = isDev ? 'Invalid node in moveNodesBefore' : 'FICT:E_NODE'\n throw new Error(message)\n }\n // Only move if not already in correct position\n if (node.nextSibling !== anchor) {\n if (node.ownerDocument !== parent.ownerDocument && parent.ownerDocument) {\n parent.ownerDocument.adoptNode(node)\n }\n try {\n parent.insertBefore(node, anchor)\n } catch (e: any) {\n if (parent.ownerDocument) {\n try {\n const clone = parent.ownerDocument.importNode(node, true)\n parent.insertBefore(clone, anchor)\n // Update the nodes array with the clone to maintain correct references.\n // This ensures future operations (like removal or reordering) work correctly.\n nodes[i] = clone\n if (isDev) {\n console.warn(\n `[fict] Node cloning fallback triggered during list reordering. ` +\n `This may indicate cross-document node insertion. ` +\n `The node reference has been updated to the clone.`,\n )\n }\n anchor = clone\n continue\n } catch {\n // Clone fallback failed\n }\n }\n throw e\n }\n }\n anchor = node\n }\n}\n\n/**\n * Remove an array of nodes from the DOM\n *\n * @param nodes - Array of nodes to remove\n */\n// Number.MAX_SAFE_INTEGER is 2^53 - 1, but we reset earlier to avoid any precision issues\nconst MAX_SAFE_VERSION = 0x1fffffffffffff // 2^53 - 1\n\nexport function createVersionedSignalAccessor<T>(initialValue: T): Signal<T> {\n let current = initialValue\n let version = 0\n const track = createSignal(version)\n\n function accessor(value?: T): T | void {\n if (arguments.length === 0) {\n track()\n return current\n }\n current = value as T\n // This is safe because we only care about version changes, not absolute values\n version = version >= MAX_SAFE_VERSION ? 1 : version + 1\n track(version)\n }\n\n return accessor as Signal<T>\n}\n\n// ============================================================================\n// Keyed List Container\n// ============================================================================\n\n/**\n * Create a container for managing a keyed list.\n * This sets up the marker nodes and provides cleanup.\n *\n * @returns Container object with markers, blocks map, and dispose function\n */\nfunction createKeyedListContainer<T = unknown>(\n startOverride?: Comment,\n endOverride?: Comment,\n): KeyedListContainer<T> {\n const startMarker = startOverride ?? document.createComment('fict:list:start')\n const endMarker = endOverride ?? document.createComment('fict:list:end')\n\n const dispose = () => {\n // Clean up all blocks\n for (const block of container.blocks.values()) {\n destroyRoot(block.root)\n // Nodes are removed by parent disposal or specific cleanup if needed\n // But for list disposal, we just clear the container\n }\n container.blocks.clear()\n container.nextBlocks.clear()\n\n // Remove nodes (including markers)\n // Check if markers are still in DOM before using Range\n if (!startMarker.parentNode || !endMarker.parentNode) {\n // Markers already removed, nothing to do\n container.currentNodes = []\n container.nextNodes = []\n container.orderedBlocks.length = 0\n container.nextOrderedBlocks.length = 0\n container.orderedIndexByKey.clear()\n return\n }\n const range = document.createRange()\n range.setStartBefore(startMarker)\n range.setEndAfter(endMarker)\n range.deleteContents()\n\n // Clear cache\n container.currentNodes = []\n container.nextNodes = []\n container.nextBlocks.clear()\n container.orderedBlocks.length = 0\n container.nextOrderedBlocks.length = 0\n container.orderedIndexByKey.clear()\n }\n\n const container: KeyedListContainer<T> = {\n startMarker,\n endMarker,\n blocks: new Map<string | number, KeyedBlock<T>>(),\n nextBlocks: new Map<string | number, KeyedBlock<T>>(),\n currentNodes: [startMarker, endMarker],\n nextNodes: [],\n orderedBlocks: [],\n nextOrderedBlocks: [],\n orderedIndexByKey: new Map<string | number, number>(),\n dispose,\n }\n\n return container\n}\n\n// ============================================================================\n// Block Creation Helpers\n// ============================================================================\n\n/**\n * Create a new keyed block with the given render function\n *\n * @param key - Unique key for this block\n * @param item - Initial item value\n * @param index - Initial index\n * @param render - Function that creates the DOM nodes and sets up bindings\n * @returns New KeyedBlock\n */\nfunction createKeyedBlock<T>(\n key: string | number,\n item: T,\n index: number,\n render: (item: Signal<T>, index: Signal<number>, key: string | number) => Node[],\n needsIndex = true,\n hostRoot?: RootContext,\n): KeyedBlock<T> {\n // Use versioned signal for all item types; avoid diffing proxy overhead for objects\n const itemSig = createVersionedSignalAccessor(item)\n\n const indexSig = needsIndex\n ? createSignal<number>(index)\n : (((next?: number) => {\n if (arguments.length === 0) return index\n index = next as number\n return index\n }) as Signal<number>)\n const root = createRootContext(hostRoot)\n const prevRoot = pushRoot(root)\n // maintaining proper cleanup chain. The scope will be disposed when\n // the root is destroyed, ensuring nested effects are properly cleaned up.\n let nodes: Node[] = []\n let scopeDispose: (() => void) | undefined\n\n // First, isolate from parent effect to prevent child effects from being\n // purged when the outer effect (e.g., performDiff) re-runs\n const prevSub = setActiveSub(undefined)\n\n try {\n // Create an effectScope that will track all effects created during render\n scopeDispose = effectScope(() => {\n const rendered = render(itemSig, indexSig, key)\n // If render returns real DOM nodes/arrays, preserve them to avoid\n // reparenting side-effects (tests may pre-insert them).\n if (\n rendered instanceof Node ||\n (Array.isArray(rendered) && rendered.every(n => n instanceof Node))\n ) {\n nodes = toNodeArray(rendered)\n } else {\n const element = createElement(rendered as unknown as FictNode)\n nodes = toNodeArray(element)\n }\n })\n\n // Register the scope cleanup with the root so effects are cleaned up\n // when the block is destroyed\n if (scopeDispose) {\n root.cleanups.push(scopeDispose)\n }\n } finally {\n setActiveSub(prevSub)\n popRoot(prevRoot)\n }\n\n return {\n key,\n nodes,\n root,\n item: itemSig,\n index: indexSig,\n rawItem: item,\n rawIndex: index,\n }\n}\n\n// ============================================================================\n// Utilities\n// ============================================================================\n\n/**\n * Check if a node is between two markers\n */\nexport function isNodeBetweenMarkers(\n node: Node,\n startMarker: Comment,\n endMarker: Comment,\n): boolean {\n let current: Node | null = startMarker.nextSibling\n while (current && current !== endMarker) {\n if (current === node) return true\n current = current.nextSibling\n }\n return false\n}\n\nfunction reorderBySwap<T>(\n parent: ParentNode & Node,\n first: KeyedBlock<T>,\n second: KeyedBlock<T>,\n): boolean {\n if (first === second) return false\n const firstNodes = first.nodes\n const secondNodes = second.nodes\n if (firstNodes.length === 0 || secondNodes.length === 0) return false\n const lastFirst = firstNodes[firstNodes.length - 1]!\n const lastSecond = secondNodes[secondNodes.length - 1]!\n const afterFirst = lastFirst.nextSibling\n const afterSecond = lastSecond.nextSibling\n moveNodesBefore(parent, firstNodes, afterSecond)\n moveNodesBefore(parent, secondNodes, afterFirst)\n return true\n}\n\nfunction getLISIndices(sequence: number[]): number[] {\n const predecessors = new Array<number>(sequence.length)\n const result: number[] = []\n\n for (let i = 0; i < sequence.length; i++) {\n const value = sequence[i]!\n if (value < 0) {\n predecessors[i] = -1\n continue\n }\n\n let low = 0\n let high = result.length\n while (low < high) {\n const mid = (low + high) >> 1\n if (sequence[result[mid]!]! < value) {\n low = mid + 1\n } else {\n high = mid\n }\n }\n\n predecessors[i] = low > 0 ? result[low - 1]! : -1\n if (low === result.length) {\n result.push(i)\n } else {\n result[low] = i\n }\n }\n\n const lis: number[] = new Array(result.length)\n let k = result.length > 0 ? result[result.length - 1]! : -1\n for (let i = result.length - 1; i >= 0; i--) {\n lis[i] = k\n k = predecessors[k]!\n }\n return lis\n}\n\nfunction reorderByLIS<T>(\n parent: ParentNode & Node,\n endMarker: Comment,\n prev: KeyedBlock<T>[],\n next: KeyedBlock<T>[],\n): boolean {\n const positions = new Map<KeyedBlock<T>, number>()\n for (let i = 0; i < prev.length; i++) {\n positions.set(prev[i]!, i)\n }\n\n const sequence = new Array<number>(next.length)\n for (let i = 0; i < next.length; i++) {\n const position = positions.get(next[i]!)\n if (position === undefined) return false\n sequence[i] = position\n }\n\n const lisIndices = getLISIndices(sequence)\n if (lisIndices.length === sequence.length) return true\n\n const inLIS = new Array<boolean>(sequence.length).fill(false)\n for (let i = 0; i < lisIndices.length; i++) {\n inLIS[lisIndices[i]!] = true\n }\n\n let anchor: Node | null = endMarker\n let moved = false\n for (let i = next.length - 1; i >= 0; i--) {\n const block = next[i]!\n const nodes = block.nodes\n if (nodes.length === 0) continue\n if (inLIS[i]) {\n anchor = nodes[0]!\n continue\n }\n moveNodesBefore(parent, nodes, anchor)\n anchor = nodes[0]!\n moved = true\n }\n\n return moved\n}\n\n// ============================================================================\n// High-Level List Binding (for compiler-generated code)\n// ============================================================================\n\n/**\n * Create a keyed list binding with automatic diffing and DOM updates.\n * This is used by compiler-generated code for efficient list rendering.\n *\n * @param getItems - Function that returns the current array of items\n * @param keyFn - Function to extract unique key from each item\n * @param renderItem - Function that creates DOM nodes for each item\n * @returns Binding handle with markers and dispose function\n */\nexport function createKeyedList<T extends object>(\n getItems: () => T[],\n keyFn: (item: T, index: number) => string | number,\n renderItem: FineGrainedRenderItem<T>,\n needsIndex?: boolean,\n startMarker?: Comment,\n endMarker?: Comment,\n): KeyedListBinding {\n const resolvedNeedsIndex =\n arguments.length >= 4 ? !!needsIndex : renderItem.length > 1 /* has index param */\n return createFineGrainedKeyedList(\n getItems,\n keyFn,\n renderItem,\n resolvedNeedsIndex,\n startMarker,\n endMarker,\n )\n}\n\nfunction createFineGrainedKeyedList<T extends object>(\n getItems: () => T[],\n keyFn: (item: T, index: number) => string | number,\n renderItem: FineGrainedRenderItem<T>,\n needsIndex: boolean,\n startOverride?: Comment,\n endOverride?: Comment,\n): KeyedListBinding {\n const container = createKeyedListContainer<T>(startOverride, endOverride)\n const hostRoot = getCurrentRoot()\n const useProvided = !!(startOverride && endOverride)\n const fragment = useProvided ? container.startMarker : document.createDocumentFragment()\n if (!useProvided) {\n ;(fragment as DocumentFragment).append(container.startMarker, container.endMarker)\n }\n let disposed = false\n let effectDispose: (() => void) | undefined\n let connectObserver: MutationObserver | null = null\n let effectStarted = false\n let startScheduled = false\n let initialHydrating = __fictIsHydrating()\n\n const collectBetween = (): Node[] => {\n const nodes: Node[] = []\n let cursor = container.startMarker.nextSibling\n while (cursor && cursor !== container.endMarker) {\n nodes.push(cursor)\n cursor = cursor.nextSibling\n }\n return nodes\n }\n\n const getConnectedParent = (): (ParentNode & Node) | null => {\n const endParent = container.endMarker.parentNode\n const startParent = container.startMarker.parentNode\n if (\n endParent &&\n startParent &&\n endParent === startParent &&\n (endParent as Node).nodeType !== 11\n ) {\n const parentNode = endParent as ParentNode & Node\n if ('isConnected' in parentNode && !parentNode.isConnected) return null\n return parentNode\n }\n return null\n }\n\n const performDiff = () => {\n if (disposed) return\n // During SSR, render synchronously without waiting for DOM connection\n const isSSR = __fictIsSSR()\n const parent = isSSR\n ? (container.startMarker.parentNode as (ParentNode & Node) | null)\n : getConnectedParent()\n if (!parent) return\n batch(() => {\n const oldBlocks = container.blocks\n const newBlocks = container.nextBlocks\n const prevOrderedBlocks = container.orderedBlocks\n const nextOrderedBlocks = container.nextOrderedBlocks\n const orderedIndexByKey = container.orderedIndexByKey\n const newItems = getItems()\n\n if (initialHydrating && isHydratingActive()) {\n initialHydrating = false\n newBlocks.clear()\n nextOrderedBlocks.length = 0\n orderedIndexByKey.clear()\n\n if (newItems.length === 0) {\n oldBlocks.clear()\n prevOrderedBlocks.length = 0\n container.currentNodes = [container.startMarker, container.endMarker]\n container.nextNodes.length = 0\n return\n }\n\n const createdBlocks: KeyedBlock<T>[] = []\n withHydrationRange(\n container.startMarker.nextSibling,\n container.endMarker,\n parent.ownerDocument ?? document,\n () => {\n for (let index = 0; index < newItems.length; index++) {\n const item = newItems[index]!\n const key = keyFn(item, index)\n if (newBlocks.has(key)) {\n if (isDev) {\n console.warn(\n `[fict] Duplicate key \"${String(key)}\" detected in list hydration. ` +\n `Each item should have a unique key.`,\n )\n }\n const existing = newBlocks.get(key)\n if (existing) {\n destroyRoot(existing.root)\n removeNodes(existing.nodes)\n }\n }\n const block = createKeyedBlock(key, item, index, renderItem, needsIndex, hostRoot)\n createdBlocks.push(block)\n newBlocks.set(key, block)\n orderedIndexByKey.set(key, nextOrderedBlocks.length)\n nextOrderedBlocks.push(block)\n }\n },\n )\n\n container.blocks = newBlocks\n container.nextBlocks = oldBlocks\n container.orderedBlocks = nextOrderedBlocks\n container.nextOrderedBlocks = prevOrderedBlocks\n oldBlocks.clear()\n prevOrderedBlocks.length = 0\n container.currentNodes = [container.startMarker, ...collectBetween(), container.endMarker]\n container.nextNodes.length = 0\n\n for (const block of createdBlocks) {\n if (newBlocks.get(block.key) === block) {\n flushOnMount(block.root)\n }\n }\n\n return\n }\n\n if (newItems.length === 0) {\n if (oldBlocks.size > 0) {\n // Destroy all block roots first\n for (const block of oldBlocks.values()) {\n destroyRoot(block.root)\n }\n // Use Range.deleteContents for efficient bulk DOM removal\n const range = document.createRange()\n range.setStartAfter(container.startMarker)\n range.setEndBefore(container.endMarker)\n range.deleteContents()\n }\n oldBlocks.clear()\n newBlocks.clear()\n prevOrderedBlocks.length = 0\n nextOrderedBlocks.length = 0\n orderedIndexByKey.clear()\n container.currentNodes.length = 0\n container.currentNodes.push(container.startMarker, container.endMarker)\n container.nextNodes.length = 0\n return\n }\n\n const prevCount = prevOrderedBlocks.length\n if (prevCount > 0 && newItems.length === prevCount && orderedIndexByKey.size === prevCount) {\n let stableOrder = true\n const seen = new Set<string | number>()\n for (let i = 0; i < prevCount; i++) {\n const item = newItems[i]!\n const key = keyFn(item, i)\n if (seen.has(key) || prevOrderedBlocks[i]!.key !== key) {\n stableOrder = false\n break\n }\n seen.add(key)\n }\n if (stableOrder) {\n for (let i = 0; i < prevCount; i++) {\n const item = newItems[i]!\n const block = prevOrderedBlocks[i]!\n if (block.rawItem !== item) {\n block.rawItem = item\n block.item(item)\n }\n if (needsIndex && block.rawIndex !== i) {\n block.rawIndex = i\n block.index(i)\n }\n }\n return\n }\n }\n\n newBlocks.clear()\n nextOrderedBlocks.length = 0\n orderedIndexByKey.clear()\n const createdBlocks: KeyedBlock<T>[] = []\n let appendCandidate = prevCount > 0 && newItems.length >= prevCount\n const appendedBlocks: KeyedBlock<T>[] = []\n let mismatchCount = 0\n let mismatchFirst = -1\n let mismatchSecond = -1\n let hasDuplicateKey = false\n\n // Phase 1: Build new blocks map (reuse or create)\n newItems.forEach((item, index) => {\n const key = keyFn(item, index)\n // Micro-optimization: single Map.get instead of has+get\n let block = oldBlocks.get(key)\n const existed = block !== undefined\n\n if (block) {\n if (block.rawItem !== item) {\n block.rawItem = item\n block.item(item)\n }\n if (needsIndex && block.rawIndex !== index) {\n block.rawIndex = index\n block.index(index)\n }\n }\n\n if (block) {\n // Reusing existing block from oldBlocks\n newBlocks.set(key, block)\n oldBlocks.delete(key)\n } else {\n // If newBlocks already has this key (duplicate key case), clean up the previous block\n const existingBlock = newBlocks.get(key)\n if (existingBlock) {\n if (isDev) {\n console.warn(\n `[fict] Duplicate key \"${String(key)}\" detected in list rendering. ` +\n `Each item should have a unique key. The previous item with this key will be replaced.`,\n )\n }\n destroyRoot(existingBlock.root)\n removeNodes(existingBlock.nodes)\n }\n // Create new block\n block = createKeyedBlock(key, item, index, renderItem, needsIndex, hostRoot)\n createdBlocks.push(block)\n }\n\n const resolvedBlock = block\n\n newBlocks.set(key, resolvedBlock)\n\n // Micro-optimization: single Map.get instead of checking position multiple times\n const position = orderedIndexByKey.get(key)\n if (position !== undefined) {\n appendCandidate = false\n hasDuplicateKey = true\n const prior = nextOrderedBlocks[position]\n if (prior && prior !== resolvedBlock) {\n destroyRoot(prior.root)\n removeNodes(prior.nodes)\n }\n nextOrderedBlocks[position] = resolvedBlock\n } else {\n if (appendCandidate) {\n if (index < prevCount) {\n if (!prevOrderedBlocks[index] || prevOrderedBlocks[index]!.key !== key) {\n appendCandidate = false\n }\n } else if (existed) {\n appendCandidate = false\n }\n }\n const nextIndex = nextOrderedBlocks.length\n orderedIndexByKey.set(key, nextIndex)\n nextOrderedBlocks.push(resolvedBlock)\n if (\n mismatchCount < 3 &&\n (nextIndex >= prevCount || prevOrderedBlocks[nextIndex] !== resolvedBlock)\n ) {\n if (mismatchCount === 0) {\n mismatchFirst = nextIndex\n } else if (mismatchCount === 1) {\n mismatchSecond = nextIndex\n }\n mismatchCount++\n }\n }\n\n if (appendCandidate && index >= prevCount) {\n appendedBlocks.push(resolvedBlock)\n }\n })\n\n const canAppend =\n appendCandidate &&\n prevCount > 0 &&\n newItems.length > prevCount &&\n oldBlocks.size === 0 &&\n appendedBlocks.length > 0\n if (canAppend) {\n const appendedNodes: Node[] = []\n for (const block of appendedBlocks) {\n for (let i = 0; i < block.nodes.length; i++) {\n appendedNodes.push(block.nodes[i]!)\n }\n }\n if (appendedNodes.length > 0) {\n insertNodesBefore(parent, appendedNodes, container.endMarker)\n const currentNodes = container.currentNodes\n currentNodes.pop()\n for (let i = 0; i < appendedNodes.length; i++) {\n currentNodes.push(appendedNodes[i]!)\n }\n currentNodes.push(container.endMarker)\n }\n\n container.blocks = newBlocks\n container.nextBlocks = oldBlocks\n container.orderedBlocks = nextOrderedBlocks\n container.nextOrderedBlocks = prevOrderedBlocks\n for (const block of createdBlocks) {\n if (newBlocks.get(block.key) === block) {\n flushOnMount(block.root)\n }\n }\n return\n }\n\n // Phase 2: Remove old blocks that are no longer in the list\n if (oldBlocks.size > 0) {\n for (const block of oldBlocks.values()) {\n destroyRoot(block.root)\n removeNodes(block.nodes)\n }\n oldBlocks.clear()\n }\n\n const canReorderInPlace =\n createdBlocks.length === 0 &&\n oldBlocks.size === 0 &&\n nextOrderedBlocks.length === prevOrderedBlocks.length\n\n let skipReconcile = false\n let updateNodeBuffer = true\n\n if (canReorderInPlace && nextOrderedBlocks.length > 0 && !hasDuplicateKey) {\n if (mismatchCount === 0) {\n skipReconcile = true\n updateNodeBuffer = false\n } else if (\n mismatchCount === 2 &&\n prevOrderedBlocks[mismatchFirst] === nextOrderedBlocks[mismatchSecond] &&\n prevOrderedBlocks[mismatchSecond] === nextOrderedBlocks[mismatchFirst]\n ) {\n if (\n reorderBySwap(\n parent,\n prevOrderedBlocks[mismatchFirst]!,\n prevOrderedBlocks[mismatchSecond]!,\n )\n ) {\n skipReconcile = true\n }\n } else if (\n reorderByLIS(parent, container.endMarker, prevOrderedBlocks, nextOrderedBlocks)\n ) {\n skipReconcile = true\n }\n }\n\n // Phase 3: Reconcile DOM with buffered node arrays\n if (!skipReconcile && (newBlocks.size > 0 || container.currentNodes.length > 0)) {\n const prevNodes = container.currentNodes\n const nextNodes = container.nextNodes\n nextNodes.length = 0\n nextNodes.push(container.startMarker)\n\n for (let i = 0; i < nextOrderedBlocks.length; i++) {\n const nodes = nextOrderedBlocks[i]!.nodes\n for (let j = 0; j < nodes.length; j++) {\n nextNodes.push(nodes[j]!)\n }\n }\n\n nextNodes.push(container.endMarker)\n\n reconcileArrays(parent, prevNodes, nextNodes)\n\n // Swap buffers to reuse arrays on next diff\n container.currentNodes = nextNodes\n container.nextNodes = prevNodes\n } else if (skipReconcile && updateNodeBuffer) {\n const prevNodes = container.currentNodes\n const nextNodes = container.nextNodes\n nextNodes.length = 0\n nextNodes.push(container.startMarker)\n for (let i = 0; i < nextOrderedBlocks.length; i++) {\n const nodes = nextOrderedBlocks[i]!.nodes\n for (let j = 0; j < nodes.length; j++) {\n nextNodes.push(nodes[j]!)\n }\n }\n nextNodes.push(container.endMarker)\n container.currentNodes = nextNodes\n container.nextNodes = prevNodes\n }\n\n // Swap block maps for reuse\n container.blocks = newBlocks\n container.nextBlocks = oldBlocks\n container.orderedBlocks = nextOrderedBlocks\n container.nextOrderedBlocks = prevOrderedBlocks\n for (const block of createdBlocks) {\n if (newBlocks.get(block.key) === block) {\n flushOnMount(block.root)\n }\n }\n })\n }\n\n const disconnectObserver = () => {\n connectObserver?.disconnect()\n connectObserver = null\n }\n\n const ensureEffectStarted = (): boolean => {\n if (disposed || effectStarted) return effectStarted\n // During SSR, render synchronously without waiting for DOM connection\n const isSSR = __fictIsSSR()\n const parent = isSSR\n ? (container.startMarker.parentNode as (ParentNode & Node) | null)\n : getConnectedParent()\n if (!parent) return false\n const start = () => {\n effectDispose = createRenderEffect(performDiff)\n effectStarted = true\n }\n if (hostRoot) {\n const prev = pushRoot(hostRoot)\n try {\n start()\n } finally {\n popRoot(prev)\n }\n } else {\n start()\n }\n return true\n }\n\n const waitForConnection = () => {\n if (connectObserver || typeof MutationObserver === 'undefined') return\n connectObserver = new MutationObserver(() => {\n if (disposed) return\n if (getConnectedParent()) {\n disconnectObserver()\n if (ensureEffectStarted()) {\n flush()\n }\n }\n })\n connectObserver.observe(document, { childList: true, subtree: true })\n }\n\n const scheduleStart = () => {\n if (startScheduled || disposed || effectStarted) return\n startScheduled = true\n const run = () => {\n startScheduled = false\n if (!ensureEffectStarted()) {\n waitForConnection()\n }\n }\n if (typeof queueMicrotask === 'function') {\n queueMicrotask(run)\n } else {\n Promise.resolve()\n .then(run)\n .catch(() => undefined)\n }\n }\n\n scheduleStart()\n\n return {\n get marker() {\n scheduleStart()\n return fragment\n },\n startMarker: container.startMarker,\n endMarker: container.endMarker,\n // Flush pending items - call after markers are inserted into DOM\n flush: () => {\n if (disposed) return\n scheduleStart()\n if (ensureEffectStarted()) {\n flush()\n } else {\n waitForConnection()\n }\n },\n dispose: () => {\n disposed = true\n effectDispose?.()\n disconnectObserver()\n container.dispose()\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCe,SAAR,gBAAiC,YAAwB,GAAW,GAAiB;AAC1F,QAAM,UAAU,EAAE;AAClB,MAAI,OAAO,EAAE;AACb,MAAI,OAAO;AACX,MAAI,SAAS;AACb,MAAI,SAAS;AACb,QAAM,QAAQ,OAAO,IAAI,EAAE,OAAO,CAAC,EAAG,cAAc;AACpD,MAAI,MAAgC;AAEpC,SAAO,SAAS,QAAQ,SAAS,MAAM;AAErC,QAAI,EAAE,MAAM,MAAM,EAAE,MAAM,GAAG;AAC3B;AACA;AACA;AAAA,IACF;AAGA,WAAO,EAAE,OAAO,CAAC,MAAM,EAAE,O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AA,IACF;AAAA,IACA,SAAS,MAAM;AACb,iBAAW;AACX,sBAAgB;AAChB,yBAAmB;AACnB,gBAAU,QAAQ;AAAA,IACpB;AAAA,EACF;AACF;","names":["render","createdBlocks"]}
@@ -0,0 +1,280 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+ var _chunk6SOPF5LZcjs = require('./chunk-6SOPF5LZ.cjs');
10
+
11
+ // src/loader.ts
12
+ function resolveModuleUrl(url) {
13
+ const manifest = globalThis.__FICT_MANIFEST__;
14
+ if (manifest) {
15
+ const resolved = manifest[url];
16
+ if (resolved) {
17
+ return resolved;
18
+ }
19
+ }
20
+ return url;
21
+ }
22
+ var hydratedScopes = /* @__PURE__ */ new Set();
23
+ var prefetchedUrls = /* @__PURE__ */ new Set();
24
+ var prefetchCleanup = null;
25
+ var eventListenerCleanup = null;
26
+ function resetHydratedScopes() {
27
+ hydratedScopes.clear();
28
+ }
29
+ function resetPrefetchedUrls() {
30
+ prefetchedUrls.clear();
31
+ }
32
+ var pendingHandlers = /* @__PURE__ */ new Set();
33
+ async function waitForPendingHandlers() {
34
+ if (pendingHandlers.size === 0) return;
35
+ await Promise.allSettled([...pendingHandlers]);
36
+ }
37
+ function cleanupEventListeners() {
38
+ if (eventListenerCleanup) {
39
+ eventListenerCleanup();
40
+ eventListenerCleanup = null;
41
+ }
42
+ }
43
+ function installResumableLoader(options = {}) {
44
+ const doc = _nullishCoalesce(options.document, () => ( window.document));
45
+ const scriptId = _nullishCoalesce(options.snapshotScriptId, () => ( "__FICT_SNAPSHOT__"));
46
+ hydratedScopes.clear();
47
+ prefetchedUrls.clear();
48
+ if (eventListenerCleanup) {
49
+ eventListenerCleanup();
50
+ eventListenerCleanup = null;
51
+ }
52
+ if (prefetchCleanup) {
53
+ prefetchCleanup();
54
+ prefetchCleanup = null;
55
+ }
56
+ const snapshotEl = doc.getElementById(scriptId);
57
+ if (_optionalChain([snapshotEl, 'optionalAccess', _ => _.textContent])) {
58
+ try {
59
+ const state = JSON.parse(snapshotEl.textContent);
60
+ _chunk6SOPF5LZcjs.__fictSetSSRState.call(void 0, state);
61
+ } catch (e) {
62
+ }
63
+ }
64
+ _chunk6SOPF5LZcjs.__fictEnableResumable.call(void 0, );
65
+ const events = _nullishCoalesce(options.events, () => ( Array.from(_chunk6SOPF5LZcjs.DelegatedEvents)));
66
+ for (const eventName of events) {
67
+ doc.addEventListener(eventName, handleResumableEvent, true);
68
+ }
69
+ eventListenerCleanup = () => {
70
+ for (const eventName of events) {
71
+ doc.removeEventListener(eventName, handleResumableEvent, true);
72
+ }
73
+ };
74
+ if (options.prefetch !== false) {
75
+ prefetchCleanup = setupPrefetch(doc, _nullishCoalesce(options.prefetch, () => ( {})));
76
+ }
77
+ }
78
+ function setupPrefetch(doc, strategy) {
79
+ const cleanupFns = [];
80
+ if (strategy.visibility !== false) {
81
+ const cleanup = setupVisibilityPrefetch(doc, _nullishCoalesce(strategy.visibilityMargin, () => ( "200px")));
82
+ cleanupFns.push(cleanup);
83
+ }
84
+ if (strategy.hover !== false) {
85
+ const cleanup = setupHoverPrefetch(doc, _nullishCoalesce(strategy.hoverDelay, () => ( 50)));
86
+ cleanupFns.push(cleanup);
87
+ }
88
+ return () => {
89
+ for (const cleanup of cleanupFns) {
90
+ cleanup();
91
+ }
92
+ };
93
+ }
94
+ function setupVisibilityPrefetch(doc, rootMargin) {
95
+ if (typeof IntersectionObserver === "undefined") {
96
+ return () => {
97
+ };
98
+ }
99
+ const observer = new IntersectionObserver(
100
+ (entries) => {
101
+ for (const entry of entries) {
102
+ if (entry.isIntersecting) {
103
+ const el = entry.target;
104
+ prefetchElementQrls(el);
105
+ observer.unobserve(el);
106
+ }
107
+ }
108
+ },
109
+ { rootMargin }
110
+ );
111
+ const interactiveElements = doc.querySelectorAll(
112
+ "[on\\:click], [on\\:input], [on\\:change], [on\\:submit], [on\\:keydown], [on\\:keyup]"
113
+ );
114
+ interactiveElements.forEach((el) => observer.observe(el));
115
+ const resumableHosts = doc.querySelectorAll("[data-fict-h]");
116
+ resumableHosts.forEach((el) => observer.observe(el));
117
+ return () => {
118
+ observer.disconnect();
119
+ };
120
+ }
121
+ function setupHoverPrefetch(doc, delay) {
122
+ let hoverTimeout = null;
123
+ let lastHoveredElement = null;
124
+ const handlePointerOver = (event) => {
125
+ const target = event.target;
126
+ if (!(target instanceof Element)) return;
127
+ const interactiveEl = target.closest("[on\\:click]") || target.closest("[on\\:input]") || target.closest("[on\\:change]") || target.closest("[on\\:submit]") || target.closest("[data-fict-h]");
128
+ if (!interactiveEl || interactiveEl === lastHoveredElement) return;
129
+ lastHoveredElement = interactiveEl;
130
+ if (hoverTimeout) {
131
+ clearTimeout(hoverTimeout);
132
+ }
133
+ hoverTimeout = setTimeout(() => {
134
+ prefetchElementQrls(interactiveEl);
135
+ }, delay);
136
+ };
137
+ const handlePointerOut = () => {
138
+ if (hoverTimeout) {
139
+ clearTimeout(hoverTimeout);
140
+ hoverTimeout = null;
141
+ }
142
+ lastHoveredElement = null;
143
+ };
144
+ doc.addEventListener("pointerover", handlePointerOver, { passive: true });
145
+ doc.addEventListener("pointerout", handlePointerOut, { passive: true });
146
+ return () => {
147
+ doc.removeEventListener("pointerover", handlePointerOver);
148
+ doc.removeEventListener("pointerout", handlePointerOut);
149
+ if (hoverTimeout) {
150
+ clearTimeout(hoverTimeout);
151
+ }
152
+ };
153
+ }
154
+ function prefetchElementQrls(el) {
155
+ const eventAttrs = ["on:click", "on:input", "on:change", "on:submit", "on:keydown", "on:keyup"];
156
+ for (const attr of eventAttrs) {
157
+ const qrl = el.getAttribute(attr);
158
+ if (qrl) {
159
+ prefetchQrl(qrl);
160
+ }
161
+ }
162
+ const resumeQrl = el.getAttribute("data-fict-h");
163
+ if (resumeQrl) {
164
+ prefetchQrl(resumeQrl);
165
+ }
166
+ const children = el.querySelectorAll(
167
+ "[on\\:click], [on\\:input], [on\\:change], [on\\:submit], [data-fict-h]"
168
+ );
169
+ children.forEach((child) => {
170
+ for (const attr of eventAttrs) {
171
+ const qrl = child.getAttribute(attr);
172
+ if (qrl) {
173
+ prefetchQrl(qrl);
174
+ }
175
+ }
176
+ const childResumeQrl = child.getAttribute("data-fict-h");
177
+ if (childResumeQrl) {
178
+ prefetchQrl(childResumeQrl);
179
+ }
180
+ });
181
+ }
182
+ function prefetchQrl(qrl) {
183
+ const { url } = parseQrl(qrl);
184
+ if (!url || prefetchedUrls.has(url)) return;
185
+ prefetchedUrls.add(url);
186
+ const resolvedUrl = resolveModuleUrl(url);
187
+ if (typeof document !== "undefined") {
188
+ const link = document.createElement("link");
189
+ link.rel = "modulepreload";
190
+ link.href = resolvedUrl;
191
+ link.crossOrigin = "anonymous";
192
+ document.head.appendChild(link);
193
+ }
194
+ }
195
+ function handleResumableEvent(event) {
196
+ const promise = handleResumableEventAsync(event);
197
+ pendingHandlers.add(promise);
198
+ promise.finally(() => {
199
+ pendingHandlers.delete(promise);
200
+ });
201
+ }
202
+ async function handleResumableEventAsync(event) {
203
+ const path = typeof event.composedPath === "function" ? event.composedPath() : buildEventPath(event);
204
+ for (const node of path) {
205
+ if (!(node instanceof Element)) continue;
206
+ const qrl = node.getAttribute(`on:${event.type}`);
207
+ if (!qrl) continue;
208
+ const host = node.closest("[data-fict-s]");
209
+ if (!host) continue;
210
+ const scopeId = host.getAttribute("data-fict-s");
211
+ if (!scopeId) continue;
212
+ const snapshot = _chunk6SOPF5LZcjs.__fictGetSSRScope.call(void 0, scopeId);
213
+ if (snapshot) {
214
+ _chunk6SOPF5LZcjs.__fictEnsureScope.call(void 0, scopeId, host, snapshot);
215
+ }
216
+ const { url, exportName } = parseQrl(qrl);
217
+ if (event.cancelable && (event.type === "click" || event.type === "submit")) {
218
+ const tag = node.tagName.toLowerCase();
219
+ if (tag === "a" || tag === "form") {
220
+ event.preventDefault();
221
+ }
222
+ }
223
+ if (!hydratedScopes.has(scopeId)) {
224
+ const resumeQrl = host.getAttribute("data-fict-h");
225
+ if (resumeQrl) {
226
+ const { url: resumeUrl, exportName: resumeExport } = parseQrl(resumeQrl);
227
+ const resolvedResumeUrl = resolveModuleUrl(resumeUrl);
228
+ await Promise.resolve().then(() => _interopRequireWildcard(require(
229
+ /* @vite-ignore */
230
+ resolvedResumeUrl
231
+ )));
232
+ const resumeFn = _chunk6SOPF5LZcjs.__fictGetResume.call(void 0, resumeExport);
233
+ if (typeof resumeFn === "function") {
234
+ await resumeFn(scopeId, host);
235
+ hydratedScopes.add(scopeId);
236
+ }
237
+ }
238
+ }
239
+ const resolvedUrl = resolveModuleUrl(url);
240
+ const mod = await Promise.resolve().then(() => _interopRequireWildcard(require(
241
+ /* @vite-ignore */
242
+ resolvedUrl
243
+ )));
244
+ const handler = mod[exportName];
245
+ if (typeof handler === "function") {
246
+ await handler(scopeId, event, node);
247
+ }
248
+ return;
249
+ }
250
+ }
251
+ function parseQrl(qrl) {
252
+ const [ref] = qrl.split("[");
253
+ if (!ref) {
254
+ return { url: "", exportName: "default" };
255
+ }
256
+ const hashIndex = ref.lastIndexOf("#");
257
+ if (hashIndex === -1) {
258
+ return { url: ref, exportName: "default" };
259
+ }
260
+ return { url: ref.slice(0, hashIndex), exportName: ref.slice(hashIndex + 1) };
261
+ }
262
+ function buildEventPath(event) {
263
+ const path = [];
264
+ let node = event.target;
265
+ while (node) {
266
+ path.push(node);
267
+ node = node.parentNode;
268
+ }
269
+ path.push(window);
270
+ return path;
271
+ }
272
+
273
+
274
+
275
+
276
+
277
+
278
+
279
+ exports.__fictUseLexicalScope = _chunk6SOPF5LZcjs.__fictUseLexicalScope; exports.cleanupEventListeners = cleanupEventListeners; exports.installResumableLoader = installResumableLoader; exports.resetHydratedScopes = resetHydratedScopes; exports.resetPrefetchedUrls = resetPrefetchedUrls; exports.waitForPendingHandlers = waitForPendingHandlers;
280
+ //# sourceMappingURL=loader.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/fict/fict/packages/runtime/dist/loader.cjs","../src/loader.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACSA,SAAS,gBAAA,CAAiB,GAAA,EAAqB;AAC7C,EAAA,MAAM,SAAA,EAAY,UAAA,CAAuC,iBAAA;AAIzD,EAAA,GAAA,CAAI,QAAA,EAAU;AAEZ,IAAA,MAAM,SAAA,EAAW,QAAA,CAAS,GAAG,CAAA;AAC7B,IAAA,GAAA,CAAI,QAAA,EAAU;AACZ,MAAA,OAAO,QAAA;AAAA,IACT;AAAA,EACF;AAEA,EAAA,OAAO,GAAA;AACT;AA+CA,IAAM,eAAA,kBAAiB,IAAI,GAAA,CAAY,CAAA;AACvC,IAAM,eAAA,kBAAiB,IAAI,GAAA,CAAY,CAAA;AACvC,IAAI,gBAAA,EAAuC,IAAA;AAC3C,IAAI,qBAAA,EAA4C,IAAA;AAKzC,SAAS,mBAAA,CAAA,EAA4B;AAC1C,EAAA,cAAA,CAAe,KAAA,CAAM,CAAA;AACvB;AAKO,SAAS,mBAAA,CAAA,EAA4B;AAC1C,EAAA,cAAA,CAAe,KAAA,CAAM,CAAA;AACvB;AAKA,IAAM,gBAAA,kBAAkB,IAAI,GAAA,CAAmB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QAAA;AAChC,IAAA,MAAM,IAAA,EAAM,IAAA,CAAK,YAAA,CAAa,CAAA,GAAA,EAAM,KAAA,CAAM,IAAI,CAAA,CAAA;AACpC,IAAA;AAE+B,IAAA;AAC9B,IAAA;AACoC,IAAA;AACjC,IAAA;AAE4B,IAAA;AAC5B,IAAA;AAC6B,MAAA;AAC3C,IAAA;AAEwC,IAAA;AAGA,IAAA;AACD,MAAA;AACF,MAAA;AACZ,QAAA;AACvB,MAAA;AACF,IAAA;AAGkC,IAAA;AACI,MAAA;AACrB,MAAA;AACuB,QAAA;AACO,QAAA;AAErC,QAAA;AAAA;AAA0B,UAAA;AAAA,QAAA;AAEC,QAAA;AACG,QAAA;AAC2C,UAAA;AACnD,UAAA;AAC5B,QAAA;AACF,MAAA;AACF,IAAA;AAGwC,IAAA;AACtB,IAAA;AAAA;AAA0B,MAAA;AAAA,IAAA;AACe,IAAA;AACxB,IAAA;AAC2D,MAAA;AAC9F,IAAA;AAEA,IAAA;AACF,EAAA;AACF;AAEoE;AACvC,EAAA;AACjB,EAAA;AACgC,IAAA;AAC1C,EAAA;AACqC,EAAA;AACf,EAAA;AACqB,IAAA;AAC3C,EAAA;AACuC,EAAA;AACzC;AAEqD;AACtB,EAAA;AACQ,EAAA;AACxB,EAAA;AACG,IAAA;AACQ,IAAA;AACxB,EAAA;AACgB,EAAA;AACT,EAAA;AACT;ADlKmD;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/fict/fict/packages/runtime/dist/loader.cjs","sourcesContent":[null,"import { DelegatedEvents } from './constants'\nimport {\n __fictEnableResumable,\n __fictEnsureScope,\n __fictGetResume,\n __fictGetSSRScope,\n __fictSetSSRState,\n __fictUseLexicalScope,\n} from './resume'\n\n// ============================================================================\n// Module Resolution\n// ============================================================================\n\n/**\n * Resolve a module URL through the manifest if available.\n * In production, virtual module URLs (virtual:fict-handler:...) are mapped\n * to their built chunk URLs through the manifest.\n */\nfunction resolveModuleUrl(url: string): string {\n const manifest = (globalThis as Record<string, unknown>).__FICT_MANIFEST__ as\n | Record<string, string>\n | undefined\n\n if (manifest) {\n // Check if the URL (without #fragment) is in the manifest\n const resolved = manifest[url]\n if (resolved) {\n return resolved\n }\n }\n\n return url\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface PrefetchStrategy {\n /**\n * Enable visibility-based prefetch using IntersectionObserver.\n * Prefetches modules when interactive elements come into view.\n * @default true\n */\n visibility?: boolean\n /**\n * Root margin for IntersectionObserver (e.g., '200px' to prefetch earlier).\n * @default '200px'\n */\n visibilityMargin?: string\n /**\n * Enable hover-based prefetch using pointerover events.\n * Prefetches modules when user hovers over interactive elements.\n * @default true\n */\n hover?: boolean\n /**\n * Delay in ms before prefetching on hover (debounce rapid movements).\n * @default 50\n */\n hoverDelay?: number\n}\n\nexport interface ResumableLoaderOptions {\n document?: Document\n snapshotScriptId?: string\n events?: string[]\n /**\n * Prefetch strategy configuration.\n * Set to false to disable all prefetching.\n * @default { visibility: true, hover: true }\n */\n prefetch?: PrefetchStrategy | false\n}\n\n// ============================================================================\n// State\n// ============================================================================\n\nconst hydratedScopes = new Set<string>()\nconst prefetchedUrls = new Set<string>()\nlet prefetchCleanup: (() => void) | null = null\nlet eventListenerCleanup: (() => void) | null = null\n\n/**\n * Reset the hydrated scopes set. Useful for testing.\n */\nexport function resetHydratedScopes(): void {\n hydratedScopes.clear()\n}\n\n/**\n * Reset the prefetched URLs set. Useful for testing.\n */\nexport function resetPrefetchedUrls(): void {\n prefetchedUrls.clear()\n}\n\n/**\n * Set of pending handler promises. Used for testing to wait for all handlers to complete.\n */\nconst pendingHandlers = new Set<Promise<void>>()\n\n/**\n * Wait for all pending event handlers to complete. Useful for testing.\n */\nexport async function waitForPendingHandlers(): Promise<void> {\n if (pendingHandlers.size === 0) return\n await Promise.allSettled([...pendingHandlers])\n}\n\n/**\n * Clean up all registered event listeners. Useful for testing.\n */\nexport function cleanupEventListeners(): void {\n if (eventListenerCleanup) {\n eventListenerCleanup()\n eventListenerCleanup = null\n }\n}\n\n// ============================================================================\n// Main Entry Point\n// ============================================================================\n\nexport function installResumableLoader(options: ResumableLoaderOptions = {}): void {\n const doc = options.document ?? window.document\n const scriptId = options.snapshotScriptId ?? '__FICT_SNAPSHOT__'\n\n // Reset hydrated scopes for fresh loader installation\n hydratedScopes.clear()\n prefetchedUrls.clear()\n\n // Clean up previous event listeners\n if (eventListenerCleanup) {\n eventListenerCleanup()\n eventListenerCleanup = null\n }\n\n // Clean up previous prefetch handlers\n if (prefetchCleanup) {\n prefetchCleanup()\n prefetchCleanup = null\n }\n\n const snapshotEl = doc.getElementById(scriptId)\n if (snapshotEl?.textContent) {\n try {\n const state = JSON.parse(snapshotEl.textContent)\n __fictSetSSRState(state)\n } catch {\n // Ignore parse errors\n }\n }\n\n __fictEnableResumable()\n\n const events = options.events ?? Array.from(DelegatedEvents)\n for (const eventName of events) {\n doc.addEventListener(eventName, handleResumableEvent, true)\n }\n\n // Store cleanup function for event listeners\n eventListenerCleanup = () => {\n for (const eventName of events) {\n doc.removeEventListener(eventName, handleResumableEvent, true)\n }\n }\n\n // Setup prefetch if enabled\n if (options.prefetch !== false) {\n prefetchCleanup = setupPrefetch(doc, options.prefetch ?? {})\n }\n}\n\n// ============================================================================\n// Prefetch Implementation\n// ============================================================================\n\nfunction setupPrefetch(doc: Document, strategy: PrefetchStrategy): () => void {\n const cleanupFns: (() => void)[] = []\n\n // Visibility-based prefetch\n if (strategy.visibility !== false) {\n const cleanup = setupVisibilityPrefetch(doc, strategy.visibilityMargin ?? '200px')\n cleanupFns.push(cleanup)\n }\n\n // Hover-based prefetch\n if (strategy.hover !== false) {\n const cleanup = setupHoverPrefetch(doc, strategy.hoverDelay ?? 50)\n cleanupFns.push(cleanup)\n }\n\n return () => {\n for (const cleanup of cleanupFns) {\n cleanup()\n }\n }\n}\n\nfunction setupVisibilityPrefetch(doc: Document, rootMargin: string): () => void {\n // Check if IntersectionObserver is available\n if (typeof IntersectionObserver === 'undefined') {\n return () => {}\n }\n\n const observer = new IntersectionObserver(\n entries => {\n for (const entry of entries) {\n if (entry.isIntersecting) {\n const el = entry.target as Element\n prefetchElementQrls(el)\n // Stop observing after prefetch\n observer.unobserve(el)\n }\n }\n },\n { rootMargin },\n )\n\n // Observe all elements with on:* attributes\n const interactiveElements = doc.querySelectorAll(\n '[on\\\\:click], [on\\\\:input], [on\\\\:change], [on\\\\:submit], [on\\\\:keydown], [on\\\\:keyup]',\n )\n interactiveElements.forEach(el => observer.observe(el))\n\n // Also observe elements with data-fict-h (resumable components)\n const resumableHosts = doc.querySelectorAll('[data-fict-h]')\n resumableHosts.forEach(el => observer.observe(el))\n\n return () => {\n observer.disconnect()\n }\n}\n\nfunction setupHoverPrefetch(doc: Document, delay: number): () => void {\n let hoverTimeout: ReturnType<typeof setTimeout> | null = null\n let lastHoveredElement: Element | null = null\n\n const handlePointerOver = (event: Event) => {\n const target = event.target\n if (!(target instanceof Element)) return\n\n // Find the closest element with interactive attributes\n const interactiveEl =\n target.closest('[on\\\\:click]') ||\n target.closest('[on\\\\:input]') ||\n target.closest('[on\\\\:change]') ||\n target.closest('[on\\\\:submit]') ||\n target.closest('[data-fict-h]')\n\n if (!interactiveEl || interactiveEl === lastHoveredElement) return\n\n lastHoveredElement = interactiveEl\n\n // Clear previous timeout\n if (hoverTimeout) {\n clearTimeout(hoverTimeout)\n }\n\n // Debounce prefetch\n hoverTimeout = setTimeout(() => {\n prefetchElementQrls(interactiveEl)\n }, delay)\n }\n\n const handlePointerOut = () => {\n if (hoverTimeout) {\n clearTimeout(hoverTimeout)\n hoverTimeout = null\n }\n lastHoveredElement = null\n }\n\n doc.addEventListener('pointerover', handlePointerOver, { passive: true })\n doc.addEventListener('pointerout', handlePointerOut, { passive: true })\n\n return () => {\n doc.removeEventListener('pointerover', handlePointerOver)\n doc.removeEventListener('pointerout', handlePointerOut)\n if (hoverTimeout) {\n clearTimeout(hoverTimeout)\n }\n }\n}\n\nfunction prefetchElementQrls(el: Element): void {\n // Prefetch event handler QRLs\n const eventAttrs = ['on:click', 'on:input', 'on:change', 'on:submit', 'on:keydown', 'on:keyup']\n for (const attr of eventAttrs) {\n const qrl = el.getAttribute(attr)\n if (qrl) {\n prefetchQrl(qrl)\n }\n }\n\n // Prefetch resume handler QRL\n const resumeQrl = el.getAttribute('data-fict-h')\n if (resumeQrl) {\n prefetchQrl(resumeQrl)\n }\n\n // Also check children for nested QRLs\n const children = el.querySelectorAll(\n '[on\\\\:click], [on\\\\:input], [on\\\\:change], [on\\\\:submit], [data-fict-h]',\n )\n children.forEach(child => {\n for (const attr of eventAttrs) {\n const qrl = child.getAttribute(attr)\n if (qrl) {\n prefetchQrl(qrl)\n }\n }\n const childResumeQrl = child.getAttribute('data-fict-h')\n if (childResumeQrl) {\n prefetchQrl(childResumeQrl)\n }\n })\n}\n\nfunction prefetchQrl(qrl: string): void {\n const { url } = parseQrl(qrl)\n if (!url || prefetchedUrls.has(url)) return\n\n prefetchedUrls.add(url)\n\n // Resolve through manifest for production builds\n const resolvedUrl = resolveModuleUrl(url)\n\n // Use modulepreload link for best browser support\n if (typeof document !== 'undefined') {\n const link = document.createElement('link')\n link.rel = 'modulepreload'\n link.href = resolvedUrl\n link.crossOrigin = 'anonymous'\n document.head.appendChild(link)\n }\n}\n\n// ============================================================================\n\n/**\n * Wrapper that tracks the async handler promise for testing.\n */\nfunction handleResumableEvent(event: Event): void {\n const promise = handleResumableEventAsync(event)\n pendingHandlers.add(promise)\n promise.finally(() => {\n pendingHandlers.delete(promise)\n })\n}\n\nasync function handleResumableEventAsync(event: Event): Promise<void> {\n const path =\n typeof event.composedPath === 'function' ? event.composedPath() : buildEventPath(event)\n\n for (const node of path) {\n if (!(node instanceof Element)) continue\n const qrl = node.getAttribute(`on:${event.type}`)\n if (!qrl) continue\n\n const host = node.closest('[data-fict-s]') as Element | null\n if (!host) continue\n const scopeId = host.getAttribute('data-fict-s')\n if (!scopeId) continue\n\n const snapshot = __fictGetSSRScope(scopeId)\n if (snapshot) {\n __fictEnsureScope(scopeId, host, snapshot)\n }\n\n const { url, exportName } = parseQrl(qrl)\n\n // Pre-emptively prevent default on navigations/forms while we await modules\n if (event.cancelable && (event.type === 'click' || event.type === 'submit')) {\n const tag = node.tagName.toLowerCase()\n if (tag === 'a' || tag === 'form') {\n event.preventDefault()\n }\n }\n\n // Resume FIRST to set up reactive bindings BEFORE the handler runs\n if (!hydratedScopes.has(scopeId)) {\n const resumeQrl = host.getAttribute('data-fict-h')\n if (resumeQrl) {\n const { url: resumeUrl, exportName: resumeExport } = parseQrl(resumeQrl)\n const resolvedResumeUrl = resolveModuleUrl(resumeUrl)\n // Load the module to ensure resume functions are registered\n await import(/* @vite-ignore */ resolvedResumeUrl)\n // Get resume function from registry (not module exports)\n const resumeFn = __fictGetResume(resumeExport)\n if (typeof resumeFn === 'function') {\n await (resumeFn as (scopeId: string, host: Element) => unknown)(scopeId, host)\n hydratedScopes.add(scopeId)\n }\n }\n }\n\n // THEN run the handler - now signal updates will trigger DOM updates\n const resolvedUrl = resolveModuleUrl(url)\n const mod = await import(/* @vite-ignore */ resolvedUrl)\n const handler = (mod as Record<string, unknown>)[exportName]\n if (typeof handler === 'function') {\n await (handler as (scopeId: string, ev: Event, el: Element) => unknown)(scopeId, event, node)\n }\n\n return\n }\n}\n\nfunction parseQrl(qrl: string): { url: string; exportName: string } {\n const [ref] = qrl.split('[')\n if (!ref) {\n return { url: '', exportName: 'default' }\n }\n const hashIndex = ref.lastIndexOf('#')\n if (hashIndex === -1) {\n return { url: ref, exportName: 'default' }\n }\n return { url: ref.slice(0, hashIndex), exportName: ref.slice(hashIndex + 1) }\n}\n\nfunction buildEventPath(event: Event): EventTarget[] {\n const path: EventTarget[] = []\n let node: EventTarget | null = event.target\n while (node) {\n path.push(node)\n node = (node as Node).parentNode\n }\n path.push(window)\n return path\n}\n\n// Re-export for handler authors (optional)\nexport { __fictUseLexicalScope } from './resume'\n"]}