@askrjs/askr 0.0.44 → 0.0.45
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/benchmark.js +2 -2
- package/dist/bin/askr-ssg.js.map +1 -1
- package/dist/boot/index.js.map +1 -1
- package/dist/common/env.js.map +1 -1
- package/dist/common/route-activity.js.map +1 -1
- package/dist/control/case.js.map +1 -1
- package/dist/control/show.js.map +1 -1
- package/dist/data/index.js.map +1 -1
- package/dist/foundations/icon/icon.js.map +1 -1
- package/dist/foundations/structures/layer.js.map +1 -1
- package/dist/foundations/structures/portal.js.map +1 -1
- package/dist/fx/fx.js.map +1 -1
- package/dist/fx/timing.js.map +1 -1
- package/dist/renderer/children.js.map +1 -1
- package/dist/renderer/cleanup.js.map +1 -1
- package/dist/renderer/dom.js.map +1 -1
- package/dist/renderer/evaluate.js.map +1 -1
- package/dist/renderer/fastpath.js.map +1 -1
- package/dist/renderer/for-commit.js.map +1 -1
- package/dist/renderer/keyed.js.map +1 -1
- package/dist/renderer/reconcile.js.map +1 -1
- package/dist/renderer/utils.js.map +1 -1
- package/dist/router/match.js.map +1 -1
- package/dist/router/navigate.js.map +1 -1
- package/dist/router/policy.js.map +1 -1
- package/dist/router/route.js.map +1 -1
- package/dist/runtime/component.d.ts +1 -0
- package/dist/runtime/component.d.ts.map +1 -1
- package/dist/runtime/component.js +16 -8
- package/dist/runtime/component.js.map +1 -1
- package/dist/runtime/context.js.map +1 -1
- package/dist/runtime/derive.js.map +1 -1
- package/dist/runtime/dev-namespace.js.map +1 -1
- package/dist/runtime/effect.js.map +1 -1
- package/dist/runtime/events.js.map +1 -1
- package/dist/runtime/fastlane.js.map +1 -1
- package/dist/runtime/for.js.map +1 -1
- package/dist/runtime/operations.js.map +1 -1
- package/dist/runtime/readable.d.ts +2 -1
- package/dist/runtime/readable.d.ts.map +1 -1
- package/dist/runtime/readable.js +41 -10
- package/dist/runtime/readable.js.map +1 -1
- package/dist/runtime/resource-cell.js.map +1 -1
- package/dist/runtime/scheduler.js.map +1 -1
- package/dist/runtime/selector.js.map +1 -1
- package/dist/ssg/batch-render.js.map +1 -1
- package/dist/ssg/create-static-gen.js.map +1 -1
- package/dist/ssg/generate-metadata.js.map +1 -1
- package/dist/ssg/incremental-manifest.js.map +1 -1
- package/dist/ssg/resolve-ssg-data.js.map +1 -1
- package/dist/ssg/write-static-files.js.map +1 -1
- package/dist/ssr/context.js.map +1 -1
- package/dist/ssr/escape.js.map +1 -1
- package/dist/ssr/index.js.map +1 -1
- package/dist/ssr/render-keys.js.map +1 -1
- package/dist/testing/index.js.map +1 -1
- package/package.json +3 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reconcile.js","names":[],"sources":["../../src/renderer/reconcile.ts"],"sourcesContent":["/**\n * ─────────────────────────────────────────────────────────────────────────────\n * RENDERER & RECONCILIATION INVARIANTS (LOCKED)\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * These invariants are NON-NEGOTIABLE. Any optimization or fast-path MUST\n * preserve them. Violations WILL produce incorrect DOM.\n *\n * 1. DOM ORDER DERIVES ONLY FROM CURRENT VNODE ORDER\n * --------------------------------------------------\n * - Final DOM child order MUST be reconstructed from the current vnode list.\n * - Reusing an existing DOM node does NOT imply it stays in the same position.\n * - Appending an existing Node to a DocumentFragment is the ONLY valid way\n * to express reordering (it moves the node).\n *\n * ❌ NEVER skip fragment insertion because a node already has a parent.\n * ✅ ALWAYS append reused nodes into the fragment to establish order.\n *\n *\n * 2. VNODE IDENTITY ≠ VNODE STABILITY\n * ----------------------------------\n * - VNodes are mutable.\n * - `vnodeA === vnodeB` does NOT imply semantic equality.\n * - DOM reuse MUST NOT be gated on vnode identity alone.\n *\n * DOM reuse is allowed ONLY when:\n * - element type is unchanged\n * - structural shape is compatible\n * - updates are applied explicitly via updateElementFromVnode\n *\n * ❌ NEVER assume \"same object\" means \"no changes\".\n *\n *\n * 3. KEYED RECONCILIATION IS ELEMENT-ONLY\n * --------------------------------------\n * - Keyed reconciliation assumes ELEMENT nodes, not Text or Comment nodes.\n * - Any fast-path using `parent.children[i]` MUST prove:\n * - all children are elements\n * - no text nodes are present\n *\n * ❌ NEVER index `parent.children` when text nodes may exist.\n * ✅ Use `parent.childNodes` or bail out to full reconciliation.\n *\n *\n * 4. PRIMITIVES MAP TO TEXT NODES\n * -------------------------------\n * - string/number children represent Text nodes, not Elements.\n * - Reconciliation MUST attempt Text-to-Text reuse before replacement.\n *\n * ❌ NEVER update element.textContent as a substitute for text reconciliation\n * unless the shape is explicitly guaranteed.\n *\n *\n * 5. FAST-PATHS MUST BE STRICTLY SAFE\n * ----------------------------------\n * - Fast-paths are OPTIONAL.\n * - Correctness always beats performance.\n *\n * A fast-path MUST:\n * - prove its eligibility\n * - fall back cleanly on ANY ambiguity\n * - never partially apply\n *\n *\n * 6. CLEANUP IS POSITION-INDEPENDENT\n * ---------------------------------\n * - Cleanup is based on removal from the DOM, not vnode position.\n * - Any node removed or replaced MUST:\n * - remove listeners\n * - cleanup component instances\n *\n *\n * 7. FOR-BOUNDARY & KEYED LISTS OBEY THE SAME RULES\n * ------------------------------------------------\n * - For-boundaries are NOT special in ordering semantics.\n * - Cached DOM nodes MUST still be reordered via fragment insertion.\n * - Cache is an optimization, not an ownership claim.\n *\n *\n * If you are unsure whether an optimization preserves these invariants:\n * DO NOT APPLY IT.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n */\n\nimport type { DOMElement, VNode } from './types';\nimport {\n createDOMNode,\n syncComponentElement,\n updateElementFromVnode,\n performBulkPositionalKeyedTextUpdate,\n} from './dom';\nimport type { Props } from '../common/props';\nimport {\n keyedElements,\n _reconcilerRecordedParents,\n planKeyedReorderFastPath,\n} from './keyed';\nimport { teardownNodeSubtree } from './cleanup';\nimport { applyRendererFastPath } from './fastpath';\nimport { getRuntimeEnv } from './env';\nimport type { ComponentFunction } from '../runtime/component';\nimport {\n evaluateCaseState,\n evaluateShowState,\n type ControlBoundaryState,\n} from '../runtime/control';\nimport { evaluateForState } from '../runtime/for';\nimport { __FOR_BOUNDARY__ } from '../common/vnode';\nimport {\n extractKey,\n checkPropChanges,\n recordFastPathStats,\n recordDOMReplace,\n tagNamesEqualIgnoreCase,\n} from './utils';\n\nexport const IS_DOM_AVAILABLE = typeof document !== 'undefined';\n\n// Helper type for narrowings\ntype VnodeObj = VNode & { type?: unknown; props?: Record<string, unknown> };\ntype ComponentVNode = DOMElement & { type: ComponentFunction };\n\nexport function reconcileKeyedChildren(\n parent: Element,\n newChildren: VNode[],\n oldKeyMap: Map<string | number, Element> | undefined\n): Map<string | number, Element> {\n const keyedVnodes = extractKeyedChildren(newChildren);\n\n // Ensure we have a key map before reconciliation to avoid O(n) DOM scans\n // during O(n) reconciliation loop (which would be O(n²))\n const ensuredOldKeyMap = oldKeyMap || buildKeyMapFromDOM(parent);\n\n // Try fast paths first\n const fastPathResult = tryFastPaths(\n parent,\n newChildren,\n keyedVnodes,\n ensuredOldKeyMap\n );\n if (fastPathResult) {\n return fastPathResult;\n }\n\n // Full reconciliation\n return performFullReconciliation(\n parent,\n newChildren,\n keyedVnodes,\n ensuredOldKeyMap\n );\n}\n\n/** Build key map from DOM children */\nfunction buildKeyMapFromDOM(parent: Element): Map<string | number, Element> {\n const keyMap = new Map<string | number, Element>();\n try {\n for (let el = parent.firstElementChild; el; el = el.nextElementSibling) {\n const k = el.getAttribute('data-key');\n if (k !== null) {\n keyMap.set(k, el);\n const n = Number(k);\n if (!Number.isNaN(n)) keyMap.set(n, el);\n }\n }\n } catch {\n // Ignore\n }\n return keyMap;\n}\n\n/** Extract keyed children in a single pass. */\nfunction extractKeyedChildren(\n newChildren: VNode[]\n): Array<{ key: string | number; vnode: VNode }> {\n const keyedVnodes: Array<{ key: string | number; vnode: VNode }> = [];\n\n for (let i = 0; i < newChildren.length; i++) {\n const child = newChildren[i];\n const key = extractKey(child);\n if (key !== undefined) {\n keyedVnodes.push({ key, vnode: child });\n }\n }\n\n return keyedVnodes;\n}\n\n/** Try fast paths before full reconciliation */\nfunction tryFastPaths(\n parent: Element,\n newChildren: VNode[],\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>,\n oldKeyMap: Map<string | number, Element> | undefined\n): Map<string | number, Element> | null {\n try {\n const forcedResult = tryForcedPositionalBulkUpdate(\n parent,\n newChildren,\n keyedVnodes\n );\n if (forcedResult) {\n return forcedResult;\n }\n\n // Try renderer fast-path for large keyed reorder-only updates\n const rendererResult = tryRendererFastPath(\n parent,\n keyedVnodes,\n newChildren.length,\n oldKeyMap\n );\n if (rendererResult) {\n return rendererResult;\n }\n\n // Try positional bulk update for medium-sized lists\n const positionalResult = tryPositionalBulkUpdate(parent, keyedVnodes);\n if (positionalResult) {\n return positionalResult;\n }\n } catch {\n // Fall through to full reconciliation\n }\n\n return null;\n}\n\n/** Try renderer fast-path */\nfunction tryRendererFastPath(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>,\n totalChildren: number,\n oldKeyMap: Map<string | number, Element> | undefined\n): Map<string | number, Element> | null {\n const decision = planKeyedReorderFastPath(\n parent,\n keyedVnodes,\n totalChildren,\n oldKeyMap\n );\n\n if (decision.useFastPath) {\n try {\n const map = applyRendererFastPath(parent, keyedVnodes, oldKeyMap);\n if (map) {\n keyedElements.set(parent, map);\n return map;\n }\n } catch {\n // Fall through\n }\n }\n\n return null;\n}\n\n/** Try the explicit test/bench forced positional keyed path. */\nfunction tryForcedPositionalBulkUpdate(\n parent: Element,\n newChildren: VNode[],\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n): Map<string | number, Element> | null {\n if (getRuntimeEnv().ASKR_FORCE_BULK_POSREUSE !== '1') return null;\n if (keyedVnodes.length === 0 || keyedVnodes.length !== newChildren.length) {\n return null;\n }\n\n try {\n const stats = performBulkPositionalKeyedTextUpdate(parent, keyedVnodes);\n recordFastPathStats(stats, 'bulkKeyedPositionalForced');\n\n rebuildKeyedMap(parent);\n return keyedElements.get(parent) as Map<string | number, Element>;\n } catch {\n return null;\n }\n}\n\n/** Try positional bulk update for medium-sized lists */\nfunction tryPositionalBulkUpdate(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n): Map<string | number, Element> | null {\n const total = keyedVnodes.length;\n if (total < 10) return null;\n\n // CRITICAL INVARIANT: Only use children[] indexing if element-only is guaranteed\n // If parent has text nodes or comment nodes, bail to full reconciliation\n if (parent.children.length !== total) {\n return null;\n }\n\n const matchCount = countPositionalMatches(parent, keyedVnodes);\n\n // For keyed lists, the positional bulk update path makes sense in two cases:\n // 1. Perfect match (100%): All keys are in the right positions, just update text\n // 2. Very low match (<10%): Keys changed en-masse, treat as bulk re-key, reuse nodes by position\n // ANY mismatch at all means we have a reorder and need full reconciliation\n // to preserve DOM node identity correctly.\n const matchFraction = matchCount / total;\n\n if (keyedVnodes.length > 0) {\n // For keyed lists: require perfect match or very low match\n // matchCount !== total catches ANY reordering, even just 2 swapped elements\n if (matchCount !== total && matchFraction >= 0.1) {\n return null;\n }\n } else {\n // For unkeyed lists: use original threshold\n if (matchFraction < 0.9) {\n return null;\n }\n }\n\n // Check for prop changes that would prevent positional update\n if (hasPositionalPropChanges(parent, keyedVnodes)) {\n return null;\n }\n\n // Perform positional update\n try {\n const stats = performBulkPositionalKeyedTextUpdate(parent, keyedVnodes);\n recordFastPathStats(stats, 'bulkKeyedPositionalHits');\n\n rebuildKeyedMap(parent);\n return keyedElements.get(parent) as Map<string | number, Element>;\n } catch {\n return null;\n }\n}\n\n/** Count how many vnodes match parent children by position and tag */\nfunction countPositionalMatches(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n): number {\n let matchCount = 0;\n\n try {\n // For keyed children, use children (elements only) since keyed nodes are elements\n for (let i = 0; i < keyedVnodes.length; i++) {\n const vnode = keyedVnodes[i].vnode as VnodeObj;\n const expectedKey = keyedVnodes[i].key;\n\n if (!vnode || typeof vnode !== 'object' || typeof vnode.type !== 'string')\n continue;\n\n const el = parent.children[i] as Element | undefined;\n if (!el) continue;\n\n // For keyed lists, check BOTH tag name AND key match\n if (tagNamesEqualIgnoreCase(el.tagName, vnode.type)) {\n // Check if the element at this position has the expected key\n const actualKey = el.getAttribute('data-key');\n const keyMatches =\n actualKey === String(expectedKey) ||\n (actualKey !== null &&\n !Number.isNaN(Number(actualKey)) &&\n Number(actualKey) === expectedKey);\n\n if (keyMatches) {\n matchCount++;\n }\n }\n }\n } catch {\n // Ignore\n }\n\n return matchCount;\n}\n\n/** Check if positional prop changes would prevent bulk update */\nfunction hasPositionalPropChanges(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n): boolean {\n try {\n // For keyed children, use children (elements only) since keyed nodes are elements\n for (let i = 0; i < keyedVnodes.length; i++) {\n const vnode = keyedVnodes[i].vnode as VnodeObj;\n const el = parent.children[i] as Element | undefined;\n if (!el || !vnode || typeof vnode !== 'object') continue;\n\n if (checkPropChanges(el, vnode.props || {})) {\n return true;\n }\n }\n } catch {\n return true;\n }\n\n return false;\n}\n\n/** Rebuild keyed map from parent children */\nfunction rebuildKeyedMap(parent: Element): void {\n try {\n const map = new Map<string | number, Element>();\n for (let el = parent.firstElementChild; el; el = el.nextElementSibling) {\n const k = el.getAttribute('data-key');\n if (k !== null) {\n map.set(k, el);\n const n = Number(k);\n if (!Number.isNaN(n)) map.set(n, el);\n }\n }\n keyedElements.set(parent, map);\n } catch {\n // Ignore\n }\n}\n\n/** Perform full reconciliation when fast paths don't apply */\nfunction performFullReconciliation(\n parent: Element,\n newChildren: VNode[],\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>,\n oldKeyMap: Map<string | number, Element> | undefined\n): Map<string | number, Element> {\n const newKeyMap = new Map<string | number, Element>();\n const finalNodes: Node[] = [];\n const usedOldEls = new WeakSet<Node>();\n\n const resolveOldElOnce = createOldElResolver(parent, oldKeyMap, usedOldEls);\n const unkeyedEls = collectUnkeyedElements(parent);\n let unkeyedIndex = 0;\n const resolveUnkeyedOnce = (): Element | undefined => {\n while (unkeyedIndex < unkeyedEls.length) {\n const candidate = unkeyedEls[unkeyedIndex++];\n if (!usedOldEls.has(candidate)) return candidate;\n }\n return undefined;\n };\n\n // Positional reconciliation\n for (let i = 0; i < newChildren.length; i++) {\n const child = newChildren[i];\n const node = reconcileSingleChild(\n child,\n i,\n parent,\n resolveOldElOnce,\n resolveUnkeyedOnce,\n usedOldEls,\n newKeyMap\n );\n if (node) finalNodes.push(node);\n }\n\n // SSR guard\n if (typeof document === 'undefined') return newKeyMap;\n\n commitReconciliation(parent, finalNodes);\n keyedElements.delete(parent);\n\n return newKeyMap;\n}\n\n/** Create resolver for finding old elements by key */\nfunction createOldElResolver(\n parent: Element,\n oldKeyMap: Map<string | number, Element> | undefined,\n usedOldEls: WeakSet<Node>\n): (k: string | number) => Element | undefined {\n return (k: string | number) => {\n if (!oldKeyMap) return undefined;\n\n // Fast-path: directly from oldKeyMap\n const direct = oldKeyMap.get(k);\n if (direct && !usedOldEls.has(direct)) {\n usedOldEls.add(direct);\n return direct;\n }\n\n // Try string form\n const s = String(k);\n const byString = oldKeyMap.get(s);\n if (byString && !usedOldEls.has(byString)) {\n usedOldEls.add(byString);\n return byString;\n }\n\n // Try numeric form\n const n = Number(s);\n if (!Number.isNaN(n)) {\n const byNum = oldKeyMap.get(n);\n if (byNum && !usedOldEls.has(byNum)) {\n usedOldEls.add(byNum);\n return byNum;\n }\n }\n\n // Fallback: scan parent children\n return scanForElementByKey(parent, k, s, usedOldEls);\n };\n}\n\n/** Scan parent children for element with matching key */\nfunction scanForElementByKey(\n parent: Element,\n k: string | number,\n keyStr: string,\n usedOldEls: WeakSet<Node>\n): Element | undefined {\n try {\n for (let ch = parent.firstElementChild; ch; ch = ch.nextElementSibling) {\n if (usedOldEls.has(ch)) continue;\n const attr = ch.getAttribute('data-key');\n if (attr === keyStr) {\n usedOldEls.add(ch);\n return ch;\n }\n if (attr !== null) {\n const numAttr = Number(attr);\n if (!Number.isNaN(numAttr) && numAttr === (k as number)) {\n usedOldEls.add(ch);\n return ch;\n }\n }\n }\n } catch {\n // Ignore\n }\n return undefined;\n}\n\n/** Reconcile a single child */\nfunction reconcileSingleChild(\n child: VNode,\n index: number,\n parent: Element,\n resolveOldElOnce: (k: string | number) => Element | undefined,\n resolveUnkeyedOnce: () => Element | undefined,\n usedOldEls: WeakSet<Node>,\n newKeyMap: Map<string | number, Element>\n): Node | null {\n const resolvedControlBoundary = prepareControlBoundaryResolution(child);\n if (resolvedControlBoundary !== null) {\n if (resolvedControlBoundary.remount) {\n return createDOMNode(resolvedControlBoundary.vnode);\n }\n\n return reconcileSingleChild(\n resolvedControlBoundary.vnode,\n index,\n parent,\n resolveOldElOnce,\n resolveUnkeyedOnce,\n usedOldEls,\n newKeyMap\n );\n }\n\n // Keyed child\n const key = extractKey(child);\n\n if (key !== undefined) {\n return reconcileKeyedChild(child, key, parent, resolveOldElOnce, newKeyMap);\n }\n\n return reconcileUnkeyedChild(\n child,\n index,\n parent,\n resolveUnkeyedOnce,\n usedOldEls\n );\n}\n\n/** Reconcile a keyed child */\nfunction reconcileKeyedChild(\n child: VNode,\n key: string | number,\n parent: Element,\n resolveOldElOnce: (k: string | number) => Element | undefined,\n newKeyMap: Map<string | number, Element>\n): Node | null {\n const el = resolveOldElOnce(key);\n\n if (el && el.parentElement === parent) {\n // Strict keyed guarantee: if the element tag changes for an existing key,\n // replace the DOM node rather than mutating in place.\n try {\n const childObj = child as VnodeObj;\n if (\n childObj &&\n typeof childObj === 'object' &&\n typeof childObj.type === 'string'\n ) {\n if (tagNamesEqualIgnoreCase(el.tagName, childObj.type)) {\n updateElementFromVnode(el, child);\n newKeyMap.set(key, el);\n return el;\n }\n }\n if (isComponentVNode(child)) {\n const synced = syncComponentElement(\n el,\n child,\n child.type,\n ((child.props ?? {}) as Props) || {}\n );\n if (synced) {\n if (synced instanceof Element) newKeyMap.set(key, synced);\n return synced;\n }\n }\n } catch {\n // Fall through to replacement\n }\n }\n\n const dom = createDOMNode(child);\n if (dom) {\n if (dom instanceof Element) newKeyMap.set(key, dom);\n return dom;\n }\n\n return null;\n}\n\n/** Reconcile an unkeyed or primitive child */\nfunction reconcileUnkeyedChild(\n child: VNode,\n index: number,\n parent: Element,\n resolveUnkeyedOnce: () => Element | undefined,\n usedOldEls: WeakSet<Node>\n): Node | null {\n try {\n // Use childNodes (includes Text nodes) instead of children (elements only)\n const existing = parent.childNodes[index] as Node | undefined;\n\n // Primitive child: try to reuse Text node if available\n if (typeof child === 'string' || typeof child === 'number') {\n if (existing && existing.nodeType === 3) {\n // Text node: reuse in-place\n (existing as Text).data = String(child);\n usedOldEls.add(existing);\n return existing;\n }\n return createDOMNode(child);\n }\n\n if (existing instanceof Element) {\n const synced = trySyncComponentChild(existing, child, usedOldEls);\n if (synced) return synced;\n }\n\n // Element child matching existing unkeyed element\n if (existing instanceof Element && canReuseElement(existing, child)) {\n updateElementFromVnode(existing, child);\n usedOldEls.add(existing);\n return existing;\n }\n\n // Try to find available unkeyed element elsewhere\n const avail = resolveUnkeyedOnce();\n if (avail) {\n const reuseResult = tryReuseElement(avail, child, usedOldEls);\n if (reuseResult) return reuseResult;\n }\n } catch {\n // Fall through to create new\n }\n\n const dom = createDOMNode(child);\n return dom;\n}\n\nfunction isComponentVNode(child: VNode): child is ComponentVNode {\n return (\n typeof child === 'object' &&\n child !== null &&\n 'type' in child &&\n typeof (child as VnodeObj).type === 'function'\n );\n}\n\nfunction isControlBoundaryVNode(child: VNode): child is DOMElement {\n return (\n typeof child === 'object' &&\n child !== null &&\n 'type' in child &&\n (child as VnodeObj).type === __FOR_BOUNDARY__\n );\n}\n\nfunction prepareControlBoundaryResolution(child: VNode): {\n remount: boolean;\n vnode: VNode | null;\n} | null {\n if (!isControlBoundaryVNode(child)) {\n return null;\n }\n\n const controlState = child._controlState ?? child._forState;\n if (!controlState) {\n return null;\n }\n if (controlState.kind === 'for') {\n const childrenVNodes = evaluateControlBoundaryChildren(controlState);\n return childrenVNodes.length === 1\n ? { remount: false, vnode: childrenVNodes[0] ?? null }\n : null;\n }\n\n const previousActiveKey = controlState.activeKey;\n const childrenVNodes = evaluateControlBoundaryChildren(controlState);\n\n return {\n remount:\n previousActiveKey !== null &&\n controlState.activeKey !== previousActiveKey,\n vnode: childrenVNodes[0] ?? null,\n };\n}\n\nfunction evaluateControlBoundaryChildren(\n controlState: ControlBoundaryState\n): VNode[] {\n if (controlState.kind === 'for') {\n return evaluateForState(controlState);\n }\n\n if (controlState.kind === 'show') {\n return evaluateShowState(controlState);\n }\n\n return evaluateCaseState(controlState);\n}\n\nfunction trySyncComponentChild(\n existing: Element,\n child: VNode,\n usedOldEls: WeakSet<Node>\n): Node | null {\n if (!isComponentVNode(child)) return null;\n\n const synced = syncComponentElement(\n existing,\n child,\n child.type,\n ((child.props ?? {}) as Props) || {}\n );\n if (!synced) return null;\n\n usedOldEls.add(existing);\n usedOldEls.add(synced);\n return synced;\n}\n\n/** Check if existing element can be reused for child */\nfunction canReuseElement(existing: Element | undefined, child: VNode): boolean {\n if (!existing) return false;\n if (typeof child !== 'object' || child === null || !('type' in child))\n return false;\n\n const childObj = child as VnodeObj;\n const existingKey = existing.getAttribute('data-key');\n const hasNoKey = existingKey === null || existingKey === undefined;\n\n return (\n hasNoKey &&\n typeof childObj.type === 'string' &&\n tagNamesEqualIgnoreCase(existing.tagName, childObj.type)\n );\n}\n\n/** Collect unkeyed element children in DOM order. */\nfunction collectUnkeyedElements(parent: Element): Element[] {\n const elements: Element[] = [];\n for (let ch = parent.firstElementChild; ch; ch = ch.nextElementSibling) {\n if (ch.getAttribute('data-key') === null) elements.push(ch);\n }\n return elements;\n}\n\n/** Try to reuse available element for child */\nfunction tryReuseElement(\n avail: Element,\n child: VNode,\n usedOldEls: WeakSet<Node>\n): Node | null {\n if (typeof child === 'string' || typeof child === 'number') {\n return null;\n }\n\n const synced = trySyncComponentChild(avail, child, usedOldEls);\n if (synced) {\n return synced;\n }\n\n if (typeof child === 'object' && child !== null && 'type' in child) {\n const childObj = child as VnodeObj;\n if (\n typeof childObj.type === 'string' &&\n tagNamesEqualIgnoreCase(avail.tagName, childObj.type)\n ) {\n updateElementFromVnode(avail, child);\n usedOldEls.add(avail);\n return avail;\n }\n }\n\n return null;\n}\n\n/** Commit reconciliation by replacing parent children */\nfunction commitReconciliation(parent: Element, finalNodes: Node[]): void {\n try {\n const finalSet = new Set<Node>(finalNodes);\n\n for (let n = parent.firstChild; n; ) {\n const next = n.nextSibling;\n if (!finalSet.has(n)) {\n teardownNodeSubtree(n);\n parent.removeChild(n);\n }\n n = next;\n }\n\n for (let i = 0; i < finalNodes.length; i++) {\n const desiredNode = finalNodes[i];\n const anchor = parent.childNodes[i] ?? null;\n if (desiredNode !== anchor) {\n parent.insertBefore(desiredNode, anchor);\n }\n }\n } catch {\n const fragment = document.createDocumentFragment();\n for (let i = 0; i < finalNodes.length; i++) {\n fragment.appendChild(finalNodes[i]);\n }\n\n try {\n for (let n = parent.firstChild; n; ) {\n const next = n.nextSibling;\n teardownNodeSubtree(n);\n n = next;\n }\n } catch {\n // Ignore fallback cleanup failures.\n }\n\n recordDOMReplace('reconcile');\n parent.replaceChildren(fragment);\n return;\n }\n}\n"],"mappings":";;;;;;;;;;;AA2HA,SAAgB,uBACd,QACA,aACA,WAC+B;CAC/B,MAAM,cAAc,qBAAqB,WAAW;CAIpD,MAAM,mBAAmB,aAAa,mBAAmB,MAAM;CAG/D,MAAM,iBAAiB,aACrB,QACA,aACA,aACA,gBACF;CACA,IAAI,gBACF,OAAO;CAIT,OAAO,0BACL,QACA,aACA,aACA,gBACF;AACF;;AAGA,SAAS,mBAAmB,QAAgD;CAC1E,MAAM,yBAAS,IAAI,IAA8B;CACjD,IAAI;EACF,KAAK,IAAI,KAAK,OAAO,mBAAmB,IAAI,KAAK,GAAG,oBAAoB;GACtE,MAAM,IAAI,GAAG,aAAa,UAAU;GACpC,IAAI,MAAM,MAAM;IACd,OAAO,IAAI,GAAG,EAAE;IAChB,MAAM,IAAI,OAAO,CAAC;IAClB,IAAI,CAAC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,IAAI,WAAW,QAAQ,KAAK;GAC1C,MAAM,cAAc,WAAW;GAC/B,MAAM,SAAS,OAAO,WAAW,MAAM;GACvC,IAAI,gBAAgB,QAClB,OAAO,aAAa,aAAa,MAAM;EAE3C;CACF,QAAQ;EACN,MAAM,WAAW,SAAS,uBAAuB;EACjD,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KACrC,SAAS,YAAY,WAAW,EAAE;EAGpC,IAAI;GACF,KAAK,IAAI,IAAI,OAAO,YAAY,IAAK;IACnC,MAAM,OAAO,EAAE;IACf,oBAAoB,CAAC;IACrB,IAAI;GACN;EACF,QAAQ,CAER;EAEA,iBAAiB,WAAW;EAC5B,OAAO,gBAAgB,QAAQ;EAC/B;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"reconcile.js","names":[],"sources":["../../src/renderer/reconcile.ts"],"sourcesContent":["/**\n * ─────────────────────────────────────────────────────────────────────────────\n * RENDERER & RECONCILIATION INVARIANTS (LOCKED)\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * These invariants are NON-NEGOTIABLE. Any optimization or fast-path MUST\n * preserve them. Violations WILL produce incorrect DOM.\n *\n * 1. DOM ORDER DERIVES ONLY FROM CURRENT VNODE ORDER\n * --------------------------------------------------\n * - Final DOM child order MUST be reconstructed from the current vnode list.\n * - Reusing an existing DOM node does NOT imply it stays in the same position.\n * - Appending an existing Node to a DocumentFragment is the ONLY valid way\n * to express reordering (it moves the node).\n *\n * ❌ NEVER skip fragment insertion because a node already has a parent.\n * ✅ ALWAYS append reused nodes into the fragment to establish order.\n *\n *\n * 2. VNODE IDENTITY ≠ VNODE STABILITY\n * ----------------------------------\n * - VNodes are mutable.\n * - `vnodeA === vnodeB` does NOT imply semantic equality.\n * - DOM reuse MUST NOT be gated on vnode identity alone.\n *\n * DOM reuse is allowed ONLY when:\n * - element type is unchanged\n * - structural shape is compatible\n * - updates are applied explicitly via updateElementFromVnode\n *\n * ❌ NEVER assume \"same object\" means \"no changes\".\n *\n *\n * 3. KEYED RECONCILIATION IS ELEMENT-ONLY\n * --------------------------------------\n * - Keyed reconciliation assumes ELEMENT nodes, not Text or Comment nodes.\n * - Any fast-path using `parent.children[i]` MUST prove:\n * - all children are elements\n * - no text nodes are present\n *\n * ❌ NEVER index `parent.children` when text nodes may exist.\n * ✅ Use `parent.childNodes` or bail out to full reconciliation.\n *\n *\n * 4. PRIMITIVES MAP TO TEXT NODES\n * -------------------------------\n * - string/number children represent Text nodes, not Elements.\n * - Reconciliation MUST attempt Text-to-Text reuse before replacement.\n *\n * ❌ NEVER update element.textContent as a substitute for text reconciliation\n * unless the shape is explicitly guaranteed.\n *\n *\n * 5. FAST-PATHS MUST BE STRICTLY SAFE\n * ----------------------------------\n * - Fast-paths are OPTIONAL.\n * - Correctness always beats performance.\n *\n * A fast-path MUST:\n * - prove its eligibility\n * - fall back cleanly on ANY ambiguity\n * - never partially apply\n *\n *\n * 6. CLEANUP IS POSITION-INDEPENDENT\n * ---------------------------------\n * - Cleanup is based on removal from the DOM, not vnode position.\n * - Any node removed or replaced MUST:\n * - remove listeners\n * - cleanup component instances\n *\n *\n * 7. FOR-BOUNDARY & KEYED LISTS OBEY THE SAME RULES\n * ------------------------------------------------\n * - For-boundaries are NOT special in ordering semantics.\n * - Cached DOM nodes MUST still be reordered via fragment insertion.\n * - Cache is an optimization, not an ownership claim.\n *\n *\n * If you are unsure whether an optimization preserves these invariants:\n * DO NOT APPLY IT.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n */\n\nimport type { DOMElement, VNode } from './types';\nimport {\n createDOMNode,\n syncComponentElement,\n updateElementFromVnode,\n performBulkPositionalKeyedTextUpdate,\n} from './dom';\nimport type { Props } from '../common/props';\nimport {\n keyedElements,\n _reconcilerRecordedParents,\n planKeyedReorderFastPath,\n} from './keyed';\nimport { teardownNodeSubtree } from './cleanup';\nimport { applyRendererFastPath } from './fastpath';\nimport { getRuntimeEnv } from './env';\nimport type { ComponentFunction } from '../runtime/component';\nimport {\n evaluateCaseState,\n evaluateShowState,\n type ControlBoundaryState,\n} from '../runtime/control';\nimport { evaluateForState } from '../runtime/for';\nimport { __FOR_BOUNDARY__ } from '../common/vnode';\nimport {\n extractKey,\n checkPropChanges,\n recordFastPathStats,\n recordDOMReplace,\n tagNamesEqualIgnoreCase,\n} from './utils';\n\nexport const IS_DOM_AVAILABLE = typeof document !== 'undefined';\n\n// Helper type for narrowings\ntype VnodeObj = VNode & { type?: unknown; props?: Record<string, unknown> };\ntype ComponentVNode = DOMElement & { type: ComponentFunction };\n\nexport function reconcileKeyedChildren(\n parent: Element,\n newChildren: VNode[],\n oldKeyMap: Map<string | number, Element> | undefined\n): Map<string | number, Element> {\n const keyedVnodes = extractKeyedChildren(newChildren);\n\n // Ensure we have a key map before reconciliation to avoid O(n) DOM scans\n // during O(n) reconciliation loop (which would be O(n²))\n const ensuredOldKeyMap = oldKeyMap || buildKeyMapFromDOM(parent);\n\n // Try fast paths first\n const fastPathResult = tryFastPaths(\n parent,\n newChildren,\n keyedVnodes,\n ensuredOldKeyMap\n );\n if (fastPathResult) {\n return fastPathResult;\n }\n\n // Full reconciliation\n return performFullReconciliation(\n parent,\n newChildren,\n keyedVnodes,\n ensuredOldKeyMap\n );\n}\n\n/** Build key map from DOM children */\nfunction buildKeyMapFromDOM(parent: Element): Map<string | number, Element> {\n const keyMap = new Map<string | number, Element>();\n try {\n for (let el = parent.firstElementChild; el; el = el.nextElementSibling) {\n const k = el.getAttribute('data-key');\n if (k !== null) {\n keyMap.set(k, el);\n const n = Number(k);\n if (!Number.isNaN(n)) keyMap.set(n, el);\n }\n }\n } catch {\n // Ignore\n }\n return keyMap;\n}\n\n/** Extract keyed children in a single pass. */\nfunction extractKeyedChildren(\n newChildren: VNode[]\n): Array<{ key: string | number; vnode: VNode }> {\n const keyedVnodes: Array<{ key: string | number; vnode: VNode }> = [];\n\n for (let i = 0; i < newChildren.length; i++) {\n const child = newChildren[i];\n const key = extractKey(child);\n if (key !== undefined) {\n keyedVnodes.push({ key, vnode: child });\n }\n }\n\n return keyedVnodes;\n}\n\n/** Try fast paths before full reconciliation */\nfunction tryFastPaths(\n parent: Element,\n newChildren: VNode[],\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>,\n oldKeyMap: Map<string | number, Element> | undefined\n): Map<string | number, Element> | null {\n try {\n const forcedResult = tryForcedPositionalBulkUpdate(\n parent,\n newChildren,\n keyedVnodes\n );\n if (forcedResult) {\n return forcedResult;\n }\n\n // Try renderer fast-path for large keyed reorder-only updates\n const rendererResult = tryRendererFastPath(\n parent,\n keyedVnodes,\n newChildren.length,\n oldKeyMap\n );\n if (rendererResult) {\n return rendererResult;\n }\n\n // Try positional bulk update for medium-sized lists\n const positionalResult = tryPositionalBulkUpdate(parent, keyedVnodes);\n if (positionalResult) {\n return positionalResult;\n }\n } catch {\n // Fall through to full reconciliation\n }\n\n return null;\n}\n\n/** Try renderer fast-path */\nfunction tryRendererFastPath(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>,\n totalChildren: number,\n oldKeyMap: Map<string | number, Element> | undefined\n): Map<string | number, Element> | null {\n const decision = planKeyedReorderFastPath(\n parent,\n keyedVnodes,\n totalChildren,\n oldKeyMap\n );\n\n if (decision.useFastPath) {\n try {\n const map = applyRendererFastPath(parent, keyedVnodes, oldKeyMap);\n if (map) {\n keyedElements.set(parent, map);\n return map;\n }\n } catch {\n // Fall through\n }\n }\n\n return null;\n}\n\n/** Try the explicit test/bench forced positional keyed path. */\nfunction tryForcedPositionalBulkUpdate(\n parent: Element,\n newChildren: VNode[],\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n): Map<string | number, Element> | null {\n if (getRuntimeEnv().ASKR_FORCE_BULK_POSREUSE !== '1') return null;\n if (keyedVnodes.length === 0 || keyedVnodes.length !== newChildren.length) {\n return null;\n }\n\n try {\n const stats = performBulkPositionalKeyedTextUpdate(parent, keyedVnodes);\n recordFastPathStats(stats, 'bulkKeyedPositionalForced');\n\n rebuildKeyedMap(parent);\n return keyedElements.get(parent) as Map<string | number, Element>;\n } catch {\n return null;\n }\n}\n\n/** Try positional bulk update for medium-sized lists */\nfunction tryPositionalBulkUpdate(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n): Map<string | number, Element> | null {\n const total = keyedVnodes.length;\n if (total < 10) return null;\n\n // CRITICAL INVARIANT: Only use children[] indexing if element-only is guaranteed\n // If parent has text nodes or comment nodes, bail to full reconciliation\n if (parent.children.length !== total) {\n return null;\n }\n\n const matchCount = countPositionalMatches(parent, keyedVnodes);\n\n // For keyed lists, the positional bulk update path makes sense in two cases:\n // 1. Perfect match (100%): All keys are in the right positions, just update text\n // 2. Very low match (<10%): Keys changed en-masse, treat as bulk re-key, reuse nodes by position\n // ANY mismatch at all means we have a reorder and need full reconciliation\n // to preserve DOM node identity correctly.\n const matchFraction = matchCount / total;\n\n if (keyedVnodes.length > 0) {\n // For keyed lists: require perfect match or very low match\n // matchCount !== total catches ANY reordering, even just 2 swapped elements\n if (matchCount !== total && matchFraction >= 0.1) {\n return null;\n }\n } else {\n // For unkeyed lists: use original threshold\n if (matchFraction < 0.9) {\n return null;\n }\n }\n\n // Check for prop changes that would prevent positional update\n if (hasPositionalPropChanges(parent, keyedVnodes)) {\n return null;\n }\n\n // Perform positional update\n try {\n const stats = performBulkPositionalKeyedTextUpdate(parent, keyedVnodes);\n recordFastPathStats(stats, 'bulkKeyedPositionalHits');\n\n rebuildKeyedMap(parent);\n return keyedElements.get(parent) as Map<string | number, Element>;\n } catch {\n return null;\n }\n}\n\n/** Count how many vnodes match parent children by position and tag */\nfunction countPositionalMatches(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n): number {\n let matchCount = 0;\n\n try {\n // For keyed children, use children (elements only) since keyed nodes are elements\n for (let i = 0; i < keyedVnodes.length; i++) {\n const vnode = keyedVnodes[i].vnode as VnodeObj;\n const expectedKey = keyedVnodes[i].key;\n\n if (!vnode || typeof vnode !== 'object' || typeof vnode.type !== 'string')\n continue;\n\n const el = parent.children[i] as Element | undefined;\n if (!el) continue;\n\n // For keyed lists, check BOTH tag name AND key match\n if (tagNamesEqualIgnoreCase(el.tagName, vnode.type)) {\n // Check if the element at this position has the expected key\n const actualKey = el.getAttribute('data-key');\n const keyMatches =\n actualKey === String(expectedKey) ||\n (actualKey !== null &&\n !Number.isNaN(Number(actualKey)) &&\n Number(actualKey) === expectedKey);\n\n if (keyMatches) {\n matchCount++;\n }\n }\n }\n } catch {\n // Ignore\n }\n\n return matchCount;\n}\n\n/** Check if positional prop changes would prevent bulk update */\nfunction hasPositionalPropChanges(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n): boolean {\n try {\n // For keyed children, use children (elements only) since keyed nodes are elements\n for (let i = 0; i < keyedVnodes.length; i++) {\n const vnode = keyedVnodes[i].vnode as VnodeObj;\n const el = parent.children[i] as Element | undefined;\n if (!el || !vnode || typeof vnode !== 'object') continue;\n\n if (checkPropChanges(el, vnode.props || {})) {\n return true;\n }\n }\n } catch {\n return true;\n }\n\n return false;\n}\n\n/** Rebuild keyed map from parent children */\nfunction rebuildKeyedMap(parent: Element): void {\n try {\n const map = new Map<string | number, Element>();\n for (let el = parent.firstElementChild; el; el = el.nextElementSibling) {\n const k = el.getAttribute('data-key');\n if (k !== null) {\n map.set(k, el);\n const n = Number(k);\n if (!Number.isNaN(n)) map.set(n, el);\n }\n }\n keyedElements.set(parent, map);\n } catch {\n // Ignore\n }\n}\n\n/** Perform full reconciliation when fast paths don't apply */\nfunction performFullReconciliation(\n parent: Element,\n newChildren: VNode[],\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>,\n oldKeyMap: Map<string | number, Element> | undefined\n): Map<string | number, Element> {\n const newKeyMap = new Map<string | number, Element>();\n const finalNodes: Node[] = [];\n const usedOldEls = new WeakSet<Node>();\n\n const resolveOldElOnce = createOldElResolver(parent, oldKeyMap, usedOldEls);\n const unkeyedEls = collectUnkeyedElements(parent);\n let unkeyedIndex = 0;\n const resolveUnkeyedOnce = (): Element | undefined => {\n while (unkeyedIndex < unkeyedEls.length) {\n const candidate = unkeyedEls[unkeyedIndex++];\n if (!usedOldEls.has(candidate)) return candidate;\n }\n return undefined;\n };\n\n // Positional reconciliation\n for (let i = 0; i < newChildren.length; i++) {\n const child = newChildren[i];\n const node = reconcileSingleChild(\n child,\n i,\n parent,\n resolveOldElOnce,\n resolveUnkeyedOnce,\n usedOldEls,\n newKeyMap\n );\n if (node) finalNodes.push(node);\n }\n\n // SSR guard\n if (typeof document === 'undefined') return newKeyMap;\n\n commitReconciliation(parent, finalNodes);\n keyedElements.delete(parent);\n\n return newKeyMap;\n}\n\n/** Create resolver for finding old elements by key */\nfunction createOldElResolver(\n parent: Element,\n oldKeyMap: Map<string | number, Element> | undefined,\n usedOldEls: WeakSet<Node>\n): (k: string | number) => Element | undefined {\n return (k: string | number) => {\n if (!oldKeyMap) return undefined;\n\n // Fast-path: directly from oldKeyMap\n const direct = oldKeyMap.get(k);\n if (direct && !usedOldEls.has(direct)) {\n usedOldEls.add(direct);\n return direct;\n }\n\n // Try string form\n const s = String(k);\n const byString = oldKeyMap.get(s);\n if (byString && !usedOldEls.has(byString)) {\n usedOldEls.add(byString);\n return byString;\n }\n\n // Try numeric form\n const n = Number(s);\n if (!Number.isNaN(n)) {\n const byNum = oldKeyMap.get(n);\n if (byNum && !usedOldEls.has(byNum)) {\n usedOldEls.add(byNum);\n return byNum;\n }\n }\n\n // Fallback: scan parent children\n return scanForElementByKey(parent, k, s, usedOldEls);\n };\n}\n\n/** Scan parent children for element with matching key */\nfunction scanForElementByKey(\n parent: Element,\n k: string | number,\n keyStr: string,\n usedOldEls: WeakSet<Node>\n): Element | undefined {\n try {\n for (let ch = parent.firstElementChild; ch; ch = ch.nextElementSibling) {\n if (usedOldEls.has(ch)) continue;\n const attr = ch.getAttribute('data-key');\n if (attr === keyStr) {\n usedOldEls.add(ch);\n return ch;\n }\n if (attr !== null) {\n const numAttr = Number(attr);\n if (!Number.isNaN(numAttr) && numAttr === (k as number)) {\n usedOldEls.add(ch);\n return ch;\n }\n }\n }\n } catch {\n // Ignore\n }\n return undefined;\n}\n\n/** Reconcile a single child */\nfunction reconcileSingleChild(\n child: VNode,\n index: number,\n parent: Element,\n resolveOldElOnce: (k: string | number) => Element | undefined,\n resolveUnkeyedOnce: () => Element | undefined,\n usedOldEls: WeakSet<Node>,\n newKeyMap: Map<string | number, Element>\n): Node | null {\n const resolvedControlBoundary = prepareControlBoundaryResolution(child);\n if (resolvedControlBoundary !== null) {\n if (resolvedControlBoundary.remount) {\n return createDOMNode(resolvedControlBoundary.vnode);\n }\n\n return reconcileSingleChild(\n resolvedControlBoundary.vnode,\n index,\n parent,\n resolveOldElOnce,\n resolveUnkeyedOnce,\n usedOldEls,\n newKeyMap\n );\n }\n\n // Keyed child\n const key = extractKey(child);\n\n if (key !== undefined) {\n return reconcileKeyedChild(child, key, parent, resolveOldElOnce, newKeyMap);\n }\n\n return reconcileUnkeyedChild(\n child,\n index,\n parent,\n resolveUnkeyedOnce,\n usedOldEls\n );\n}\n\n/** Reconcile a keyed child */\nfunction reconcileKeyedChild(\n child: VNode,\n key: string | number,\n parent: Element,\n resolveOldElOnce: (k: string | number) => Element | undefined,\n newKeyMap: Map<string | number, Element>\n): Node | null {\n const el = resolveOldElOnce(key);\n\n if (el && el.parentElement === parent) {\n // Strict keyed guarantee: if the element tag changes for an existing key,\n // replace the DOM node rather than mutating in place.\n try {\n const childObj = child as VnodeObj;\n if (\n childObj &&\n typeof childObj === 'object' &&\n typeof childObj.type === 'string'\n ) {\n if (tagNamesEqualIgnoreCase(el.tagName, childObj.type)) {\n updateElementFromVnode(el, child);\n newKeyMap.set(key, el);\n return el;\n }\n }\n if (isComponentVNode(child)) {\n const synced = syncComponentElement(\n el,\n child,\n child.type,\n ((child.props ?? {}) as Props) || {}\n );\n if (synced) {\n if (synced instanceof Element) newKeyMap.set(key, synced);\n return synced;\n }\n }\n } catch {\n // Fall through to replacement\n }\n }\n\n const dom = createDOMNode(child);\n if (dom) {\n if (dom instanceof Element) newKeyMap.set(key, dom);\n return dom;\n }\n\n return null;\n}\n\n/** Reconcile an unkeyed or primitive child */\nfunction reconcileUnkeyedChild(\n child: VNode,\n index: number,\n parent: Element,\n resolveUnkeyedOnce: () => Element | undefined,\n usedOldEls: WeakSet<Node>\n): Node | null {\n try {\n // Use childNodes (includes Text nodes) instead of children (elements only)\n const existing = parent.childNodes[index] as Node | undefined;\n\n // Primitive child: try to reuse Text node if available\n if (typeof child === 'string' || typeof child === 'number') {\n if (existing && existing.nodeType === 3) {\n // Text node: reuse in-place\n (existing as Text).data = String(child);\n usedOldEls.add(existing);\n return existing;\n }\n return createDOMNode(child);\n }\n\n if (existing instanceof Element) {\n const synced = trySyncComponentChild(existing, child, usedOldEls);\n if (synced) return synced;\n }\n\n // Element child matching existing unkeyed element\n if (existing instanceof Element && canReuseElement(existing, child)) {\n updateElementFromVnode(existing, child);\n usedOldEls.add(existing);\n return existing;\n }\n\n // Try to find available unkeyed element elsewhere\n const avail = resolveUnkeyedOnce();\n if (avail) {\n const reuseResult = tryReuseElement(avail, child, usedOldEls);\n if (reuseResult) return reuseResult;\n }\n } catch {\n // Fall through to create new\n }\n\n const dom = createDOMNode(child);\n return dom;\n}\n\nfunction isComponentVNode(child: VNode): child is ComponentVNode {\n return (\n typeof child === 'object' &&\n child !== null &&\n 'type' in child &&\n typeof (child as VnodeObj).type === 'function'\n );\n}\n\nfunction isControlBoundaryVNode(child: VNode): child is DOMElement {\n return (\n typeof child === 'object' &&\n child !== null &&\n 'type' in child &&\n (child as VnodeObj).type === __FOR_BOUNDARY__\n );\n}\n\nfunction prepareControlBoundaryResolution(child: VNode): {\n remount: boolean;\n vnode: VNode | null;\n} | null {\n if (!isControlBoundaryVNode(child)) {\n return null;\n }\n\n const controlState = child._controlState ?? child._forState;\n if (!controlState) {\n return null;\n }\n if (controlState.kind === 'for') {\n const childrenVNodes = evaluateControlBoundaryChildren(controlState);\n return childrenVNodes.length === 1\n ? { remount: false, vnode: childrenVNodes[0] ?? null }\n : null;\n }\n\n const previousActiveKey = controlState.activeKey;\n const childrenVNodes = evaluateControlBoundaryChildren(controlState);\n\n return {\n remount:\n previousActiveKey !== null &&\n controlState.activeKey !== previousActiveKey,\n vnode: childrenVNodes[0] ?? null,\n };\n}\n\nfunction evaluateControlBoundaryChildren(\n controlState: ControlBoundaryState\n): VNode[] {\n if (controlState.kind === 'for') {\n return evaluateForState(controlState);\n }\n\n if (controlState.kind === 'show') {\n return evaluateShowState(controlState);\n }\n\n return evaluateCaseState(controlState);\n}\n\nfunction trySyncComponentChild(\n existing: Element,\n child: VNode,\n usedOldEls: WeakSet<Node>\n): Node | null {\n if (!isComponentVNode(child)) return null;\n\n const synced = syncComponentElement(\n existing,\n child,\n child.type,\n ((child.props ?? {}) as Props) || {}\n );\n if (!synced) return null;\n\n usedOldEls.add(existing);\n usedOldEls.add(synced);\n return synced;\n}\n\n/** Check if existing element can be reused for child */\nfunction canReuseElement(existing: Element | undefined, child: VNode): boolean {\n if (!existing) return false;\n if (typeof child !== 'object' || child === null || !('type' in child))\n return false;\n\n const childObj = child as VnodeObj;\n const existingKey = existing.getAttribute('data-key');\n const hasNoKey = existingKey === null || existingKey === undefined;\n\n return (\n hasNoKey &&\n typeof childObj.type === 'string' &&\n tagNamesEqualIgnoreCase(existing.tagName, childObj.type)\n );\n}\n\n/** Collect unkeyed element children in DOM order. */\nfunction collectUnkeyedElements(parent: Element): Element[] {\n const elements: Element[] = [];\n for (let ch = parent.firstElementChild; ch; ch = ch.nextElementSibling) {\n if (ch.getAttribute('data-key') === null) elements.push(ch);\n }\n return elements;\n}\n\n/** Try to reuse available element for child */\nfunction tryReuseElement(\n avail: Element,\n child: VNode,\n usedOldEls: WeakSet<Node>\n): Node | null {\n if (typeof child === 'string' || typeof child === 'number') {\n return null;\n }\n\n const synced = trySyncComponentChild(avail, child, usedOldEls);\n if (synced) {\n return synced;\n }\n\n if (typeof child === 'object' && child !== null && 'type' in child) {\n const childObj = child as VnodeObj;\n if (\n typeof childObj.type === 'string' &&\n tagNamesEqualIgnoreCase(avail.tagName, childObj.type)\n ) {\n updateElementFromVnode(avail, child);\n usedOldEls.add(avail);\n return avail;\n }\n }\n\n return null;\n}\n\n/** Commit reconciliation by replacing parent children */\nfunction commitReconciliation(parent: Element, finalNodes: Node[]): void {\n try {\n const finalSet = new Set<Node>(finalNodes);\n\n for (let n = parent.firstChild; n; ) {\n const next = n.nextSibling;\n if (!finalSet.has(n)) {\n teardownNodeSubtree(n);\n parent.removeChild(n);\n }\n n = next;\n }\n\n for (let i = 0; i < finalNodes.length; i++) {\n const desiredNode = finalNodes[i];\n const anchor = parent.childNodes[i] ?? null;\n if (desiredNode !== anchor) {\n parent.insertBefore(desiredNode, anchor);\n }\n }\n } catch {\n const fragment = document.createDocumentFragment();\n for (let i = 0; i < finalNodes.length; i++) {\n fragment.appendChild(finalNodes[i]);\n }\n\n try {\n for (let n = parent.firstChild; n; ) {\n const next = n.nextSibling;\n teardownNodeSubtree(n);\n n = next;\n }\n } catch {\n // Ignore fallback cleanup failures.\n }\n\n recordDOMReplace('reconcile');\n parent.replaceChildren(fragment);\n return;\n }\n}\n"],"mappings":";;;;;;;;;;;AA2HA,SAAgB,uBACd,QACA,aACA,WAC+B;CAC/B,MAAM,cAAc,qBAAqB,WAAW;CAIpD,MAAM,mBAAmB,aAAa,mBAAmB,MAAM;CAG/D,MAAM,iBAAiB,aACrB,QACA,aACA,aACA,gBACF;CACA,IAAI,gBACF,OAAO;CAIT,OAAO,0BACL,QACA,aACA,aACA,gBACF;AACF;;AAGA,SAAS,mBAAmB,QAAgD;CAC1E,MAAM,yBAAS,IAAI,IAA8B;CACjD,IAAI;EACF,KAAK,IAAI,KAAK,OAAO,mBAAmB,IAAI,KAAK,GAAG,oBAAoB;GACtE,MAAM,IAAI,GAAG,aAAa,UAAU;GACpC,IAAI,MAAM,MAAM;IACd,OAAO,IAAI,GAAG,EAAE;I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;IACrB,OAAO,YAAY,CAAC;GACtB;GACA,IAAI;EACN;EAEA,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KAAK;GAC1C,MAAM,cAAc,WAAW;GAC/B,MAAM,SAAS,OAAO,WAAW,MAAM;GACvC,IAAI,gBAAgB,QAClB,OAAO,aAAa,aAAa,MAAM;EAE3C;CACF,QAAQ;EACN,MAAM,WAAW,SAAS,uBAAuB;EACjD,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KACrC,SAAS,YAAY,WAAW,EAAE;EAGpC,IAAI;GACF,KAAK,IAAI,IAAI,OAAO,YAAY,IAAK;IACnC,MAAM,OAAO,EAAE;IACf,oBAAoB,CAAC;IACrB,IAAI;GACN;EACF,QAAQ,CAER;EAEA,iBAAiB,WAAW;EAC5B,OAAO,gBAAgB,QAAQ;EAC/B;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[],"sources":["../../src/renderer/utils.ts"],"sourcesContent":["/**\n * Shared utilities for the renderer module.\n * Consolidates common patterns to reduce code duplication.\n */\n\nimport { globalScheduler } from '../runtime/scheduler';\nimport { logger } from '../dev/logger';\nimport { getPublicAttributeName } from '../common/attr-names';\nimport { getRuntimeEnv } from './env';\nimport { setDevValue, incDevCounter } from '../runtime/dev-namespace';\n\nconst SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n\n// Keep direct replaceChildren(...nodes) commits below a conservative argument\n// count until browser benchmarks prove larger spreads are safe.\nexport const DIRECT_REPLACE_CHILDREN_SPREAD_LIMIT = 4096;\n\nexport function canUseDirectReplaceChildrenSpread(count: number): boolean {\n return count <= DIRECT_REPLACE_CHILDREN_SPREAD_LIMIT;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Types\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface ListenerEntry {\n handler: EventListener;\n original: EventListener;\n eventName: string;\n options?: boolean | AddEventListenerOptions;\n updateHandler?: (nextHandler: EventListener) => void;\n}\n\nexport interface ParsedEventProp {\n eventName: string;\n capture: boolean;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Event Handler Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n// Handler pooling cache to avoid recreating wrapped handlers\n// Key: handler reference, Value: { wrapped: EventListener, flushAfter: boolean }\nconst handlerCache = new WeakMap<EventListener, Map<boolean, EventListener>>();\nlet cacheSize = 0;\nconst MAX_CACHE_SIZE = 1000;\n\n/**\n * Parse an event prop name (e.g., 'onClick') to its DOM event name (e.g., 'click')\n */\nexport function parseEventName(propName: string): string | null {\n return parseEventProp(propName)?.eventName ?? null;\n}\n\nexport function parseEventProp(propName: string): ParsedEventProp | null {\n if (!propName.startsWith('on') || propName.length <= 2) return null;\n const capture =\n propName.endsWith('Capture') && propName.length > 'onCapture'.length;\n const normalizedPropName = capture\n ? propName.slice(0, -'Capture'.length)\n : propName;\n\n return normalizedPropName.length <= 2\n ? null\n : {\n eventName:\n normalizedPropName.slice(2).charAt(0).toLowerCase() +\n normalizedPropName.slice(3).toLowerCase(),\n capture,\n };\n}\n\nexport function getEventListenerKey(\n eventName: string,\n capture = false\n): string {\n return capture ? `${eventName}:capture` : eventName;\n}\n\nexport function getEventListenerOptions(\n eventName: string,\n capture = false\n): AddEventListenerOptions | undefined {\n const passiveOptions = getPassiveOptions(eventName);\n if (!capture) {\n return passiveOptions;\n }\n\n return passiveOptions\n ? { ...passiveOptions, capture: true }\n : { capture: true };\n}\n\n/**\n * Get default event listener options for passive events\n */\nexport function getPassiveOptions(\n eventName: string\n): AddEventListenerOptions | undefined {\n if (\n eventName === 'wheel' ||\n eventName === 'scroll' ||\n eventName.startsWith('touch')\n ) {\n return { passive: true };\n }\n return undefined;\n}\n\n/**\n * Create a wrapped event handler that integrates with the scheduler\n * Uses caching to avoid recreating wrappers for the same handler\n */\nexport function createWrappedHandler(\n handler: EventListener,\n flushAfter = false\n): EventListener {\n // Check cache first\n const cachedByFlush = handlerCache.get(handler);\n if (cachedByFlush) {\n const cached = cachedByFlush.get(flushAfter);\n if (cached) return cached;\n }\n\n const wrapped: EventListener = (event: Event) => {\n try {\n globalScheduler.runInHandlerScope(\n () => {\n try {\n handler(event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n }\n },\n flushAfter ? 'sync' : 'defer'\n );\n } catch (err) {\n if (flushAfter) {\n queueMicrotask(() => {\n throw err;\n });\n } else {\n logger.error('[Askr] Event handler error:', err);\n }\n }\n };\n\n // Cache the wrapped handler\n try {\n if (!handlerCache.has(handler)) {\n // Limit cache size to prevent memory leaks\n if (cacheSize >= MAX_CACHE_SIZE) {\n // Simple eviction - just don't cache new entries when full\n } else {\n cacheSize++;\n handlerCache.set(handler, new Map());\n }\n }\n handlerCache.get(handler)?.set(flushAfter, wrapped);\n } catch {\n // WeakMap can throw if handler is not a valid key\n }\n\n return wrapped;\n}\n\nexport function createMutableWrappedHandler(\n handler: EventListener,\n flushAfter = false\n): {\n handler: EventListener;\n updateHandler: (nextHandler: EventListener) => void;\n} {\n let currentHandler = handler;\n\n const wrapped: EventListener = (event: Event) => {\n try {\n globalScheduler.runInHandlerScope(\n () => {\n try {\n currentHandler(event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n }\n },\n flushAfter ? 'sync' : 'defer'\n );\n } catch (err) {\n if (flushAfter) {\n queueMicrotask(() => {\n throw err;\n });\n } else {\n logger.error('[Askr] Event handler error:', err);\n }\n }\n };\n\n return {\n handler: wrapped,\n updateHandler(nextHandler: EventListener) {\n currentHandler = nextHandler;\n },\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Prop/Attribute Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Props that should be skipped during attribute processing */\nexport function isSkippedProp(key: string): boolean {\n return key === 'children' || key === 'key' || key === 'ref';\n}\n\n/** Check if prop should be ignored for prop-change detection */\nexport function isIgnoredForPropChanges(key: string): boolean {\n if (key === 'children' || key === 'key') return true;\n if (key.startsWith('on') && key.length > 2) return true;\n if (key.startsWith('data-')) return true;\n return false;\n}\n\n/**\n * Check if an element's current attribute value differs from vnode value\n */\nexport function hasPropChanged(\n el: Element,\n key: string,\n value: unknown\n): boolean {\n try {\n if (key === 'class' || key === 'className') {\n return readElementClassName(el) !== String(value);\n }\n if (key === 'value' || key === 'checked') {\n return (el as HTMLElement & Record<string, unknown>)[key] !== value;\n }\n const attr = el.getAttribute(getRenderedAttributeName(el, key));\n if (value === undefined || value === null || value === false) {\n return attr !== null;\n }\n return String(value) !== attr;\n } catch {\n return true;\n }\n}\n\nexport function isSVGDomElement(el: Element): el is SVGElement {\n return typeof SVGElement !== 'undefined' && el instanceof SVGElement;\n}\n\nexport function getRenderedAttributeName(\n el: Element,\n propName: string\n): string {\n const attributeName = getPublicAttributeName(propName);\n\n return el.namespaceURI === SVG_NAMESPACE\n ? attributeName\n : attributeName.toLowerCase();\n}\n\nexport function setRenderedAttribute(\n el: Element,\n propName: string,\n value: string\n): void {\n el.setAttribute(getRenderedAttributeName(el, propName), value);\n}\n\nexport function removeRenderedAttribute(el: Element, propName: string): void {\n el.removeAttribute(getRenderedAttributeName(el, propName));\n}\n\nexport function readElementClassName(el: Element): string {\n if (isSVGDomElement(el)) {\n return el.getAttribute('class') ?? '';\n }\n\n return (el as HTMLElement).className;\n}\n\nexport function writeElementClassName(el: Element, value: string): void {\n if (isSVGDomElement(el)) {\n if (value.length > 0) {\n el.setAttribute('class', value);\n } else {\n el.removeAttribute('class');\n }\n return;\n }\n\n (el as HTMLElement).className = value;\n}\n\nexport function tagNamesEqualIgnoreCase(a: string, b: string): boolean {\n if (a === b) return true;\n if (a.length !== b.length) return false;\n\n for (let index = 0; index < a.length; index += 1) {\n const aCode = a.charCodeAt(index);\n const bCode = b.charCodeAt(index);\n if (aCode === bCode) continue;\n\n const normalizedA = aCode >= 65 && aCode <= 90 ? aCode + 32 : aCode;\n const normalizedB = bCode >= 65 && bCode <= 90 ? bCode + 32 : bCode;\n if (normalizedA !== normalizedB) return false;\n }\n\n return true;\n}\n\n/**\n * Check if a vnode has non-trivial props (excluding events and data-*)\n */\nexport function hasNonTrivialProps(props: Record<string, unknown>): boolean {\n for (const k of Object.keys(props)) {\n if (isIgnoredForPropChanges(k)) continue;\n return true;\n }\n return false;\n}\n\n/**\n * Check for prop changes between vnode and existing element\n */\nexport function checkPropChanges(\n el: Element,\n props: Record<string, unknown>\n): boolean {\n for (const k of Object.keys(props)) {\n if (isIgnoredForPropChanges(k)) continue;\n if (hasPropChanged(el, k, props[k])) {\n return true;\n }\n }\n return false;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Key Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Extract key from a vnode object\n */\nexport function extractKey(vnode: unknown): string | number | undefined {\n if (typeof vnode !== 'object' || vnode === null) return undefined;\n const obj = vnode as Record<string, unknown>;\n const rawKey =\n obj.key ?? (obj.props as Record<string, unknown> | undefined)?.key;\n if (rawKey === undefined || rawKey === null) return undefined;\n return typeof rawKey === 'symbol'\n ? String(rawKey)\n : (rawKey as string | number);\n}\n\n/**\n * Build a key map from element's children\n */\nexport function buildKeyMapFromChildren(\n parent: Element\n): Map<string | number, Element> {\n const map = new Map<string | number, Element>();\n for (let ch = parent.firstElementChild; ch; ch = ch.nextElementSibling) {\n const k = ch.getAttribute('data-key');\n if (k !== null) {\n map.set(k, ch);\n const n = Number(k);\n if (!Number.isNaN(n)) map.set(n, ch);\n }\n }\n return map;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Diagnostic Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Record DOM replace operation for diagnostics\n */\nexport function recordDOMReplace(source: string): void {\n try {\n incDevCounter('__DOM_REPLACE_COUNT');\n setDevValue(`__LAST_DOM_REPLACE_STACK_${source}`, new Error().stack);\n } catch {\n // ignore\n }\n}\n\n/**\n * Record fast-path stats for diagnostics\n */\nexport function recordFastPathStats(\n stats: Record<string, unknown>,\n counterName?: string\n): void {\n try {\n setDevValue('__LAST_FASTPATH_STATS', stats);\n setDevValue('__LAST_FASTPATH_COMMIT_COUNT', 1);\n if (counterName) {\n incDevCounter(counterName);\n }\n } catch {\n // ignore\n }\n}\n\n/**\n * Conditionally log debug info for fast-path operations\n */\nexport function logFastPathDebug(\n message: string,\n indexOrData?: number | unknown,\n data?: unknown\n): void {\n const env = getRuntimeEnv();\n if (env.ASKR_FASTPATH_DEBUG === '1' || env.ASKR_FASTPATH_DEBUG === 'true') {\n if (data !== undefined) {\n logger.warn(`[Askr][FASTPATH] ${message}`, indexOrData, data);\n } else if (indexOrData !== undefined) {\n logger.warn(`[Askr][FASTPATH] ${message}`, indexOrData);\n } else {\n logger.warn(`[Askr][FASTPATH] ${message}`);\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Performance Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get current high-resolution timestamp\n */\nexport function now(): number {\n return typeof performance !== 'undefined' && performance.now\n ? performance.now()\n : Date.now();\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,gBAAgB;AAItB,MAAa,uCAAuC;AAEpD,SAAgB,kCAAkC,OAAwB;CACxE,OAAO,SAAS;AAClB;AAyBA,MAAM,+BAAe,IAAI,QAAoD;AAC7E,IAAI,YAAY;AAChB,MAAM,iBAAiB;;;;AAKvB,SAAgB,eAAe,UAAiC;CAC9D,OAAO,eAAe,QAAQ,GAAG,aAAa;AAChD;AAEA,SAAgB,eAAe,UAA0C;CACvE,IAAI,CAAC,SAAS,WAAW,IAAI,KAAK,SAAS,UAAU,GAAG,OAAO;CAC/D,MAAM,UACJ,SAAS,SAAS,SAAS,KAAK,SAAS,SAAS;CACpD,MAAM,qBAAqB,UACvB,SAAS,MAAM,GAAG,EAAiB,IACnC;CAEJ,OAAO,mBAAmB,UAAU,IAChC,OACA;EACE,WACE,mBAAmB,MAAM,CAAC,EAAE,OAAO,CAAC,EAAE,YAAY,IAClD,mBAAmB,MAAM,CAAC,EAA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AAW,UAAa,WAAW,MAAM,OAAO;CACpD,OAAO,OAAO,WAAW,WACrB,OAAO,MAAM,IACZ;AACP;;;;AAKA,SAAgB,wBACd,QAC+B;CAC/B,MAAM,sBAAM,IAAI,IAA8B;CAC9C,KAAK,IAAI,KAAK,OAAO,mBAAmB,IAAI,KAAK,GAAG,oBAAoB;EACtE,MAAM,IAAI,GAAG,aAAa,UAAU;EACpC,IAAI,MAAM,MAAM;GACd,IAAI,IAAI,GAAG,EAAE;GACb,MAAM,IAAI,OAAO,CAAC;GAClB,IAAI,CAAC,OAAO,MAAM,CAAC,GAAG,IAAI,IAAI,GAAG,EAAE;EACrC;CACF;CACA,OAAO;AACT;;;;AASA,SAAgB,iBAAiB,QAAsB;CACrD,IAAI;EACF,cAAc,qBAAqB;EACnC,YAAY,4BAA4B,2BAAU,IAAI,MAAM,GAAE,KAAK;CACrE,QAAQ,CAER;AACF;;;;AAKA,SAAgB,oBACd,OACA,aACM;CACN,IAAI;EACF,YAAY,yBAAyB,KAAK;EAC1C,YAAY,gCAAgC,CAAC;EAC7C,IAAI,aACF,cAAc,WAAW;CAE7B,QAAQ,CAER;AACF;;;;AAKA,SAAgB,iBACd,SACA,aACA,MACM;CACN,MAAM,MAAM,cAAc;CAC1B,IAAI,IAAI,wBAAwB,OAAO,IAAI,wBAAwB,QACjE,IAAI,SAAS,QACX,OAAO,KAAK,oBAAoB,WAAW,aAAa,IAAI;MACvD,IAAI,gBAAgB,QACzB,OAAO,KAAK,oBAAoB,WAAW,WAAW;MAEtD,OAAO,KAAK,oBAAoB,SAAS;AAG/C;;;;AASA,SAAgB,MAAc;CAC5B,OAAO,OAAO,gBAAgB,eAAe,YAAY,MACrD,YAAY,IAAI,IAChB,KAAK,IAAI;AACf"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../../src/renderer/utils.ts"],"sourcesContent":["/**\n * Shared utilities for the renderer module.\n * Consolidates common patterns to reduce code duplication.\n */\n\nimport { globalScheduler } from '../runtime/scheduler';\nimport { logger } from '../dev/logger';\nimport { getPublicAttributeName } from '../common/attr-names';\nimport { getRuntimeEnv } from './env';\nimport { setDevValue, incDevCounter } from '../runtime/dev-namespace';\n\nconst SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n\n// Keep direct replaceChildren(...nodes) commits below a conservative argument\n// count until browser benchmarks prove larger spreads are safe.\nexport const DIRECT_REPLACE_CHILDREN_SPREAD_LIMIT = 4096;\n\nexport function canUseDirectReplaceChildrenSpread(count: number): boolean {\n return count <= DIRECT_REPLACE_CHILDREN_SPREAD_LIMIT;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Types\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface ListenerEntry {\n handler: EventListener;\n original: EventListener;\n eventName: string;\n options?: boolean | AddEventListenerOptions;\n updateHandler?: (nextHandler: EventListener) => void;\n}\n\nexport interface ParsedEventProp {\n eventName: string;\n capture: boolean;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Event Handler Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n// Handler pooling cache to avoid recreating wrapped handlers\n// Key: handler reference, Value: { wrapped: EventListener, flushAfter: boolean }\nconst handlerCache = new WeakMap<EventListener, Map<boolean, EventListener>>();\nlet cacheSize = 0;\nconst MAX_CACHE_SIZE = 1000;\n\n/**\n * Parse an event prop name (e.g., 'onClick') to its DOM event name (e.g., 'click')\n */\nexport function parseEventName(propName: string): string | null {\n return parseEventProp(propName)?.eventName ?? null;\n}\n\nexport function parseEventProp(propName: string): ParsedEventProp | null {\n if (!propName.startsWith('on') || propName.length <= 2) return null;\n const capture =\n propName.endsWith('Capture') && propName.length > 'onCapture'.length;\n const normalizedPropName = capture\n ? propName.slice(0, -'Capture'.length)\n : propName;\n\n return normalizedPropName.length <= 2\n ? null\n : {\n eventName:\n normalizedPropName.slice(2).charAt(0).toLowerCase() +\n normalizedPropName.slice(3).toLowerCase(),\n capture,\n };\n}\n\nexport function getEventListenerKey(\n eventName: string,\n capture = false\n): string {\n return capture ? `${eventName}:capture` : eventName;\n}\n\nexport function getEventListenerOptions(\n eventName: string,\n capture = false\n): AddEventListenerOptions | undefined {\n const passiveOptions = getPassiveOptions(eventName);\n if (!capture) {\n return passiveOptions;\n }\n\n return passiveOptions\n ? { ...passiveOptions, capture: true }\n : { capture: true };\n}\n\n/**\n * Get default event listener options for passive events\n */\nexport function getPassiveOptions(\n eventName: string\n): AddEventListenerOptions | undefined {\n if (\n eventName === 'wheel' ||\n eventName === 'scroll' ||\n eventName.startsWith('touch')\n ) {\n return { passive: true };\n }\n return undefined;\n}\n\n/**\n * Create a wrapped event handler that integrates with the scheduler\n * Uses caching to avoid recreating wrappers for the same handler\n */\nexport function createWrappedHandler(\n handler: EventListener,\n flushAfter = false\n): EventListener {\n // Check cache first\n const cachedByFlush = handlerCache.get(handler);\n if (cachedByFlush) {\n const cached = cachedByFlush.get(flushAfter);\n if (cached) return cached;\n }\n\n const wrapped: EventListener = (event: Event) => {\n try {\n globalScheduler.runInHandlerScope(\n () => {\n try {\n handler(event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n }\n },\n flushAfter ? 'sync' : 'defer'\n );\n } catch (err) {\n if (flushAfter) {\n queueMicrotask(() => {\n throw err;\n });\n } else {\n logger.error('[Askr] Event handler error:', err);\n }\n }\n };\n\n // Cache the wrapped handler\n try {\n if (!handlerCache.has(handler)) {\n // Limit cache size to prevent memory leaks\n if (cacheSize >= MAX_CACHE_SIZE) {\n // Simple eviction - just don't cache new entries when full\n } else {\n cacheSize++;\n handlerCache.set(handler, new Map());\n }\n }\n handlerCache.get(handler)?.set(flushAfter, wrapped);\n } catch {\n // WeakMap can throw if handler is not a valid key\n }\n\n return wrapped;\n}\n\nexport function createMutableWrappedHandler(\n handler: EventListener,\n flushAfter = false\n): {\n handler: EventListener;\n updateHandler: (nextHandler: EventListener) => void;\n} {\n let currentHandler = handler;\n\n const wrapped: EventListener = (event: Event) => {\n try {\n globalScheduler.runInHandlerScope(\n () => {\n try {\n currentHandler(event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n }\n },\n flushAfter ? 'sync' : 'defer'\n );\n } catch (err) {\n if (flushAfter) {\n queueMicrotask(() => {\n throw err;\n });\n } else {\n logger.error('[Askr] Event handler error:', err);\n }\n }\n };\n\n return {\n handler: wrapped,\n updateHandler(nextHandler: EventListener) {\n currentHandler = nextHandler;\n },\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Prop/Attribute Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Props that should be skipped during attribute processing */\nexport function isSkippedProp(key: string): boolean {\n return key === 'children' || key === 'key' || key === 'ref';\n}\n\n/** Check if prop should be ignored for prop-change detection */\nexport function isIgnoredForPropChanges(key: string): boolean {\n if (key === 'children' || key === 'key') return true;\n if (key.startsWith('on') && key.length > 2) return true;\n if (key.startsWith('data-')) return true;\n return false;\n}\n\n/**\n * Check if an element's current attribute value differs from vnode value\n */\nexport function hasPropChanged(\n el: Element,\n key: string,\n value: unknown\n): boolean {\n try {\n if (key === 'class' || key === 'className') {\n return readElementClassName(el) !== String(value);\n }\n if (key === 'value' || key === 'checked') {\n return (el as HTMLElement & Record<string, unknown>)[key] !== value;\n }\n const attr = el.getAttribute(getRenderedAttributeName(el, key));\n if (value === undefined || value === null || value === false) {\n return attr !== null;\n }\n return String(value) !== attr;\n } catch {\n return true;\n }\n}\n\nexport function isSVGDomElement(el: Element): el is SVGElement {\n return typeof SVGElement !== 'undefined' && el instanceof SVGElement;\n}\n\nexport function getRenderedAttributeName(\n el: Element,\n propName: string\n): string {\n const attributeName = getPublicAttributeName(propName);\n\n return el.namespaceURI === SVG_NAMESPACE\n ? attributeName\n : attributeName.toLowerCase();\n}\n\nexport function setRenderedAttribute(\n el: Element,\n propName: string,\n value: string\n): void {\n el.setAttribute(getRenderedAttributeName(el, propName), value);\n}\n\nexport function removeRenderedAttribute(el: Element, propName: string): void {\n el.removeAttribute(getRenderedAttributeName(el, propName));\n}\n\nexport function readElementClassName(el: Element): string {\n if (isSVGDomElement(el)) {\n return el.getAttribute('class') ?? '';\n }\n\n return (el as HTMLElement).className;\n}\n\nexport function writeElementClassName(el: Element, value: string): void {\n if (isSVGDomElement(el)) {\n if (value.length > 0) {\n el.setAttribute('class', value);\n } else {\n el.removeAttribute('class');\n }\n return;\n }\n\n (el as HTMLElement).className = value;\n}\n\nexport function tagNamesEqualIgnoreCase(a: string, b: string): boolean {\n if (a === b) return true;\n if (a.length !== b.length) return false;\n\n for (let index = 0; index < a.length; index += 1) {\n const aCode = a.charCodeAt(index);\n const bCode = b.charCodeAt(index);\n if (aCode === bCode) continue;\n\n const normalizedA = aCode >= 65 && aCode <= 90 ? aCode + 32 : aCode;\n const normalizedB = bCode >= 65 && bCode <= 90 ? bCode + 32 : bCode;\n if (normalizedA !== normalizedB) return false;\n }\n\n return true;\n}\n\n/**\n * Check if a vnode has non-trivial props (excluding events and data-*)\n */\nexport function hasNonTrivialProps(props: Record<string, unknown>): boolean {\n for (const k of Object.keys(props)) {\n if (isIgnoredForPropChanges(k)) continue;\n return true;\n }\n return false;\n}\n\n/**\n * Check for prop changes between vnode and existing element\n */\nexport function checkPropChanges(\n el: Element,\n props: Record<string, unknown>\n): boolean {\n for (const k of Object.keys(props)) {\n if (isIgnoredForPropChanges(k)) continue;\n if (hasPropChanged(el, k, props[k])) {\n return true;\n }\n }\n return false;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Key Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Extract key from a vnode object\n */\nexport function extractKey(vnode: unknown): string | number | undefined {\n if (typeof vnode !== 'object' || vnode === null) return undefined;\n const obj = vnode as Record<string, unknown>;\n const rawKey =\n obj.key ?? (obj.props as Record<string, unknown> | undefined)?.key;\n if (rawKey === undefined || rawKey === null) return undefined;\n return typeof rawKey === 'symbol'\n ? String(rawKey)\n : (rawKey as string | number);\n}\n\n/**\n * Build a key map from element's children\n */\nexport function buildKeyMapFromChildren(\n parent: Element\n): Map<string | number, Element> {\n const map = new Map<string | number, Element>();\n for (let ch = parent.firstElementChild; ch; ch = ch.nextElementSibling) {\n const k = ch.getAttribute('data-key');\n if (k !== null) {\n map.set(k, ch);\n const n = Number(k);\n if (!Number.isNaN(n)) map.set(n, ch);\n }\n }\n return map;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Diagnostic Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Record DOM replace operation for diagnostics\n */\nexport function recordDOMReplace(source: string): void {\n try {\n incDevCounter('__DOM_REPLACE_COUNT');\n setDevValue(`__LAST_DOM_REPLACE_STACK_${source}`, new Error().stack);\n } catch {\n // ignore\n }\n}\n\n/**\n * Record fast-path stats for diagnostics\n */\nexport function recordFastPathStats(\n stats: Record<string, unknown>,\n counterName?: string\n): void {\n try {\n setDevValue('__LAST_FASTPATH_STATS', stats);\n setDevValue('__LAST_FASTPATH_COMMIT_COUNT', 1);\n if (counterName) {\n incDevCounter(counterName);\n }\n } catch {\n // ignore\n }\n}\n\n/**\n * Conditionally log debug info for fast-path operations\n */\nexport function logFastPathDebug(\n message: string,\n indexOrData?: number | unknown,\n data?: unknown\n): void {\n const env = getRuntimeEnv();\n if (env.ASKR_FASTPATH_DEBUG === '1' || env.ASKR_FASTPATH_DEBUG === 'true') {\n if (data !== undefined) {\n logger.warn(`[Askr][FASTPATH] ${message}`, indexOrData, data);\n } else if (indexOrData !== undefined) {\n logger.warn(`[Askr][FASTPATH] ${message}`, indexOrData);\n } else {\n logger.warn(`[Askr][FASTPATH] ${message}`);\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Performance Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get current high-resolution timestamp\n */\nexport function now(): number {\n return typeof performance !== 'undefined' && performance.now\n ? performance.now()\n : Date.now();\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,gBAAgB;AAItB,MAAa,uCAAuC;AAEpD,SAAgB,kCAAk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,WAAW;CAE7B,QAAQ,CAER;AACF;;;;AAKA,SAAgB,iBACd,SACA,aACA,MACM;CACN,MAAM,MAAM,cAAc;CAC1B,IAAI,IAAI,wBAAwB,OAAO,IAAI,wBAAwB,QACjE,IAAI,SAAS,QACX,OAAO,KAAK,oBAAoB,WAAW,aAAa,IAAI;MACvD,IAAI,gBAAgB,QACzB,OAAO,KAAK,oBAAoB,WAAW,WAAW;MAEtD,OAAO,KAAK,oBAAoB,SAAS;AAG/C;;;;AASA,SAAgB,MAAc;CAC5B,OAAO,OAAO,gBAAgB,eAAe,YAAY,MACrD,YAAY,IAAI,IAChB,KAAK,IAAI;AACf"}
|
package/dist/router/match.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"match.js","names":[],"sources":["../../src/router/match.ts"],"sourcesContent":["/**\n * Path matching, segment parsing, and specificity scoring.\n */\n\nimport type { ParsedSegment } from '../common/router';\n\nexport function splitPathSegments(path: string): string[] {\n const normalized =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n\n if (!normalized || normalized === '/') {\n return [];\n }\n\n const withoutLeadingSlash = normalized.startsWith('/')\n ? normalized.slice(1)\n : normalized;\n\n return withoutLeadingSlash.length === 0 ? [] : withoutLeadingSlash.split('/');\n}\n\nexport function normalizeRouteSegmentName(value: string): string {\n return value.trim();\n}\n\n/**\n * Parse a route template path into typed segments.\n *\n * @example\n * parseSegments('/users/{id}') // [{kind:'static',value:'users'},{kind:'param',value:'id'}]\n * parseSegments('/*') // [{kind:'catchall',value:'*'}]\n * parseSegments('/posts/*') // [{kind:'static',value:'posts'},{kind:'wildcard',value:'*'}]\n * parseSegments('/files/{*path}') // [{kind:'static',value:'files'},{kind:'splat',value:'path'}]\n */\nexport function parseSegments(path: string): ParsedSegment[] {\n const normalized =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n\n const parts = normalized.split('/').filter(Boolean);\n\n // Bare catch-all: /*\n if (parts.length === 1 && parts[0] === '*') {\n return [{ kind: 'catchall', value: '*' }];\n }\n\n return parts.map((segment): ParsedSegment => {\n if (segment.startsWith('{') && segment.endsWith('}')) {\n const value = normalizeRouteSegmentName(segment.slice(1, -1));\n if (value.startsWith('*')) {\n return {\n kind: 'splat',\n value: normalizeRouteSegmentName(value.slice(1)),\n };\n }\n return { kind: 'param', value };\n }\n if (segment === '*') {\n return { kind: 'wildcard', value: '*' };\n }\n return { kind: 'static', value: segment };\n });\n}\n\n/**\n * Compute a numeric specificity rank from a parsed segment list.\n *\n * Scoring: static = 3, param = 2, wildcard = 1, catchall = 0.\n * Higher rank wins when multiple routes match the same path.\n */\nexport function computeRank(segments: ParsedSegment[]): number {\n if (segments.length === 1 && segments[0].kind === 'catchall') return -1;\n let score = 0;\n for (const seg of segments) {\n if (seg.kind === 'static') score += 3;\n else if (seg.kind === 'param') score += 2;\n else if (seg.kind === 'wildcard') score += 1;\n else if (seg.kind === 'splat') score -= 0.5;\n // catchall contributes 0 per segment but is handled above\n }\n return score;\n}\n\n/** Reused frozen empty params object — returned for purely-static (no-capture) routes. */\nconst emptyParams: Record<string, string> = Object.freeze(\n Object.create(null) as Record<string, string>\n);\n\n/** Returned for every failed match — avoids per-call allocation. */\nconst noMatch: MatchResult = Object.freeze({\n matched: false,\n params: emptyParams,\n});\n\nfunction decodeRouteParam(part: string): string {\n if (!part.includes('%')) {\n return part;\n }\n\n try {\n return decodeURIComponent(part);\n } catch {\n return part;\n }\n}\n\n/**\n * Match pre-split URL parts against pre-parsed route segments.\n *\n * This is the hot-path matcher used by `resolveRoute` and\n * `resolveRouteFromRoutes`. Callers split the URL path **once** and reuse\n * `urlParts` across all route comparisons in a single resolution call.\n *\n * - Returns a params object (possibly the shared `{}`) on match.\n * - Returns `null` on no match.\n * - Params are allocated lazily — purely-static routes return the frozen\n * empty sentinel without any heap allocation.\n */\nexport function matchSegments(\n urlParts: string[],\n segments: ParsedSegment[]\n): Record<string, string> | null {\n // catch-all /* — matches every URL at any depth\n if (segments.length === 1 && segments[0].kind === 'catchall') {\n return {\n '*':\n urlParts.length === 0\n ? '/'\n : urlParts.length === 1\n ? urlParts[0]\n : '/' + urlParts.join('/'),\n };\n }\n\n const splatIndex = segments.findIndex((segment) => segment.kind === 'splat');\n if (splatIndex !== -1) {\n if (splatIndex !== segments.length - 1) {\n return null;\n }\n if (urlParts.length < splatIndex) {\n return null;\n }\n } else if (urlParts.length !== segments.length) {\n return null;\n }\n\n // non-catchall: part count must equal segment count\n\n // Walk segments; allocate the params object lazily on first capture\n let params: Record<string, string> | null = null;\n\n const normalizeCapturedSplatParts = (parts: string[]): string[] => {\n let start = 0;\n while (start < parts.length && parts[start] === '') {\n start += 1;\n }\n\n return start === 0 ? parts : parts.slice(start);\n };\n\n for (let i = 0; i < segments.length; i++) {\n const seg = segments[i];\n const part = urlParts[i];\n if (seg.kind === 'static') {\n if (seg.value !== part) return null;\n } else if (seg.kind === 'splat') {\n if (params === null) params = {};\n params[seg.value] = normalizeCapturedSplatParts(\n urlParts.slice(i).map(decodeRouteParam)\n ).join('/');\n return params;\n } else {\n if (params === null) params = {};\n if (seg.kind === 'param') {\n params[seg.value] = decodeRouteParam(part);\n } else {\n // wildcard\n params['*'] = part;\n }\n }\n }\n return params ?? emptyParams;\n}\n\nexport interface MatchResult {\n matched: boolean;\n params: Record<string, string>;\n}\n\n/**\n * Match a path against a route pattern and extract params\n *\n * @example\n * match('/users/123', '/users/{id}')\n * // → { matched: true, params: { id: '123' } }\n *\n * match('/posts/hello-world/edit', '/posts/{slug}/{action}')\n * // → { matched: true, params: { slug: 'hello-world', action: 'edit' } }\n *\n * match('/users', '/posts/{id}')\n * // → { matched: false, params: {} }\n */\nexport function match(path: string, pattern: string): MatchResult {\n // Normalize trailing slashes\n const normalizedPath =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n const normalizedPattern =\n pattern.endsWith('/') && pattern !== '/' ? pattern.slice(0, -1) : pattern;\n\n const pathSegments = splitPathSegments(normalizedPath);\n const patternSegments = parseSegments(normalizedPattern);\n const params = matchSegments(pathSegments, patternSegments);\n\n return params === null ? noMatch : { matched: true, params };\n}\n"],"mappings":";AAMA,SAAgB,kBAAkB,MAAwB;CACxD,MAAM,aACJ,KAAK,SAAS,GAAG,KAAK,SAAS,MAAM,KAAK,MAAM,GAAG,EAAE,IAAI;CAE3D,IAAI,CAAC,cAAc,eAAe,KAChC,OAAO,CAAC;CAGV,MAAM,sBAAsB,WAAW,WAAW,GAAG,IACjD,WAAW,MAAM,CAAC,IAClB;CAEJ,OAAO,oBAAoB,WAAW,IAAI,CAAC,IAAI,oBAAoB,MAAM,GAAG;AAC9E;AAEA,SAAgB,0BAA0B,OAAuB;CAC/D,OAAO,MAAM,KAAK;AACpB;;;;;;;;;;AAWA,SAAgB,cAAc,MAA+B;CAI3D,MAAM,SAFJ,KAAK,SAAS,GAAG,KAAK,SAAS,MAAM,KAAK,MAAM,GAAG,EAAE,IAAI,
|
|
1
|
+
{"version":3,"file":"match.js","names":[],"sources":["../../src/router/match.ts"],"sourcesContent":["/**\n * Path matching, segment parsing, and specificity scoring.\n */\n\nimport type { ParsedSegment } from '../common/router';\n\nexport function splitPathSegments(path: string): string[] {\n const normalized =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n\n if (!normalized || normalized === '/') {\n return [];\n }\n\n const withoutLeadingSlash = normalized.startsWith('/')\n ? normalized.slice(1)\n : normalized;\n\n return withoutLeadingSlash.length === 0 ? [] : withoutLeadingSlash.split('/');\n}\n\nexport function normalizeRouteSegmentName(value: string): string {\n return value.trim();\n}\n\n/**\n * Parse a route template path into typed segments.\n *\n * @example\n * parseSegments('/users/{id}') // [{kind:'static',value:'users'},{kind:'param',value:'id'}]\n * parseSegments('/*') // [{kind:'catchall',value:'*'}]\n * parseSegments('/posts/*') // [{kind:'static',value:'posts'},{kind:'wildcard',value:'*'}]\n * parseSegments('/files/{*path}') // [{kind:'static',value:'files'},{kind:'splat',value:'path'}]\n */\nexport function parseSegments(path: string): ParsedSegment[] {\n const normalized =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n\n const parts = normalized.split('/').filter(Boolean);\n\n // Bare catch-all: /*\n if (parts.length === 1 && parts[0] === '*') {\n return [{ kind: 'catchall', value: '*' }];\n }\n\n return parts.map((segment): ParsedSegment => {\n if (segment.startsWith('{') && segment.endsWith('}')) {\n const value = normalizeRouteSegmentName(segment.slice(1, -1));\n if (value.startsWith('*')) {\n return {\n kind: 'splat',\n value: normalizeRouteSegmentName(value.slice(1)),\n };\n }\n return { kind: 'param', value };\n }\n if (segment === '*') {\n return { kind: 'wildcard', value: '*' };\n }\n return { kind: 'static', value: segment };\n });\n}\n\n/**\n * Compute a numeric specificity rank from a parsed segment list.\n *\n * Scoring: static = 3, param = 2, wildcard = 1, catchall = 0.\n * Higher rank wins when multiple routes match the same path.\n */\nexport function computeRank(segments: ParsedSegment[]): number {\n if (segments.length === 1 && segments[0].kind === 'catchall') return -1;\n let score = 0;\n for (const seg of segments) {\n if (seg.kind === 'static') score += 3;\n else if (seg.kind === 'param') score += 2;\n else if (seg.kind === 'wildcard') score += 1;\n else if (seg.kind === 'splat') score -= 0.5;\n // catchall contributes 0 per segment but is handled above\n }\n return score;\n}\n\n/** Reused frozen empty params object — returned for purely-static (no-capture) routes. */\nconst emptyParams: Record<string, string> = Object.freeze(\n Object.create(null) as Record<string, string>\n);\n\n/** Returned for every failed match — avoids per-call allocation. */\nconst noMatch: MatchResult = Object.freeze({\n matched: false,\n params: emptyParams,\n});\n\nfunction decodeRouteParam(part: string): string {\n if (!part.includes('%')) {\n return part;\n }\n\n try {\n return decodeURIComponent(part);\n } catch {\n return part;\n }\n}\n\n/**\n * Match pre-split URL parts against pre-parsed route segments.\n *\n * This is the hot-path matcher used by `resolveRoute` and\n * `resolveRouteFromRoutes`. Callers split the URL path **once** and reuse\n * `urlParts` across all route comparisons in a single resolution call.\n *\n * - Returns a params object (possibly the shared `{}`) on match.\n * - Returns `null` on no match.\n * - Params are allocated lazily — purely-static routes return the frozen\n * empty sentinel without any heap allocation.\n */\nexport function matchSegments(\n urlParts: string[],\n segments: ParsedSegment[]\n): Record<string, string> | null {\n // catch-all /* — matches every URL at any depth\n if (segments.length === 1 && segments[0].kind === 'catchall') {\n return {\n '*':\n urlParts.length === 0\n ? '/'\n : urlParts.length === 1\n ? urlParts[0]\n : '/' + urlParts.join('/'),\n };\n }\n\n const splatIndex = segments.findIndex((segment) => segment.kind === 'splat');\n if (splatIndex !== -1) {\n if (splatIndex !== segments.length - 1) {\n return null;\n }\n if (urlParts.length < splatIndex) {\n return null;\n }\n } else if (urlParts.length !== segments.length) {\n return null;\n }\n\n // non-catchall: part count must equal segment count\n\n // Walk segments; allocate the params object lazily on first capture\n let params: Record<string, string> | null = null;\n\n const normalizeCapturedSplatParts = (parts: string[]): string[] => {\n let start = 0;\n while (start < parts.length && parts[start] === '') {\n start += 1;\n }\n\n return start === 0 ? parts : parts.slice(start);\n };\n\n for (let i = 0; i < segments.length; i++) {\n const seg = segments[i];\n const part = urlParts[i];\n if (seg.kind === 'static') {\n if (seg.value !== part) return null;\n } else if (seg.kind === 'splat') {\n if (params === null) params = {};\n params[seg.value] = normalizeCapturedSplatParts(\n urlParts.slice(i).map(decodeRouteParam)\n ).join('/');\n return params;\n } else {\n if (params === null) params = {};\n if (seg.kind === 'param') {\n params[seg.value] = decodeRouteParam(part);\n } else {\n // wildcard\n params['*'] = part;\n }\n }\n }\n return params ?? emptyParams;\n}\n\nexport interface MatchResult {\n matched: boolean;\n params: Record<string, string>;\n}\n\n/**\n * Match a path against a route pattern and extract params\n *\n * @example\n * match('/users/123', '/users/{id}')\n * // → { matched: true, params: { id: '123' } }\n *\n * match('/posts/hello-world/edit', '/posts/{slug}/{action}')\n * // → { matched: true, params: { slug: 'hello-world', action: 'edit' } }\n *\n * match('/users', '/posts/{id}')\n * // → { matched: false, params: {} }\n */\nexport function match(path: string, pattern: string): MatchResult {\n // Normalize trailing slashes\n const normalizedPath =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n const normalizedPattern =\n pattern.endsWith('/') && pattern !== '/' ? pattern.slice(0, -1) : pattern;\n\n const pathSegments = splitPathSegments(normalizedPath);\n const patternSegments = parseSegments(normalizedPattern);\n const params = matchSegments(pathSegments, patternSegments);\n\n return params === null ? noMatch : { matched: true, params };\n}\n"],"mappings":";AAMA,SAAgB,kBAAkB,MAAwB;CACxD,MAAM,aACJ,KAAK,SAAS,GAAG,KAAK,SAAS,MAAM,KAAK,MAAM,GAAG,EAAE,IAAI;CAE3D,IAAI,CAAC,cAAc,eAAe,KAChC,OAAO,CAAC;CAGV,MAAM,sBAAsB,WAAW,WAAW,GAAG,IACjD,WAAW,MAAM,CAAC,IAClB;CAEJ,OAAO,oBAAoB,WAAW,IAAI,CAAC,IAAI,oBAAoB,MAAM,GAAG;AAC9E;AAEA,SAAgB,0BAA0B,OAAuB;CAC/D,OAAO,MAAM,KAAK;AACpB;;;;;;;;;;AAWA,SAAgB,cAAc,MAA+B;CAI3D,MAAM,SAFJ,KAAK,SAAS,GAAG,KAAK,SAAS,MAAM,KAAK,MAAM,GAAG,EAAE,IAAI,KAE7C,CAAW,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO;CAGlD,IAAI,MAAM,WAAW,KAAK,MAAM,OAAO,KACrC,OAAO,CAAC;EAAE,MAAM;EAAY,OAAO;CAAI,CAAC;CAG1C,OAAO,MAAM,KAAK,YAA2B;EAC3C,IAAI,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,GAAG,GAAG;GACpD,MAAM,QAAQ,0BAA0B,QAAQ,MAAM,GAAG,EAAE,CAAC;GAC5D,IAAI,MAAM,WAAW,GAAG,GACtB,OAAO;IACL,MAAM;IACN,OAAO,0BAA0B,MAAM,MAAM,CAAC,CAAC;GACjD;GAEF,OAAO;IAAE,MAAM;IAAS;GAAM;EAChC;EACA,IAAI,YAAY,KACd,OAAO;GAAE,MAAM;GAAY,OAAO;EAAI;EAExC,OAAO;GAAE,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,SAAS,QAAQ,KAAK;EACxC,MAAM,MAAM,SAAS;EACrB,MAAM,OAAO,SAAS;EACtB,IAAI,IAAI,SAAS,UACf;OAAI,IAAI,UAAU,MAAM,OAAO;EAAA,OAC1B,IAAI,IAAI,SAAS,SAAS;GAC/B,IAAI,WAAW,MAAM,SAAS,CAAC;GAC/B,OAAO,IAAI,SAAS,4BAClB,SAAS,MAAM,CAAC,CAAC,CAAC,IAAI,gBAAgB,CACxC,CAAC,CAAC,KAAK,GAAG;GACV,OAAO;EACT,OAAO;GACL,IAAI,WAAW,MAAM,SAAS,CAAC;GAC/B,IAAI,IAAI,SAAS,SACf,OAAO,IAAI,SAAS,iBAAiB,IAAI;QAGzC,OAAO,OAAO;EAElB;CACF;CACA,OAAO,UAAU;AACnB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"navigate.js","names":[],"sources":["../../src/router/navigate.ts"],"sourcesContent":["/**\n * Client-side navigation with History API\n */\n\nimport {\n computeRouteActivityMatches,\n resolveRouteRequest,\n resolveRouteFromRoutes,\n lockRouteRegistration,\n syncCurrentRouteSnapshot,\n type ResolvedRoute,\n} from './route';\nimport {\n cleanupComponent,\n mountComponent,\n type ComponentInstance,\n} from '../runtime/component';\nimport {\n isDevelopmentEnvironment,\n isProductionEnvironment,\n} from '../common/env';\nimport { logger } from '../dev/logger';\nimport type {\n Route,\n RouteAuthOptions,\n RouteManifest,\n RouteRenderResult,\n RouteRequestResult,\n} from '../common/router';\nimport { Fragment, ELEMENT_TYPE } from '../jsx';\nimport {\n DefaultPortal,\n clearDefaultPortalForInstance,\n} from '../foundations/structures/portal';\nimport { isPromiseLike } from '../common/promise';\nimport { cleanupInstancesUnder } from '../renderer/cleanup';\n\n// Global app state for navigation\nlet currentInstance: ComponentInstance | null = null;\nlet currentPathname = '/';\nlet currentHref = '/';\nlet navigationInitialized = false;\nlet activeRouteRequestId = 0;\nlet activeRouteRequestController: AbortController | null = null;\nconst MAX_NAVIGATION_REDIRECTS = 20;\n\ntype AppNavigationSource = {\n manifest?: RouteManifest;\n routes?: readonly Route[];\n auth?: RouteAuthOptions;\n};\n\ntype AppRegistration = AppNavigationSource & {\n instance: ComponentInstance;\n pathname: string;\n href: string;\n};\n\nconst registeredApps: AppRegistration[] = [];\n\nfunction collectRouteActivityMatches(\n pathname: string,\n apps: readonly AppRegistration[] = registeredApps\n) {\n const matches: ReturnType<typeof computeRouteActivityMatches> = [];\n const seenPaths = new Set<string>();\n\n for (const app of apps) {\n const appMatches = computeRouteActivityMatches(pathname, {\n manifest: app.manifest,\n routes: app.routes,\n });\n\n for (const match of appMatches) {\n if (seenPaths.has(match.path)) {\n continue;\n }\n seenPaths.add(match.path);\n matches.push(match);\n }\n }\n\n return matches;\n}\n\nfunction syncRegisteredRouteSnapshot(): void {\n if (typeof window === 'undefined') {\n return;\n }\n\n const pathname = window.location.pathname || '/';\n syncCurrentRouteSnapshot(\n pathname,\n window.location.search || '',\n window.location.hash || '',\n collectRouteActivityMatches(pathname)\n );\n}\n\nfunction syncAppRegistrationLocation(\n app: AppRegistration,\n pathname: string,\n href: string\n): void {\n app.pathname = pathname;\n app.href = href;\n}\n\nexport type NavigationScrollBehavior = 'top' | 'preserve';\nexport type HistoryScrollBehavior = 'restore' | 'top' | 'preserve';\n\nexport type ScrollRestorationOptions = {\n navigation?: NavigationScrollBehavior;\n history?: HistoryScrollBehavior;\n};\n\ntype NormalizedScrollRestorationOptions = {\n enabled: boolean;\n navigation: NavigationScrollBehavior;\n history: HistoryScrollBehavior;\n};\n\nconst DEFAULT_SCROLL_RESTORATION: NormalizedScrollRestorationOptions = {\n enabled: true,\n navigation: 'top',\n history: 'restore',\n};\n\nlet scrollRestorationOptions: NormalizedScrollRestorationOptions = {\n ...DEFAULT_SCROLL_RESTORATION,\n};\n\nconst scrollPositions = new Map<string, { x: number; y: number }>();\n\nexport type NavigateOptions = {\n history?: 'push' | 'replace';\n replace?: boolean;\n scroll?: NavigationScrollBehavior;\n};\n\nfunction getWindowHref(): string {\n if (typeof window === 'undefined') {\n return currentHref;\n }\n\n return `${window.location.pathname}${window.location.search}${window.location.hash}`;\n}\n\nfunction normalizeScrollRestorationOptions(\n options?: boolean | ScrollRestorationOptions\n): NormalizedScrollRestorationOptions {\n if (options === false) {\n return {\n enabled: false,\n navigation: DEFAULT_SCROLL_RESTORATION.navigation,\n history: DEFAULT_SCROLL_RESTORATION.history,\n };\n }\n\n if (options === true || options === undefined) {\n return { ...DEFAULT_SCROLL_RESTORATION };\n }\n\n return {\n enabled: true,\n navigation: options.navigation ?? DEFAULT_SCROLL_RESTORATION.navigation,\n history: options.history ?? DEFAULT_SCROLL_RESTORATION.history,\n };\n}\n\nfunction readScrollPosition(): { x: number; y: number } {\n if (typeof window === 'undefined') {\n return { x: 0, y: 0 };\n }\n\n const x =\n typeof window.scrollX === 'number'\n ? window.scrollX\n : typeof window.pageXOffset === 'number'\n ? window.pageXOffset\n : 0;\n const y =\n typeof window.scrollY === 'number'\n ? window.scrollY\n : typeof window.pageYOffset === 'number'\n ? window.pageYOffset\n : 0;\n\n return { x, y };\n}\n\nfunction writeHistoryScrollPosition(\n href: string,\n position: { x: number; y: number }\n): void {\n if (typeof window === 'undefined' || getWindowHref() !== href) {\n return;\n }\n if (typeof window.history?.replaceState !== 'function') {\n return;\n }\n const state =\n window.history.state && typeof window.history.state === 'object'\n ? window.history.state\n : {};\n\n window.history.replaceState(\n {\n ...state,\n path: href,\n scroll: position,\n },\n '',\n href\n );\n}\n\nfunction saveScrollPosition(href: string): void {\n if (!scrollRestorationOptions.enabled || typeof window === 'undefined') {\n return;\n }\n\n const position = readScrollPosition();\n scrollPositions.set(href, position);\n writeHistoryScrollPosition(href, position);\n}\n\nfunction scrollToPosition(position: { x: number; y: number }): void {\n if (typeof window === 'undefined' || typeof window.scrollTo !== 'function') {\n return;\n }\n\n window.scrollTo(position.x, position.y);\n}\n\nfunction applyNavigationScroll(behavior: NavigationScrollBehavior): void {\n if (!scrollRestorationOptions.enabled || behavior === 'preserve') {\n return;\n }\n\n scrollToPosition({ x: 0, y: 0 });\n}\n\nfunction applyHistoryScroll(href: string, state: PopStateEvent['state']): void {\n if (!scrollRestorationOptions.enabled) {\n return;\n }\n\n if (scrollRestorationOptions.history === 'preserve') {\n return;\n }\n\n if (scrollRestorationOptions.history === 'top') {\n scrollToPosition({ x: 0, y: 0 });\n return;\n }\n\n const fromState =\n state && typeof state === 'object' && 'scroll' in state\n ? (state.scroll as { x?: unknown; y?: unknown })\n : undefined;\n const saved =\n fromState &&\n typeof fromState.x === 'number' &&\n typeof fromState.y === 'number'\n ? { x: fromState.x, y: fromState.y }\n : scrollPositions.get(href);\n\n scrollToPosition(saved ?? { x: 0, y: 0 });\n}\n\nexport function configureScrollRestoration(\n options?: boolean | ScrollRestorationOptions\n): void {\n scrollRestorationOptions = normalizeScrollRestorationOptions(options);\n\n if (typeof window === 'undefined') {\n return;\n }\n\n if ('scrollRestoration' in window.history) {\n try {\n window.history.scrollRestoration = scrollRestorationOptions.enabled\n ? 'manual'\n : 'auto';\n } catch {\n // Ignore environments that expose but do not allow setting scrollRestoration.\n }\n }\n}\n\nfunction parseTargetUrl(path: string): URL {\n const pathname = window.location.pathname || '/';\n const search = window.location.search || '';\n const hash = window.location.hash || '';\n const href =\n typeof window.location.href === 'string' ? window.location.href : '';\n const base =\n href &&\n href !== 'about:blank' &&\n !href.startsWith('about:') &&\n !href.startsWith('data:')\n ? href\n : `http://localhost${pathname}${search}${hash}`;\n\n return new URL(path, base);\n}\n\nfunction isRenderResult(\n result: RouteRequestResult\n): result is RouteRenderResult {\n return result !== null && result.kind === 'render';\n}\n\nfunction getRedirectHistoryMode(\n replace: boolean | undefined\n): 'push' | 'replace' {\n return replace === false ? 'push' : 'replace';\n}\n\nfunction getNavigationHistoryMode(\n options: NavigateOptions\n): 'push' | 'replace' {\n if (options.history) {\n return options.history;\n }\n\n return options.replace ? 'replace' : 'push';\n}\n\nfunction beginRouteRequest(): { id: number; signal: AbortSignal } {\n activeRouteRequestId += 1;\n activeRouteRequestController?.abort();\n activeRouteRequestController = new AbortController();\n\n return {\n id: activeRouteRequestId,\n signal: activeRouteRequestController.signal,\n };\n}\n\nfunction isStaleRouteRequest(requestId: number): boolean {\n return requestId !== activeRouteRequestId;\n}\n\nfunction createDeniedResolvedRoute(status: number): ResolvedRoute {\n return {\n handler: () => ({\n type: 'div',\n props: {\n 'data-route-denied': String(status),\n },\n children: [String(status)],\n }),\n params: {},\n };\n}\n\nfunction bindResolvedRouteHandler(\n resolved: ResolvedRoute\n): ComponentInstance['fn'] {\n return () =>\n resolved.handler(resolved.params) as ReturnType<ComponentInstance['fn']>;\n}\n\nfunction wrapRootRouteHandler(\n componentFn: ComponentInstance['fn']\n): ComponentInstance['fn'] {\n const wrappedFn: ComponentInstance['fn'] = (props, ctx) => {\n const out = componentFn(props, ctx);\n if (isPromiseLike(out)) {\n throw new Error(\n 'Async components are not supported. Components must return synchronously.'\n );\n }\n const portalVNode = {\n $$typeof: ELEMENT_TYPE,\n type: DefaultPortal,\n props: {},\n key: '__default_portal',\n } as unknown;\n\n return {\n $$typeof: ELEMENT_TYPE,\n type: Fragment,\n props: {\n children:\n out === undefined || out === null\n ? [portalVNode]\n : [out, portalVNode],\n },\n } as ReturnType<ComponentInstance['fn']>;\n };\n\n Object.defineProperty(wrappedFn, 'name', {\n value: componentFn.name || 'Component',\n });\n\n return wrappedFn;\n}\n\nfunction cleanupRouteOwnership(instance: ComponentInstance): void {\n const cleanupErrors: unknown[] = [];\n const children = instance.target\n ? Array.from(instance.target.childNodes)\n : [];\n\n for (const child of children) {\n try {\n cleanupInstancesUnder(child, { strict: instance.cleanupStrict });\n } catch (error) {\n cleanupErrors.push(error);\n }\n }\n\n try {\n cleanupComponent(instance);\n } catch (error) {\n cleanupErrors.push(error);\n }\n\n if (cleanupErrors.length > 0) {\n throw new AggregateError(cleanupErrors, 'Route cleanup failed');\n }\n}\n\nfunction remountResolvedRoute(\n instance: ComponentInstance,\n resolved: ResolvedRoute,\n pathname: string,\n href: string\n): boolean {\n // The route handler IS the component function\n // It takes params as props and renders the route\n clearDefaultPortalForInstance(instance);\n cleanupRouteOwnership(instance);\n\n instance.fn = wrapRootRouteHandler(bindResolvedRouteHandler(resolved));\n instance.props = {};\n\n // Reset state to prevent leakage from previous route\n // Each route navigation starts completely fresh\n instance.stateValues = [];\n instance.expectedStateIndices = [];\n instance.firstRenderComplete = false;\n instance.stateIndexCheck = -1;\n // Increment generation to invalidate pending async evaluations from previous route\n instance.evaluationGeneration++;\n instance.notifyUpdate = null;\n instance.mountOperations = [];\n instance.commitOperations = [];\n instance.lifecycleSlots = [];\n instance.cleanupFns = [];\n instance._placeholder = undefined;\n instance.hasPendingUpdate = false;\n instance._currentRenderToken = undefined;\n instance.lastRenderToken = 0;\n instance._pendingReadSources = undefined;\n instance._lastReadSources = undefined;\n\n // Route-local async work should create a fresh abort controller lazily.\n instance.abortController = null;\n\n // Re-execute component against the existing host so reconciliation can\n // preserve any shared layout DOM between sibling routes.\n mountComponent(instance);\n currentPathname = pathname;\n currentHref = href;\n return true;\n}\n\nfunction rerenderResolvedRoute(\n instance: ComponentInstance,\n pathname: string,\n href: string\n): boolean {\n currentPathname = pathname;\n currentHref = href;\n instance._enqueueRun?.();\n return true;\n}\n\nfunction resolveAppRouteRequest(\n app: AppRegistration,\n pathname: string,\n href: string,\n signal: AbortSignal\n): RouteRequestResult | Promise<RouteRequestResult> {\n if (app.routes) {\n const resolved = resolveRouteFromRoutes(pathname, app.routes);\n if (!resolved) {\n return null;\n }\n\n return {\n kind: 'render',\n handler: resolved.handler,\n params: resolved.params,\n };\n }\n\n return resolveRouteRequest(href, {\n manifest: app.manifest,\n auth: app.auth,\n signal,\n });\n}\n\ntype AppNavigationTarget = {\n app: AppRegistration;\n resolved: RouteRequestResult;\n};\n\nfunction resolveNavigationTargetsForApps(\n pathname: string,\n href: string,\n signal: AbortSignal\n): AppNavigationTarget[] | Promise<AppNavigationTarget[]> {\n const apps = [...registeredApps];\n\n if (apps.length === 1) {\n const app = apps[0]!;\n const resolved = resolveAppRouteRequest(app, pathname, href, signal);\n if (isPromiseLike<RouteRequestResult>(resolved)) {\n return Promise.resolve(resolved).then((next) => [\n {\n app,\n resolved: next,\n },\n ]);\n }\n\n return [\n {\n app,\n resolved,\n },\n ];\n }\n\n const syncTargets: AppNavigationTarget[] = [];\n const pendingTargets: Array<Promise<AppNavigationTarget>> = [];\n\n for (const app of apps) {\n const resolved = resolveAppRouteRequest(app, pathname, href, signal);\n if (isPromiseLike<RouteRequestResult>(resolved)) {\n pendingTargets.push(\n Promise.resolve(resolved).then((next) => ({ app, resolved: next }))\n );\n continue;\n }\n\n syncTargets.push({ app, resolved });\n }\n\n if (pendingTargets.length === 0) {\n return syncTargets;\n }\n\n return Promise.all([\n ...syncTargets.map((target) => Promise.resolve(target)),\n ...pendingTargets,\n ]);\n}\n\nfunction applyNavigationTargets(\n path: string,\n options: NavigateOptions,\n redirectState: NavigationRedirectState,\n pathname: string,\n href: string,\n targets: AppNavigationTarget[]\n): void {\n const previousPathname = currentPathname;\n\n for (const target of targets) {\n const resolved = target.resolved;\n if (!resolved || resolved.kind !== 'redirect') {\n continue;\n }\n\n const redirectTarget = parseTargetUrl(resolved.to);\n const redirectHref = `${redirectTarget.pathname}${redirectTarget.search}${redirectTarget.hash}`;\n if (redirectHref === href) {\n if (isDevelopmentEnvironment()) {\n logger.warn(\n `Navigation guard redirected to the same path: ${redirectHref}`\n );\n }\n return;\n }\n\n if (redirectState.visited.has(redirectHref)) {\n throw new Error(\n `[Askr] Navigation redirect cycle detected at ${redirectHref}.`\n );\n }\n if (redirectState.redirects >= MAX_NAVIGATION_REDIRECTS) {\n throw new Error(\n `[Askr] Navigation redirect limit exceeded (${MAX_NAVIGATION_REDIRECTS}).`\n );\n }\n\n redirectState.visited.add(redirectHref);\n redirectState.redirects++;\n navigateWithRedirectState(\n redirectHref,\n {\n history: getRedirectHistoryMode(resolved.replace),\n },\n redirectState\n );\n return;\n }\n\n const matchedTargets = targets.filter((target) => target.resolved !== null);\n if (matchedTargets.length === 0) {\n if (isDevelopmentEnvironment()) {\n logger.warn(`No route found for path: ${path}`);\n }\n return;\n }\n\n saveScrollPosition(currentHref);\n\n const historyMethod =\n getNavigationHistoryMode(options) === 'replace'\n ? 'replaceState'\n : 'pushState';\n window.history[historyMethod]({ path: href }, '', href);\n syncRegisteredRouteSnapshot();\n\n for (const target of matchedTargets) {\n const resolved = target.resolved!;\n if (resolved.kind === 'redirect') {\n continue;\n }\n\n if (pathname === target.app.pathname && isRenderResult(resolved)) {\n rerenderResolvedRoute(target.app.instance, pathname, href);\n syncAppRegistrationLocation(target.app, pathname, href);\n continue;\n }\n\n remountResolvedRoute(\n target.app.instance,\n resolved.kind === 'deny'\n ? createDeniedResolvedRoute(resolved.status)\n : {\n handler: resolved.handler,\n params: resolved.params,\n },\n pathname,\n href\n );\n syncAppRegistrationLocation(target.app, pathname, href);\n }\n\n if (pathname !== previousPathname) {\n applyNavigationScroll(\n options.scroll ?? scrollRestorationOptions.navigation\n );\n }\n}\n\n/** Register the current app instance (called by createSPA/hydrateSPA). */\nexport function registerAppInstance(\n instance: ComponentInstance,\n path: string,\n source: AppNavigationSource = {}\n): void {\n const existingIndex = registeredApps.findIndex(\n (app) => app.instance === instance\n );\n const registration: AppRegistration = {\n instance,\n pathname: path,\n href: getWindowHref(),\n ...source,\n };\n if (existingIndex >= 0) {\n registeredApps[existingIndex] = registration;\n } else {\n registeredApps.push(registration);\n }\n\n currentInstance = instance;\n currentPathname = path;\n currentHref = getWindowHref();\n syncRegisteredRouteSnapshot();\n // Lock further route registrations after the app has started — but allow tests to register routes.\n // Enforce only in production to avoid breaking test infra which registers routes dynamically.\n if (isProductionEnvironment()) {\n lockRouteRegistration();\n }\n}\n\nexport function unregisterAppInstance(instance: ComponentInstance): void {\n const existingIndex = registeredApps.findIndex(\n (app) => app.instance === instance\n );\n if (existingIndex >= 0) {\n registeredApps.splice(existingIndex, 1);\n }\n syncRegisteredRouteSnapshot();\n\n if (currentInstance !== instance) {\n return;\n }\n\n const nextApp =\n registeredApps.length > 0\n ? registeredApps[registeredApps.length - 1]!\n : null;\n currentInstance = nextApp?.instance ?? null;\n if (nextApp) {\n currentPathname = nextApp.pathname;\n currentHref = nextApp.href;\n syncRegisteredRouteSnapshot();\n return;\n }\n\n activeRouteRequestId += 1;\n activeRouteRequestController?.abort();\n activeRouteRequestController = null;\n currentPathname = '/';\n currentHref = '/';\n if (typeof window === 'undefined') {\n syncCurrentRouteSnapshot('/', '', '', []);\n }\n}\n\n/**\n * Navigate to a new path\n * Updates URL, resolves route, and re-mounts app with new handler\n */\nexport function navigate(path: string, options: NavigateOptions = {}): void {\n if (typeof window === 'undefined') {\n return;\n }\n\n const initialTarget = parseTargetUrl(path);\n navigateWithRedirectState(path, options, {\n redirects: 0,\n visited: new Set([\n `${initialTarget.pathname}${initialTarget.search}${initialTarget.hash}`,\n ]),\n });\n}\n\ntype NavigationRedirectState = {\n redirects: number;\n visited: Set<string>;\n};\n\nfunction navigateWithRedirectState(\n path: string,\n options: NavigateOptions,\n redirectState: NavigationRedirectState\n): void {\n if (typeof window === 'undefined') {\n // SSR context\n return;\n }\n\n const request = beginRouteRequest();\n\n const target = parseTargetUrl(path);\n const pathname = target.pathname;\n const href = `${target.pathname}${target.search}${target.hash}`;\n const resolvedTargets = resolveNavigationTargetsForApps(\n pathname,\n href,\n request.signal\n );\n\n if (isPromiseLike(resolvedTargets)) {\n void Promise.resolve(resolvedTargets).then(\n (targets) => {\n if (isStaleRouteRequest(request.id)) {\n return;\n }\n\n try {\n applyNavigationTargets(\n path,\n options,\n redirectState,\n pathname,\n href,\n targets\n );\n } catch (error) {\n logger.error('[Askr] navigation failed:', error);\n }\n },\n (error) => {\n logger.error('[Askr] navigation failed:', error);\n }\n );\n return;\n }\n\n applyNavigationTargets(\n path,\n options,\n redirectState,\n pathname,\n href,\n resolvedTargets\n );\n}\n\n/**\n * Handle browser back/forward buttons\n */\nfunction handlePopState(_event: PopStateEvent): void {\n const request = beginRouteRequest();\n const previousHref = currentHref;\n const pathname = window.location.pathname;\n const href = `${window.location.pathname}${window.location.search}${window.location.hash}`;\n\n saveScrollPosition(previousHref);\n\n if (registeredApps.length === 0) {\n return;\n }\n\n const applyResolved = (targets: AppNavigationTarget[]) => {\n if (isStaleRouteRequest(request.id)) {\n return;\n }\n\n const matchedTargets = targets.filter((target) => target.resolved !== null);\n if (matchedTargets.length === 0) {\n if (isDevelopmentEnvironment()) {\n logger.warn(`No route found for path: ${pathname}`);\n }\n return;\n }\n\n for (const target of matchedTargets) {\n const resolved = target.resolved!;\n if (resolved.kind !== 'redirect') {\n continue;\n }\n\n navigate(resolved.to, {\n history: getRedirectHistoryMode(resolved.replace),\n });\n return;\n }\n\n syncRegisteredRouteSnapshot();\n\n for (const target of matchedTargets) {\n const resolved = target.resolved!;\n if (pathname === target.app.pathname && isRenderResult(resolved)) {\n rerenderResolvedRoute(target.app.instance, pathname, href);\n syncAppRegistrationLocation(target.app, pathname, href);\n continue;\n }\n\n if (resolved.kind === 'redirect') {\n continue;\n }\n\n remountResolvedRoute(\n target.app.instance,\n resolved.kind === 'deny'\n ? createDeniedResolvedRoute(resolved.status)\n : {\n handler: resolved.handler,\n params: resolved.params,\n },\n pathname,\n href\n );\n syncAppRegistrationLocation(target.app, pathname, href);\n }\n\n applyHistoryScroll(href, _event.state);\n };\n\n const resolvedTargets = resolveNavigationTargetsForApps(\n pathname,\n href,\n request.signal\n );\n\n if (isPromiseLike<AppNavigationTarget[]>(resolvedTargets)) {\n void Promise.resolve(resolvedTargets).then(\n (next) => {\n try {\n applyResolved(next);\n } catch (error) {\n logger.error('[Askr] popstate navigation failed:', error);\n }\n },\n (error) => {\n logger.error('[Askr] popstate navigation failed:', error);\n }\n );\n return;\n }\n\n applyResolved(resolvedTargets);\n}\n\n/**\n * Setup popstate listener for browser navigation\n */\nexport function initializeNavigation(): void {\n if (typeof window === 'undefined' || navigationInitialized) {\n return;\n }\n\n navigationInitialized = true;\n window.addEventListener('popstate', handlePopState);\n}\n\n/**\n * Cleanup navigation listeners\n */\nexport function cleanupNavigation(): void {\n activeRouteRequestId += 1;\n activeRouteRequestController?.abort();\n activeRouteRequestController = null;\n\n if (typeof window === 'undefined' || !navigationInitialized) {\n return;\n }\n\n navigationInitialized = false;\n window.removeEventListener('popstate', handlePopState);\n}\n"],"mappings":";;;;;;;;;;;;;AAsCA,IAAI,kBAA4C;AAChD,IAAI,kBAAkB;AACtB,IAAI,cAAc;AAClB,IAAI,wBAAwB;AAC5B,IAAI,uBAAuB;AAC3B,IAAI,+BAAuD;AAC3D,MAAM,2BAA2B;AAcjC,MAAM,iBAAoC,CAAC;AAE3C,SAAS,4BACP,UACA,OAAmC,gBACnC;CACA,MAAM,UAA0D,CAAC;CACjE,MAAM,4BAAY,IAAI,IAAY;CAElC,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,aAAa,4BAA4B,UAAU;GACvD,UAAU,IAAI;GACd,QAAQ,IAAI;EACd,CAAC;EAED,KAAK,MAAM,SAAS,YAAY;GAC9B,IAAI,UAAU,IAAI,MAAM,IAAI,GAC1B;GAEF,UAAU,IAAI,MAAM,IAAI;GACxB,QAAQ,KAAK,KAAK;EACpB;CACF;CAEA,OAAO;AACT;AAEA,SAAS,8BAAoC;CAC3C,IAAI,OAAO,WAAW,aACpB;CAGF,MAAM,WAAW,OAAO,SAAS,YAAY;CAC7C,yBACE,UACA,OAAO,SAAS,UAAU,IAC1B,OAAO,SAAS,QAAQ,IACxB,4BAA4B,QAAQ,CACtC;AACF;AAEA,SAAS,4BACP,KACA,UACA,MACM;CACN,IAAI,WAAW;CACf,IAAI,OAAO;AACb;AAgBA,MAAM,6BAAiE;CACrE,SAAS;CACT,YAAY;CACZ,SAAS;AACX;AAEA,IAAI,2BAA+D,EACjE,GAAG,2BACL;AAEA,MAAM,kCAAkB,IAAI,IAAsC;AAQlE,SAAS,gBAAwB;CAC/B,IAAI,OAAO,WAAW,aACpB,OAAO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,QAAQ,MACV;CAEA,IAAI,cAAqC,eAAe,GAAG;EACzD,AAAK,QAAQ,QAAQ,eAAe,EAAE,MACnC,SAAS;GACR,IAAI;IACF,cAAc,IAAI;GACpB,SAAS,OAAO;IACd,OAAO,MAAM,sCAAsC,KAAK;GAC1D;EACF,IACC,UAAU;GACT,OAAO,MAAM,sCAAsC,KAAK;EAC1D,CACF;EACA;CACF;CAEA,cAAc,eAAe;AAC/B;;;;AAKA,SAAgB,uBAA6B;CAC3C,IAAI,OAAO,WAAW,eAAe,uBACnC;CAGF,wBAAwB;CACxB,OAAO,iBAAiB,YAAY,cAAc;AACpD"}
|
|
1
|
+
{"version":3,"file":"navigate.js","names":[],"sources":["../../src/router/navigate.ts"],"sourcesContent":["/**\n * Client-side navigation with History API\n */\n\nimport {\n computeRouteActivityMatches,\n resolveRouteRequest,\n resolveRouteFromRoutes,\n lockRouteRegistration,\n syncCurrentRouteSnapshot,\n type ResolvedRoute,\n} from './route';\nimport {\n cleanupComponent,\n mountComponent,\n type ComponentInstance,\n} from '../runtime/component';\nimport {\n isDevelopmentEnvironment,\n isProductionEnvironment,\n} from '../common/env';\nimport { logger } from '../dev/logger';\nimport type {\n Route,\n RouteAuthOptions,\n RouteManifest,\n RouteRenderResult,\n RouteRequestResult,\n} from '../common/router';\nimport { Fragment, ELEMENT_TYPE } from '../jsx';\nimport {\n DefaultPortal,\n clearDefaultPortalForInstance,\n} from '../foundations/structures/portal';\nimport { isPromiseLike } from '../common/promise';\nimport { cleanupInstancesUnder } from '../renderer/cleanup';\n\n// Global app state for navigation\nlet currentInstance: ComponentInstance | null = null;\nlet currentPathname = '/';\nlet currentHref = '/';\nlet navigationInitialized = false;\nlet activeRouteRequestId = 0;\nlet activeRouteRequestController: AbortController | null = null;\nconst MAX_NAVIGATION_REDIRECTS = 20;\n\ntype AppNavigationSource = {\n manifest?: RouteManifest;\n routes?: readonly Route[];\n auth?: RouteAuthOptions;\n};\n\ntype AppRegistration = AppNavigationSource & {\n instance: ComponentInstance;\n pathname: string;\n href: string;\n};\n\nconst registeredApps: AppRegistration[] = [];\n\nfunction collectRouteActivityMatches(\n pathname: string,\n apps: readonly AppRegistration[] = registeredApps\n) {\n const matches: ReturnType<typeof computeRouteActivityMatches> = [];\n const seenPaths = new Set<string>();\n\n for (const app of apps) {\n const appMatches = computeRouteActivityMatches(pathname, {\n manifest: app.manifest,\n routes: app.routes,\n });\n\n for (const match of appMatches) {\n if (seenPaths.has(match.path)) {\n continue;\n }\n seenPaths.add(match.path);\n matches.push(match);\n }\n }\n\n return matches;\n}\n\nfunction syncRegisteredRouteSnapshot(): void {\n if (typeof window === 'undefined') {\n return;\n }\n\n const pathname = window.location.pathname || '/';\n syncCurrentRouteSnapshot(\n pathname,\n window.location.search || '',\n window.location.hash || '',\n collectRouteActivityMatches(pathname)\n );\n}\n\nfunction syncAppRegistrationLocation(\n app: AppRegistration,\n pathname: string,\n href: string\n): void {\n app.pathname = pathname;\n app.href = href;\n}\n\nexport type NavigationScrollBehavior = 'top' | 'preserve';\nexport type HistoryScrollBehavior = 'restore' | 'top' | 'preserve';\n\nexport type ScrollRestorationOptions = {\n navigation?: NavigationScrollBehavior;\n history?: HistoryScrollBehavior;\n};\n\ntype NormalizedScrollRestorationOptions = {\n enabled: boolean;\n navigation: NavigationScrollBehavior;\n history: HistoryScrollBehavior;\n};\n\nconst DEFAULT_SCROLL_RESTORATION: NormalizedScrollRestorationOptions = {\n enabled: true,\n navigation: 'top',\n history: 'restore',\n};\n\nlet scrollRestorationOptions: NormalizedScrollRestorationOptions = {\n ...DEFAULT_SCROLL_RESTORATION,\n};\n\nconst scrollPositions = new Map<string, { x: number; y: number }>();\n\nexport type NavigateOptions = {\n history?: 'push' | 'replace';\n replace?: boolean;\n scroll?: NavigationScrollBehavior;\n};\n\nfunction getWindowHref(): string {\n if (typeof window === 'undefined') {\n return currentHref;\n }\n\n return `${window.location.pathname}${window.location.search}${window.location.hash}`;\n}\n\nfunction normalizeScrollRestorationOptions(\n options?: boolean | ScrollRestorationOptions\n): NormalizedScrollRestorationOptions {\n if (options === false) {\n return {\n enabled: false,\n navigation: DEFAULT_SCROLL_RESTORATION.navigation,\n history: DEFAULT_SCROLL_RESTORATION.history,\n };\n }\n\n if (options === true || options === undefined) {\n return { ...DEFAULT_SCROLL_RESTORATION };\n }\n\n return {\n enabled: true,\n navigation: options.navigation ?? DEFAULT_SCROLL_RESTORATION.navigation,\n history: options.history ?? DEFAULT_SCROLL_RESTORATION.history,\n };\n}\n\nfunction readScrollPosition(): { x: number; y: number } {\n if (typeof window === 'undefined') {\n return { x: 0, y: 0 };\n }\n\n const x =\n typeof window.scrollX === 'number'\n ? window.scrollX\n : typeof window.pageXOffset === 'number'\n ? window.pageXOffset\n : 0;\n const y =\n typeof window.scrollY === 'number'\n ? window.scrollY\n : typeof window.pageYOffset === 'number'\n ? window.pageYOffset\n : 0;\n\n return { x, y };\n}\n\nfunction writeHistoryScrollPosition(\n href: string,\n position: { x: number; y: number }\n): void {\n if (typeof window === 'undefined' || getWindowHref() !== href) {\n return;\n }\n if (typeof window.history?.replaceState !== 'function') {\n return;\n }\n const state =\n window.history.state && typeof window.history.state === 'object'\n ? window.history.state\n : {};\n\n window.history.replaceState(\n {\n ...state,\n path: href,\n scroll: position,\n },\n '',\n href\n );\n}\n\nfunction saveScrollPosition(href: string): void {\n if (!scrollRestorationOptions.enabled || typeof window === 'undefined') {\n return;\n }\n\n const position = readScrollPosition();\n scrollPositions.set(href, position);\n writeHistoryScrollPosition(href, position);\n}\n\nfunction scrollToPosition(position: { x: number; y: number }): void {\n if (typeof window === 'undefined' || typeof window.scrollTo !== 'function') {\n return;\n }\n\n window.scrollTo(position.x, position.y);\n}\n\nfunction applyNavigationScroll(behavior: NavigationScrollBehavior): void {\n if (!scrollRestorationOptions.enabled || behavior === 'preserve') {\n return;\n }\n\n scrollToPosition({ x: 0, y: 0 });\n}\n\nfunction applyHistoryScroll(href: string, state: PopStateEvent['state']): void {\n if (!scrollRestorationOptions.enabled) {\n return;\n }\n\n if (scrollRestorationOptions.history === 'preserve') {\n return;\n }\n\n if (scrollRestorationOptions.history === 'top') {\n scrollToPosition({ x: 0, y: 0 });\n return;\n }\n\n const fromState =\n state && typeof state === 'object' && 'scroll' in state\n ? (state.scroll as { x?: unknown; y?: unknown })\n : undefined;\n const saved =\n fromState &&\n typeof fromState.x === 'number' &&\n typeof fromState.y === 'number'\n ? { x: fromState.x, y: fromState.y }\n : scrollPositions.get(href);\n\n scrollToPosition(saved ?? { x: 0, y: 0 });\n}\n\nexport function configureScrollRestoration(\n options?: boolean | ScrollRestorationOptions\n): void {\n scrollRestorationOptions = normalizeScrollRestorationOptions(options);\n\n if (typeof window === 'undefined') {\n return;\n }\n\n if ('scrollRestoration' in window.history) {\n try {\n window.history.scrollRestoration = scrollRestorationOptions.enabled\n ? 'manual'\n : 'auto';\n } catch {\n // Ignore environments that expose but do not allow setting scrollRestoration.\n }\n }\n}\n\nfunction parseTargetUrl(path: string): URL {\n const pathname = window.location.pathname || '/';\n const search = window.location.search || '';\n const hash = window.location.hash || '';\n const href =\n typeof window.location.href === 'string' ? window.location.href : '';\n const base =\n href &&\n href !== 'about:blank' &&\n !href.startsWith('about:') &&\n !href.startsWith('data:')\n ? href\n : `http://localhost${pathname}${search}${hash}`;\n\n return new URL(path, base);\n}\n\nfunction isRenderResult(\n result: RouteRequestResult\n): result is RouteRenderResult {\n return result !== null && result.kind === 'render';\n}\n\nfunction getRedirectHistoryMode(\n replace: boolean | undefined\n): 'push' | 'replace' {\n return replace === false ? 'push' : 'replace';\n}\n\nfunction getNavigationHistoryMode(\n options: NavigateOptions\n): 'push' | 'replace' {\n if (options.history) {\n return options.history;\n }\n\n return options.replace ? 'replace' : 'push';\n}\n\nfunction beginRouteRequest(): { id: number; signal: AbortSignal } {\n activeRouteRequestId += 1;\n activeRouteRequestController?.abort();\n activeRouteRequestController = new AbortController();\n\n return {\n id: activeRouteRequestId,\n signal: activeRouteRequestController.signal,\n };\n}\n\nfunction isStaleRouteRequest(requestId: number): boolean {\n return requestId !== activeRouteRequestId;\n}\n\nfunction createDeniedResolvedRoute(status: number): ResolvedRoute {\n return {\n handler: () => ({\n type: 'div',\n props: {\n 'data-route-denied': String(status),\n },\n children: [String(status)],\n }),\n params: {},\n };\n}\n\nfunction bindResolvedRouteHandler(\n resolved: ResolvedRoute\n): ComponentInstance['fn'] {\n return () =>\n resolved.handler(resolved.params) as ReturnType<ComponentInstance['fn']>;\n}\n\nfunction wrapRootRouteHandler(\n componentFn: ComponentInstance['fn']\n): ComponentInstance['fn'] {\n const wrappedFn: ComponentInstance['fn'] = (props, ctx) => {\n const out = componentFn(props, ctx);\n if (isPromiseLike(out)) {\n throw new Error(\n 'Async components are not supported. Components must return synchronously.'\n );\n }\n const portalVNode = {\n $$typeof: ELEMENT_TYPE,\n type: DefaultPortal,\n props: {},\n key: '__default_portal',\n } as unknown;\n\n return {\n $$typeof: ELEMENT_TYPE,\n type: Fragment,\n props: {\n children:\n out === undefined || out === null\n ? [portalVNode]\n : [out, portalVNode],\n },\n } as ReturnType<ComponentInstance['fn']>;\n };\n\n Object.defineProperty(wrappedFn, 'name', {\n value: componentFn.name || 'Component',\n });\n\n return wrappedFn;\n}\n\nfunction cleanupRouteOwnership(instance: ComponentInstance): void {\n const cleanupErrors: unknown[] = [];\n const children = instance.target\n ? Array.from(instance.target.childNodes)\n : [];\n\n for (const child of children) {\n try {\n cleanupInstancesUnder(child, { strict: instance.cleanupStrict });\n } catch (error) {\n cleanupErrors.push(error);\n }\n }\n\n try {\n cleanupComponent(instance);\n } catch (error) {\n cleanupErrors.push(error);\n }\n\n if (cleanupErrors.length > 0) {\n throw new AggregateError(cleanupErrors, 'Route cleanup failed');\n }\n}\n\nfunction remountResolvedRoute(\n instance: ComponentInstance,\n resolved: ResolvedRoute,\n pathname: string,\n href: string\n): boolean {\n // The route handler IS the component function\n // It takes params as props and renders the route\n clearDefaultPortalForInstance(instance);\n cleanupRouteOwnership(instance);\n\n instance.fn = wrapRootRouteHandler(bindResolvedRouteHandler(resolved));\n instance.props = {};\n\n // Reset state to prevent leakage from previous route\n // Each route navigation starts completely fresh\n instance.stateValues = [];\n instance.expectedStateIndices = [];\n instance.firstRenderComplete = false;\n instance.stateIndexCheck = -1;\n // Increment generation to invalidate pending async evaluations from previous route\n instance.evaluationGeneration++;\n instance.notifyUpdate = null;\n instance.mountOperations = [];\n instance.commitOperations = [];\n instance.lifecycleSlots = [];\n instance.cleanupFns = [];\n instance._placeholder = undefined;\n instance.hasPendingUpdate = false;\n instance._currentRenderToken = undefined;\n instance.lastRenderToken = 0;\n instance._pendingReadSources = undefined;\n instance._lastReadSources = undefined;\n\n // Route-local async work should create a fresh abort controller lazily.\n instance.abortController = null;\n\n // Re-execute component against the existing host so reconciliation can\n // preserve any shared layout DOM between sibling routes.\n mountComponent(instance);\n currentPathname = pathname;\n currentHref = href;\n return true;\n}\n\nfunction rerenderResolvedRoute(\n instance: ComponentInstance,\n pathname: string,\n href: string\n): boolean {\n currentPathname = pathname;\n currentHref = href;\n instance._enqueueRun?.();\n return true;\n}\n\nfunction resolveAppRouteRequest(\n app: AppRegistration,\n pathname: string,\n href: string,\n signal: AbortSignal\n): RouteRequestResult | Promise<RouteRequestResult> {\n if (app.routes) {\n const resolved = resolveRouteFromRoutes(pathname, app.routes);\n if (!resolved) {\n return null;\n }\n\n return {\n kind: 'render',\n handler: resolved.handler,\n params: resolved.params,\n };\n }\n\n return resolveRouteRequest(href, {\n manifest: app.manifest,\n auth: app.auth,\n signal,\n });\n}\n\ntype AppNavigationTarget = {\n app: AppRegistration;\n resolved: RouteRequestResult;\n};\n\nfunction resolveNavigationTargetsForApps(\n pathname: string,\n href: string,\n signal: AbortSignal\n): AppNavigationTarget[] | Promise<AppNavigationTarget[]> {\n const apps = [...registeredApps];\n\n if (apps.length === 1) {\n const app = apps[0]!;\n const resolved = resolveAppRouteRequest(app, pathname, href, signal);\n if (isPromiseLike<RouteRequestResult>(resolved)) {\n return Promise.resolve(resolved).then((next) => [\n {\n app,\n resolved: next,\n },\n ]);\n }\n\n return [\n {\n app,\n resolved,\n },\n ];\n }\n\n const syncTargets: AppNavigationTarget[] = [];\n const pendingTargets: Array<Promise<AppNavigationTarget>> = [];\n\n for (const app of apps) {\n const resolved = resolveAppRouteRequest(app, pathname, href, signal);\n if (isPromiseLike<RouteRequestResult>(resolved)) {\n pendingTargets.push(\n Promise.resolve(resolved).then((next) => ({ app, resolved: next }))\n );\n continue;\n }\n\n syncTargets.push({ app, resolved });\n }\n\n if (pendingTargets.length === 0) {\n return syncTargets;\n }\n\n return Promise.all([\n ...syncTargets.map((target) => Promise.resolve(target)),\n ...pendingTargets,\n ]);\n}\n\nfunction applyNavigationTargets(\n path: string,\n options: NavigateOptions,\n redirectState: NavigationRedirectState,\n pathname: string,\n href: string,\n targets: AppNavigationTarget[]\n): void {\n const previousPathname = currentPathname;\n\n for (const target of targets) {\n const resolved = target.resolved;\n if (!resolved || resolved.kind !== 'redirect') {\n continue;\n }\n\n const redirectTarget = parseTargetUrl(resolved.to);\n const redirectHref = `${redirectTarget.pathname}${redirectTarget.search}${redirectTarget.hash}`;\n if (redirectHref === href) {\n if (isDevelopmentEnvironment()) {\n logger.warn(\n `Navigation guard redirected to the same path: ${redirectHref}`\n );\n }\n return;\n }\n\n if (redirectState.visited.has(redirectHref)) {\n throw new Error(\n `[Askr] Navigation redirect cycle detected at ${redirectHref}.`\n );\n }\n if (redirectState.redirects >= MAX_NAVIGATION_REDIRECTS) {\n throw new Error(\n `[Askr] Navigation redirect limit exceeded (${MAX_NAVIGATION_REDIRECTS}).`\n );\n }\n\n redirectState.visited.add(redirectHref);\n redirectState.redirects++;\n navigateWithRedirectState(\n redirectHref,\n {\n history: getRedirectHistoryMode(resolved.replace),\n },\n redirectState\n );\n return;\n }\n\n const matchedTargets = targets.filter((target) => target.resolved !== null);\n if (matchedTargets.length === 0) {\n if (isDevelopmentEnvironment()) {\n logger.warn(`No route found for path: ${path}`);\n }\n return;\n }\n\n saveScrollPosition(currentHref);\n\n const historyMethod =\n getNavigationHistoryMode(options) === 'replace'\n ? 'replaceState'\n : 'pushState';\n window.history[historyMethod]({ path: href }, '', href);\n syncRegisteredRouteSnapshot();\n\n for (const target of matchedTargets) {\n const resolved = target.resolved!;\n if (resolved.kind === 'redirect') {\n continue;\n }\n\n if (pathname === target.app.pathname && isRenderResult(resolved)) {\n rerenderResolvedRoute(target.app.instance, pathname, href);\n syncAppRegistrationLocation(target.app, pathname, href);\n continue;\n }\n\n remountResolvedRoute(\n target.app.instance,\n resolved.kind === 'deny'\n ? createDeniedResolvedRoute(resolved.status)\n : {\n handler: resolved.handler,\n params: resolved.params,\n },\n pathname,\n href\n );\n syncAppRegistrationLocation(target.app, pathname, href);\n }\n\n if (pathname !== previousPathname) {\n applyNavigationScroll(\n options.scroll ?? scrollRestorationOptions.navigation\n );\n }\n}\n\n/** Register the current app instance (called by createSPA/hydrateSPA). */\nexport function registerAppInstance(\n instance: ComponentInstance,\n path: string,\n source: AppNavigationSource = {}\n): void {\n const existingIndex = registeredApps.findIndex(\n (app) => app.instance === instance\n );\n const registration: AppRegistration = {\n instance,\n pathname: path,\n href: getWindowHref(),\n ...source,\n };\n if (existingIndex >= 0) {\n registeredApps[existingIndex] = registration;\n } else {\n registeredApps.push(registration);\n }\n\n currentInstance = instance;\n currentPathname = path;\n currentHref = getWindowHref();\n syncRegisteredRouteSnapshot();\n // Lock further route registrations after the app has started — but allow tests to register routes.\n // Enforce only in production to avoid breaking test infra which registers routes dynamically.\n if (isProductionEnvironment()) {\n lockRouteRegistration();\n }\n}\n\nexport function unregisterAppInstance(instance: ComponentInstance): void {\n const existingIndex = registeredApps.findIndex(\n (app) => app.instance === instance\n );\n if (existingIndex >= 0) {\n registeredApps.splice(existingIndex, 1);\n }\n syncRegisteredRouteSnapshot();\n\n if (currentInstance !== instance) {\n return;\n }\n\n const nextApp =\n registeredApps.length > 0\n ? registeredApps[registeredApps.length - 1]!\n : null;\n currentInstance = nextApp?.instance ?? null;\n if (nextApp) {\n currentPathname = nextApp.pathname;\n currentHref = nextApp.href;\n syncRegisteredRouteSnapshot();\n return;\n }\n\n activeRouteRequestId += 1;\n activeRouteRequestController?.abort();\n activeRouteRequestController = null;\n currentPathname = '/';\n currentHref = '/';\n if (typeof window === 'undefined') {\n syncCurrentRouteSnapshot('/', '', '', []);\n }\n}\n\n/**\n * Navigate to a new path\n * Updates URL, resolves route, and re-mounts app with new handler\n */\nexport function navigate(path: string, options: NavigateOptions = {}): void {\n if (typeof window === 'undefined') {\n return;\n }\n\n const initialTarget = parseTargetUrl(path);\n navigateWithRedirectState(path, options, {\n redirects: 0,\n visited: new Set([\n `${initialTarget.pathname}${initialTarget.search}${initialTarget.hash}`,\n ]),\n });\n}\n\ntype NavigationRedirectState = {\n redirects: number;\n visited: Set<string>;\n};\n\nfunction navigateWithRedirectState(\n path: string,\n options: NavigateOptions,\n redirectState: NavigationRedirectState\n): void {\n if (typeof window === 'undefined') {\n // SSR context\n return;\n }\n\n const request = beginRouteRequest();\n\n const target = parseTargetUrl(path);\n const pathname = target.pathname;\n const href = `${target.pathname}${target.search}${target.hash}`;\n const resolvedTargets = resolveNavigationTargetsForApps(\n pathname,\n href,\n request.signal\n );\n\n if (isPromiseLike(resolvedTargets)) {\n void Promise.resolve(resolvedTargets).then(\n (targets) => {\n if (isStaleRouteRequest(request.id)) {\n return;\n }\n\n try {\n applyNavigationTargets(\n path,\n options,\n redirectState,\n pathname,\n href,\n targets\n );\n } catch (error) {\n logger.error('[Askr] navigation failed:', error);\n }\n },\n (error) => {\n logger.error('[Askr] navigation failed:', error);\n }\n );\n return;\n }\n\n applyNavigationTargets(\n path,\n options,\n redirectState,\n pathname,\n href,\n resolvedTargets\n );\n}\n\n/**\n * Handle browser back/forward buttons\n */\nfunction handlePopState(_event: PopStateEvent): void {\n const request = beginRouteRequest();\n const previousHref = currentHref;\n const pathname = window.location.pathname;\n const href = `${window.location.pathname}${window.location.search}${window.location.hash}`;\n\n saveScrollPosition(previousHref);\n\n if (registeredApps.length === 0) {\n return;\n }\n\n const applyResolved = (targets: AppNavigationTarget[]) => {\n if (isStaleRouteRequest(request.id)) {\n return;\n }\n\n const matchedTargets = targets.filter((target) => target.resolved !== null);\n if (matchedTargets.length === 0) {\n if (isDevelopmentEnvironment()) {\n logger.warn(`No route found for path: ${pathname}`);\n }\n return;\n }\n\n for (const target of matchedTargets) {\n const resolved = target.resolved!;\n if (resolved.kind !== 'redirect') {\n continue;\n }\n\n navigate(resolved.to, {\n history: getRedirectHistoryMode(resolved.replace),\n });\n return;\n }\n\n syncRegisteredRouteSnapshot();\n\n for (const target of matchedTargets) {\n const resolved = target.resolved!;\n if (pathname === target.app.pathname && isRenderResult(resolved)) {\n rerenderResolvedRoute(target.app.instance, pathname, href);\n syncAppRegistrationLocation(target.app, pathname, href);\n continue;\n }\n\n if (resolved.kind === 'redirect') {\n continue;\n }\n\n remountResolvedRoute(\n target.app.instance,\n resolved.kind === 'deny'\n ? createDeniedResolvedRoute(resolved.status)\n : {\n handler: resolved.handler,\n params: resolved.params,\n },\n pathname,\n href\n );\n syncAppRegistrationLocation(target.app, pathname, href);\n }\n\n applyHistoryScroll(href, _event.state);\n };\n\n const resolvedTargets = resolveNavigationTargetsForApps(\n pathname,\n href,\n request.signal\n );\n\n if (isPromiseLike<AppNavigationTarget[]>(resolvedTargets)) {\n void Promise.resolve(resolvedTargets).then(\n (next) => {\n try {\n applyResolved(next);\n } catch (error) {\n logger.error('[Askr] popstate navigation failed:', error);\n }\n },\n (error) => {\n logger.error('[Askr] popstate navigation failed:', error);\n }\n );\n return;\n }\n\n applyResolved(resolvedTargets);\n}\n\n/**\n * Setup popstate listener for browser navigation\n */\nexport function initializeNavigation(): void {\n if (typeof window === 'undefined' || navigationInitialized) {\n return;\n }\n\n navigationInitialized = true;\n window.addEventListener('popstate', handlePopState);\n}\n\n/**\n * Cleanup navigation listeners\n */\nexport function cleanupNavigation(): void {\n activeRouteRequestId += 1;\n activeRouteRequestController?.abort();\n activeRouteRequestController = null;\n\n if (typeof window === 'undefined' || !navigationInitialized) {\n return;\n }\n\n navigationInitialized = false;\n window.removeEventListener('popstate', handlePopState);\n}\n"],"mappings":";;;;;;;;;;;;;AAsCA,IAAI,kBAA4C;AAChD,IAAI,kBAAkB;AACtB,IAAI,cAAc;AAClB,IAAI,wBAAwB;AAC5B,IAAI,uBAAuB;AAC3B,IAAI,+BAAuD;AAC3D,MAAM,2BAA2B;AAcjC,MAAM,iBAAoC,CAAC;AAE3C,SAAS,4BACP,UACA,OAAmC,gBACnC;CACA,MAAM,UAA0D,CAAC;CACjE,MAAM,4BAAY,IAAI,IAAY;CAElC,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,aAAa,4BAA4B,UAAU;GACvD,UAAU,IAAI;GACd,QAAQ,IAAI;EACd,CAAC;EAED,KAAK,MAAM,SAAS,YAAY;GAC9B,IAAI,UAAU,IAAI,MAAM,IAAI,GAC1B;GAEF,UAAU,IAAI,MAAM,IAAI;GACxB,QAAQ,KAAK,KAAK;EACpB;CACF;CAEA,OAAO;AACT;AAEA,SAAS,8BAAoC;CAC3C,IAAI,OAAO,WAAW,aACpB;CAGF,MAAM,WAAW,OAAO,SAAS,YAAY;CAC7C,yBACE,UACA,OAAO,SAAS,UAAU,IAC1B,OAAO,SAAS,QAAQ,IACxB,4BAA4B,QAAQ,CACtC;AACF;AAEA,SAAS,4BACP,KACA,UACA,MACM;CACN,IAAI,WAAW;CACf,IAAI,OAAO;AACb;AAgBA,MAAM,6BAAiE;CACrE,SAAS;CACT,YAAY;CACZ,SAAS;AACX;AAEA,IAAI,2BAA+D,EACjE,GAAG,2BACL;AAEA,MAAM,kCAAkB,IAAI,IAAsC;AAQlE,SAAS,gBAAwB;CAC/B,IAAI,OAAO,WAAW,aACpB,OAAO;CAGT,OAAO,GAAG,OAAO,SAAS,WAAW,OAAO,SAAS,SAAS,OAAO,SAAS;AAChF;AAEA,SAAS,kCACP,SACoC;CACpC,IAAI,YAA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MACnC,SAAS;GACR,IAAI;IACF,cAAc,IAAI;GACpB,SAAS,OAAO;IACd,OAAO,MAAM,sCAAsC,KAAK;GAC1D;EACF,IACC,UAAU;GACT,OAAO,MAAM,sCAAsC,KAAK;EAC1D,CACF;EACA;CACF;CAEA,cAAc,eAAe;AAC/B;;;;AAKA,SAAgB,uBAA6B;CAC3C,IAAI,OAAO,WAAW,eAAe,uBACnC;CAGF,wBAAwB;CACxB,OAAO,iBAAiB,YAAY,cAAc;AACpD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"policy.js","names":[],"sources":["../../src/router/policy.ts"],"sourcesContent":["import type {\n AccessDecision,\n AccessAllowDecision,\n AccessDenyDecision,\n AccessDenyStatus,\n AccessRedirectDecision,\n AccessRedirectStatus,\n RouteAuthOptions,\n RouteContext,\n RoutePolicy,\n} from '../common/router';\nimport { isPromiseLike } from '../common/promise';\n\nconst ROUTE_AUTH_OPTIONS = Symbol.for('__ASKR_ROUTE_AUTH_OPTIONS__');\n\ntype InternalRouteContext = RouteContext & {\n [ROUTE_AUTH_OPTIONS]?: RouteAuthOptions;\n};\n\ntype RoutePathResolver =\n | string\n | ((context: RouteContext) => string | PromiseLike<string>);\n\nexport function allow(): AccessAllowDecision {\n return { kind: 'allow' };\n}\n\nexport function redirect(\n to: string,\n init: {\n status?: AccessRedirectStatus;\n replace?: boolean;\n } = {}\n): AccessRedirectDecision {\n return {\n kind: 'redirect',\n to,\n ...(init.status ? { status: init.status } : {}),\n ...(init.replace !== undefined ? { replace: init.replace } : {}),\n };\n}\n\nexport function deny(status: AccessDenyStatus): AccessDenyDecision {\n return { kind: 'deny', status };\n}\n\nexport function unauthorized(): AccessDenyDecision {\n return deny(401);\n}\n\nexport function forbidden(): AccessDenyDecision {\n return deny(403);\n}\n\nexport function notFound(): AccessDenyDecision {\n return deny(404);\n}\n\nexport function normalizeAccessDecision(\n result: AccessDecision\n): AccessDecision {\n return result;\n}\n\nexport function withRouteAuthOptions(\n context: RouteContext,\n auth: RouteAuthOptions | undefined\n): RouteContext {\n const internal = context as InternalRouteContext;\n\n if (!auth) {\n delete internal[ROUTE_AUTH_OPTIONS];\n return context;\n }\n\n internal[ROUTE_AUTH_OPTIONS] = auth;\n return context;\n}\n\nfunction getRouteAuthOptions(\n context: RouteContext\n): RouteAuthOptions | undefined {\n return (context as InternalRouteContext)[ROUTE_AUTH_OPTIONS];\n}\n\nfunction assertRouteAuthOptions(context: RouteContext): RouteAuthOptions {\n const auth = getRouteAuthOptions(context);\n if (!auth?.resolve) {\n throw new Error(\n 'Built-in auth policies require router auth configuration. ' +\n 'Provide `auth` to registerRoutes(...), createSPA(...), hydrateSPA(...), or SSR route resolution.'\n );\n }\n\n return auth;\n}\n\nfunction resolvePathSetting(\n value: RoutePathResolver | undefined,\n fallback: string,\n context: RouteContext\n): string | PromiseLike<string> {\n if (!value) {\n return fallback;\n }\n\n if (typeof value === 'function') {\n return value(context);\n }\n\n return value;\n}\n\nfunction appendNextTarget(path: string, href: string): string {\n const resolved = new URL(path, 'http://localhost');\n resolved.searchParams.set('next', href);\n return `${resolved.pathname}${resolved.search}${resolved.hash}`;\n}\n\nfunction collectStringValues(value: unknown): string[] {\n if (typeof value === 'string') {\n return [value];\n }\n\n if (Array.isArray(value)) {\n return value.filter((entry): entry is string => typeof entry === 'string');\n }\n\n if (value instanceof Set) {\n return Array.from(value).filter(\n (entry): entry is string => typeof entry === 'string'\n );\n }\n\n return [];\n}\n\nfunction defaultHasRole(user: unknown, role: string): boolean {\n if (!user || typeof user !== 'object') {\n return false;\n }\n\n return collectStringValues((user as { roles?: unknown }).roles).includes(\n role\n );\n}\n\nfunction defaultHasPermission(user: unknown, permission: string): boolean {\n if (!user || typeof user !== 'object') {\n return false;\n }\n\n return collectStringValues(\n (user as { permissions?: unknown }).permissions\n ).includes(permission);\n}\n\nfunction resolveUnauthenticatedRedirect(\n context: RouteContext\n): AccessDecision | Promise<AccessDecision> {\n const auth = assertRouteAuthOptions(context);\n const loginPath = resolvePathSetting(auth.loginPath, '/login', context);\n if (isPromiseLike<string>(loginPath)) {\n return Promise.resolve(loginPath).then((nextPath) =>\n redirect(appendNextTarget(nextPath, context.href), {\n replace: context.mode === 'spa',\n })\n );\n }\n\n return redirect(appendNextTarget(loginPath, context.href), {\n replace: context.mode === 'spa',\n });\n}\n\nfunction resolveAuthenticatedRedirect(\n context: RouteContext\n): AccessDecision | Promise<AccessDecision> {\n const auth = assertRouteAuthOptions(context);\n const target = resolvePathSetting(auth.guestRedirectTo, '/', context);\n if (isPromiseLike<string>(target)) {\n return Promise.resolve(target).then((nextTarget) =>\n redirect(nextTarget, {\n replace: true,\n })\n );\n }\n\n return redirect(target, {\n replace: true,\n });\n}\n\nexport function requireAuth(): RoutePolicy {\n return (context) => {\n if (context.session) {\n return allow();\n }\n\n return resolveUnauthenticatedRedirect(context);\n };\n}\n\nexport function requireGuest(): RoutePolicy {\n return (context) => {\n if (!context.session) {\n return allow();\n }\n\n return resolveAuthenticatedRedirect(context);\n };\n}\n\nexport function requireRole(role: string): RoutePolicy {\n return (context) => {\n if (!context.user) {\n return resolveUnauthenticatedRedirect(context);\n }\n\n const auth = assertRouteAuthOptions(context);\n const hasRole = auth.hasRole\n ? auth.hasRole(context.user, role, context)\n : defaultHasRole(context.user, role);\n\n if (isPromiseLike<boolean>(hasRole)) {\n return Promise.resolve(hasRole).then((next) =>\n next ? allow() : forbidden()\n );\n }\n\n return hasRole ? allow() : forbidden();\n };\n}\n\nexport function requirePermission(permission: string): RoutePolicy {\n return (context) => {\n if (!context.user) {\n return resolveUnauthenticatedRedirect(context);\n }\n\n const auth = assertRouteAuthOptions(context);\n const hasPermission = auth.hasPermission\n ? auth.hasPermission(context.user, permission, context)\n : defaultHasPermission(context.user, permission);\n\n if (isPromiseLike<boolean>(hasPermission)) {\n return Promise.resolve(hasPermission).then((next) =>\n next ? allow() : forbidden()\n );\n }\n\n return hasPermission ? allow() : forbidden();\n };\n}\n\nexport async function evaluateRoutePolicy(\n policy: RoutePolicy,\n context: RouteContext\n): Promise<AccessDecision> {\n const result = await policy(context);\n return result;\n}\n"],"mappings":";;AAaA,MAAM,qBAAqB,OAAO,IAAI,6BAA6B;AAUnE,SAAgB,QAA6B;CAC3C,OAAO,EAAE,MAAM,QAAQ;AACzB;AAEA,SAAgB,SACd,IACA,OAGI,CAAC,GACmB;CACxB,OAAO;EACL,MAAM;EACN;EACA,GAAI,KAAK,SAAS,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC;EAC7C,GAAI,KAAK,YAAY,SAAY,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;CAChE;AACF;AAEA,SAAgB,KAAK,QAA8C;CACjE,OAAO;EAAE,MAAM;EAAQ;CAAO;AAChC;AAEA,SAAgB,eAAmC;CACjD,OAAO,KAAK,GAAG;AACjB;AAEA,SAAgB,YAAgC;CAC9C,OAAO,KAAK,GAAG;AACjB;AAEA,SAAgB,WAA+B;CAC7C,OAAO,KAAK,GAAG;AACjB;AAQA,SAAgB,qBACd,SACA,MACc;CACd,MAAM,WAAW;CAEjB,IAAI,CAAC,MAAM;EACT,OAAO,SAAS;EAChB,OAAO;CACT;CAEA,SAAS,sBAAsB;CAC/B,OAAO;AACT;AAEA,SAAS,oBACP,SAC8B;CAC9B,OAAQ,QAAiC;AAC3C;AAEA,SAAS,uBAAuB,SAAyC;CACvE,MAAM,OAAO,oBAAoB,OAAO;CACxC,IAAI,CAAC,MAAM,SACT,MAAM,IAAI,MACR,4JAEF;CAGF,OAAO;AACT;AAEA,SAAS,mBACP,OACA,UACA,SAC8B;CAC9B,IAAI,CAAC,OACH,OAAO;CAGT,IAAI,OAAO,UAAU,YACnB,OAAO,MAAM,OAAO;CAGtB,OAAO;AACT;AAEA,SAAS,iBAAiB,MAAc,MAAsB;CAC5D,MAAM,WAAW,IAAI,IAAI,MAAM,kBAAkB;CACjD,SAAS,aAAa,IAAI,QAAQ,IAAI;CACtC,OAAO,GAAG,SAAS,WAAW,SAAS,SAAS,SAAS;AAC3D;AAEA,SAAS,oBAAoB,OAA0B;CACrD,IAAI,OAAO,UAAU,UACnB,OAAO,CAAC,KAAK;CAGf,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,QAAQ,UAA2B,OAAO,UAAU,QAAQ;CAG3E,IAAI,iBAAiB,KACnB,OAAO,MAAM,KAAK,KAAK,
|
|
1
|
+
{"version":3,"file":"policy.js","names":[],"sources":["../../src/router/policy.ts"],"sourcesContent":["import type {\n AccessDecision,\n AccessAllowDecision,\n AccessDenyDecision,\n AccessDenyStatus,\n AccessRedirectDecision,\n AccessRedirectStatus,\n RouteAuthOptions,\n RouteContext,\n RoutePolicy,\n} from '../common/router';\nimport { isPromiseLike } from '../common/promise';\n\nconst ROUTE_AUTH_OPTIONS = Symbol.for('__ASKR_ROUTE_AUTH_OPTIONS__');\n\ntype InternalRouteContext = RouteContext & {\n [ROUTE_AUTH_OPTIONS]?: RouteAuthOptions;\n};\n\ntype RoutePathResolver =\n | string\n | ((context: RouteContext) => string | PromiseLike<string>);\n\nexport function allow(): AccessAllowDecision {\n return { kind: 'allow' };\n}\n\nexport function redirect(\n to: string,\n init: {\n status?: AccessRedirectStatus;\n replace?: boolean;\n } = {}\n): AccessRedirectDecision {\n return {\n kind: 'redirect',\n to,\n ...(init.status ? { status: init.status } : {}),\n ...(init.replace !== undefined ? { replace: init.replace } : {}),\n };\n}\n\nexport function deny(status: AccessDenyStatus): AccessDenyDecision {\n return { kind: 'deny', status };\n}\n\nexport function unauthorized(): AccessDenyDecision {\n return deny(401);\n}\n\nexport function forbidden(): AccessDenyDecision {\n return deny(403);\n}\n\nexport function notFound(): AccessDenyDecision {\n return deny(404);\n}\n\nexport function normalizeAccessDecision(\n result: AccessDecision\n): AccessDecision {\n return result;\n}\n\nexport function withRouteAuthOptions(\n context: RouteContext,\n auth: RouteAuthOptions | undefined\n): RouteContext {\n const internal = context as InternalRouteContext;\n\n if (!auth) {\n delete internal[ROUTE_AUTH_OPTIONS];\n return context;\n }\n\n internal[ROUTE_AUTH_OPTIONS] = auth;\n return context;\n}\n\nfunction getRouteAuthOptions(\n context: RouteContext\n): RouteAuthOptions | undefined {\n return (context as InternalRouteContext)[ROUTE_AUTH_OPTIONS];\n}\n\nfunction assertRouteAuthOptions(context: RouteContext): RouteAuthOptions {\n const auth = getRouteAuthOptions(context);\n if (!auth?.resolve) {\n throw new Error(\n 'Built-in auth policies require router auth configuration. ' +\n 'Provide `auth` to registerRoutes(...), createSPA(...), hydrateSPA(...), or SSR route resolution.'\n );\n }\n\n return auth;\n}\n\nfunction resolvePathSetting(\n value: RoutePathResolver | undefined,\n fallback: string,\n context: RouteContext\n): string | PromiseLike<string> {\n if (!value) {\n return fallback;\n }\n\n if (typeof value === 'function') {\n return value(context);\n }\n\n return value;\n}\n\nfunction appendNextTarget(path: string, href: string): string {\n const resolved = new URL(path, 'http://localhost');\n resolved.searchParams.set('next', href);\n return `${resolved.pathname}${resolved.search}${resolved.hash}`;\n}\n\nfunction collectStringValues(value: unknown): string[] {\n if (typeof value === 'string') {\n return [value];\n }\n\n if (Array.isArray(value)) {\n return value.filter((entry): entry is string => typeof entry === 'string');\n }\n\n if (value instanceof Set) {\n return Array.from(value).filter(\n (entry): entry is string => typeof entry === 'string'\n );\n }\n\n return [];\n}\n\nfunction defaultHasRole(user: unknown, role: string): boolean {\n if (!user || typeof user !== 'object') {\n return false;\n }\n\n return collectStringValues((user as { roles?: unknown }).roles).includes(\n role\n );\n}\n\nfunction defaultHasPermission(user: unknown, permission: string): boolean {\n if (!user || typeof user !== 'object') {\n return false;\n }\n\n return collectStringValues(\n (user as { permissions?: unknown }).permissions\n ).includes(permission);\n}\n\nfunction resolveUnauthenticatedRedirect(\n context: RouteContext\n): AccessDecision | Promise<AccessDecision> {\n const auth = assertRouteAuthOptions(context);\n const loginPath = resolvePathSetting(auth.loginPath, '/login', context);\n if (isPromiseLike<string>(loginPath)) {\n return Promise.resolve(loginPath).then((nextPath) =>\n redirect(appendNextTarget(nextPath, context.href), {\n replace: context.mode === 'spa',\n })\n );\n }\n\n return redirect(appendNextTarget(loginPath, context.href), {\n replace: context.mode === 'spa',\n });\n}\n\nfunction resolveAuthenticatedRedirect(\n context: RouteContext\n): AccessDecision | Promise<AccessDecision> {\n const auth = assertRouteAuthOptions(context);\n const target = resolvePathSetting(auth.guestRedirectTo, '/', context);\n if (isPromiseLike<string>(target)) {\n return Promise.resolve(target).then((nextTarget) =>\n redirect(nextTarget, {\n replace: true,\n })\n );\n }\n\n return redirect(target, {\n replace: true,\n });\n}\n\nexport function requireAuth(): RoutePolicy {\n return (context) => {\n if (context.session) {\n return allow();\n }\n\n return resolveUnauthenticatedRedirect(context);\n };\n}\n\nexport function requireGuest(): RoutePolicy {\n return (context) => {\n if (!context.session) {\n return allow();\n }\n\n return resolveAuthenticatedRedirect(context);\n };\n}\n\nexport function requireRole(role: string): RoutePolicy {\n return (context) => {\n if (!context.user) {\n return resolveUnauthenticatedRedirect(context);\n }\n\n const auth = assertRouteAuthOptions(context);\n const hasRole = auth.hasRole\n ? auth.hasRole(context.user, role, context)\n : defaultHasRole(context.user, role);\n\n if (isPromiseLike<boolean>(hasRole)) {\n return Promise.resolve(hasRole).then((next) =>\n next ? allow() : forbidden()\n );\n }\n\n return hasRole ? allow() : forbidden();\n };\n}\n\nexport function requirePermission(permission: string): RoutePolicy {\n return (context) => {\n if (!context.user) {\n return resolveUnauthenticatedRedirect(context);\n }\n\n const auth = assertRouteAuthOptions(context);\n const hasPermission = auth.hasPermission\n ? auth.hasPermission(context.user, permission, context)\n : defaultHasPermission(context.user, permission);\n\n if (isPromiseLike<boolean>(hasPermission)) {\n return Promise.resolve(hasPermission).then((next) =>\n next ? allow() : forbidden()\n );\n }\n\n return hasPermission ? allow() : forbidden();\n };\n}\n\nexport async function evaluateRoutePolicy(\n policy: RoutePolicy,\n context: RouteContext\n): Promise<AccessDecision> {\n const result = await policy(context);\n return result;\n}\n"],"mappings":";;AAaA,MAAM,qBAAqB,OAAO,IA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