@tanstack/router-core 1.139.5 → 1.139.7
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/cjs/new-process-route-tree.cjs +3 -0
- package/dist/cjs/new-process-route-tree.cjs.map +1 -1
- package/dist/cjs/ssr/transformStreamWithRouter.cjs +31 -21
- package/dist/cjs/ssr/transformStreamWithRouter.cjs.map +1 -1
- package/dist/esm/new-process-route-tree.js +3 -0
- package/dist/esm/new-process-route-tree.js.map +1 -1
- package/dist/esm/ssr/transformStreamWithRouter.js +31 -21
- package/dist/esm/ssr/transformStreamWithRouter.js.map +1 -1
- package/package.json +1 -1
- package/src/new-process-route-tree.ts +6 -0
- package/src/ssr/transformStreamWithRouter.ts +37 -27
|
@@ -635,6 +635,9 @@ function getNodeMatch(path, parts, segmentTree, fuzzy) {
|
|
|
635
635
|
}
|
|
636
636
|
}
|
|
637
637
|
}
|
|
638
|
+
if (bestMatch && wildcardMatch) {
|
|
639
|
+
return isFrameMoreSpecific(wildcardMatch, bestMatch) ? bestMatch : wildcardMatch;
|
|
640
|
+
}
|
|
638
641
|
if (bestMatch) return bestMatch;
|
|
639
642
|
if (wildcardMatch) return wildcardMatch;
|
|
640
643
|
if (fuzzy && bestFuzzy) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"new-process-route-tree.cjs","sources":["../../src/new-process-route-tree.ts"],"sourcesContent":["import invariant from 'tiny-invariant'\nimport { createLRUCache } from './lru-cache'\nimport { last } from './utils'\nimport type { LRUCache } from './lru-cache'\n\nexport const SEGMENT_TYPE_PATHNAME = 0\nexport const SEGMENT_TYPE_PARAM = 1\nexport const SEGMENT_TYPE_WILDCARD = 2\nexport const SEGMENT_TYPE_OPTIONAL_PARAM = 3\n\nexport type SegmentKind =\n | typeof SEGMENT_TYPE_PATHNAME\n | typeof SEGMENT_TYPE_PARAM\n | typeof SEGMENT_TYPE_WILDCARD\n | typeof SEGMENT_TYPE_OPTIONAL_PARAM\n\nconst PARAM_W_CURLY_BRACES_RE =\n /^([^{]*)\\{\\$([a-zA-Z_$][a-zA-Z0-9_$]*)\\}([^}]*)$/ // prefix{$paramName}suffix\nconst OPTIONAL_PARAM_W_CURLY_BRACES_RE =\n /^([^{]*)\\{-\\$([a-zA-Z_$][a-zA-Z0-9_$]*)\\}([^}]*)$/ // prefix{-$paramName}suffix\nconst WILDCARD_W_CURLY_BRACES_RE = /^([^{]*)\\{\\$\\}([^}]*)$/ // prefix{$}suffix\n\ntype ParsedSegment = Uint16Array & {\n /** segment type (0 = pathname, 1 = param, 2 = wildcard, 3 = optional param) */\n 0: SegmentKind\n /** index of the end of the prefix */\n 1: number\n /** index of the start of the value */\n 2: number\n /** index of the end of the value */\n 3: number\n /** index of the start of the suffix */\n 4: number\n /** index of the end of the segment */\n 5: number\n}\n\n/**\n * Populates the `output` array with the parsed representation of the given `segment` string.\n *\n * Usage:\n * ```ts\n * let output\n * let cursor = 0\n * while (cursor < path.length) {\n * output = parseSegment(path, cursor, output)\n * const end = output[5]\n * cursor = end + 1\n * ```\n *\n * `output` is stored outside to avoid allocations during repeated calls. It doesn't need to be typed\n * or initialized, it will be done automatically.\n */\nexport function parseSegment(\n /** The full path string containing the segment. */\n path: string,\n /** The starting index of the segment within the path. */\n start: number,\n /** A Uint16Array (length: 6) to populate with the parsed segment data. */\n output: Uint16Array = new Uint16Array(6),\n): ParsedSegment {\n const next = path.indexOf('/', start)\n const end = next === -1 ? path.length : next\n const part = path.substring(start, end)\n\n if (!part || !part.includes('$')) {\n // early escape for static pathname\n output[0] = SEGMENT_TYPE_PATHNAME\n output[1] = start\n output[2] = start\n output[3] = end\n output[4] = end\n output[5] = end\n return output as ParsedSegment\n }\n\n // $ (wildcard)\n if (part === '$') {\n const total = path.length\n output[0] = SEGMENT_TYPE_WILDCARD\n output[1] = start\n output[2] = start\n output[3] = total\n output[4] = total\n output[5] = total\n return output as ParsedSegment\n }\n\n // $paramName\n if (part.charCodeAt(0) === 36) {\n output[0] = SEGMENT_TYPE_PARAM\n output[1] = start\n output[2] = start + 1 // skip '$'\n output[3] = end\n output[4] = end\n output[5] = end\n return output as ParsedSegment\n }\n\n const wildcardBracesMatch = part.match(WILDCARD_W_CURLY_BRACES_RE)\n if (wildcardBracesMatch) {\n const prefix = wildcardBracesMatch[1]!\n const pLength = prefix.length\n output[0] = SEGMENT_TYPE_WILDCARD\n output[1] = start + pLength\n output[2] = start + pLength + 1 // skip '{'\n output[3] = start + pLength + 2 // '$'\n output[4] = start + pLength + 3 // skip '}'\n output[5] = path.length\n return output as ParsedSegment\n }\n\n const optionalParamBracesMatch = part.match(OPTIONAL_PARAM_W_CURLY_BRACES_RE)\n if (optionalParamBracesMatch) {\n const prefix = optionalParamBracesMatch[1]!\n const paramName = optionalParamBracesMatch[2]!\n const suffix = optionalParamBracesMatch[3]!\n const pLength = prefix.length\n output[0] = SEGMENT_TYPE_OPTIONAL_PARAM\n output[1] = start + pLength\n output[2] = start + pLength + 3 // skip '{-$'\n output[3] = start + pLength + 3 + paramName.length\n output[4] = end - suffix.length\n output[5] = end\n return output as ParsedSegment\n }\n\n const paramBracesMatch = part.match(PARAM_W_CURLY_BRACES_RE)\n if (paramBracesMatch) {\n const prefix = paramBracesMatch[1]!\n const paramName = paramBracesMatch[2]!\n const suffix = paramBracesMatch[3]!\n const pLength = prefix.length\n output[0] = SEGMENT_TYPE_PARAM\n output[1] = start + pLength\n output[2] = start + pLength + 2 // skip '{$'\n output[3] = start + pLength + 2 + paramName.length\n output[4] = end - suffix.length\n output[5] = end\n return output as ParsedSegment\n }\n\n // fallback to static pathname (should never happen)\n output[0] = SEGMENT_TYPE_PATHNAME\n output[1] = start\n output[2] = start\n output[3] = end\n output[4] = end\n output[5] = end\n return output as ParsedSegment\n}\n\n/**\n * Recursively parses the segments of the given route tree and populates a segment trie.\n *\n * @param data A reusable Uint16Array for parsing segments. (non important, we're just avoiding allocations)\n * @param route The current route to parse.\n * @param start The starting index for parsing within the route's full path.\n * @param node The current segment node in the trie to populate.\n * @param onRoute Callback invoked for each route processed.\n */\nfunction parseSegments<TRouteLike extends RouteLike>(\n defaultCaseSensitive: boolean,\n data: Uint16Array,\n route: TRouteLike,\n start: number,\n node: AnySegmentNode<TRouteLike>,\n depth: number,\n onRoute?: (route: TRouteLike) => void,\n) {\n onRoute?.(route)\n let cursor = start\n {\n const path = route.fullPath ?? route.from\n const length = path.length\n const caseSensitive = route.options?.caseSensitive ?? defaultCaseSensitive\n while (cursor < length) {\n const segment = parseSegment(path, cursor, data)\n let nextNode: AnySegmentNode<TRouteLike>\n const start = cursor\n const end = segment[5]\n cursor = end + 1\n depth++\n const kind = segment[0]\n switch (kind) {\n case SEGMENT_TYPE_PATHNAME: {\n const value = path.substring(segment[2], segment[3])\n if (caseSensitive) {\n const existingNode = node.static?.get(value)\n if (existingNode) {\n nextNode = existingNode\n } else {\n node.static ??= new Map()\n const next = createStaticNode<TRouteLike>(\n route.fullPath ?? route.from,\n )\n next.parent = node\n next.depth = depth\n nextNode = next\n node.static.set(value, next)\n }\n } else {\n const name = value.toLowerCase()\n const existingNode = node.staticInsensitive?.get(name)\n if (existingNode) {\n nextNode = existingNode\n } else {\n node.staticInsensitive ??= new Map()\n const next = createStaticNode<TRouteLike>(\n route.fullPath ?? route.from,\n )\n next.parent = node\n next.depth = depth\n nextNode = next\n node.staticInsensitive.set(name, next)\n }\n }\n break\n }\n case SEGMENT_TYPE_PARAM: {\n const prefix_raw = path.substring(start, segment[1])\n const suffix_raw = path.substring(segment[4], end)\n const actuallyCaseSensitive =\n caseSensitive && !!(prefix_raw || suffix_raw)\n const prefix = !prefix_raw\n ? undefined\n : actuallyCaseSensitive\n ? prefix_raw\n : prefix_raw.toLowerCase()\n const suffix = !suffix_raw\n ? undefined\n : actuallyCaseSensitive\n ? suffix_raw\n : suffix_raw.toLowerCase()\n const existingNode = node.dynamic?.find(\n (s) =>\n s.caseSensitive === actuallyCaseSensitive &&\n s.prefix === prefix &&\n s.suffix === suffix,\n )\n if (existingNode) {\n nextNode = existingNode\n } else {\n const next = createDynamicNode<TRouteLike>(\n SEGMENT_TYPE_PARAM,\n route.fullPath ?? route.from,\n actuallyCaseSensitive,\n prefix,\n suffix,\n )\n nextNode = next\n next.depth = depth\n next.parent = node\n node.dynamic ??= []\n node.dynamic.push(next)\n }\n break\n }\n case SEGMENT_TYPE_OPTIONAL_PARAM: {\n const prefix_raw = path.substring(start, segment[1])\n const suffix_raw = path.substring(segment[4], end)\n const actuallyCaseSensitive =\n caseSensitive && !!(prefix_raw || suffix_raw)\n const prefix = !prefix_raw\n ? undefined\n : actuallyCaseSensitive\n ? prefix_raw\n : prefix_raw.toLowerCase()\n const suffix = !suffix_raw\n ? undefined\n : actuallyCaseSensitive\n ? suffix_raw\n : suffix_raw.toLowerCase()\n const existingNode = node.optional?.find(\n (s) =>\n s.caseSensitive === actuallyCaseSensitive &&\n s.prefix === prefix &&\n s.suffix === suffix,\n )\n if (existingNode) {\n nextNode = existingNode\n } else {\n const next = createDynamicNode<TRouteLike>(\n SEGMENT_TYPE_OPTIONAL_PARAM,\n route.fullPath ?? route.from,\n actuallyCaseSensitive,\n prefix,\n suffix,\n )\n nextNode = next\n next.parent = node\n next.depth = depth\n node.optional ??= []\n node.optional.push(next)\n }\n break\n }\n case SEGMENT_TYPE_WILDCARD: {\n const prefix_raw = path.substring(start, segment[1])\n const suffix_raw = path.substring(segment[4], end)\n const actuallyCaseSensitive =\n caseSensitive && !!(prefix_raw || suffix_raw)\n const prefix = !prefix_raw\n ? undefined\n : actuallyCaseSensitive\n ? prefix_raw\n : prefix_raw.toLowerCase()\n const suffix = !suffix_raw\n ? undefined\n : actuallyCaseSensitive\n ? suffix_raw\n : suffix_raw.toLowerCase()\n const next = createDynamicNode<TRouteLike>(\n SEGMENT_TYPE_WILDCARD,\n route.fullPath ?? route.from,\n actuallyCaseSensitive,\n prefix,\n suffix,\n )\n nextNode = next\n next.parent = node\n next.depth = depth\n node.wildcard ??= []\n node.wildcard.push(next)\n }\n }\n node = nextNode\n }\n if ((route.path || !route.children) && !route.isRoot) {\n const isIndex = path.endsWith('/')\n // we cannot fuzzy match an index route,\n // but if there is *also* a layout route at this path, save it as notFound\n // we can use it when fuzzy matching to display the NotFound component in the layout route\n if (!isIndex) node.notFound = route\n if (!node.route || (!node.isIndex && isIndex)) node.route = route\n node.isIndex ||= isIndex\n }\n }\n if (route.children)\n for (const child of route.children) {\n parseSegments(\n defaultCaseSensitive,\n data,\n child as TRouteLike,\n cursor,\n node,\n depth,\n onRoute,\n )\n }\n}\n\nfunction sortDynamic(\n a: { prefix?: string; suffix?: string; caseSensitive: boolean },\n b: { prefix?: string; suffix?: string; caseSensitive: boolean },\n) {\n if (a.prefix && b.prefix && a.prefix !== b.prefix) {\n if (a.prefix.startsWith(b.prefix)) return -1\n if (b.prefix.startsWith(a.prefix)) return 1\n }\n if (a.suffix && b.suffix && a.suffix !== b.suffix) {\n if (a.suffix.endsWith(b.suffix)) return -1\n if (b.suffix.endsWith(a.suffix)) return 1\n }\n if (a.prefix && !b.prefix) return -1\n if (!a.prefix && b.prefix) return 1\n if (a.suffix && !b.suffix) return -1\n if (!a.suffix && b.suffix) return 1\n if (a.caseSensitive && !b.caseSensitive) return -1\n if (!a.caseSensitive && b.caseSensitive) return 1\n\n // we don't need a tiebreaker here\n // at this point the 2 nodes cannot conflict during matching\n return 0\n}\n\nfunction sortTreeNodes(node: SegmentNode<RouteLike>) {\n if (node.static) {\n for (const child of node.static.values()) {\n sortTreeNodes(child)\n }\n }\n if (node.staticInsensitive) {\n for (const child of node.staticInsensitive.values()) {\n sortTreeNodes(child)\n }\n }\n if (node.dynamic?.length) {\n node.dynamic.sort(sortDynamic)\n for (const child of node.dynamic) {\n sortTreeNodes(child)\n }\n }\n if (node.optional?.length) {\n node.optional.sort(sortDynamic)\n for (const child of node.optional) {\n sortTreeNodes(child)\n }\n }\n if (node.wildcard?.length) {\n node.wildcard.sort(sortDynamic)\n for (const child of node.wildcard) {\n sortTreeNodes(child)\n }\n }\n}\n\nfunction createStaticNode<T extends RouteLike>(\n fullPath: string,\n): StaticSegmentNode<T> {\n return {\n kind: SEGMENT_TYPE_PATHNAME,\n depth: 0,\n static: null,\n staticInsensitive: null,\n dynamic: null,\n optional: null,\n wildcard: null,\n route: null,\n fullPath,\n parent: null,\n isIndex: false,\n notFound: null,\n }\n}\n\n/**\n * Keys must be declared in the same order as in `SegmentNode` type,\n * to ensure they are represented as the same object class in the engine.\n */\nfunction createDynamicNode<T extends RouteLike>(\n kind:\n | typeof SEGMENT_TYPE_PARAM\n | typeof SEGMENT_TYPE_WILDCARD\n | typeof SEGMENT_TYPE_OPTIONAL_PARAM,\n fullPath: string,\n caseSensitive: boolean,\n prefix?: string,\n suffix?: string,\n): DynamicSegmentNode<T> {\n return {\n kind,\n depth: 0,\n static: null,\n staticInsensitive: null,\n dynamic: null,\n optional: null,\n wildcard: null,\n route: null,\n fullPath,\n parent: null,\n isIndex: false,\n notFound: null,\n caseSensitive,\n prefix,\n suffix,\n }\n}\n\ntype StaticSegmentNode<T extends RouteLike> = SegmentNode<T> & {\n kind: typeof SEGMENT_TYPE_PATHNAME\n}\n\ntype DynamicSegmentNode<T extends RouteLike> = SegmentNode<T> & {\n kind:\n | typeof SEGMENT_TYPE_PARAM\n | typeof SEGMENT_TYPE_WILDCARD\n | typeof SEGMENT_TYPE_OPTIONAL_PARAM\n prefix?: string\n suffix?: string\n caseSensitive: boolean\n}\n\ntype AnySegmentNode<T extends RouteLike> =\n | StaticSegmentNode<T>\n | DynamicSegmentNode<T>\n\ntype SegmentNode<T extends RouteLike> = {\n kind: SegmentKind\n\n /** Static segments (highest priority) */\n static: Map<string, StaticSegmentNode<T>> | null\n\n /** Case insensitive static segments (second highest priority) */\n staticInsensitive: Map<string, StaticSegmentNode<T>> | null\n\n /** Dynamic segments ($param) */\n dynamic: Array<DynamicSegmentNode<T>> | null\n\n /** Optional dynamic segments ({-$param}) */\n optional: Array<DynamicSegmentNode<T>> | null\n\n /** Wildcard segments ($ - lowest priority) */\n wildcard: Array<DynamicSegmentNode<T>> | null\n\n /** Terminal route (if this path can end here) */\n route: T | null\n\n /** The full path for this segment node (will only be valid on leaf nodes) */\n fullPath: string\n\n parent: AnySegmentNode<T> | null\n\n depth: number\n\n /** is it an index route (trailing / path), only valid for nodes with a `route` */\n isIndex: boolean\n\n /** Same as `route`, but only present if both an \"index route\" and a \"layout route\" exist at this path */\n notFound: T | null\n}\n\ntype RouteLike = {\n path?: string // relative path from the parent,\n children?: Array<RouteLike> // child routes,\n parentRoute?: RouteLike // parent route,\n isRoot?: boolean\n options?: {\n caseSensitive?: boolean\n }\n} &\n // router tree\n (| { fullPath: string; from?: never } // full path from the root\n // flat route masks list\n | { fullPath?: never; from: string } // full path from the root\n )\n\nexport type ProcessedTree<\n TTree extends Extract<RouteLike, { fullPath: string }>,\n TFlat extends Extract<RouteLike, { from: string }>,\n TSingle extends Extract<RouteLike, { from: string }>,\n> = {\n /** a representation of the `routeTree` as a segment tree */\n segmentTree: AnySegmentNode<TTree>\n /** a mini route tree generated from the flat `routeMasks` list */\n masksTree: AnySegmentNode<TFlat> | null\n /** @deprecated keep until v2 so that `router.matchRoute` can keep not caring about the actual route tree */\n singleCache: LRUCache<string, AnySegmentNode<TSingle>>\n /** a cache of route matches from the `segmentTree` */\n matchCache: LRUCache<string, RouteMatch<TTree> | null>\n /** a cache of route matches from the `masksTree` */\n flatCache: LRUCache<string, ReturnType<typeof findMatch<TFlat>>> | null\n}\n\nexport function processRouteMasks<\n TRouteLike extends Extract<RouteLike, { from: string }>,\n>(\n routeList: Array<TRouteLike>,\n processedTree: ProcessedTree<any, TRouteLike, any>,\n) {\n const segmentTree = createStaticNode<TRouteLike>('/')\n const data = new Uint16Array(6)\n for (const route of routeList) {\n parseSegments(false, data, route, 1, segmentTree, 0)\n }\n sortTreeNodes(segmentTree)\n processedTree.masksTree = segmentTree\n processedTree.flatCache = createLRUCache<\n string,\n ReturnType<typeof findMatch<TRouteLike>>\n >(1000)\n}\n\n/**\n * Take an arbitrary list of routes, create a tree from them (if it hasn't been created already), and match a path against it.\n */\nexport function findFlatMatch<T extends Extract<RouteLike, { from: string }>>(\n /** The path to match. */\n path: string,\n /** The `processedTree` returned by the initial `processRouteTree` call. */\n processedTree: ProcessedTree<any, T, any>,\n) {\n path ||= '/'\n const cached = processedTree.flatCache!.get(path)\n if (cached) return cached\n const result = findMatch(path, processedTree.masksTree!)\n processedTree.flatCache!.set(path, result)\n return result\n}\n\n/**\n * @deprecated keep until v2 so that `router.matchRoute` can keep not caring about the actual route tree\n */\nexport function findSingleMatch(\n from: string,\n caseSensitive: boolean,\n fuzzy: boolean,\n path: string,\n processedTree: ProcessedTree<any, any, { from: string }>,\n) {\n from ||= '/'\n path ||= '/'\n const key = caseSensitive ? `case\\0${from}` : from\n let tree = processedTree.singleCache.get(key)\n if (!tree) {\n // single flat routes (router.matchRoute) are not eagerly processed,\n // if we haven't seen this route before, process it now\n tree = createStaticNode<{ from: string }>('/')\n const data = new Uint16Array(6)\n parseSegments(caseSensitive, data, { from }, 1, tree, 0)\n processedTree.singleCache.set(key, tree)\n }\n return findMatch(path, tree, fuzzy)\n}\n\ntype RouteMatch<T extends Extract<RouteLike, { fullPath: string }>> = {\n route: T\n params: Record<string, string>\n branch: ReadonlyArray<T>\n}\n\nexport function findRouteMatch<\n T extends Extract<RouteLike, { fullPath: string }>,\n>(\n /** The path to match against the route tree. */\n path: string,\n /** The `processedTree` returned by the initial `processRouteTree` call. */\n processedTree: ProcessedTree<T, any, any>,\n /** If `true`, allows fuzzy matching (partial matches), i.e. which node in the tree would have been an exact match if the `path` had been shorter? */\n fuzzy = false,\n): RouteMatch<T> | null {\n const key = fuzzy ? path : `nofuzz\\0${path}` // the main use for `findRouteMatch` is fuzzy:true, so we optimize for that case\n const cached = processedTree.matchCache.get(key)\n if (cached !== undefined) return cached\n path ||= '/'\n const result = findMatch(\n path,\n processedTree.segmentTree,\n fuzzy,\n ) as RouteMatch<T> | null\n if (result) result.branch = buildRouteBranch(result.route)\n processedTree.matchCache.set(key, result)\n return result\n}\n\n/** Trim trailing slashes (except preserving root '/'). */\nexport function trimPathRight(path: string) {\n return path === '/' ? path : path.replace(/\\/{1,}$/, '')\n}\n\n/**\n * Processes a route tree into a segment trie for efficient path matching.\n * Also builds lookup maps for routes by ID and by trimmed full path.\n */\nexport function processRouteTree<\n TRouteLike extends Extract<RouteLike, { fullPath: string }> & { id: string },\n>(\n /** The root of the route tree to process. */\n routeTree: TRouteLike,\n /** Whether matching should be case sensitive by default (overridden by individual route options). */\n caseSensitive: boolean = false,\n /** Optional callback invoked for each route during processing. */\n initRoute?: (route: TRouteLike, index: number) => void,\n): {\n /** Should be considered a black box, needs to be provided to all matching functions in this module. */\n processedTree: ProcessedTree<TRouteLike, any, any>\n /** A lookup map of routes by their unique IDs. */\n routesById: Record<string, TRouteLike>\n /** A lookup map of routes by their trimmed full paths. */\n routesByPath: Record<string, TRouteLike>\n} {\n const segmentTree = createStaticNode<TRouteLike>(routeTree.fullPath)\n const data = new Uint16Array(6)\n const routesById = {} as Record<string, TRouteLike>\n const routesByPath = {} as Record<string, TRouteLike>\n let index = 0\n parseSegments(caseSensitive, data, routeTree, 1, segmentTree, 0, (route) => {\n initRoute?.(route, index)\n\n invariant(\n !(route.id in routesById),\n `Duplicate routes found with id: ${String(route.id)}`,\n )\n\n routesById[route.id] = route\n\n if (index !== 0 && route.path) {\n const trimmedFullPath = trimPathRight(route.fullPath)\n if (!routesByPath[trimmedFullPath] || route.fullPath.endsWith('/')) {\n routesByPath[trimmedFullPath] = route\n }\n }\n\n index++\n })\n sortTreeNodes(segmentTree)\n const processedTree: ProcessedTree<TRouteLike, any, any> = {\n segmentTree,\n singleCache: createLRUCache<string, AnySegmentNode<any>>(1000),\n matchCache: createLRUCache<string, RouteMatch<TRouteLike> | null>(1000),\n flatCache: null,\n masksTree: null,\n }\n return {\n processedTree,\n routesById,\n routesByPath,\n }\n}\n\nfunction findMatch<T extends RouteLike>(\n path: string,\n segmentTree: AnySegmentNode<T>,\n fuzzy = false,\n): { route: T; params: Record<string, string> } | null {\n const parts = path.split('/')\n const leaf = getNodeMatch(path, parts, segmentTree, fuzzy)\n if (!leaf) return null\n const params = extractParams(path, parts, leaf)\n const isFuzzyMatch = '**' in leaf\n if (isFuzzyMatch) params['**'] = leaf['**']\n const route = isFuzzyMatch\n ? (leaf.node.notFound ?? leaf.node.route!)\n : leaf.node.route!\n return {\n route,\n params,\n }\n}\n\nfunction extractParams<T extends RouteLike>(\n path: string,\n parts: Array<string>,\n leaf: { node: AnySegmentNode<T>; skipped: number },\n) {\n const list = buildBranch(leaf.node)\n let nodeParts: Array<string> | null = null\n const params: Record<string, string> = {}\n for (\n let partIndex = 0, nodeIndex = 0, pathIndex = 0;\n nodeIndex < list.length;\n partIndex++, nodeIndex++, pathIndex++\n ) {\n const node = list[nodeIndex]!\n const part = parts[partIndex]\n const currentPathIndex = pathIndex\n if (part) pathIndex += part.length\n if (node.kind === SEGMENT_TYPE_PARAM) {\n nodeParts ??= leaf.node.fullPath.split('/')\n const nodePart = nodeParts[nodeIndex]!\n const preLength = node.prefix?.length ?? 0\n // we can't rely on the presence of prefix/suffix to know whether it's curly-braced or not, because `/{$param}/` is valid, but has no prefix/suffix\n const isCurlyBraced = nodePart.charCodeAt(preLength) === 123 // '{'\n // param name is extracted at match-time so that tree nodes that are identical except for param name can share the same node\n if (isCurlyBraced) {\n const sufLength = node.suffix?.length ?? 0\n const name = nodePart.substring(\n preLength + 2,\n nodePart.length - sufLength - 1,\n )\n const value = part!.substring(preLength, part!.length - sufLength)\n params[name] = decodeURIComponent(value)\n } else {\n const name = nodePart.substring(1)\n params[name] = decodeURIComponent(part!)\n }\n } else if (node.kind === SEGMENT_TYPE_OPTIONAL_PARAM) {\n if (leaf.skipped & (1 << nodeIndex)) {\n partIndex-- // stay on the same part\n continue\n }\n nodeParts ??= leaf.node.fullPath.split('/')\n const nodePart = nodeParts[nodeIndex]!\n const preLength = node.prefix?.length ?? 0\n const sufLength = node.suffix?.length ?? 0\n const name = nodePart.substring(\n preLength + 3,\n nodePart.length - sufLength - 1,\n )\n const value =\n node.suffix || node.prefix\n ? part!.substring(preLength, part!.length - sufLength)\n : part\n if (value) params[name] = decodeURIComponent(value)\n } else if (node.kind === SEGMENT_TYPE_WILDCARD) {\n const n = node\n const value = path.substring(\n currentPathIndex + (n.prefix?.length ?? 0),\n path.length - (n.suffix?.length ?? 0),\n )\n const splat = decodeURIComponent(value)\n // TODO: Deprecate *\n params['*'] = splat\n params._splat = splat\n break\n }\n }\n return params\n}\n\nfunction buildRouteBranch<T extends RouteLike>(route: T) {\n const list = [route]\n while (route.parentRoute) {\n route = route.parentRoute as T\n list.push(route)\n }\n list.reverse()\n return list\n}\n\nfunction buildBranch<T extends RouteLike>(node: AnySegmentNode<T>) {\n const list: Array<AnySegmentNode<T>> = Array(node.depth + 1)\n do {\n list[node.depth] = node\n node = node.parent!\n } while (node)\n return list\n}\n\ntype MatchStackFrame<T extends RouteLike> = {\n node: AnySegmentNode<T>\n /** index of the segment of path */\n index: number\n /** how many nodes between `node` and the root of the segment tree */\n depth: number\n /**\n * Bitmask of skipped optional segments.\n *\n * This is a very performant way of storing an \"array of booleans\", but it means beyond 32 segments we can't track skipped optionals.\n * If we really really need to support more than 32 segments we can switch to using a `BigInt` here. It's about 2x slower in worst case scenarios.\n */\n skipped: number\n statics: number\n dynamics: number\n optionals: number\n}\n\nfunction getNodeMatch<T extends RouteLike>(\n path: string,\n parts: Array<string>,\n segmentTree: AnySegmentNode<T>,\n fuzzy: boolean,\n) {\n const trailingSlash = !last(parts)\n const pathIsIndex = trailingSlash && path !== '/'\n const partsLength = parts.length - (trailingSlash ? 1 : 0)\n\n type Frame = MatchStackFrame<T>\n\n // use a stack to explore all possible paths (params cause branching)\n // iterate \"backwards\" (low priority first) so that we can push() each candidate, and pop() the highest priority candidate first\n // - pros: it is depth-first, so we find full matches faster\n // - cons: we cannot short-circuit, because highest priority matches are at the end of the loop (for loop with i--) (but we have no good short-circuiting anyway)\n // other possible approaches:\n // - shift instead of pop (measure performance difference), this allows iterating \"forwards\" (effectively breadth-first)\n // - never remove from the stack, keep a cursor instead. Then we can push \"forwards\" and avoid reversing the order of candidates (effectively breadth-first)\n const stack: Array<Frame> = [\n {\n node: segmentTree,\n index: 1,\n skipped: 0,\n depth: 1,\n statics: 1,\n dynamics: 0,\n optionals: 0,\n },\n ]\n\n let wildcardMatch: Frame | null = null\n let bestFuzzy: Frame | null = null\n let bestMatch: Frame | null = null\n\n while (stack.length) {\n const frame = stack.pop()!\n // eslint-disable-next-line prefer-const\n let { node, index, skipped, depth, statics, dynamics, optionals } = frame\n\n // In fuzzy mode, track the best partial match we've found so far\n if (fuzzy && node.notFound && isFrameMoreSpecific(bestFuzzy, frame)) {\n bestFuzzy = frame\n }\n\n const isBeyondPath = index === partsLength\n if (isBeyondPath) {\n if (node.route && (!pathIsIndex || node.isIndex)) {\n if (isFrameMoreSpecific(bestMatch, frame)) {\n bestMatch = frame\n }\n\n // perfect match, no need to continue\n if (statics === partsLength && node.isIndex) return bestMatch\n }\n // beyond the length of the path parts, only skipped optional segments or wildcard segments can match\n if (!node.optional && !node.wildcard) continue\n }\n\n const part = isBeyondPath ? undefined : parts[index]!\n let lowerPart: string\n\n // 5. Try wildcard match\n if (node.wildcard && isFrameMoreSpecific(wildcardMatch, frame)) {\n for (const segment of node.wildcard) {\n const { prefix, suffix } = segment\n if (prefix) {\n if (isBeyondPath) continue\n const casePart = segment.caseSensitive\n ? part\n : (lowerPart ??= part!.toLowerCase())\n if (!casePart!.startsWith(prefix)) continue\n }\n if (suffix) {\n if (isBeyondPath) continue\n const end = parts.slice(index).join('/').slice(-suffix.length)\n const casePart = segment.caseSensitive ? end : end.toLowerCase()\n if (casePart !== suffix) continue\n }\n // the first wildcard match is the highest priority one\n wildcardMatch = {\n node: segment,\n index,\n skipped,\n depth,\n statics,\n dynamics,\n optionals,\n }\n break\n }\n }\n\n // 4. Try optional match\n if (node.optional) {\n const nextSkipped = skipped | (1 << depth)\n const nextDepth = depth + 1\n for (let i = node.optional.length - 1; i >= 0; i--) {\n const segment = node.optional[i]!\n // when skipping, node and depth advance by 1, but index doesn't\n stack.push({\n node: segment,\n index,\n skipped: nextSkipped,\n depth: nextDepth,\n statics,\n dynamics,\n optionals,\n }) // enqueue skipping the optional\n }\n if (!isBeyondPath) {\n for (let i = node.optional.length - 1; i >= 0; i--) {\n const segment = node.optional[i]!\n const { prefix, suffix } = segment\n if (prefix || suffix) {\n const casePart = segment.caseSensitive\n ? part!\n : (lowerPart ??= part!.toLowerCase())\n if (prefix && !casePart.startsWith(prefix)) continue\n if (suffix && !casePart.endsWith(suffix)) continue\n }\n stack.push({\n node: segment,\n index: index + 1,\n skipped,\n depth: nextDepth,\n statics,\n dynamics,\n optionals: optionals + 1,\n })\n }\n }\n }\n\n // 3. Try dynamic match\n if (!isBeyondPath && node.dynamic && part) {\n for (let i = node.dynamic.length - 1; i >= 0; i--) {\n const segment = node.dynamic[i]!\n const { prefix, suffix } = segment\n if (prefix || suffix) {\n const casePart = segment.caseSensitive\n ? part\n : (lowerPart ??= part.toLowerCase())\n if (prefix && !casePart.startsWith(prefix)) continue\n if (suffix && !casePart.endsWith(suffix)) continue\n }\n stack.push({\n node: segment,\n index: index + 1,\n skipped,\n depth: depth + 1,\n statics,\n dynamics: dynamics + 1,\n optionals,\n })\n }\n }\n\n // 2. Try case insensitive static match\n if (!isBeyondPath && node.staticInsensitive) {\n const match = node.staticInsensitive.get(\n (lowerPart ??= part!.toLowerCase()),\n )\n if (match) {\n stack.push({\n node: match,\n index: index + 1,\n skipped,\n depth: depth + 1,\n statics: statics + 1,\n dynamics,\n optionals,\n })\n }\n }\n\n // 1. Try static match\n if (!isBeyondPath && node.static) {\n const match = node.static.get(part!)\n if (match) {\n stack.push({\n node: match,\n index: index + 1,\n skipped,\n depth: depth + 1,\n statics: statics + 1,\n dynamics,\n optionals,\n })\n }\n }\n }\n\n if (bestMatch) return bestMatch\n\n if (wildcardMatch) return wildcardMatch\n\n if (fuzzy && bestFuzzy) {\n let sliceIndex = bestFuzzy.index\n for (let i = 0; i < bestFuzzy.index; i++) {\n sliceIndex += parts[i]!.length\n }\n const splat = sliceIndex === path.length ? '/' : path.slice(sliceIndex)\n return {\n node: bestFuzzy.node,\n skipped: bestFuzzy.skipped,\n '**': decodeURIComponent(splat),\n }\n }\n\n return null\n}\n\nfunction isFrameMoreSpecific(\n // the stack frame previously saved as \"best match\"\n prev: MatchStackFrame<any> | null,\n // the candidate stack frame\n next: MatchStackFrame<any>,\n): boolean {\n if (!prev) return true\n return (\n next.statics > prev.statics ||\n (next.statics === prev.statics &&\n (next.dynamics > prev.dynamics ||\n (next.dynamics === prev.dynamics &&\n (next.optionals > prev.optionals ||\n (next.optionals === prev.optionals &&\n (next.node.isIndex > prev.node.isIndex ||\n (next.node.isIndex === prev.node.isIndex &&\n next.depth > prev.depth)))))))\n )\n}\n"],"names":["start","createLRUCache","last"],"mappings":";;;;;AAKO,MAAM,wBAAwB;AAC9B,MAAM,qBAAqB;AAC3B,MAAM,wBAAwB;AAC9B,MAAM,8BAA8B;AAQ3C,MAAM,0BACJ;AACF,MAAM,mCACJ;AACF,MAAM,6BAA6B;AAiC5B,SAAS,aAEd,MAEA,OAEA,SAAsB,IAAI,YAAY,CAAC,GACxB;AACf,QAAM,OAAO,KAAK,QAAQ,KAAK,KAAK;AACpC,QAAM,MAAM,SAAS,KAAK,KAAK,SAAS;AACxC,QAAM,OAAO,KAAK,UAAU,OAAO,GAAG;AAEtC,MAAI,CAAC,QAAQ,CAAC,KAAK,SAAS,GAAG,GAAG;AAEhC,WAAO,CAAC,IAAI;AACZ,WAAO,CAAC,IAAI;AACZ,WAAO,CAAC,IAAI;AACZ,WAAO,CAAC,IAAI;AACZ,WAAO,CAAC,IAAI;AACZ,WAAO,CAAC,IAAI;AACZ,WAAO;AAAA,EACT;AAGA,MAAI,SAAS,KAAK;AAChB,UAAM,QA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UACf;AAAA,UACA,OAAO,QAAQ;AAAA,UACf,SAAS,UAAU;AAAA,UACnB;AAAA,UACA;AAAA,QAAA,CACD;AAAA,MACH;AAAA,IACF;AAGA,QAAI,CAAC,gBAAgB,KAAK,QAAQ;AAChC,YAAM,QAAQ,KAAK,OAAO,IAAI,IAAK;AACnC,UAAI,OAAO;AACT,cAAM,KAAK;AAAA,UACT,MAAM;AAAA,UACN,OAAO,QAAQ;AAAA,UACf;AAAA,UACA,OAAO,QAAQ;AAAA,UACf,SAAS,UAAU;AAAA,UACnB;AAAA,UACA;AAAA,QAAA,CACD;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAEA,MAAI,UAAW,QAAO;AAEtB,MAAI,cAAe,QAAO;AAE1B,MAAI,SAAS,WAAW;AACtB,QAAI,aAAa,UAAU;AAC3B,aAAS,IAAI,GAAG,IAAI,UAAU,OAAO,KAAK;AACxC,oBAAc,MAAM,CAAC,EAAG;AAAA,IAC1B;AACA,UAAM,QAAQ,eAAe,KAAK,SAAS,MAAM,KAAK,MAAM,UAAU;AACtE,WAAO;AAAA,MACL,MAAM,UAAU;AAAA,MAChB,SAAS,UAAU;AAAA,MACnB,MAAM,mBAAmB,KAAK;AAAA,IAAA;AAAA,EAElC;AAEA,SAAO;AACT;AAEA,SAAS,oBAEP,MAEA,MACS;AACT,MAAI,CAAC,KAAM,QAAO;AAClB,SACE,KAAK,UAAU,KAAK,WACnB,KAAK,YAAY,KAAK,YACpB,KAAK,WAAW,KAAK,YACnB,KAAK,aAAa,KAAK,aACrB,KAAK,YAAY,KAAK,aACpB,KAAK,cAAc,KAAK,cACtB,KAAK,KAAK,UAAU,KAAK,KAAK,WAC5B,KAAK,KAAK,YAAY,KAAK,KAAK,WAC/B,KAAK,QAAQ,KAAK;AAEpC;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"new-process-route-tree.cjs","sources":["../../src/new-process-route-tree.ts"],"sourcesContent":["import invariant from 'tiny-invariant'\nimport { createLRUCache } from './lru-cache'\nimport { last } from './utils'\nimport type { LRUCache } from './lru-cache'\n\nexport const SEGMENT_TYPE_PATHNAME = 0\nexport const SEGMENT_TYPE_PARAM = 1\nexport const SEGMENT_TYPE_WILDCARD = 2\nexport const SEGMENT_TYPE_OPTIONAL_PARAM = 3\n\nexport type SegmentKind =\n | typeof SEGMENT_TYPE_PATHNAME\n | typeof SEGMENT_TYPE_PARAM\n | typeof SEGMENT_TYPE_WILDCARD\n | typeof SEGMENT_TYPE_OPTIONAL_PARAM\n\nconst PARAM_W_CURLY_BRACES_RE =\n /^([^{]*)\\{\\$([a-zA-Z_$][a-zA-Z0-9_$]*)\\}([^}]*)$/ // prefix{$paramName}suffix\nconst OPTIONAL_PARAM_W_CURLY_BRACES_RE =\n /^([^{]*)\\{-\\$([a-zA-Z_$][a-zA-Z0-9_$]*)\\}([^}]*)$/ // prefix{-$paramName}suffix\nconst WILDCARD_W_CURLY_BRACES_RE = /^([^{]*)\\{\\$\\}([^}]*)$/ // prefix{$}suffix\n\ntype ParsedSegment = Uint16Array & {\n /** segment type (0 = pathname, 1 = param, 2 = wildcard, 3 = optional param) */\n 0: SegmentKind\n /** index of the end of the prefix */\n 1: number\n /** index of the start of the value */\n 2: number\n /** index of the end of the value */\n 3: number\n /** index of the start of the suffix */\n 4: number\n /** index of the end of the segment */\n 5: number\n}\n\n/**\n * Populates the `output` array with the parsed representation of the given `segment` string.\n *\n * Usage:\n * ```ts\n * let output\n * let cursor = 0\n * while (cursor < path.length) {\n * output = parseSegment(path, cursor, output)\n * const end = output[5]\n * cursor = end + 1\n * ```\n *\n * `output` is stored outside to avoid allocations during repeated calls. It doesn't need to be typed\n * or initialized, it will be done automatically.\n */\nexport function parseSegment(\n /** The full path string containing the segment. */\n path: string,\n /** The starting index of the segment within the path. */\n start: number,\n /** A Uint16Array (length: 6) to populate with the parsed segment data. */\n output: Uint16Array = new Uint16Array(6),\n): ParsedSegment {\n const next = path.indexOf('/', start)\n const end = next === -1 ? path.length : next\n const part = path.substring(start, end)\n\n if (!part || !part.includes('$')) {\n // early escape for static pathname\n output[0] = SEGMENT_TYPE_PATHNAME\n output[1] = start\n output[2] = start\n output[3] = end\n output[4] = end\n output[5] = end\n return output as ParsedSegment\n }\n\n // $ (wildcard)\n if (part === '$') {\n const total = path.length\n output[0] = SEGMENT_TYPE_WILDCARD\n output[1] = start\n output[2] = start\n output[3] = total\n output[4] = total\n output[5] = total\n return output as ParsedSegment\n }\n\n // $paramName\n if (part.charCodeAt(0) === 36) {\n output[0] = SEGMENT_TYPE_PARAM\n output[1] = start\n output[2] = start + 1 // skip '$'\n output[3] = end\n output[4] = end\n output[5] = end\n return output as ParsedSegment\n }\n\n const wildcardBracesMatch = part.match(WILDCARD_W_CURLY_BRACES_RE)\n if (wildcardBracesMatch) {\n const prefix = wildcardBracesMatch[1]!\n const pLength = prefix.length\n output[0] = SEGMENT_TYPE_WILDCARD\n output[1] = start + pLength\n output[2] = start + pLength + 1 // skip '{'\n output[3] = start + pLength + 2 // '$'\n output[4] = start + pLength + 3 // skip '}'\n output[5] = path.length\n return output as ParsedSegment\n }\n\n const optionalParamBracesMatch = part.match(OPTIONAL_PARAM_W_CURLY_BRACES_RE)\n if (optionalParamBracesMatch) {\n const prefix = optionalParamBracesMatch[1]!\n const paramName = optionalParamBracesMatch[2]!\n const suffix = optionalParamBracesMatch[3]!\n const pLength = prefix.length\n output[0] = SEGMENT_TYPE_OPTIONAL_PARAM\n output[1] = start + pLength\n output[2] = start + pLength + 3 // skip '{-$'\n output[3] = start + pLength + 3 + paramName.length\n output[4] = end - suffix.length\n output[5] = end\n return output as ParsedSegment\n }\n\n const paramBracesMatch = part.match(PARAM_W_CURLY_BRACES_RE)\n if (paramBracesMatch) {\n const prefix = paramBracesMatch[1]!\n const paramName = paramBracesMatch[2]!\n const suffix = paramBracesMatch[3]!\n const pLength = prefix.length\n output[0] = SEGMENT_TYPE_PARAM\n output[1] = start + pLength\n output[2] = start + pLength + 2 // skip '{$'\n output[3] = start + pLength + 2 + paramName.length\n output[4] = end - suffix.length\n output[5] = end\n return output as ParsedSegment\n }\n\n // fallback to static pathname (should never happen)\n output[0] = SEGMENT_TYPE_PATHNAME\n output[1] = start\n output[2] = start\n output[3] = end\n output[4] = end\n output[5] = end\n return output as ParsedSegment\n}\n\n/**\n * Recursively parses the segments of the given route tree and populates a segment trie.\n *\n * @param data A reusable Uint16Array for parsing segments. (non important, we're just avoiding allocations)\n * @param route The current route to parse.\n * @param start The starting index for parsing within the route's full path.\n * @param node The current segment node in the trie to populate.\n * @param onRoute Callback invoked for each route processed.\n */\nfunction parseSegments<TRouteLike extends RouteLike>(\n defaultCaseSensitive: boolean,\n data: Uint16Array,\n route: TRouteLike,\n start: number,\n node: AnySegmentNode<TRouteLike>,\n depth: number,\n onRoute?: (route: TRouteLike) => void,\n) {\n onRoute?.(route)\n let cursor = start\n {\n const path = route.fullPath ?? route.from\n const length = path.length\n const caseSensitive = route.options?.caseSensitive ?? defaultCaseSensitive\n while (cursor < length) {\n const segment = parseSegment(path, cursor, data)\n let nextNode: AnySegmentNode<TRouteLike>\n const start = cursor\n const end = segment[5]\n cursor = end + 1\n depth++\n const kind = segment[0]\n switch (kind) {\n case SEGMENT_TYPE_PATHNAME: {\n const value = path.substring(segment[2], segment[3])\n if (caseSensitive) {\n const existingNode = node.static?.get(value)\n if (existingNode) {\n nextNode = existingNode\n } else {\n node.static ??= new Map()\n const next = createStaticNode<TRouteLike>(\n route.fullPath ?? route.from,\n )\n next.parent = node\n next.depth = depth\n nextNode = next\n node.static.set(value, next)\n }\n } else {\n const name = value.toLowerCase()\n const existingNode = node.staticInsensitive?.get(name)\n if (existingNode) {\n nextNode = existingNode\n } else {\n node.staticInsensitive ??= new Map()\n const next = createStaticNode<TRouteLike>(\n route.fullPath ?? route.from,\n )\n next.parent = node\n next.depth = depth\n nextNode = next\n node.staticInsensitive.set(name, next)\n }\n }\n break\n }\n case SEGMENT_TYPE_PARAM: {\n const prefix_raw = path.substring(start, segment[1])\n const suffix_raw = path.substring(segment[4], end)\n const actuallyCaseSensitive =\n caseSensitive && !!(prefix_raw || suffix_raw)\n const prefix = !prefix_raw\n ? undefined\n : actuallyCaseSensitive\n ? prefix_raw\n : prefix_raw.toLowerCase()\n const suffix = !suffix_raw\n ? undefined\n : actuallyCaseSensitive\n ? suffix_raw\n : suffix_raw.toLowerCase()\n const existingNode = node.dynamic?.find(\n (s) =>\n s.caseSensitive === actuallyCaseSensitive &&\n s.prefix === prefix &&\n s.suffix === suffix,\n )\n if (existingNode) {\n nextNode = existingNode\n } else {\n const next = createDynamicNode<TRouteLike>(\n SEGMENT_TYPE_PARAM,\n route.fullPath ?? route.from,\n actuallyCaseSensitive,\n prefix,\n suffix,\n )\n nextNode = next\n next.depth = depth\n next.parent = node\n node.dynamic ??= []\n node.dynamic.push(next)\n }\n break\n }\n case SEGMENT_TYPE_OPTIONAL_PARAM: {\n const prefix_raw = path.substring(start, segment[1])\n const suffix_raw = path.substring(segment[4], end)\n const actuallyCaseSensitive =\n caseSensitive && !!(prefix_raw || suffix_raw)\n const prefix = !prefix_raw\n ? undefined\n : actuallyCaseSensitive\n ? prefix_raw\n : prefix_raw.toLowerCase()\n const suffix = !suffix_raw\n ? undefined\n : actuallyCaseSensitive\n ? suffix_raw\n : suffix_raw.toLowerCase()\n const existingNode = node.optional?.find(\n (s) =>\n s.caseSensitive === actuallyCaseSensitive &&\n s.prefix === prefix &&\n s.suffix === suffix,\n )\n if (existingNode) {\n nextNode = existingNode\n } else {\n const next = createDynamicNode<TRouteLike>(\n SEGMENT_TYPE_OPTIONAL_PARAM,\n route.fullPath ?? route.from,\n actuallyCaseSensitive,\n prefix,\n suffix,\n )\n nextNode = next\n next.parent = node\n next.depth = depth\n node.optional ??= []\n node.optional.push(next)\n }\n break\n }\n case SEGMENT_TYPE_WILDCARD: {\n const prefix_raw = path.substring(start, segment[1])\n const suffix_raw = path.substring(segment[4], end)\n const actuallyCaseSensitive =\n caseSensitive && !!(prefix_raw || suffix_raw)\n const prefix = !prefix_raw\n ? undefined\n : actuallyCaseSensitive\n ? prefix_raw\n : prefix_raw.toLowerCase()\n const suffix = !suffix_raw\n ? undefined\n : actuallyCaseSensitive\n ? suffix_raw\n : suffix_raw.toLowerCase()\n const next = createDynamicNode<TRouteLike>(\n SEGMENT_TYPE_WILDCARD,\n route.fullPath ?? route.from,\n actuallyCaseSensitive,\n prefix,\n suffix,\n )\n nextNode = next\n next.parent = node\n next.depth = depth\n node.wildcard ??= []\n node.wildcard.push(next)\n }\n }\n node = nextNode\n }\n if ((route.path || !route.children) && !route.isRoot) {\n const isIndex = path.endsWith('/')\n // we cannot fuzzy match an index route,\n // but if there is *also* a layout route at this path, save it as notFound\n // we can use it when fuzzy matching to display the NotFound component in the layout route\n if (!isIndex) node.notFound = route\n if (!node.route || (!node.isIndex && isIndex)) node.route = route\n node.isIndex ||= isIndex\n }\n }\n if (route.children)\n for (const child of route.children) {\n parseSegments(\n defaultCaseSensitive,\n data,\n child as TRouteLike,\n cursor,\n node,\n depth,\n onRoute,\n )\n }\n}\n\nfunction sortDynamic(\n a: { prefix?: string; suffix?: string; caseSensitive: boolean },\n b: { prefix?: string; suffix?: string; caseSensitive: boolean },\n) {\n if (a.prefix && b.prefix && a.prefix !== b.prefix) {\n if (a.prefix.startsWith(b.prefix)) return -1\n if (b.prefix.startsWith(a.prefix)) return 1\n }\n if (a.suffix && b.suffix && a.suffix !== b.suffix) {\n if (a.suffix.endsWith(b.suffix)) return -1\n if (b.suffix.endsWith(a.suffix)) return 1\n }\n if (a.prefix && !b.prefix) return -1\n if (!a.prefix && b.prefix) return 1\n if (a.suffix && !b.suffix) return -1\n if (!a.suffix && b.suffix) return 1\n if (a.caseSensitive && !b.caseSensitive) return -1\n if (!a.caseSensitive && b.caseSensitive) return 1\n\n // we don't need a tiebreaker here\n // at this point the 2 nodes cannot conflict during matching\n return 0\n}\n\nfunction sortTreeNodes(node: SegmentNode<RouteLike>) {\n if (node.static) {\n for (const child of node.static.values()) {\n sortTreeNodes(child)\n }\n }\n if (node.staticInsensitive) {\n for (const child of node.staticInsensitive.values()) {\n sortTreeNodes(child)\n }\n }\n if (node.dynamic?.length) {\n node.dynamic.sort(sortDynamic)\n for (const child of node.dynamic) {\n sortTreeNodes(child)\n }\n }\n if (node.optional?.length) {\n node.optional.sort(sortDynamic)\n for (const child of node.optional) {\n sortTreeNodes(child)\n }\n }\n if (node.wildcard?.length) {\n node.wildcard.sort(sortDynamic)\n for (const child of node.wildcard) {\n sortTreeNodes(child)\n }\n }\n}\n\nfunction createStaticNode<T extends RouteLike>(\n fullPath: string,\n): StaticSegmentNode<T> {\n return {\n kind: SEGMENT_TYPE_PATHNAME,\n depth: 0,\n static: null,\n staticInsensitive: null,\n dynamic: null,\n optional: null,\n wildcard: null,\n route: null,\n fullPath,\n parent: null,\n isIndex: false,\n notFound: null,\n }\n}\n\n/**\n * Keys must be declared in the same order as in `SegmentNode` type,\n * to ensure they are represented as the same object class in the engine.\n */\nfunction createDynamicNode<T extends RouteLike>(\n kind:\n | typeof SEGMENT_TYPE_PARAM\n | typeof SEGMENT_TYPE_WILDCARD\n | typeof SEGMENT_TYPE_OPTIONAL_PARAM,\n fullPath: string,\n caseSensitive: boolean,\n prefix?: string,\n suffix?: string,\n): DynamicSegmentNode<T> {\n return {\n kind,\n depth: 0,\n static: null,\n staticInsensitive: null,\n dynamic: null,\n optional: null,\n wildcard: null,\n route: null,\n fullPath,\n parent: null,\n isIndex: false,\n notFound: null,\n caseSensitive,\n prefix,\n suffix,\n }\n}\n\ntype StaticSegmentNode<T extends RouteLike> = SegmentNode<T> & {\n kind: typeof SEGMENT_TYPE_PATHNAME\n}\n\ntype DynamicSegmentNode<T extends RouteLike> = SegmentNode<T> & {\n kind:\n | typeof SEGMENT_TYPE_PARAM\n | typeof SEGMENT_TYPE_WILDCARD\n | typeof SEGMENT_TYPE_OPTIONAL_PARAM\n prefix?: string\n suffix?: string\n caseSensitive: boolean\n}\n\ntype AnySegmentNode<T extends RouteLike> =\n | StaticSegmentNode<T>\n | DynamicSegmentNode<T>\n\ntype SegmentNode<T extends RouteLike> = {\n kind: SegmentKind\n\n /** Static segments (highest priority) */\n static: Map<string, StaticSegmentNode<T>> | null\n\n /** Case insensitive static segments (second highest priority) */\n staticInsensitive: Map<string, StaticSegmentNode<T>> | null\n\n /** Dynamic segments ($param) */\n dynamic: Array<DynamicSegmentNode<T>> | null\n\n /** Optional dynamic segments ({-$param}) */\n optional: Array<DynamicSegmentNode<T>> | null\n\n /** Wildcard segments ($ - lowest priority) */\n wildcard: Array<DynamicSegmentNode<T>> | null\n\n /** Terminal route (if this path can end here) */\n route: T | null\n\n /** The full path for this segment node (will only be valid on leaf nodes) */\n fullPath: string\n\n parent: AnySegmentNode<T> | null\n\n depth: number\n\n /** is it an index route (trailing / path), only valid for nodes with a `route` */\n isIndex: boolean\n\n /** Same as `route`, but only present if both an \"index route\" and a \"layout route\" exist at this path */\n notFound: T | null\n}\n\ntype RouteLike = {\n path?: string // relative path from the parent,\n children?: Array<RouteLike> // child routes,\n parentRoute?: RouteLike // parent route,\n isRoot?: boolean\n options?: {\n caseSensitive?: boolean\n }\n} &\n // router tree\n (| { fullPath: string; from?: never } // full path from the root\n // flat route masks list\n | { fullPath?: never; from: string } // full path from the root\n )\n\nexport type ProcessedTree<\n TTree extends Extract<RouteLike, { fullPath: string }>,\n TFlat extends Extract<RouteLike, { from: string }>,\n TSingle extends Extract<RouteLike, { from: string }>,\n> = {\n /** a representation of the `routeTree` as a segment tree */\n segmentTree: AnySegmentNode<TTree>\n /** a mini route tree generated from the flat `routeMasks` list */\n masksTree: AnySegmentNode<TFlat> | null\n /** @deprecated keep until v2 so that `router.matchRoute` can keep not caring about the actual route tree */\n singleCache: LRUCache<string, AnySegmentNode<TSingle>>\n /** a cache of route matches from the `segmentTree` */\n matchCache: LRUCache<string, RouteMatch<TTree> | null>\n /** a cache of route matches from the `masksTree` */\n flatCache: LRUCache<string, ReturnType<typeof findMatch<TFlat>>> | null\n}\n\nexport function processRouteMasks<\n TRouteLike extends Extract<RouteLike, { from: string }>,\n>(\n routeList: Array<TRouteLike>,\n processedTree: ProcessedTree<any, TRouteLike, any>,\n) {\n const segmentTree = createStaticNode<TRouteLike>('/')\n const data = new Uint16Array(6)\n for (const route of routeList) {\n parseSegments(false, data, route, 1, segmentTree, 0)\n }\n sortTreeNodes(segmentTree)\n processedTree.masksTree = segmentTree\n processedTree.flatCache = createLRUCache<\n string,\n ReturnType<typeof findMatch<TRouteLike>>\n >(1000)\n}\n\n/**\n * Take an arbitrary list of routes, create a tree from them (if it hasn't been created already), and match a path against it.\n */\nexport function findFlatMatch<T extends Extract<RouteLike, { from: string }>>(\n /** The path to match. */\n path: string,\n /** The `processedTree` returned by the initial `processRouteTree` call. */\n processedTree: ProcessedTree<any, T, any>,\n) {\n path ||= '/'\n const cached = processedTree.flatCache!.get(path)\n if (cached) return cached\n const result = findMatch(path, processedTree.masksTree!)\n processedTree.flatCache!.set(path, result)\n return result\n}\n\n/**\n * @deprecated keep until v2 so that `router.matchRoute` can keep not caring about the actual route tree\n */\nexport function findSingleMatch(\n from: string,\n caseSensitive: boolean,\n fuzzy: boolean,\n path: string,\n processedTree: ProcessedTree<any, any, { from: string }>,\n) {\n from ||= '/'\n path ||= '/'\n const key = caseSensitive ? `case\\0${from}` : from\n let tree = processedTree.singleCache.get(key)\n if (!tree) {\n // single flat routes (router.matchRoute) are not eagerly processed,\n // if we haven't seen this route before, process it now\n tree = createStaticNode<{ from: string }>('/')\n const data = new Uint16Array(6)\n parseSegments(caseSensitive, data, { from }, 1, tree, 0)\n processedTree.singleCache.set(key, tree)\n }\n return findMatch(path, tree, fuzzy)\n}\n\ntype RouteMatch<T extends Extract<RouteLike, { fullPath: string }>> = {\n route: T\n params: Record<string, string>\n branch: ReadonlyArray<T>\n}\n\nexport function findRouteMatch<\n T extends Extract<RouteLike, { fullPath: string }>,\n>(\n /** The path to match against the route tree. */\n path: string,\n /** The `processedTree` returned by the initial `processRouteTree` call. */\n processedTree: ProcessedTree<T, any, any>,\n /** If `true`, allows fuzzy matching (partial matches), i.e. which node in the tree would have been an exact match if the `path` had been shorter? */\n fuzzy = false,\n): RouteMatch<T> | null {\n const key = fuzzy ? path : `nofuzz\\0${path}` // the main use for `findRouteMatch` is fuzzy:true, so we optimize for that case\n const cached = processedTree.matchCache.get(key)\n if (cached !== undefined) return cached\n path ||= '/'\n const result = findMatch(\n path,\n processedTree.segmentTree,\n fuzzy,\n ) as RouteMatch<T> | null\n if (result) result.branch = buildRouteBranch(result.route)\n processedTree.matchCache.set(key, result)\n return result\n}\n\n/** Trim trailing slashes (except preserving root '/'). */\nexport function trimPathRight(path: string) {\n return path === '/' ? path : path.replace(/\\/{1,}$/, '')\n}\n\n/**\n * Processes a route tree into a segment trie for efficient path matching.\n * Also builds lookup maps for routes by ID and by trimmed full path.\n */\nexport function processRouteTree<\n TRouteLike extends Extract<RouteLike, { fullPath: string }> & { id: string },\n>(\n /** The root of the route tree to process. */\n routeTree: TRouteLike,\n /** Whether matching should be case sensitive by default (overridden by individual route options). */\n caseSensitive: boolean = false,\n /** Optional callback invoked for each route during processing. */\n initRoute?: (route: TRouteLike, index: number) => void,\n): {\n /** Should be considered a black box, needs to be provided to all matching functions in this module. */\n processedTree: ProcessedTree<TRouteLike, any, any>\n /** A lookup map of routes by their unique IDs. */\n routesById: Record<string, TRouteLike>\n /** A lookup map of routes by their trimmed full paths. */\n routesByPath: Record<string, TRouteLike>\n} {\n const segmentTree = createStaticNode<TRouteLike>(routeTree.fullPath)\n const data = new Uint16Array(6)\n const routesById = {} as Record<string, TRouteLike>\n const routesByPath = {} as Record<string, TRouteLike>\n let index = 0\n parseSegments(caseSensitive, data, routeTree, 1, segmentTree, 0, (route) => {\n initRoute?.(route, index)\n\n invariant(\n !(route.id in routesById),\n `Duplicate routes found with id: ${String(route.id)}`,\n )\n\n routesById[route.id] = route\n\n if (index !== 0 && route.path) {\n const trimmedFullPath = trimPathRight(route.fullPath)\n if (!routesByPath[trimmedFullPath] || route.fullPath.endsWith('/')) {\n routesByPath[trimmedFullPath] = route\n }\n }\n\n index++\n })\n sortTreeNodes(segmentTree)\n const processedTree: ProcessedTree<TRouteLike, any, any> = {\n segmentTree,\n singleCache: createLRUCache<string, AnySegmentNode<any>>(1000),\n matchCache: createLRUCache<string, RouteMatch<TRouteLike> | null>(1000),\n flatCache: null,\n masksTree: null,\n }\n return {\n processedTree,\n routesById,\n routesByPath,\n }\n}\n\nfunction findMatch<T extends RouteLike>(\n path: string,\n segmentTree: AnySegmentNode<T>,\n fuzzy = false,\n): { route: T; params: Record<string, string> } | null {\n const parts = path.split('/')\n const leaf = getNodeMatch(path, parts, segmentTree, fuzzy)\n if (!leaf) return null\n const params = extractParams(path, parts, leaf)\n const isFuzzyMatch = '**' in leaf\n if (isFuzzyMatch) params['**'] = leaf['**']\n const route = isFuzzyMatch\n ? (leaf.node.notFound ?? leaf.node.route!)\n : leaf.node.route!\n return {\n route,\n params,\n }\n}\n\nfunction extractParams<T extends RouteLike>(\n path: string,\n parts: Array<string>,\n leaf: { node: AnySegmentNode<T>; skipped: number },\n) {\n const list = buildBranch(leaf.node)\n let nodeParts: Array<string> | null = null\n const params: Record<string, string> = {}\n for (\n let partIndex = 0, nodeIndex = 0, pathIndex = 0;\n nodeIndex < list.length;\n partIndex++, nodeIndex++, pathIndex++\n ) {\n const node = list[nodeIndex]!\n const part = parts[partIndex]\n const currentPathIndex = pathIndex\n if (part) pathIndex += part.length\n if (node.kind === SEGMENT_TYPE_PARAM) {\n nodeParts ??= leaf.node.fullPath.split('/')\n const nodePart = nodeParts[nodeIndex]!\n const preLength = node.prefix?.length ?? 0\n // we can't rely on the presence of prefix/suffix to know whether it's curly-braced or not, because `/{$param}/` is valid, but has no prefix/suffix\n const isCurlyBraced = nodePart.charCodeAt(preLength) === 123 // '{'\n // param name is extracted at match-time so that tree nodes that are identical except for param name can share the same node\n if (isCurlyBraced) {\n const sufLength = node.suffix?.length ?? 0\n const name = nodePart.substring(\n preLength + 2,\n nodePart.length - sufLength - 1,\n )\n const value = part!.substring(preLength, part!.length - sufLength)\n params[name] = decodeURIComponent(value)\n } else {\n const name = nodePart.substring(1)\n params[name] = decodeURIComponent(part!)\n }\n } else if (node.kind === SEGMENT_TYPE_OPTIONAL_PARAM) {\n if (leaf.skipped & (1 << nodeIndex)) {\n partIndex-- // stay on the same part\n continue\n }\n nodeParts ??= leaf.node.fullPath.split('/')\n const nodePart = nodeParts[nodeIndex]!\n const preLength = node.prefix?.length ?? 0\n const sufLength = node.suffix?.length ?? 0\n const name = nodePart.substring(\n preLength + 3,\n nodePart.length - sufLength - 1,\n )\n const value =\n node.suffix || node.prefix\n ? part!.substring(preLength, part!.length - sufLength)\n : part\n if (value) params[name] = decodeURIComponent(value)\n } else if (node.kind === SEGMENT_TYPE_WILDCARD) {\n const n = node\n const value = path.substring(\n currentPathIndex + (n.prefix?.length ?? 0),\n path.length - (n.suffix?.length ?? 0),\n )\n const splat = decodeURIComponent(value)\n // TODO: Deprecate *\n params['*'] = splat\n params._splat = splat\n break\n }\n }\n return params\n}\n\nfunction buildRouteBranch<T extends RouteLike>(route: T) {\n const list = [route]\n while (route.parentRoute) {\n route = route.parentRoute as T\n list.push(route)\n }\n list.reverse()\n return list\n}\n\nfunction buildBranch<T extends RouteLike>(node: AnySegmentNode<T>) {\n const list: Array<AnySegmentNode<T>> = Array(node.depth + 1)\n do {\n list[node.depth] = node\n node = node.parent!\n } while (node)\n return list\n}\n\ntype MatchStackFrame<T extends RouteLike> = {\n node: AnySegmentNode<T>\n /** index of the segment of path */\n index: number\n /** how many nodes between `node` and the root of the segment tree */\n depth: number\n /**\n * Bitmask of skipped optional segments.\n *\n * This is a very performant way of storing an \"array of booleans\", but it means beyond 32 segments we can't track skipped optionals.\n * If we really really need to support more than 32 segments we can switch to using a `BigInt` here. It's about 2x slower in worst case scenarios.\n */\n skipped: number\n statics: number\n dynamics: number\n optionals: number\n}\n\nfunction getNodeMatch<T extends RouteLike>(\n path: string,\n parts: Array<string>,\n segmentTree: AnySegmentNode<T>,\n fuzzy: boolean,\n) {\n const trailingSlash = !last(parts)\n const pathIsIndex = trailingSlash && path !== '/'\n const partsLength = parts.length - (trailingSlash ? 1 : 0)\n\n type Frame = MatchStackFrame<T>\n\n // use a stack to explore all possible paths (params cause branching)\n // iterate \"backwards\" (low priority first) so that we can push() each candidate, and pop() the highest priority candidate first\n // - pros: it is depth-first, so we find full matches faster\n // - cons: we cannot short-circuit, because highest priority matches are at the end of the loop (for loop with i--) (but we have no good short-circuiting anyway)\n // other possible approaches:\n // - shift instead of pop (measure performance difference), this allows iterating \"forwards\" (effectively breadth-first)\n // - never remove from the stack, keep a cursor instead. Then we can push \"forwards\" and avoid reversing the order of candidates (effectively breadth-first)\n const stack: Array<Frame> = [\n {\n node: segmentTree,\n index: 1,\n skipped: 0,\n depth: 1,\n statics: 1,\n dynamics: 0,\n optionals: 0,\n },\n ]\n\n let wildcardMatch: Frame | null = null\n let bestFuzzy: Frame | null = null\n let bestMatch: Frame | null = null\n\n while (stack.length) {\n const frame = stack.pop()!\n // eslint-disable-next-line prefer-const\n let { node, index, skipped, depth, statics, dynamics, optionals } = frame\n\n // In fuzzy mode, track the best partial match we've found so far\n if (fuzzy && node.notFound && isFrameMoreSpecific(bestFuzzy, frame)) {\n bestFuzzy = frame\n }\n\n const isBeyondPath = index === partsLength\n if (isBeyondPath) {\n if (node.route && (!pathIsIndex || node.isIndex)) {\n if (isFrameMoreSpecific(bestMatch, frame)) {\n bestMatch = frame\n }\n\n // perfect match, no need to continue\n if (statics === partsLength && node.isIndex) return bestMatch\n }\n // beyond the length of the path parts, only skipped optional segments or wildcard segments can match\n if (!node.optional && !node.wildcard) continue\n }\n\n const part = isBeyondPath ? undefined : parts[index]!\n let lowerPart: string\n\n // 5. Try wildcard match\n if (node.wildcard && isFrameMoreSpecific(wildcardMatch, frame)) {\n for (const segment of node.wildcard) {\n const { prefix, suffix } = segment\n if (prefix) {\n if (isBeyondPath) continue\n const casePart = segment.caseSensitive\n ? part\n : (lowerPart ??= part!.toLowerCase())\n if (!casePart!.startsWith(prefix)) continue\n }\n if (suffix) {\n if (isBeyondPath) continue\n const end = parts.slice(index).join('/').slice(-suffix.length)\n const casePart = segment.caseSensitive ? end : end.toLowerCase()\n if (casePart !== suffix) continue\n }\n // the first wildcard match is the highest priority one\n wildcardMatch = {\n node: segment,\n index,\n skipped,\n depth,\n statics,\n dynamics,\n optionals,\n }\n break\n }\n }\n\n // 4. Try optional match\n if (node.optional) {\n const nextSkipped = skipped | (1 << depth)\n const nextDepth = depth + 1\n for (let i = node.optional.length - 1; i >= 0; i--) {\n const segment = node.optional[i]!\n // when skipping, node and depth advance by 1, but index doesn't\n stack.push({\n node: segment,\n index,\n skipped: nextSkipped,\n depth: nextDepth,\n statics,\n dynamics,\n optionals,\n }) // enqueue skipping the optional\n }\n if (!isBeyondPath) {\n for (let i = node.optional.length - 1; i >= 0; i--) {\n const segment = node.optional[i]!\n const { prefix, suffix } = segment\n if (prefix || suffix) {\n const casePart = segment.caseSensitive\n ? part!\n : (lowerPart ??= part!.toLowerCase())\n if (prefix && !casePart.startsWith(prefix)) continue\n if (suffix && !casePart.endsWith(suffix)) continue\n }\n stack.push({\n node: segment,\n index: index + 1,\n skipped,\n depth: nextDepth,\n statics,\n dynamics,\n optionals: optionals + 1,\n })\n }\n }\n }\n\n // 3. Try dynamic match\n if (!isBeyondPath && node.dynamic && part) {\n for (let i = node.dynamic.length - 1; i >= 0; i--) {\n const segment = node.dynamic[i]!\n const { prefix, suffix } = segment\n if (prefix || suffix) {\n const casePart = segment.caseSensitive\n ? part\n : (lowerPart ??= part.toLowerCase())\n if (prefix && !casePart.startsWith(prefix)) continue\n if (suffix && !casePart.endsWith(suffix)) continue\n }\n stack.push({\n node: segment,\n index: index + 1,\n skipped,\n depth: depth + 1,\n statics,\n dynamics: dynamics + 1,\n optionals,\n })\n }\n }\n\n // 2. Try case insensitive static match\n if (!isBeyondPath && node.staticInsensitive) {\n const match = node.staticInsensitive.get(\n (lowerPart ??= part!.toLowerCase()),\n )\n if (match) {\n stack.push({\n node: match,\n index: index + 1,\n skipped,\n depth: depth + 1,\n statics: statics + 1,\n dynamics,\n optionals,\n })\n }\n }\n\n // 1. Try static match\n if (!isBeyondPath && node.static) {\n const match = node.static.get(part!)\n if (match) {\n stack.push({\n node: match,\n index: index + 1,\n skipped,\n depth: depth + 1,\n statics: statics + 1,\n dynamics,\n optionals,\n })\n }\n }\n }\n\n if (bestMatch && wildcardMatch) {\n return isFrameMoreSpecific(wildcardMatch, bestMatch)\n ? bestMatch\n : wildcardMatch\n }\n\n if (bestMatch) return bestMatch\n\n if (wildcardMatch) return wildcardMatch\n\n if (fuzzy && bestFuzzy) {\n let sliceIndex = bestFuzzy.index\n for (let i = 0; i < bestFuzzy.index; i++) {\n sliceIndex += parts[i]!.length\n }\n const splat = sliceIndex === path.length ? '/' : path.slice(sliceIndex)\n return {\n node: bestFuzzy.node,\n skipped: bestFuzzy.skipped,\n '**': decodeURIComponent(splat),\n }\n }\n\n return null\n}\n\nfunction isFrameMoreSpecific(\n // the stack frame previously saved as \"best match\"\n prev: MatchStackFrame<any> | null,\n // the candidate stack frame\n next: MatchStackFrame<any>,\n): boolean {\n if (!prev) return true\n return (\n next.statics > prev.statics ||\n (next.statics === prev.statics &&\n (next.dynamics > prev.dynamics ||\n (next.dynamics === prev.dynamics &&\n (next.optionals > prev.optionals ||\n (next.optionals === prev.optionals &&\n (next.node.isIndex > prev.node.isIndex ||\n (next.node.isIndex === prev.node.isIndex &&\n next.depth > prev.depth)))))))\n )\n}\n"],"names":["start","createLRUCache","last"],"mappings":";;;;;AAKO,MAAM,wBAAwB;AAC9B,MAAM,qBAAqB;AAC3B,MAAM,wBAAwB;AAC9B,MAAM,8BAA8B;AAQ3C,MAAM,0BACJ;AACF,MAAM,mCACJ;AACF,MAAM,6BAA6B;AAiC5B,SAAS,aAEd,MAEA,OAEA,SAAsB,IAAI,YAAY,CAAC,GACxB;A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,EAElC;AAEA,SAAO;AACT;AAEA,SAAS,oBAEP,MAEA,MACS;AACT,MAAI,CAAC,KAAM,QAAO;AAClB,SACE,KAAK,UAAU,KAAK,WACnB,KAAK,YAAY,KAAK,YACpB,KAAK,WAAW,KAAK,YACnB,KAAK,aAAa,KAAK,aACrB,KAAK,YAAY,KAAK,aACpB,KAAK,cAAc,KAAK,cACtB,KAAK,KAAK,UAAU,KAAK,KAAK,WAC5B,KAAK,KAAK,YAAY,KAAK,KAAK,WAC/B,KAAK,QAAQ,KAAK;AAEpC;;;;;;;;;;;;"}
|
|
@@ -66,7 +66,10 @@ function transformStreamWithRouter(router, appStream, opts) {
|
|
|
66
66
|
let stopListeningToInjectedHtml = void 0;
|
|
67
67
|
let timeoutHandle;
|
|
68
68
|
const finalPassThrough = createPassthrough(() => {
|
|
69
|
-
stopListeningToInjectedHtml
|
|
69
|
+
if (stopListeningToInjectedHtml) {
|
|
70
|
+
stopListeningToInjectedHtml();
|
|
71
|
+
stopListeningToInjectedHtml = void 0;
|
|
72
|
+
}
|
|
70
73
|
clearTimeout(timeoutHandle);
|
|
71
74
|
});
|
|
72
75
|
const textDecoder = new TextDecoder();
|
|
@@ -89,26 +92,28 @@ function transformStreamWithRouter(router, appStream, opts) {
|
|
|
89
92
|
}
|
|
90
93
|
const injectedHtmlDonePromise = utils.createControlledPromise();
|
|
91
94
|
let processingCount = 0;
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
95
|
+
handleInjectedHtml();
|
|
96
|
+
stopListeningToInjectedHtml = router.subscribe(
|
|
97
|
+
"onInjectedHtml",
|
|
98
|
+
handleInjectedHtml
|
|
99
|
+
);
|
|
100
|
+
function handleInjectedHtml() {
|
|
101
|
+
router.serverSsr.injectedHtml.forEach((promise) => {
|
|
102
|
+
processingCount++;
|
|
103
|
+
promise.then((html) => {
|
|
104
|
+
if (isAppRendering) {
|
|
105
|
+
routerStreamBuffer += html;
|
|
106
|
+
} else {
|
|
107
|
+
finalPassThrough.write(html);
|
|
108
|
+
}
|
|
109
|
+
}).catch(injectedHtmlDonePromise.reject).finally(() => {
|
|
110
|
+
processingCount--;
|
|
111
|
+
if (!isAppRendering && processingCount === 0) {
|
|
112
|
+
injectedHtmlDonePromise.resolve();
|
|
113
|
+
}
|
|
114
|
+
});
|
|
111
115
|
});
|
|
116
|
+
router.serverSsr.injectedHtml = [];
|
|
112
117
|
}
|
|
113
118
|
injectedHtmlDonePromise.then(() => {
|
|
114
119
|
clearTimeout(timeoutHandle);
|
|
@@ -117,7 +122,12 @@ function transformStreamWithRouter(router, appStream, opts) {
|
|
|
117
122
|
}).catch((err) => {
|
|
118
123
|
console.error("Error reading routerStream:", err);
|
|
119
124
|
finalPassThrough.destroy(err);
|
|
120
|
-
}).finally(() =>
|
|
125
|
+
}).finally(() => {
|
|
126
|
+
if (stopListeningToInjectedHtml) {
|
|
127
|
+
stopListeningToInjectedHtml();
|
|
128
|
+
stopListeningToInjectedHtml = void 0;
|
|
129
|
+
}
|
|
130
|
+
});
|
|
121
131
|
readStream(appStream, {
|
|
122
132
|
onData: (chunk) => {
|
|
123
133
|
const text = decodeChunk(chunk.value);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transformStreamWithRouter.cjs","sources":["../../../src/ssr/transformStreamWithRouter.ts"],"sourcesContent":["import { ReadableStream } from 'node:stream/web'\nimport { Readable } from 'node:stream'\nimport { createControlledPromise } from '../utils'\nimport type { AnyRouter } from '../router'\n\nexport function transformReadableStreamWithRouter(\n router: AnyRouter,\n routerStream: ReadableStream,\n) {\n return transformStreamWithRouter(router, routerStream)\n}\n\nexport function transformPipeableStreamWithRouter(\n router: AnyRouter,\n routerStream: Readable,\n) {\n return Readable.fromWeb(\n transformStreamWithRouter(router, Readable.toWeb(routerStream)),\n )\n}\n\nexport const TSR_SCRIPT_BARRIER_ID = '$tsr-stream-barrier'\n\n// regex pattern for matching closing body and html tags\nconst patternBodyEnd = /(<\\/body>)/\nconst patternHtmlEnd = /(<\\/html>)/\n// regex pattern for matching closing tags\nconst patternClosingTag = /(<\\/[a-zA-Z][\\w:.-]*?>)/g\n\ntype ReadablePassthrough = {\n stream: ReadableStream\n write: (chunk: unknown) => void\n end: (chunk?: string) => void\n destroy: (error: unknown) => void\n destroyed: boolean\n}\n\nfunction createPassthrough(onCancel?: () => void) {\n let controller: ReadableStreamDefaultController<any>\n const encoder = new TextEncoder()\n const stream = new ReadableStream({\n start(c) {\n controller = c\n },\n cancel() {\n res.destroyed = true\n onCancel?.()\n },\n })\n\n const res: ReadablePassthrough = {\n stream,\n write: (chunk) => {\n if (typeof chunk === 'string') {\n controller.enqueue(encoder.encode(chunk))\n } else {\n controller.enqueue(chunk)\n }\n },\n end: (chunk) => {\n if (chunk) {\n res.write(chunk)\n }\n controller.close()\n res.destroyed = true\n },\n destroy: (error) => {\n controller.error(error)\n },\n destroyed: false,\n }\n\n return res\n}\n\nasync function readStream(\n stream: ReadableStream,\n opts: {\n onData?: (chunk: ReadableStreamReadValueResult<any>) => void\n onEnd?: () => void\n onError?: (error: unknown) => void\n },\n) {\n try {\n const reader = stream.getReader()\n let chunk\n while (!(chunk = await reader.read()).done) {\n opts.onData?.(chunk)\n }\n opts.onEnd?.()\n } catch (error) {\n opts.onError?.(error)\n }\n}\n\nexport function transformStreamWithRouter(\n router: AnyRouter,\n appStream: ReadableStream,\n opts?: {\n timeoutMs?: number\n },\n) {\n let stopListeningToInjectedHtml: (() => void) | undefined = undefined\n let timeoutHandle: NodeJS.Timeout\n\n const finalPassThrough = createPassthrough(() => {\n stopListeningToInjectedHtml?.()\n clearTimeout(timeoutHandle)\n })\n const textDecoder = new TextDecoder()\n\n let isAppRendering = true as boolean\n let routerStreamBuffer = ''\n let pendingClosingTags = ''\n let streamBarrierLifted = false as boolean\n let leftover = ''\n let leftoverHtml = ''\n\n function getBufferedRouterStream() {\n const html = routerStreamBuffer\n routerStreamBuffer = ''\n return html\n }\n\n function decodeChunk(chunk: unknown): string {\n if (chunk instanceof Uint8Array) {\n return textDecoder.decode(chunk, { stream: true })\n }\n return String(chunk)\n }\n\n const injectedHtmlDonePromise = createControlledPromise<void>()\n\n let processingCount = 0\n\n // Process any already-injected HTML\n router.serverSsr!.injectedHtml.forEach((promise) => {\n handleInjectedHtml(promise)\n })\n\n // Listen for any new injected HTML\n stopListeningToInjectedHtml = router.subscribe('onInjectedHtml', (e) => {\n handleInjectedHtml(e.promise)\n })\n\n function handleInjectedHtml(promise: Promise<string>) {\n processingCount++\n\n promise\n .then((html) => {\n if (isAppRendering) {\n routerStreamBuffer += html\n } else {\n finalPassThrough.write(html)\n }\n })\n .catch(injectedHtmlDonePromise.reject)\n .finally(() => {\n processingCount--\n\n if (!isAppRendering && processingCount === 0) {\n injectedHtmlDonePromise.resolve()\n }\n })\n }\n\n injectedHtmlDonePromise\n .then(() => {\n clearTimeout(timeoutHandle)\n const finalHtml =\n leftoverHtml + getBufferedRouterStream() + pendingClosingTags\n\n finalPassThrough.end(finalHtml)\n })\n .catch((err) => {\n console.error('Error reading routerStream:', err)\n finalPassThrough.destroy(err)\n })\n .finally(() => stopListeningToInjectedHtml?.())\n\n // Transform the appStream\n readStream(appStream, {\n onData: (chunk) => {\n const text = decodeChunk(chunk.value)\n const chunkString = leftover + text\n const bodyEndMatch = chunkString.match(patternBodyEnd)\n const htmlEndMatch = chunkString.match(patternHtmlEnd)\n\n if (!streamBarrierLifted) {\n const streamBarrierIdIncluded = chunkString.includes(\n TSR_SCRIPT_BARRIER_ID,\n )\n if (streamBarrierIdIncluded) {\n streamBarrierLifted = true\n router.serverSsr!.liftScriptBarrier()\n }\n }\n\n // If either the body end or html end is in the chunk,\n // We need to get all of our data in asap\n if (\n bodyEndMatch &&\n htmlEndMatch &&\n bodyEndMatch.index! < htmlEndMatch.index!\n ) {\n const bodyEndIndex = bodyEndMatch.index!\n pendingClosingTags = chunkString.slice(bodyEndIndex)\n\n finalPassThrough.write(\n chunkString.slice(0, bodyEndIndex) + getBufferedRouterStream(),\n )\n\n leftover = ''\n return\n }\n\n let result: RegExpExecArray | null\n let lastIndex = 0\n while ((result = patternClosingTag.exec(chunkString)) !== null) {\n lastIndex = result.index + result[0].length\n }\n\n if (lastIndex > 0) {\n const processed =\n chunkString.slice(0, lastIndex) +\n getBufferedRouterStream() +\n leftoverHtml\n\n finalPassThrough.write(processed)\n leftover = chunkString.slice(lastIndex)\n } else {\n leftover = chunkString\n leftoverHtml += getBufferedRouterStream()\n }\n },\n onEnd: () => {\n // Mark the app as done rendering\n isAppRendering = false\n router.serverSsr!.setRenderFinished()\n\n // If there are no pending promises, resolve the injectedHtmlDonePromise\n if (processingCount === 0) {\n injectedHtmlDonePromise.resolve()\n } else {\n const timeoutMs = opts?.timeoutMs ?? 60000\n timeoutHandle = setTimeout(() => {\n injectedHtmlDonePromise.reject(\n new Error('Injected HTML timeout after app render finished'),\n )\n }, timeoutMs)\n }\n },\n onError: (error) => {\n console.error('Error reading appStream:', error)\n finalPassThrough.destroy(error)\n injectedHtmlDonePromise.reject(error)\n },\n })\n\n return finalPassThrough.stream\n}\n"],"names":["Readable","ReadableStream","createControlledPromise"],"mappings":";;;;;AAKO,SAAS,kCACd,QACA,cACA;AACA,SAAO,0BAA0B,QAAQ,YAAY;AACvD;AAEO,SAAS,kCACd,QACA,cACA;AACA,SAAOA,YAAAA,SAAS;AAAA,IACd,0BAA0B,QAAQA,qBAAS,MAAM,YAAY,CAAC;AAAA,EAAA;AAElE;AAEO,MAAM,wBAAwB;AAGrC,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AAEvB,MAAM,oBAAoB;AAU1B,SAAS,kBAAkB,UAAuB;AAChD,MAAI;AACJ,QAAM,UAAU,IAAI,YAAA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AI,yBAAyB;AAC3B,gCAAsB;AACtB,iBAAO,UAAW,kBAAA;AAAA,QACpB;AAAA,MACF;AAIA,UACE,gBACA,gBACA,aAAa,QAAS,aAAa,OACnC;AACA,cAAM,eAAe,aAAa;AAClC,6BAAqB,YAAY,MAAM,YAAY;AAEnD,yBAAiB;AAAA,UACf,YAAY,MAAM,GAAG,YAAY,IAAI,wBAAA;AAAA,QAAwB;AAG/D,mBAAW;AACX;AAAA,MACF;AAEA,UAAI;AACJ,UAAI,YAAY;AAChB,cAAQ,SAAS,kBAAkB,KAAK,WAAW,OAAO,MAAM;AAC9D,oBAAY,OAAO,QAAQ,OAAO,CAAC,EAAE;AAAA,MACvC;AAEA,UAAI,YAAY,GAAG;AACjB,cAAM,YACJ,YAAY,MAAM,GAAG,SAAS,IAC9B,4BACA;AAEF,yBAAiB,MAAM,SAAS;AAChC,mBAAW,YAAY,MAAM,SAAS;AAAA,MACxC,OAAO;AACL,mBAAW;AACX,wBAAgB,wBAAA;AAAA,MAClB;AAAA,IACF;AAAA,IACA,OAAO,MAAM;AAEX,uBAAiB;AACjB,aAAO,UAAW,kBAAA;AAGlB,UAAI,oBAAoB,GAAG;AACzB,gCAAwB,QAAA;AAAA,MAC1B,OAAO;AACL,cAAM,YAAY,MAAM,aAAa;AACrC,wBAAgB,WAAW,MAAM;AAC/B,kCAAwB;AAAA,YACtB,IAAI,MAAM,iDAAiD;AAAA,UAAA;AAAA,QAE/D,GAAG,SAAS;AAAA,MACd;AAAA,IACF;AAAA,IACA,SAAS,CAAC,UAAU;AAClB,cAAQ,MAAM,4BAA4B,KAAK;AAC/C,uBAAiB,QAAQ,KAAK;AAC9B,8BAAwB,OAAO,KAAK;AAAA,IACtC;AAAA,EAAA,CACD;AAED,SAAO,iBAAiB;AAC1B;;;;;"}
|
|
1
|
+
{"version":3,"file":"transformStreamWithRouter.cjs","sources":["../../../src/ssr/transformStreamWithRouter.ts"],"sourcesContent":["import { ReadableStream } from 'node:stream/web'\nimport { Readable } from 'node:stream'\nimport { createControlledPromise } from '../utils'\nimport type { AnyRouter } from '../router'\n\nexport function transformReadableStreamWithRouter(\n router: AnyRouter,\n routerStream: ReadableStream,\n) {\n return transformStreamWithRouter(router, routerStream)\n}\n\nexport function transformPipeableStreamWithRouter(\n router: AnyRouter,\n routerStream: Readable,\n) {\n return Readable.fromWeb(\n transformStreamWithRouter(router, Readable.toWeb(routerStream)),\n )\n}\n\nexport const TSR_SCRIPT_BARRIER_ID = '$tsr-stream-barrier'\n\n// regex pattern for matching closing body and html tags\nconst patternBodyEnd = /(<\\/body>)/\nconst patternHtmlEnd = /(<\\/html>)/\n// regex pattern for matching closing tags\nconst patternClosingTag = /(<\\/[a-zA-Z][\\w:.-]*?>)/g\n\ntype ReadablePassthrough = {\n stream: ReadableStream\n write: (chunk: unknown) => void\n end: (chunk?: string) => void\n destroy: (error: unknown) => void\n destroyed: boolean\n}\n\nfunction createPassthrough(onCancel?: () => void) {\n let controller: ReadableStreamDefaultController<any>\n const encoder = new TextEncoder()\n const stream = new ReadableStream({\n start(c) {\n controller = c\n },\n cancel() {\n res.destroyed = true\n onCancel?.()\n },\n })\n\n const res: ReadablePassthrough = {\n stream,\n write: (chunk) => {\n if (typeof chunk === 'string') {\n controller.enqueue(encoder.encode(chunk))\n } else {\n controller.enqueue(chunk)\n }\n },\n end: (chunk) => {\n if (chunk) {\n res.write(chunk)\n }\n controller.close()\n res.destroyed = true\n },\n destroy: (error) => {\n controller.error(error)\n },\n destroyed: false,\n }\n\n return res\n}\n\nasync function readStream(\n stream: ReadableStream,\n opts: {\n onData?: (chunk: ReadableStreamReadValueResult<any>) => void\n onEnd?: () => void\n onError?: (error: unknown) => void\n },\n) {\n try {\n const reader = stream.getReader()\n let chunk\n while (!(chunk = await reader.read()).done) {\n opts.onData?.(chunk)\n }\n opts.onEnd?.()\n } catch (error) {\n opts.onError?.(error)\n }\n}\n\nexport function transformStreamWithRouter(\n router: AnyRouter,\n appStream: ReadableStream,\n opts?: {\n timeoutMs?: number\n },\n) {\n let stopListeningToInjectedHtml: (() => void) | undefined = undefined\n let timeoutHandle: NodeJS.Timeout\n\n const finalPassThrough = createPassthrough(() => {\n if (stopListeningToInjectedHtml) {\n stopListeningToInjectedHtml()\n stopListeningToInjectedHtml = undefined\n }\n clearTimeout(timeoutHandle)\n })\n const textDecoder = new TextDecoder()\n\n let isAppRendering = true as boolean\n let routerStreamBuffer = ''\n let pendingClosingTags = ''\n let streamBarrierLifted = false as boolean\n let leftover = ''\n let leftoverHtml = ''\n\n function getBufferedRouterStream() {\n const html = routerStreamBuffer\n routerStreamBuffer = ''\n return html\n }\n\n function decodeChunk(chunk: unknown): string {\n if (chunk instanceof Uint8Array) {\n return textDecoder.decode(chunk, { stream: true })\n }\n return String(chunk)\n }\n\n const injectedHtmlDonePromise = createControlledPromise<void>()\n\n let processingCount = 0\n\n // Process any already-injected HTML\n handleInjectedHtml()\n\n // Listen for any new injected HTML\n stopListeningToInjectedHtml = router.subscribe(\n 'onInjectedHtml',\n handleInjectedHtml,\n )\n\n function handleInjectedHtml() {\n router.serverSsr!.injectedHtml.forEach((promise) => {\n processingCount++\n\n promise\n .then((html) => {\n if (isAppRendering) {\n routerStreamBuffer += html\n } else {\n finalPassThrough.write(html)\n }\n })\n .catch(injectedHtmlDonePromise.reject)\n .finally(() => {\n processingCount--\n\n if (!isAppRendering && processingCount === 0) {\n injectedHtmlDonePromise.resolve()\n }\n })\n })\n router.serverSsr!.injectedHtml = []\n }\n\n injectedHtmlDonePromise\n .then(() => {\n clearTimeout(timeoutHandle)\n const finalHtml =\n leftoverHtml + getBufferedRouterStream() + pendingClosingTags\n\n finalPassThrough.end(finalHtml)\n })\n .catch((err) => {\n console.error('Error reading routerStream:', err)\n finalPassThrough.destroy(err)\n })\n .finally(() => {\n if (stopListeningToInjectedHtml) {\n stopListeningToInjectedHtml()\n stopListeningToInjectedHtml = undefined\n }\n })\n\n // Transform the appStream\n readStream(appStream, {\n onData: (chunk) => {\n const text = decodeChunk(chunk.value)\n const chunkString = leftover + text\n const bodyEndMatch = chunkString.match(patternBodyEnd)\n const htmlEndMatch = chunkString.match(patternHtmlEnd)\n\n if (!streamBarrierLifted) {\n const streamBarrierIdIncluded = chunkString.includes(\n TSR_SCRIPT_BARRIER_ID,\n )\n if (streamBarrierIdIncluded) {\n streamBarrierLifted = true\n router.serverSsr!.liftScriptBarrier()\n }\n }\n\n // If either the body end or html end is in the chunk,\n // We need to get all of our data in asap\n if (\n bodyEndMatch &&\n htmlEndMatch &&\n bodyEndMatch.index! < htmlEndMatch.index!\n ) {\n const bodyEndIndex = bodyEndMatch.index!\n pendingClosingTags = chunkString.slice(bodyEndIndex)\n\n finalPassThrough.write(\n chunkString.slice(0, bodyEndIndex) + getBufferedRouterStream(),\n )\n\n leftover = ''\n return\n }\n\n let result: RegExpExecArray | null\n let lastIndex = 0\n while ((result = patternClosingTag.exec(chunkString)) !== null) {\n lastIndex = result.index + result[0].length\n }\n\n if (lastIndex > 0) {\n const processed =\n chunkString.slice(0, lastIndex) +\n getBufferedRouterStream() +\n leftoverHtml\n\n finalPassThrough.write(processed)\n leftover = chunkString.slice(lastIndex)\n } else {\n leftover = chunkString\n leftoverHtml += getBufferedRouterStream()\n }\n },\n onEnd: () => {\n // Mark the app as done rendering\n isAppRendering = false\n router.serverSsr!.setRenderFinished()\n\n // If there are no pending promises, resolve the injectedHtmlDonePromise\n if (processingCount === 0) {\n injectedHtmlDonePromise.resolve()\n } else {\n const timeoutMs = opts?.timeoutMs ?? 60000\n timeoutHandle = setTimeout(() => {\n injectedHtmlDonePromise.reject(\n new Error('Injected HTML timeout after app render finished'),\n )\n }, timeoutMs)\n }\n },\n onError: (error) => {\n console.error('Error reading appStream:', error)\n finalPassThrough.destroy(error)\n injectedHtmlDonePromise.reject(error)\n },\n })\n\n return finalPassThrough.stream\n}\n"],"names":["Readable","ReadableStream","createControlledPromise"],"mappings":";;;;;AAKO,SAAS,kCACd,QACA,cACA;AACA,SAAO,0BAA0B,QAAQ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AAI,MAAM,iDAAiD;AAAA,UAAA;AAAA,QAE/D,GAAG,SAAS;AAAA,MACd;AAAA,IACF;AAAA,IACA,SAAS,CAAC,UAAU;AAClB,cAAQ,MAAM,4BAA4B,KAAK;AAC/C,uBAAiB,QAAQ,KAAK;AAC9B,8BAAwB,OAAO,KAAK;AAAA,IACtC;AAAA,EAAA,CACD;AAED,SAAO,iBAAiB;AAC1B;;;;;"}
|
|
@@ -633,6 +633,9 @@ function getNodeMatch(path, parts, segmentTree, fuzzy) {
|
|
|
633
633
|
}
|
|
634
634
|
}
|
|
635
635
|
}
|
|
636
|
+
if (bestMatch && wildcardMatch) {
|
|
637
|
+
return isFrameMoreSpecific(wildcardMatch, bestMatch) ? bestMatch : wildcardMatch;
|
|
638
|
+
}
|
|
636
639
|
if (bestMatch) return bestMatch;
|
|
637
640
|
if (wildcardMatch) return wildcardMatch;
|
|
638
641
|
if (fuzzy && bestFuzzy) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"new-process-route-tree.js","sources":["../../src/new-process-route-tree.ts"],"sourcesContent":["import invariant from 'tiny-invariant'\nimport { createLRUCache } from './lru-cache'\nimport { last } from './utils'\nimport type { LRUCache } from './lru-cache'\n\nexport const SEGMENT_TYPE_PATHNAME = 0\nexport const SEGMENT_TYPE_PARAM = 1\nexport const SEGMENT_TYPE_WILDCARD = 2\nexport const SEGMENT_TYPE_OPTIONAL_PARAM = 3\n\nexport type SegmentKind =\n | typeof SEGMENT_TYPE_PATHNAME\n | typeof SEGMENT_TYPE_PARAM\n | typeof SEGMENT_TYPE_WILDCARD\n | typeof SEGMENT_TYPE_OPTIONAL_PARAM\n\nconst PARAM_W_CURLY_BRACES_RE =\n /^([^{]*)\\{\\$([a-zA-Z_$][a-zA-Z0-9_$]*)\\}([^}]*)$/ // prefix{$paramName}suffix\nconst OPTIONAL_PARAM_W_CURLY_BRACES_RE =\n /^([^{]*)\\{-\\$([a-zA-Z_$][a-zA-Z0-9_$]*)\\}([^}]*)$/ // prefix{-$paramName}suffix\nconst WILDCARD_W_CURLY_BRACES_RE = /^([^{]*)\\{\\$\\}([^}]*)$/ // prefix{$}suffix\n\ntype ParsedSegment = Uint16Array & {\n /** segment type (0 = pathname, 1 = param, 2 = wildcard, 3 = optional param) */\n 0: SegmentKind\n /** index of the end of the prefix */\n 1: number\n /** index of the start of the value */\n 2: number\n /** index of the end of the value */\n 3: number\n /** index of the start of the suffix */\n 4: number\n /** index of the end of the segment */\n 5: number\n}\n\n/**\n * Populates the `output` array with the parsed representation of the given `segment` string.\n *\n * Usage:\n * ```ts\n * let output\n * let cursor = 0\n * while (cursor < path.length) {\n * output = parseSegment(path, cursor, output)\n * const end = output[5]\n * cursor = end + 1\n * ```\n *\n * `output` is stored outside to avoid allocations during repeated calls. It doesn't need to be typed\n * or initialized, it will be done automatically.\n */\nexport function parseSegment(\n /** The full path string containing the segment. */\n path: string,\n /** The starting index of the segment within the path. */\n start: number,\n /** A Uint16Array (length: 6) to populate with the parsed segment data. */\n output: Uint16Array = new Uint16Array(6),\n): ParsedSegment {\n const next = path.indexOf('/', start)\n const end = next === -1 ? path.length : next\n const part = path.substring(start, end)\n\n if (!part || !part.includes('$')) {\n // early escape for static pathname\n output[0] = SEGMENT_TYPE_PATHNAME\n output[1] = start\n output[2] = start\n output[3] = end\n output[4] = end\n output[5] = end\n return output as ParsedSegment\n }\n\n // $ (wildcard)\n if (part === '$') {\n const total = path.length\n output[0] = SEGMENT_TYPE_WILDCARD\n output[1] = start\n output[2] = start\n output[3] = total\n output[4] = total\n output[5] = total\n return output as ParsedSegment\n }\n\n // $paramName\n if (part.charCodeAt(0) === 36) {\n output[0] = SEGMENT_TYPE_PARAM\n output[1] = start\n output[2] = start + 1 // skip '$'\n output[3] = end\n output[4] = end\n output[5] = end\n return output as ParsedSegment\n }\n\n const wildcardBracesMatch = part.match(WILDCARD_W_CURLY_BRACES_RE)\n if (wildcardBracesMatch) {\n const prefix = wildcardBracesMatch[1]!\n const pLength = prefix.length\n output[0] = SEGMENT_TYPE_WILDCARD\n output[1] = start + pLength\n output[2] = start + pLength + 1 // skip '{'\n output[3] = start + pLength + 2 // '$'\n output[4] = start + pLength + 3 // skip '}'\n output[5] = path.length\n return output as ParsedSegment\n }\n\n const optionalParamBracesMatch = part.match(OPTIONAL_PARAM_W_CURLY_BRACES_RE)\n if (optionalParamBracesMatch) {\n const prefix = optionalParamBracesMatch[1]!\n const paramName = optionalParamBracesMatch[2]!\n const suffix = optionalParamBracesMatch[3]!\n const pLength = prefix.length\n output[0] = SEGMENT_TYPE_OPTIONAL_PARAM\n output[1] = start + pLength\n output[2] = start + pLength + 3 // skip '{-$'\n output[3] = start + pLength + 3 + paramName.length\n output[4] = end - suffix.length\n output[5] = end\n return output as ParsedSegment\n }\n\n const paramBracesMatch = part.match(PARAM_W_CURLY_BRACES_RE)\n if (paramBracesMatch) {\n const prefix = paramBracesMatch[1]!\n const paramName = paramBracesMatch[2]!\n const suffix = paramBracesMatch[3]!\n const pLength = prefix.length\n output[0] = SEGMENT_TYPE_PARAM\n output[1] = start + pLength\n output[2] = start + pLength + 2 // skip '{$'\n output[3] = start + pLength + 2 + paramName.length\n output[4] = end - suffix.length\n output[5] = end\n return output as ParsedSegment\n }\n\n // fallback to static pathname (should never happen)\n output[0] = SEGMENT_TYPE_PATHNAME\n output[1] = start\n output[2] = start\n output[3] = end\n output[4] = end\n output[5] = end\n return output as ParsedSegment\n}\n\n/**\n * Recursively parses the segments of the given route tree and populates a segment trie.\n *\n * @param data A reusable Uint16Array for parsing segments. (non important, we're just avoiding allocations)\n * @param route The current route to parse.\n * @param start The starting index for parsing within the route's full path.\n * @param node The current segment node in the trie to populate.\n * @param onRoute Callback invoked for each route processed.\n */\nfunction parseSegments<TRouteLike extends RouteLike>(\n defaultCaseSensitive: boolean,\n data: Uint16Array,\n route: TRouteLike,\n start: number,\n node: AnySegmentNode<TRouteLike>,\n depth: number,\n onRoute?: (route: TRouteLike) => void,\n) {\n onRoute?.(route)\n let cursor = start\n {\n const path = route.fullPath ?? route.from\n const length = path.length\n const caseSensitive = route.options?.caseSensitive ?? defaultCaseSensitive\n while (cursor < length) {\n const segment = parseSegment(path, cursor, data)\n let nextNode: AnySegmentNode<TRouteLike>\n const start = cursor\n const end = segment[5]\n cursor = end + 1\n depth++\n const kind = segment[0]\n switch (kind) {\n case SEGMENT_TYPE_PATHNAME: {\n const value = path.substring(segment[2], segment[3])\n if (caseSensitive) {\n const existingNode = node.static?.get(value)\n if (existingNode) {\n nextNode = existingNode\n } else {\n node.static ??= new Map()\n const next = createStaticNode<TRouteLike>(\n route.fullPath ?? route.from,\n )\n next.parent = node\n next.depth = depth\n nextNode = next\n node.static.set(value, next)\n }\n } else {\n const name = value.toLowerCase()\n const existingNode = node.staticInsensitive?.get(name)\n if (existingNode) {\n nextNode = existingNode\n } else {\n node.staticInsensitive ??= new Map()\n const next = createStaticNode<TRouteLike>(\n route.fullPath ?? route.from,\n )\n next.parent = node\n next.depth = depth\n nextNode = next\n node.staticInsensitive.set(name, next)\n }\n }\n break\n }\n case SEGMENT_TYPE_PARAM: {\n const prefix_raw = path.substring(start, segment[1])\n const suffix_raw = path.substring(segment[4], end)\n const actuallyCaseSensitive =\n caseSensitive && !!(prefix_raw || suffix_raw)\n const prefix = !prefix_raw\n ? undefined\n : actuallyCaseSensitive\n ? prefix_raw\n : prefix_raw.toLowerCase()\n const suffix = !suffix_raw\n ? undefined\n : actuallyCaseSensitive\n ? suffix_raw\n : suffix_raw.toLowerCase()\n const existingNode = node.dynamic?.find(\n (s) =>\n s.caseSensitive === actuallyCaseSensitive &&\n s.prefix === prefix &&\n s.suffix === suffix,\n )\n if (existingNode) {\n nextNode = existingNode\n } else {\n const next = createDynamicNode<TRouteLike>(\n SEGMENT_TYPE_PARAM,\n route.fullPath ?? route.from,\n actuallyCaseSensitive,\n prefix,\n suffix,\n )\n nextNode = next\n next.depth = depth\n next.parent = node\n node.dynamic ??= []\n node.dynamic.push(next)\n }\n break\n }\n case SEGMENT_TYPE_OPTIONAL_PARAM: {\n const prefix_raw = path.substring(start, segment[1])\n const suffix_raw = path.substring(segment[4], end)\n const actuallyCaseSensitive =\n caseSensitive && !!(prefix_raw || suffix_raw)\n const prefix = !prefix_raw\n ? undefined\n : actuallyCaseSensitive\n ? prefix_raw\n : prefix_raw.toLowerCase()\n const suffix = !suffix_raw\n ? undefined\n : actuallyCaseSensitive\n ? suffix_raw\n : suffix_raw.toLowerCase()\n const existingNode = node.optional?.find(\n (s) =>\n s.caseSensitive === actuallyCaseSensitive &&\n s.prefix === prefix &&\n s.suffix === suffix,\n )\n if (existingNode) {\n nextNode = existingNode\n } else {\n const next = createDynamicNode<TRouteLike>(\n SEGMENT_TYPE_OPTIONAL_PARAM,\n route.fullPath ?? route.from,\n actuallyCaseSensitive,\n prefix,\n suffix,\n )\n nextNode = next\n next.parent = node\n next.depth = depth\n node.optional ??= []\n node.optional.push(next)\n }\n break\n }\n case SEGMENT_TYPE_WILDCARD: {\n const prefix_raw = path.substring(start, segment[1])\n const suffix_raw = path.substring(segment[4], end)\n const actuallyCaseSensitive =\n caseSensitive && !!(prefix_raw || suffix_raw)\n const prefix = !prefix_raw\n ? undefined\n : actuallyCaseSensitive\n ? prefix_raw\n : prefix_raw.toLowerCase()\n const suffix = !suffix_raw\n ? undefined\n : actuallyCaseSensitive\n ? suffix_raw\n : suffix_raw.toLowerCase()\n const next = createDynamicNode<TRouteLike>(\n SEGMENT_TYPE_WILDCARD,\n route.fullPath ?? route.from,\n actuallyCaseSensitive,\n prefix,\n suffix,\n )\n nextNode = next\n next.parent = node\n next.depth = depth\n node.wildcard ??= []\n node.wildcard.push(next)\n }\n }\n node = nextNode\n }\n if ((route.path || !route.children) && !route.isRoot) {\n const isIndex = path.endsWith('/')\n // we cannot fuzzy match an index route,\n // but if there is *also* a layout route at this path, save it as notFound\n // we can use it when fuzzy matching to display the NotFound component in the layout route\n if (!isIndex) node.notFound = route\n if (!node.route || (!node.isIndex && isIndex)) node.route = route\n node.isIndex ||= isIndex\n }\n }\n if (route.children)\n for (const child of route.children) {\n parseSegments(\n defaultCaseSensitive,\n data,\n child as TRouteLike,\n cursor,\n node,\n depth,\n onRoute,\n )\n }\n}\n\nfunction sortDynamic(\n a: { prefix?: string; suffix?: string; caseSensitive: boolean },\n b: { prefix?: string; suffix?: string; caseSensitive: boolean },\n) {\n if (a.prefix && b.prefix && a.prefix !== b.prefix) {\n if (a.prefix.startsWith(b.prefix)) return -1\n if (b.prefix.startsWith(a.prefix)) return 1\n }\n if (a.suffix && b.suffix && a.suffix !== b.suffix) {\n if (a.suffix.endsWith(b.suffix)) return -1\n if (b.suffix.endsWith(a.suffix)) return 1\n }\n if (a.prefix && !b.prefix) return -1\n if (!a.prefix && b.prefix) return 1\n if (a.suffix && !b.suffix) return -1\n if (!a.suffix && b.suffix) return 1\n if (a.caseSensitive && !b.caseSensitive) return -1\n if (!a.caseSensitive && b.caseSensitive) return 1\n\n // we don't need a tiebreaker here\n // at this point the 2 nodes cannot conflict during matching\n return 0\n}\n\nfunction sortTreeNodes(node: SegmentNode<RouteLike>) {\n if (node.static) {\n for (const child of node.static.values()) {\n sortTreeNodes(child)\n }\n }\n if (node.staticInsensitive) {\n for (const child of node.staticInsensitive.values()) {\n sortTreeNodes(child)\n }\n }\n if (node.dynamic?.length) {\n node.dynamic.sort(sortDynamic)\n for (const child of node.dynamic) {\n sortTreeNodes(child)\n }\n }\n if (node.optional?.length) {\n node.optional.sort(sortDynamic)\n for (const child of node.optional) {\n sortTreeNodes(child)\n }\n }\n if (node.wildcard?.length) {\n node.wildcard.sort(sortDynamic)\n for (const child of node.wildcard) {\n sortTreeNodes(child)\n }\n }\n}\n\nfunction createStaticNode<T extends RouteLike>(\n fullPath: string,\n): StaticSegmentNode<T> {\n return {\n kind: SEGMENT_TYPE_PATHNAME,\n depth: 0,\n static: null,\n staticInsensitive: null,\n dynamic: null,\n optional: null,\n wildcard: null,\n route: null,\n fullPath,\n parent: null,\n isIndex: false,\n notFound: null,\n }\n}\n\n/**\n * Keys must be declared in the same order as in `SegmentNode` type,\n * to ensure they are represented as the same object class in the engine.\n */\nfunction createDynamicNode<T extends RouteLike>(\n kind:\n | typeof SEGMENT_TYPE_PARAM\n | typeof SEGMENT_TYPE_WILDCARD\n | typeof SEGMENT_TYPE_OPTIONAL_PARAM,\n fullPath: string,\n caseSensitive: boolean,\n prefix?: string,\n suffix?: string,\n): DynamicSegmentNode<T> {\n return {\n kind,\n depth: 0,\n static: null,\n staticInsensitive: null,\n dynamic: null,\n optional: null,\n wildcard: null,\n route: null,\n fullPath,\n parent: null,\n isIndex: false,\n notFound: null,\n caseSensitive,\n prefix,\n suffix,\n }\n}\n\ntype StaticSegmentNode<T extends RouteLike> = SegmentNode<T> & {\n kind: typeof SEGMENT_TYPE_PATHNAME\n}\n\ntype DynamicSegmentNode<T extends RouteLike> = SegmentNode<T> & {\n kind:\n | typeof SEGMENT_TYPE_PARAM\n | typeof SEGMENT_TYPE_WILDCARD\n | typeof SEGMENT_TYPE_OPTIONAL_PARAM\n prefix?: string\n suffix?: string\n caseSensitive: boolean\n}\n\ntype AnySegmentNode<T extends RouteLike> =\n | StaticSegmentNode<T>\n | DynamicSegmentNode<T>\n\ntype SegmentNode<T extends RouteLike> = {\n kind: SegmentKind\n\n /** Static segments (highest priority) */\n static: Map<string, StaticSegmentNode<T>> | null\n\n /** Case insensitive static segments (second highest priority) */\n staticInsensitive: Map<string, StaticSegmentNode<T>> | null\n\n /** Dynamic segments ($param) */\n dynamic: Array<DynamicSegmentNode<T>> | null\n\n /** Optional dynamic segments ({-$param}) */\n optional: Array<DynamicSegmentNode<T>> | null\n\n /** Wildcard segments ($ - lowest priority) */\n wildcard: Array<DynamicSegmentNode<T>> | null\n\n /** Terminal route (if this path can end here) */\n route: T | null\n\n /** The full path for this segment node (will only be valid on leaf nodes) */\n fullPath: string\n\n parent: AnySegmentNode<T> | null\n\n depth: number\n\n /** is it an index route (trailing / path), only valid for nodes with a `route` */\n isIndex: boolean\n\n /** Same as `route`, but only present if both an \"index route\" and a \"layout route\" exist at this path */\n notFound: T | null\n}\n\ntype RouteLike = {\n path?: string // relative path from the parent,\n children?: Array<RouteLike> // child routes,\n parentRoute?: RouteLike // parent route,\n isRoot?: boolean\n options?: {\n caseSensitive?: boolean\n }\n} &\n // router tree\n (| { fullPath: string; from?: never } // full path from the root\n // flat route masks list\n | { fullPath?: never; from: string } // full path from the root\n )\n\nexport type ProcessedTree<\n TTree extends Extract<RouteLike, { fullPath: string }>,\n TFlat extends Extract<RouteLike, { from: string }>,\n TSingle extends Extract<RouteLike, { from: string }>,\n> = {\n /** a representation of the `routeTree` as a segment tree */\n segmentTree: AnySegmentNode<TTree>\n /** a mini route tree generated from the flat `routeMasks` list */\n masksTree: AnySegmentNode<TFlat> | null\n /** @deprecated keep until v2 so that `router.matchRoute` can keep not caring about the actual route tree */\n singleCache: LRUCache<string, AnySegmentNode<TSingle>>\n /** a cache of route matches from the `segmentTree` */\n matchCache: LRUCache<string, RouteMatch<TTree> | null>\n /** a cache of route matches from the `masksTree` */\n flatCache: LRUCache<string, ReturnType<typeof findMatch<TFlat>>> | null\n}\n\nexport function processRouteMasks<\n TRouteLike extends Extract<RouteLike, { from: string }>,\n>(\n routeList: Array<TRouteLike>,\n processedTree: ProcessedTree<any, TRouteLike, any>,\n) {\n const segmentTree = createStaticNode<TRouteLike>('/')\n const data = new Uint16Array(6)\n for (const route of routeList) {\n parseSegments(false, data, route, 1, segmentTree, 0)\n }\n sortTreeNodes(segmentTree)\n processedTree.masksTree = segmentTree\n processedTree.flatCache = createLRUCache<\n string,\n ReturnType<typeof findMatch<TRouteLike>>\n >(1000)\n}\n\n/**\n * Take an arbitrary list of routes, create a tree from them (if it hasn't been created already), and match a path against it.\n */\nexport function findFlatMatch<T extends Extract<RouteLike, { from: string }>>(\n /** The path to match. */\n path: string,\n /** The `processedTree` returned by the initial `processRouteTree` call. */\n processedTree: ProcessedTree<any, T, any>,\n) {\n path ||= '/'\n const cached = processedTree.flatCache!.get(path)\n if (cached) return cached\n const result = findMatch(path, processedTree.masksTree!)\n processedTree.flatCache!.set(path, result)\n return result\n}\n\n/**\n * @deprecated keep until v2 so that `router.matchRoute` can keep not caring about the actual route tree\n */\nexport function findSingleMatch(\n from: string,\n caseSensitive: boolean,\n fuzzy: boolean,\n path: string,\n processedTree: ProcessedTree<any, any, { from: string }>,\n) {\n from ||= '/'\n path ||= '/'\n const key = caseSensitive ? `case\\0${from}` : from\n let tree = processedTree.singleCache.get(key)\n if (!tree) {\n // single flat routes (router.matchRoute) are not eagerly processed,\n // if we haven't seen this route before, process it now\n tree = createStaticNode<{ from: string }>('/')\n const data = new Uint16Array(6)\n parseSegments(caseSensitive, data, { from }, 1, tree, 0)\n processedTree.singleCache.set(key, tree)\n }\n return findMatch(path, tree, fuzzy)\n}\n\ntype RouteMatch<T extends Extract<RouteLike, { fullPath: string }>> = {\n route: T\n params: Record<string, string>\n branch: ReadonlyArray<T>\n}\n\nexport function findRouteMatch<\n T extends Extract<RouteLike, { fullPath: string }>,\n>(\n /** The path to match against the route tree. */\n path: string,\n /** The `processedTree` returned by the initial `processRouteTree` call. */\n processedTree: ProcessedTree<T, any, any>,\n /** If `true`, allows fuzzy matching (partial matches), i.e. which node in the tree would have been an exact match if the `path` had been shorter? */\n fuzzy = false,\n): RouteMatch<T> | null {\n const key = fuzzy ? path : `nofuzz\\0${path}` // the main use for `findRouteMatch` is fuzzy:true, so we optimize for that case\n const cached = processedTree.matchCache.get(key)\n if (cached !== undefined) return cached\n path ||= '/'\n const result = findMatch(\n path,\n processedTree.segmentTree,\n fuzzy,\n ) as RouteMatch<T> | null\n if (result) result.branch = buildRouteBranch(result.route)\n processedTree.matchCache.set(key, result)\n return result\n}\n\n/** Trim trailing slashes (except preserving root '/'). */\nexport function trimPathRight(path: string) {\n return path === '/' ? path : path.replace(/\\/{1,}$/, '')\n}\n\n/**\n * Processes a route tree into a segment trie for efficient path matching.\n * Also builds lookup maps for routes by ID and by trimmed full path.\n */\nexport function processRouteTree<\n TRouteLike extends Extract<RouteLike, { fullPath: string }> & { id: string },\n>(\n /** The root of the route tree to process. */\n routeTree: TRouteLike,\n /** Whether matching should be case sensitive by default (overridden by individual route options). */\n caseSensitive: boolean = false,\n /** Optional callback invoked for each route during processing. */\n initRoute?: (route: TRouteLike, index: number) => void,\n): {\n /** Should be considered a black box, needs to be provided to all matching functions in this module. */\n processedTree: ProcessedTree<TRouteLike, any, any>\n /** A lookup map of routes by their unique IDs. */\n routesById: Record<string, TRouteLike>\n /** A lookup map of routes by their trimmed full paths. */\n routesByPath: Record<string, TRouteLike>\n} {\n const segmentTree = createStaticNode<TRouteLike>(routeTree.fullPath)\n const data = new Uint16Array(6)\n const routesById = {} as Record<string, TRouteLike>\n const routesByPath = {} as Record<string, TRouteLike>\n let index = 0\n parseSegments(caseSensitive, data, routeTree, 1, segmentTree, 0, (route) => {\n initRoute?.(route, index)\n\n invariant(\n !(route.id in routesById),\n `Duplicate routes found with id: ${String(route.id)}`,\n )\n\n routesById[route.id] = route\n\n if (index !== 0 && route.path) {\n const trimmedFullPath = trimPathRight(route.fullPath)\n if (!routesByPath[trimmedFullPath] || route.fullPath.endsWith('/')) {\n routesByPath[trimmedFullPath] = route\n }\n }\n\n index++\n })\n sortTreeNodes(segmentTree)\n const processedTree: ProcessedTree<TRouteLike, any, any> = {\n segmentTree,\n singleCache: createLRUCache<string, AnySegmentNode<any>>(1000),\n matchCache: createLRUCache<string, RouteMatch<TRouteLike> | null>(1000),\n flatCache: null,\n masksTree: null,\n }\n return {\n processedTree,\n routesById,\n routesByPath,\n }\n}\n\nfunction findMatch<T extends RouteLike>(\n path: string,\n segmentTree: AnySegmentNode<T>,\n fuzzy = false,\n): { route: T; params: Record<string, string> } | null {\n const parts = path.split('/')\n const leaf = getNodeMatch(path, parts, segmentTree, fuzzy)\n if (!leaf) return null\n const params = extractParams(path, parts, leaf)\n const isFuzzyMatch = '**' in leaf\n if (isFuzzyMatch) params['**'] = leaf['**']\n const route = isFuzzyMatch\n ? (leaf.node.notFound ?? leaf.node.route!)\n : leaf.node.route!\n return {\n route,\n params,\n }\n}\n\nfunction extractParams<T extends RouteLike>(\n path: string,\n parts: Array<string>,\n leaf: { node: AnySegmentNode<T>; skipped: number },\n) {\n const list = buildBranch(leaf.node)\n let nodeParts: Array<string> | null = null\n const params: Record<string, string> = {}\n for (\n let partIndex = 0, nodeIndex = 0, pathIndex = 0;\n nodeIndex < list.length;\n partIndex++, nodeIndex++, pathIndex++\n ) {\n const node = list[nodeIndex]!\n const part = parts[partIndex]\n const currentPathIndex = pathIndex\n if (part) pathIndex += part.length\n if (node.kind === SEGMENT_TYPE_PARAM) {\n nodeParts ??= leaf.node.fullPath.split('/')\n const nodePart = nodeParts[nodeIndex]!\n const preLength = node.prefix?.length ?? 0\n // we can't rely on the presence of prefix/suffix to know whether it's curly-braced or not, because `/{$param}/` is valid, but has no prefix/suffix\n const isCurlyBraced = nodePart.charCodeAt(preLength) === 123 // '{'\n // param name is extracted at match-time so that tree nodes that are identical except for param name can share the same node\n if (isCurlyBraced) {\n const sufLength = node.suffix?.length ?? 0\n const name = nodePart.substring(\n preLength + 2,\n nodePart.length - sufLength - 1,\n )\n const value = part!.substring(preLength, part!.length - sufLength)\n params[name] = decodeURIComponent(value)\n } else {\n const name = nodePart.substring(1)\n params[name] = decodeURIComponent(part!)\n }\n } else if (node.kind === SEGMENT_TYPE_OPTIONAL_PARAM) {\n if (leaf.skipped & (1 << nodeIndex)) {\n partIndex-- // stay on the same part\n continue\n }\n nodeParts ??= leaf.node.fullPath.split('/')\n const nodePart = nodeParts[nodeIndex]!\n const preLength = node.prefix?.length ?? 0\n const sufLength = node.suffix?.length ?? 0\n const name = nodePart.substring(\n preLength + 3,\n nodePart.length - sufLength - 1,\n )\n const value =\n node.suffix || node.prefix\n ? part!.substring(preLength, part!.length - sufLength)\n : part\n if (value) params[name] = decodeURIComponent(value)\n } else if (node.kind === SEGMENT_TYPE_WILDCARD) {\n const n = node\n const value = path.substring(\n currentPathIndex + (n.prefix?.length ?? 0),\n path.length - (n.suffix?.length ?? 0),\n )\n const splat = decodeURIComponent(value)\n // TODO: Deprecate *\n params['*'] = splat\n params._splat = splat\n break\n }\n }\n return params\n}\n\nfunction buildRouteBranch<T extends RouteLike>(route: T) {\n const list = [route]\n while (route.parentRoute) {\n route = route.parentRoute as T\n list.push(route)\n }\n list.reverse()\n return list\n}\n\nfunction buildBranch<T extends RouteLike>(node: AnySegmentNode<T>) {\n const list: Array<AnySegmentNode<T>> = Array(node.depth + 1)\n do {\n list[node.depth] = node\n node = node.parent!\n } while (node)\n return list\n}\n\ntype MatchStackFrame<T extends RouteLike> = {\n node: AnySegmentNode<T>\n /** index of the segment of path */\n index: number\n /** how many nodes between `node` and the root of the segment tree */\n depth: number\n /**\n * Bitmask of skipped optional segments.\n *\n * This is a very performant way of storing an \"array of booleans\", but it means beyond 32 segments we can't track skipped optionals.\n * If we really really need to support more than 32 segments we can switch to using a `BigInt` here. It's about 2x slower in worst case scenarios.\n */\n skipped: number\n statics: number\n dynamics: number\n optionals: number\n}\n\nfunction getNodeMatch<T extends RouteLike>(\n path: string,\n parts: Array<string>,\n segmentTree: AnySegmentNode<T>,\n fuzzy: boolean,\n) {\n const trailingSlash = !last(parts)\n const pathIsIndex = trailingSlash && path !== '/'\n const partsLength = parts.length - (trailingSlash ? 1 : 0)\n\n type Frame = MatchStackFrame<T>\n\n // use a stack to explore all possible paths (params cause branching)\n // iterate \"backwards\" (low priority first) so that we can push() each candidate, and pop() the highest priority candidate first\n // - pros: it is depth-first, so we find full matches faster\n // - cons: we cannot short-circuit, because highest priority matches are at the end of the loop (for loop with i--) (but we have no good short-circuiting anyway)\n // other possible approaches:\n // - shift instead of pop (measure performance difference), this allows iterating \"forwards\" (effectively breadth-first)\n // - never remove from the stack, keep a cursor instead. Then we can push \"forwards\" and avoid reversing the order of candidates (effectively breadth-first)\n const stack: Array<Frame> = [\n {\n node: segmentTree,\n index: 1,\n skipped: 0,\n depth: 1,\n statics: 1,\n dynamics: 0,\n optionals: 0,\n },\n ]\n\n let wildcardMatch: Frame | null = null\n let bestFuzzy: Frame | null = null\n let bestMatch: Frame | null = null\n\n while (stack.length) {\n const frame = stack.pop()!\n // eslint-disable-next-line prefer-const\n let { node, index, skipped, depth, statics, dynamics, optionals } = frame\n\n // In fuzzy mode, track the best partial match we've found so far\n if (fuzzy && node.notFound && isFrameMoreSpecific(bestFuzzy, frame)) {\n bestFuzzy = frame\n }\n\n const isBeyondPath = index === partsLength\n if (isBeyondPath) {\n if (node.route && (!pathIsIndex || node.isIndex)) {\n if (isFrameMoreSpecific(bestMatch, frame)) {\n bestMatch = frame\n }\n\n // perfect match, no need to continue\n if (statics === partsLength && node.isIndex) return bestMatch\n }\n // beyond the length of the path parts, only skipped optional segments or wildcard segments can match\n if (!node.optional && !node.wildcard) continue\n }\n\n const part = isBeyondPath ? undefined : parts[index]!\n let lowerPart: string\n\n // 5. Try wildcard match\n if (node.wildcard && isFrameMoreSpecific(wildcardMatch, frame)) {\n for (const segment of node.wildcard) {\n const { prefix, suffix } = segment\n if (prefix) {\n if (isBeyondPath) continue\n const casePart = segment.caseSensitive\n ? part\n : (lowerPart ??= part!.toLowerCase())\n if (!casePart!.startsWith(prefix)) continue\n }\n if (suffix) {\n if (isBeyondPath) continue\n const end = parts.slice(index).join('/').slice(-suffix.length)\n const casePart = segment.caseSensitive ? end : end.toLowerCase()\n if (casePart !== suffix) continue\n }\n // the first wildcard match is the highest priority one\n wildcardMatch = {\n node: segment,\n index,\n skipped,\n depth,\n statics,\n dynamics,\n optionals,\n }\n break\n }\n }\n\n // 4. Try optional match\n if (node.optional) {\n const nextSkipped = skipped | (1 << depth)\n const nextDepth = depth + 1\n for (let i = node.optional.length - 1; i >= 0; i--) {\n const segment = node.optional[i]!\n // when skipping, node and depth advance by 1, but index doesn't\n stack.push({\n node: segment,\n index,\n skipped: nextSkipped,\n depth: nextDepth,\n statics,\n dynamics,\n optionals,\n }) // enqueue skipping the optional\n }\n if (!isBeyondPath) {\n for (let i = node.optional.length - 1; i >= 0; i--) {\n const segment = node.optional[i]!\n const { prefix, suffix } = segment\n if (prefix || suffix) {\n const casePart = segment.caseSensitive\n ? part!\n : (lowerPart ??= part!.toLowerCase())\n if (prefix && !casePart.startsWith(prefix)) continue\n if (suffix && !casePart.endsWith(suffix)) continue\n }\n stack.push({\n node: segment,\n index: index + 1,\n skipped,\n depth: nextDepth,\n statics,\n dynamics,\n optionals: optionals + 1,\n })\n }\n }\n }\n\n // 3. Try dynamic match\n if (!isBeyondPath && node.dynamic && part) {\n for (let i = node.dynamic.length - 1; i >= 0; i--) {\n const segment = node.dynamic[i]!\n const { prefix, suffix } = segment\n if (prefix || suffix) {\n const casePart = segment.caseSensitive\n ? part\n : (lowerPart ??= part.toLowerCase())\n if (prefix && !casePart.startsWith(prefix)) continue\n if (suffix && !casePart.endsWith(suffix)) continue\n }\n stack.push({\n node: segment,\n index: index + 1,\n skipped,\n depth: depth + 1,\n statics,\n dynamics: dynamics + 1,\n optionals,\n })\n }\n }\n\n // 2. Try case insensitive static match\n if (!isBeyondPath && node.staticInsensitive) {\n const match = node.staticInsensitive.get(\n (lowerPart ??= part!.toLowerCase()),\n )\n if (match) {\n stack.push({\n node: match,\n index: index + 1,\n skipped,\n depth: depth + 1,\n statics: statics + 1,\n dynamics,\n optionals,\n })\n }\n }\n\n // 1. Try static match\n if (!isBeyondPath && node.static) {\n const match = node.static.get(part!)\n if (match) {\n stack.push({\n node: match,\n index: index + 1,\n skipped,\n depth: depth + 1,\n statics: statics + 1,\n dynamics,\n optionals,\n })\n }\n }\n }\n\n if (bestMatch) return bestMatch\n\n if (wildcardMatch) return wildcardMatch\n\n if (fuzzy && bestFuzzy) {\n let sliceIndex = bestFuzzy.index\n for (let i = 0; i < bestFuzzy.index; i++) {\n sliceIndex += parts[i]!.length\n }\n const splat = sliceIndex === path.length ? '/' : path.slice(sliceIndex)\n return {\n node: bestFuzzy.node,\n skipped: bestFuzzy.skipped,\n '**': decodeURIComponent(splat),\n }\n }\n\n return null\n}\n\nfunction isFrameMoreSpecific(\n // the stack frame previously saved as \"best match\"\n prev: MatchStackFrame<any> | null,\n // the candidate stack frame\n next: MatchStackFrame<any>,\n): boolean {\n if (!prev) return true\n return (\n next.statics > prev.statics ||\n (next.statics === prev.statics &&\n (next.dynamics > prev.dynamics ||\n (next.dynamics === prev.dynamics &&\n (next.optionals > prev.optionals ||\n (next.optionals === prev.optionals &&\n (next.node.isIndex > prev.node.isIndex ||\n (next.node.isIndex === prev.node.isIndex &&\n next.depth > prev.depth)))))))\n )\n}\n"],"names":["start"],"mappings":";;;AAKO,MAAM,wBAAwB;AAC9B,MAAM,qBAAqB;AAC3B,MAAM,wBAAwB;AAC9B,MAAM,8BAA8B;AAQ3C,MAAM,0BACJ;AACF,MAAM,mCACJ;AACF,MAAM,6BAA6B;AAiC5B,SAAS,aAEd,MAEA,OAEA,SAAsB,IAAI,YAAY,CAAC,GACxB;AACf,QAAM,OAAO,KAAK,QAAQ,KAAK,KAAK;AACpC,QAAM,MAAM,SAAS,KAAK,KAAK,SAAS;AACxC,QAAM,OAAO,KAAK,UAAU,OAAO,GAAG;AAEtC,MAAI,CAAC,QAAQ,CAAC,KAAK,SAAS,GAAG,GAAG;AAEhC,WAAO,CAAC,IAAI;AACZ,WAAO,CAAC,IAAI;AACZ,WAAO,CAAC,IAAI;AACZ,WAAO,CAAC,IAAI;AACZ,WAAO,CAAC,IAAI;AACZ,WAAO,CAAC,IAAI;AACZ,WAAO;AAAA,EACT;AAGA,MAAI,SAAS,KAAK;AAChB,UAAM,QAAQ,KAAK;AACnB,WAAO,CAAC,IAAI;AACZ,WAAO,CAAC,IAAI;AACZ,WAAO,CAAC,IAAI;AACZ,WAAO,CAAC,IAAI;AACZ,WAAO,CAAC,IAAI;AACZ,WAAO,CAAC,IAAI;AACZ,WAAO;AAAA,EACT;AAGA,MAAI,KAAK,WAAW,CAAC,MAAM,IAAI;AAC7B,WAAO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QAAQ;AAAA,UACf;AAAA,UACA,OAAO,QAAQ;AAAA,UACf,SAAS,UAAU;AAAA,UACnB;AAAA,UACA;AAAA,QAAA,CACD;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAEA,MAAI,UAAW,QAAO;AAEtB,MAAI,cAAe,QAAO;AAE1B,MAAI,SAAS,WAAW;AACtB,QAAI,aAAa,UAAU;AAC3B,aAAS,IAAI,GAAG,IAAI,UAAU,OAAO,KAAK;AACxC,oBAAc,MAAM,CAAC,EAAG;AAAA,IAC1B;AACA,UAAM,QAAQ,eAAe,KAAK,SAAS,MAAM,KAAK,MAAM,UAAU;AACtE,WAAO;AAAA,MACL,MAAM,UAAU;AAAA,MAChB,SAAS,UAAU;AAAA,MACnB,MAAM,mBAAmB,KAAK;AAAA,IAAA;AAAA,EAElC;AAEA,SAAO;AACT;AAEA,SAAS,oBAEP,MAEA,MACS;AACT,MAAI,CAAC,KAAM,QAAO;AAClB,SACE,KAAK,UAAU,KAAK,WACnB,KAAK,YAAY,KAAK,YACpB,KAAK,WAAW,KAAK,YACnB,KAAK,aAAa,KAAK,aACrB,KAAK,YAAY,KAAK,aACpB,KAAK,cAAc,KAAK,cACtB,KAAK,KAAK,UAAU,KAAK,KAAK,WAC5B,KAAK,KAAK,YAAY,KAAK,KAAK,WAC/B,KAAK,QAAQ,KAAK;AAEpC;"}
|
|
1
|
+
{"version":3,"file":"new-process-route-tree.js","sources":["../../src/new-process-route-tree.ts"],"sourcesContent":["import invariant from 'tiny-invariant'\nimport { createLRUCache } from './lru-cache'\nimport { last } from './utils'\nimport type { LRUCache } from './lru-cache'\n\nexport const SEGMENT_TYPE_PATHNAME = 0\nexport const SEGMENT_TYPE_PARAM = 1\nexport const SEGMENT_TYPE_WILDCARD = 2\nexport const SEGMENT_TYPE_OPTIONAL_PARAM = 3\n\nexport type SegmentKind =\n | typeof SEGMENT_TYPE_PATHNAME\n | typeof SEGMENT_TYPE_PARAM\n | typeof SEGMENT_TYPE_WILDCARD\n | typeof SEGMENT_TYPE_OPTIONAL_PARAM\n\nconst PARAM_W_CURLY_BRACES_RE =\n /^([^{]*)\\{\\$([a-zA-Z_$][a-zA-Z0-9_$]*)\\}([^}]*)$/ // prefix{$paramName}suffix\nconst OPTIONAL_PARAM_W_CURLY_BRACES_RE =\n /^([^{]*)\\{-\\$([a-zA-Z_$][a-zA-Z0-9_$]*)\\}([^}]*)$/ // prefix{-$paramName}suffix\nconst WILDCARD_W_CURLY_BRACES_RE = /^([^{]*)\\{\\$\\}([^}]*)$/ // prefix{$}suffix\n\ntype ParsedSegment = Uint16Array & {\n /** segment type (0 = pathname, 1 = param, 2 = wildcard, 3 = optional param) */\n 0: SegmentKind\n /** index of the end of the prefix */\n 1: number\n /** index of the start of the value */\n 2: number\n /** index of the end of the value */\n 3: number\n /** index of the start of the suffix */\n 4: number\n /** index of the end of the segment */\n 5: number\n}\n\n/**\n * Populates the `output` array with the parsed representation of the given `segment` string.\n *\n * Usage:\n * ```ts\n * let output\n * let cursor = 0\n * while (cursor < path.length) {\n * output = parseSegment(path, cursor, output)\n * const end = output[5]\n * cursor = end + 1\n * ```\n *\n * `output` is stored outside to avoid allocations during repeated calls. It doesn't need to be typed\n * or initialized, it will be done automatically.\n */\nexport function parseSegment(\n /** The full path string containing the segment. */\n path: string,\n /** The starting index of the segment within the path. */\n start: number,\n /** A Uint16Array (length: 6) to populate with the parsed segment data. */\n output: Uint16Array = new Uint16Array(6),\n): ParsedSegment {\n const next = path.indexOf('/', start)\n const end = next === -1 ? path.length : next\n const part = path.substring(start, end)\n\n if (!part || !part.includes('$')) {\n // early escape for static pathname\n output[0] = SEGMENT_TYPE_PATHNAME\n output[1] = start\n output[2] = start\n output[3] = end\n output[4] = end\n output[5] = end\n return output as ParsedSegment\n }\n\n // $ (wildcard)\n if (part === '$') {\n const total = path.length\n output[0] = SEGMENT_TYPE_WILDCARD\n output[1] = start\n output[2] = start\n output[3] = total\n output[4] = total\n output[5] = total\n return output as ParsedSegment\n }\n\n // $paramName\n if (part.charCodeAt(0) === 36) {\n output[0] = SEGMENT_TYPE_PARAM\n output[1] = start\n output[2] = start + 1 // skip '$'\n output[3] = end\n output[4] = end\n output[5] = end\n return output as ParsedSegment\n }\n\n const wildcardBracesMatch = part.match(WILDCARD_W_CURLY_BRACES_RE)\n if (wildcardBracesMatch) {\n const prefix = wildcardBracesMatch[1]!\n const pLength = prefix.length\n output[0] = SEGMENT_TYPE_WILDCARD\n output[1] = start + pLength\n output[2] = start + pLength + 1 // skip '{'\n output[3] = start + pLength + 2 // '$'\n output[4] = start + pLength + 3 // skip '}'\n output[5] = path.length\n return output as ParsedSegment\n }\n\n const optionalParamBracesMatch = part.match(OPTIONAL_PARAM_W_CURLY_BRACES_RE)\n if (optionalParamBracesMatch) {\n const prefix = optionalParamBracesMatch[1]!\n const paramName = optionalParamBracesMatch[2]!\n const suffix = optionalParamBracesMatch[3]!\n const pLength = prefix.length\n output[0] = SEGMENT_TYPE_OPTIONAL_PARAM\n output[1] = start + pLength\n output[2] = start + pLength + 3 // skip '{-$'\n output[3] = start + pLength + 3 + paramName.length\n output[4] = end - suffix.length\n output[5] = end\n return output as ParsedSegment\n }\n\n const paramBracesMatch = part.match(PARAM_W_CURLY_BRACES_RE)\n if (paramBracesMatch) {\n const prefix = paramBracesMatch[1]!\n const paramName = paramBracesMatch[2]!\n const suffix = paramBracesMatch[3]!\n const pLength = prefix.length\n output[0] = SEGMENT_TYPE_PARAM\n output[1] = start + pLength\n output[2] = start + pLength + 2 // skip '{$'\n output[3] = start + pLength + 2 + paramName.length\n output[4] = end - suffix.length\n output[5] = end\n return output as ParsedSegment\n }\n\n // fallback to static pathname (should never happen)\n output[0] = SEGMENT_TYPE_PATHNAME\n output[1] = start\n output[2] = start\n output[3] = end\n output[4] = end\n output[5] = end\n return output as ParsedSegment\n}\n\n/**\n * Recursively parses the segments of the given route tree and populates a segment trie.\n *\n * @param data A reusable Uint16Array for parsing segments. (non important, we're just avoiding allocations)\n * @param route The current route to parse.\n * @param start The starting index for parsing within the route's full path.\n * @param node The current segment node in the trie to populate.\n * @param onRoute Callback invoked for each route processed.\n */\nfunction parseSegments<TRouteLike extends RouteLike>(\n defaultCaseSensitive: boolean,\n data: Uint16Array,\n route: TRouteLike,\n start: number,\n node: AnySegmentNode<TRouteLike>,\n depth: number,\n onRoute?: (route: TRouteLike) => void,\n) {\n onRoute?.(route)\n let cursor = start\n {\n const path = route.fullPath ?? route.from\n const length = path.length\n const caseSensitive = route.options?.caseSensitive ?? defaultCaseSensitive\n while (cursor < length) {\n const segment = parseSegment(path, cursor, data)\n let nextNode: AnySegmentNode<TRouteLike>\n const start = cursor\n const end = segment[5]\n cursor = end + 1\n depth++\n const kind = segment[0]\n switch (kind) {\n case SEGMENT_TYPE_PATHNAME: {\n const value = path.substring(segment[2], segment[3])\n if (caseSensitive) {\n const existingNode = node.static?.get(value)\n if (existingNode) {\n nextNode = existingNode\n } else {\n node.static ??= new Map()\n const next = createStaticNode<TRouteLike>(\n route.fullPath ?? route.from,\n )\n next.parent = node\n next.depth = depth\n nextNode = next\n node.static.set(value, next)\n }\n } else {\n const name = value.toLowerCase()\n const existingNode = node.staticInsensitive?.get(name)\n if (existingNode) {\n nextNode = existingNode\n } else {\n node.staticInsensitive ??= new Map()\n const next = createStaticNode<TRouteLike>(\n route.fullPath ?? route.from,\n )\n next.parent = node\n next.depth = depth\n nextNode = next\n node.staticInsensitive.set(name, next)\n }\n }\n break\n }\n case SEGMENT_TYPE_PARAM: {\n const prefix_raw = path.substring(start, segment[1])\n const suffix_raw = path.substring(segment[4], end)\n const actuallyCaseSensitive =\n caseSensitive && !!(prefix_raw || suffix_raw)\n const prefix = !prefix_raw\n ? undefined\n : actuallyCaseSensitive\n ? prefix_raw\n : prefix_raw.toLowerCase()\n const suffix = !suffix_raw\n ? undefined\n : actuallyCaseSensitive\n ? suffix_raw\n : suffix_raw.toLowerCase()\n const existingNode = node.dynamic?.find(\n (s) =>\n s.caseSensitive === actuallyCaseSensitive &&\n s.prefix === prefix &&\n s.suffix === suffix,\n )\n if (existingNode) {\n nextNode = existingNode\n } else {\n const next = createDynamicNode<TRouteLike>(\n SEGMENT_TYPE_PARAM,\n route.fullPath ?? route.from,\n actuallyCaseSensitive,\n prefix,\n suffix,\n )\n nextNode = next\n next.depth = depth\n next.parent = node\n node.dynamic ??= []\n node.dynamic.push(next)\n }\n break\n }\n case SEGMENT_TYPE_OPTIONAL_PARAM: {\n const prefix_raw = path.substring(start, segment[1])\n const suffix_raw = path.substring(segment[4], end)\n const actuallyCaseSensitive =\n caseSensitive && !!(prefix_raw || suffix_raw)\n const prefix = !prefix_raw\n ? undefined\n : actuallyCaseSensitive\n ? prefix_raw\n : prefix_raw.toLowerCase()\n const suffix = !suffix_raw\n ? undefined\n : actuallyCaseSensitive\n ? suffix_raw\n : suffix_raw.toLowerCase()\n const existingNode = node.optional?.find(\n (s) =>\n s.caseSensitive === actuallyCaseSensitive &&\n s.prefix === prefix &&\n s.suffix === suffix,\n )\n if (existingNode) {\n nextNode = existingNode\n } else {\n const next = createDynamicNode<TRouteLike>(\n SEGMENT_TYPE_OPTIONAL_PARAM,\n route.fullPath ?? route.from,\n actuallyCaseSensitive,\n prefix,\n suffix,\n )\n nextNode = next\n next.parent = node\n next.depth = depth\n node.optional ??= []\n node.optional.push(next)\n }\n break\n }\n case SEGMENT_TYPE_WILDCARD: {\n const prefix_raw = path.substring(start, segment[1])\n const suffix_raw = path.substring(segment[4], end)\n const actuallyCaseSensitive =\n caseSensitive && !!(prefix_raw || suffix_raw)\n const prefix = !prefix_raw\n ? undefined\n : actuallyCaseSensitive\n ? prefix_raw\n : prefix_raw.toLowerCase()\n const suffix = !suffix_raw\n ? undefined\n : actuallyCaseSensitive\n ? suffix_raw\n : suffix_raw.toLowerCase()\n const next = createDynamicNode<TRouteLike>(\n SEGMENT_TYPE_WILDCARD,\n route.fullPath ?? route.from,\n actuallyCaseSensitive,\n prefix,\n suffix,\n )\n nextNode = next\n next.parent = node\n next.depth = depth\n node.wildcard ??= []\n node.wildcard.push(next)\n }\n }\n node = nextNode\n }\n if ((route.path || !route.children) && !route.isRoot) {\n const isIndex = path.endsWith('/')\n // we cannot fuzzy match an index route,\n // but if there is *also* a layout route at this path, save it as notFound\n // we can use it when fuzzy matching to display the NotFound component in the layout route\n if (!isIndex) node.notFound = route\n if (!node.route || (!node.isIndex && isIndex)) node.route = route\n node.isIndex ||= isIndex\n }\n }\n if (route.children)\n for (const child of route.children) {\n parseSegments(\n defaultCaseSensitive,\n data,\n child as TRouteLike,\n cursor,\n node,\n depth,\n onRoute,\n )\n }\n}\n\nfunction sortDynamic(\n a: { prefix?: string; suffix?: string; caseSensitive: boolean },\n b: { prefix?: string; suffix?: string; caseSensitive: boolean },\n) {\n if (a.prefix && b.prefix && a.prefix !== b.prefix) {\n if (a.prefix.startsWith(b.prefix)) return -1\n if (b.prefix.startsWith(a.prefix)) return 1\n }\n if (a.suffix && b.suffix && a.suffix !== b.suffix) {\n if (a.suffix.endsWith(b.suffix)) return -1\n if (b.suffix.endsWith(a.suffix)) return 1\n }\n if (a.prefix && !b.prefix) return -1\n if (!a.prefix && b.prefix) return 1\n if (a.suffix && !b.suffix) return -1\n if (!a.suffix && b.suffix) return 1\n if (a.caseSensitive && !b.caseSensitive) return -1\n if (!a.caseSensitive && b.caseSensitive) return 1\n\n // we don't need a tiebreaker here\n // at this point the 2 nodes cannot conflict during matching\n return 0\n}\n\nfunction sortTreeNodes(node: SegmentNode<RouteLike>) {\n if (node.static) {\n for (const child of node.static.values()) {\n sortTreeNodes(child)\n }\n }\n if (node.staticInsensitive) {\n for (const child of node.staticInsensitive.values()) {\n sortTreeNodes(child)\n }\n }\n if (node.dynamic?.length) {\n node.dynamic.sort(sortDynamic)\n for (const child of node.dynamic) {\n sortTreeNodes(child)\n }\n }\n if (node.optional?.length) {\n node.optional.sort(sortDynamic)\n for (const child of node.optional) {\n sortTreeNodes(child)\n }\n }\n if (node.wildcard?.length) {\n node.wildcard.sort(sortDynamic)\n for (const child of node.wildcard) {\n sortTreeNodes(child)\n }\n }\n}\n\nfunction createStaticNode<T extends RouteLike>(\n fullPath: string,\n): StaticSegmentNode<T> {\n return {\n kind: SEGMENT_TYPE_PATHNAME,\n depth: 0,\n static: null,\n staticInsensitive: null,\n dynamic: null,\n optional: null,\n wildcard: null,\n route: null,\n fullPath,\n parent: null,\n isIndex: false,\n notFound: null,\n }\n}\n\n/**\n * Keys must be declared in the same order as in `SegmentNode` type,\n * to ensure they are represented as the same object class in the engine.\n */\nfunction createDynamicNode<T extends RouteLike>(\n kind:\n | typeof SEGMENT_TYPE_PARAM\n | typeof SEGMENT_TYPE_WILDCARD\n | typeof SEGMENT_TYPE_OPTIONAL_PARAM,\n fullPath: string,\n caseSensitive: boolean,\n prefix?: string,\n suffix?: string,\n): DynamicSegmentNode<T> {\n return {\n kind,\n depth: 0,\n static: null,\n staticInsensitive: null,\n dynamic: null,\n optional: null,\n wildcard: null,\n route: null,\n fullPath,\n parent: null,\n isIndex: false,\n notFound: null,\n caseSensitive,\n prefix,\n suffix,\n }\n}\n\ntype StaticSegmentNode<T extends RouteLike> = SegmentNode<T> & {\n kind: typeof SEGMENT_TYPE_PATHNAME\n}\n\ntype DynamicSegmentNode<T extends RouteLike> = SegmentNode<T> & {\n kind:\n | typeof SEGMENT_TYPE_PARAM\n | typeof SEGMENT_TYPE_WILDCARD\n | typeof SEGMENT_TYPE_OPTIONAL_PARAM\n prefix?: string\n suffix?: string\n caseSensitive: boolean\n}\n\ntype AnySegmentNode<T extends RouteLike> =\n | StaticSegmentNode<T>\n | DynamicSegmentNode<T>\n\ntype SegmentNode<T extends RouteLike> = {\n kind: SegmentKind\n\n /** Static segments (highest priority) */\n static: Map<string, StaticSegmentNode<T>> | null\n\n /** Case insensitive static segments (second highest priority) */\n staticInsensitive: Map<string, StaticSegmentNode<T>> | null\n\n /** Dynamic segments ($param) */\n dynamic: Array<DynamicSegmentNode<T>> | null\n\n /** Optional dynamic segments ({-$param}) */\n optional: Array<DynamicSegmentNode<T>> | null\n\n /** Wildcard segments ($ - lowest priority) */\n wildcard: Array<DynamicSegmentNode<T>> | null\n\n /** Terminal route (if this path can end here) */\n route: T | null\n\n /** The full path for this segment node (will only be valid on leaf nodes) */\n fullPath: string\n\n parent: AnySegmentNode<T> | null\n\n depth: number\n\n /** is it an index route (trailing / path), only valid for nodes with a `route` */\n isIndex: boolean\n\n /** Same as `route`, but only present if both an \"index route\" and a \"layout route\" exist at this path */\n notFound: T | null\n}\n\ntype RouteLike = {\n path?: string // relative path from the parent,\n children?: Array<RouteLike> // child routes,\n parentRoute?: RouteLike // parent route,\n isRoot?: boolean\n options?: {\n caseSensitive?: boolean\n }\n} &\n // router tree\n (| { fullPath: string; from?: never } // full path from the root\n // flat route masks list\n | { fullPath?: never; from: string } // full path from the root\n )\n\nexport type ProcessedTree<\n TTree extends Extract<RouteLike, { fullPath: string }>,\n TFlat extends Extract<RouteLike, { from: string }>,\n TSingle extends Extract<RouteLike, { from: string }>,\n> = {\n /** a representation of the `routeTree` as a segment tree */\n segmentTree: AnySegmentNode<TTree>\n /** a mini route tree generated from the flat `routeMasks` list */\n masksTree: AnySegmentNode<TFlat> | null\n /** @deprecated keep until v2 so that `router.matchRoute` can keep not caring about the actual route tree */\n singleCache: LRUCache<string, AnySegmentNode<TSingle>>\n /** a cache of route matches from the `segmentTree` */\n matchCache: LRUCache<string, RouteMatch<TTree> | null>\n /** a cache of route matches from the `masksTree` */\n flatCache: LRUCache<string, ReturnType<typeof findMatch<TFlat>>> | null\n}\n\nexport function processRouteMasks<\n TRouteLike extends Extract<RouteLike, { from: string }>,\n>(\n routeList: Array<TRouteLike>,\n processedTree: ProcessedTree<any, TRouteLike, any>,\n) {\n const segmentTree = createStaticNode<TRouteLike>('/')\n const data = new Uint16Array(6)\n for (const route of routeList) {\n parseSegments(false, data, route, 1, segmentTree, 0)\n }\n sortTreeNodes(segmentTree)\n processedTree.masksTree = segmentTree\n processedTree.flatCache = createLRUCache<\n string,\n ReturnType<typeof findMatch<TRouteLike>>\n >(1000)\n}\n\n/**\n * Take an arbitrary list of routes, create a tree from them (if it hasn't been created already), and match a path against it.\n */\nexport function findFlatMatch<T extends Extract<RouteLike, { from: string }>>(\n /** The path to match. */\n path: string,\n /** The `processedTree` returned by the initial `processRouteTree` call. */\n processedTree: ProcessedTree<any, T, any>,\n) {\n path ||= '/'\n const cached = processedTree.flatCache!.get(path)\n if (cached) return cached\n const result = findMatch(path, processedTree.masksTree!)\n processedTree.flatCache!.set(path, result)\n return result\n}\n\n/**\n * @deprecated keep until v2 so that `router.matchRoute` can keep not caring about the actual route tree\n */\nexport function findSingleMatch(\n from: string,\n caseSensitive: boolean,\n fuzzy: boolean,\n path: string,\n processedTree: ProcessedTree<any, any, { from: string }>,\n) {\n from ||= '/'\n path ||= '/'\n const key = caseSensitive ? `case\\0${from}` : from\n let tree = processedTree.singleCache.get(key)\n if (!tree) {\n // single flat routes (router.matchRoute) are not eagerly processed,\n // if we haven't seen this route before, process it now\n tree = createStaticNode<{ from: string }>('/')\n const data = new Uint16Array(6)\n parseSegments(caseSensitive, data, { from }, 1, tree, 0)\n processedTree.singleCache.set(key, tree)\n }\n return findMatch(path, tree, fuzzy)\n}\n\ntype RouteMatch<T extends Extract<RouteLike, { fullPath: string }>> = {\n route: T\n params: Record<string, string>\n branch: ReadonlyArray<T>\n}\n\nexport function findRouteMatch<\n T extends Extract<RouteLike, { fullPath: string }>,\n>(\n /** The path to match against the route tree. */\n path: string,\n /** The `processedTree` returned by the initial `processRouteTree` call. */\n processedTree: ProcessedTree<T, any, any>,\n /** If `true`, allows fuzzy matching (partial matches), i.e. which node in the tree would have been an exact match if the `path` had been shorter? */\n fuzzy = false,\n): RouteMatch<T> | null {\n const key = fuzzy ? path : `nofuzz\\0${path}` // the main use for `findRouteMatch` is fuzzy:true, so we optimize for that case\n const cached = processedTree.matchCache.get(key)\n if (cached !== undefined) return cached\n path ||= '/'\n const result = findMatch(\n path,\n processedTree.segmentTree,\n fuzzy,\n ) as RouteMatch<T> | null\n if (result) result.branch = buildRouteBranch(result.route)\n processedTree.matchCache.set(key, result)\n return result\n}\n\n/** Trim trailing slashes (except preserving root '/'). */\nexport function trimPathRight(path: string) {\n return path === '/' ? path : path.replace(/\\/{1,}$/, '')\n}\n\n/**\n * Processes a route tree into a segment trie for efficient path matching.\n * Also builds lookup maps for routes by ID and by trimmed full path.\n */\nexport function processRouteTree<\n TRouteLike extends Extract<RouteLike, { fullPath: string }> & { id: string },\n>(\n /** The root of the route tree to process. */\n routeTree: TRouteLike,\n /** Whether matching should be case sensitive by default (overridden by individual route options). */\n caseSensitive: boolean = false,\n /** Optional callback invoked for each route during processing. */\n initRoute?: (route: TRouteLike, index: number) => void,\n): {\n /** Should be considered a black box, needs to be provided to all matching functions in this module. */\n processedTree: ProcessedTree<TRouteLike, any, any>\n /** A lookup map of routes by their unique IDs. */\n routesById: Record<string, TRouteLike>\n /** A lookup map of routes by their trimmed full paths. */\n routesByPath: Record<string, TRouteLike>\n} {\n const segmentTree = createStaticNode<TRouteLike>(routeTree.fullPath)\n const data = new Uint16Array(6)\n const routesById = {} as Record<string, TRouteLike>\n const routesByPath = {} as Record<string, TRouteLike>\n let index = 0\n parseSegments(caseSensitive, data, routeTree, 1, segmentTree, 0, (route) => {\n initRoute?.(route, index)\n\n invariant(\n !(route.id in routesById),\n `Duplicate routes found with id: ${String(route.id)}`,\n )\n\n routesById[route.id] = route\n\n if (index !== 0 && route.path) {\n const trimmedFullPath = trimPathRight(route.fullPath)\n if (!routesByPath[trimmedFullPath] || route.fullPath.endsWith('/')) {\n routesByPath[trimmedFullPath] = route\n }\n }\n\n index++\n })\n sortTreeNodes(segmentTree)\n const processedTree: ProcessedTree<TRouteLike, any, any> = {\n segmentTree,\n singleCache: createLRUCache<string, AnySegmentNode<any>>(1000),\n matchCache: createLRUCache<string, RouteMatch<TRouteLike> | null>(1000),\n flatCache: null,\n masksTree: null,\n }\n return {\n processedTree,\n routesById,\n routesByPath,\n }\n}\n\nfunction findMatch<T extends RouteLike>(\n path: string,\n segmentTree: AnySegmentNode<T>,\n fuzzy = false,\n): { route: T; params: Record<string, string> } | null {\n const parts = path.split('/')\n const leaf = getNodeMatch(path, parts, segmentTree, fuzzy)\n if (!leaf) return null\n const params = extractParams(path, parts, leaf)\n const isFuzzyMatch = '**' in leaf\n if (isFuzzyMatch) params['**'] = leaf['**']\n const route = isFuzzyMatch\n ? (leaf.node.notFound ?? leaf.node.route!)\n : leaf.node.route!\n return {\n route,\n params,\n }\n}\n\nfunction extractParams<T extends RouteLike>(\n path: string,\n parts: Array<string>,\n leaf: { node: AnySegmentNode<T>; skipped: number },\n) {\n const list = buildBranch(leaf.node)\n let nodeParts: Array<string> | null = null\n const params: Record<string, string> = {}\n for (\n let partIndex = 0, nodeIndex = 0, pathIndex = 0;\n nodeIndex < list.length;\n partIndex++, nodeIndex++, pathIndex++\n ) {\n const node = list[nodeIndex]!\n const part = parts[partIndex]\n const currentPathIndex = pathIndex\n if (part) pathIndex += part.length\n if (node.kind === SEGMENT_TYPE_PARAM) {\n nodeParts ??= leaf.node.fullPath.split('/')\n const nodePart = nodeParts[nodeIndex]!\n const preLength = node.prefix?.length ?? 0\n // we can't rely on the presence of prefix/suffix to know whether it's curly-braced or not, because `/{$param}/` is valid, but has no prefix/suffix\n const isCurlyBraced = nodePart.charCodeAt(preLength) === 123 // '{'\n // param name is extracted at match-time so that tree nodes that are identical except for param name can share the same node\n if (isCurlyBraced) {\n const sufLength = node.suffix?.length ?? 0\n const name = nodePart.substring(\n preLength + 2,\n nodePart.length - sufLength - 1,\n )\n const value = part!.substring(preLength, part!.length - sufLength)\n params[name] = decodeURIComponent(value)\n } else {\n const name = nodePart.substring(1)\n params[name] = decodeURIComponent(part!)\n }\n } else if (node.kind === SEGMENT_TYPE_OPTIONAL_PARAM) {\n if (leaf.skipped & (1 << nodeIndex)) {\n partIndex-- // stay on the same part\n continue\n }\n nodeParts ??= leaf.node.fullPath.split('/')\n const nodePart = nodeParts[nodeIndex]!\n const preLength = node.prefix?.length ?? 0\n const sufLength = node.suffix?.length ?? 0\n const name = nodePart.substring(\n preLength + 3,\n nodePart.length - sufLength - 1,\n )\n const value =\n node.suffix || node.prefix\n ? part!.substring(preLength, part!.length - sufLength)\n : part\n if (value) params[name] = decodeURIComponent(value)\n } else if (node.kind === SEGMENT_TYPE_WILDCARD) {\n const n = node\n const value = path.substring(\n currentPathIndex + (n.prefix?.length ?? 0),\n path.length - (n.suffix?.length ?? 0),\n )\n const splat = decodeURIComponent(value)\n // TODO: Deprecate *\n params['*'] = splat\n params._splat = splat\n break\n }\n }\n return params\n}\n\nfunction buildRouteBranch<T extends RouteLike>(route: T) {\n const list = [route]\n while (route.parentRoute) {\n route = route.parentRoute as T\n list.push(route)\n }\n list.reverse()\n return list\n}\n\nfunction buildBranch<T extends RouteLike>(node: AnySegmentNode<T>) {\n const list: Array<AnySegmentNode<T>> = Array(node.depth + 1)\n do {\n list[node.depth] = node\n node = node.parent!\n } while (node)\n return list\n}\n\ntype MatchStackFrame<T extends RouteLike> = {\n node: AnySegmentNode<T>\n /** index of the segment of path */\n index: number\n /** how many nodes between `node` and the root of the segment tree */\n depth: number\n /**\n * Bitmask of skipped optional segments.\n *\n * This is a very performant way of storing an \"array of booleans\", but it means beyond 32 segments we can't track skipped optionals.\n * If we really really need to support more than 32 segments we can switch to using a `BigInt` here. It's about 2x slower in worst case scenarios.\n */\n skipped: number\n statics: number\n dynamics: number\n optionals: number\n}\n\nfunction getNodeMatch<T extends RouteLike>(\n path: string,\n parts: Array<string>,\n segmentTree: AnySegmentNode<T>,\n fuzzy: boolean,\n) {\n const trailingSlash = !last(parts)\n const pathIsIndex = trailingSlash && path !== '/'\n const partsLength = parts.length - (trailingSlash ? 1 : 0)\n\n type Frame = MatchStackFrame<T>\n\n // use a stack to explore all possible paths (params cause branching)\n // iterate \"backwards\" (low priority first) so that we can push() each candidate, and pop() the highest priority candidate first\n // - pros: it is depth-first, so we find full matches faster\n // - cons: we cannot short-circuit, because highest priority matches are at the end of the loop (for loop with i--) (but we have no good short-circuiting anyway)\n // other possible approaches:\n // - shift instead of pop (measure performance difference), this allows iterating \"forwards\" (effectively breadth-first)\n // - never remove from the stack, keep a cursor instead. Then we can push \"forwards\" and avoid reversing the order of candidates (effectively breadth-first)\n const stack: Array<Frame> = [\n {\n node: segmentTree,\n index: 1,\n skipped: 0,\n depth: 1,\n statics: 1,\n dynamics: 0,\n optionals: 0,\n },\n ]\n\n let wildcardMatch: Frame | null = null\n let bestFuzzy: Frame | null = null\n let bestMatch: Frame | null = null\n\n while (stack.length) {\n const frame = stack.pop()!\n // eslint-disable-next-line prefer-const\n let { node, index, skipped, depth, statics, dynamics, optionals } = frame\n\n // In fuzzy mode, track the best partial match we've found so far\n if (fuzzy && node.notFound && isFrameMoreSpecific(bestFuzzy, frame)) {\n bestFuzzy = frame\n }\n\n const isBeyondPath = index === partsLength\n if (isBeyondPath) {\n if (node.route && (!pathIsIndex || node.isIndex)) {\n if (isFrameMoreSpecific(bestMatch, frame)) {\n bestMatch = frame\n }\n\n // perfect match, no need to continue\n if (statics === partsLength && node.isIndex) return bestMatch\n }\n // beyond the length of the path parts, only skipped optional segments or wildcard segments can match\n if (!node.optional && !node.wildcard) continue\n }\n\n const part = isBeyondPath ? undefined : parts[index]!\n let lowerPart: string\n\n // 5. Try wildcard match\n if (node.wildcard && isFrameMoreSpecific(wildcardMatch, frame)) {\n for (const segment of node.wildcard) {\n const { prefix, suffix } = segment\n if (prefix) {\n if (isBeyondPath) continue\n const casePart = segment.caseSensitive\n ? part\n : (lowerPart ??= part!.toLowerCase())\n if (!casePart!.startsWith(prefix)) continue\n }\n if (suffix) {\n if (isBeyondPath) continue\n const end = parts.slice(index).join('/').slice(-suffix.length)\n const casePart = segment.caseSensitive ? end : end.toLowerCase()\n if (casePart !== suffix) continue\n }\n // the first wildcard match is the highest priority one\n wildcardMatch = {\n node: segment,\n index,\n skipped,\n depth,\n statics,\n dynamics,\n optionals,\n }\n break\n }\n }\n\n // 4. Try optional match\n if (node.optional) {\n const nextSkipped = skipped | (1 << depth)\n const nextDepth = depth + 1\n for (let i = node.optional.length - 1; i >= 0; i--) {\n const segment = node.optional[i]!\n // when skipping, node and depth advance by 1, but index doesn't\n stack.push({\n node: segment,\n index,\n skipped: nextSkipped,\n depth: nextDepth,\n statics,\n dynamics,\n optionals,\n }) // enqueue skipping the optional\n }\n if (!isBeyondPath) {\n for (let i = node.optional.length - 1; i >= 0; i--) {\n const segment = node.optional[i]!\n const { prefix, suffix } = segment\n if (prefix || suffix) {\n const casePart = segment.caseSensitive\n ? part!\n : (lowerPart ??= part!.toLowerCase())\n if (prefix && !casePart.startsWith(prefix)) continue\n if (suffix && !casePart.endsWith(suffix)) continue\n }\n stack.push({\n node: segment,\n index: index + 1,\n skipped,\n depth: nextDepth,\n statics,\n dynamics,\n optionals: optionals + 1,\n })\n }\n }\n }\n\n // 3. Try dynamic match\n if (!isBeyondPath && node.dynamic && part) {\n for (let i = node.dynamic.length - 1; i >= 0; i--) {\n const segment = node.dynamic[i]!\n const { prefix, suffix } = segment\n if (prefix || suffix) {\n const casePart = segment.caseSensitive\n ? part\n : (lowerPart ??= part.toLowerCase())\n if (prefix && !casePart.startsWith(prefix)) continue\n if (suffix && !casePart.endsWith(suffix)) continue\n }\n stack.push({\n node: segment,\n index: index + 1,\n skipped,\n depth: depth + 1,\n statics,\n dynamics: dynamics + 1,\n optionals,\n })\n }\n }\n\n // 2. Try case insensitive static match\n if (!isBeyondPath && node.staticInsensitive) {\n const match = node.staticInsensitive.get(\n (lowerPart ??= part!.toLowerCase()),\n )\n if (match) {\n stack.push({\n node: match,\n index: index + 1,\n skipped,\n depth: depth + 1,\n statics: statics + 1,\n dynamics,\n optionals,\n })\n }\n }\n\n // 1. Try static match\n if (!isBeyondPath && node.static) {\n const match = node.static.get(part!)\n if (match) {\n stack.push({\n node: match,\n index: index + 1,\n skipped,\n depth: depth + 1,\n statics: statics + 1,\n dynamics,\n optionals,\n })\n }\n }\n }\n\n if (bestMatch && wildcardMatch) {\n return isFrameMoreSpecific(wildcardMatch, bestMatch)\n ? bestMatch\n : wildcardMatch\n }\n\n if (bestMatch) return bestMatch\n\n if (wildcardMatch) return wildcardMatch\n\n if (fuzzy && bestFuzzy) {\n let sliceIndex = bestFuzzy.index\n for (let i = 0; i < bestFuzzy.index; i++) {\n sliceIndex += parts[i]!.length\n }\n const splat = sliceIndex === path.length ? '/' : path.slice(sliceIndex)\n return {\n node: bestFuzzy.node,\n skipped: bestFuzzy.skipped,\n '**': decodeURIComponent(splat),\n }\n }\n\n return null\n}\n\nfunction isFrameMoreSpecific(\n // the stack frame previously saved as \"best match\"\n prev: MatchStackFrame<any> | null,\n // the candidate stack frame\n next: MatchStackFrame<any>,\n): boolean {\n if (!prev) return true\n return (\n next.statics > prev.statics ||\n (next.statics === prev.statics &&\n (next.dynamics > prev.dynamics ||\n (next.dynamics === prev.dynamics &&\n (next.optionals > prev.optionals ||\n (next.optionals === prev.optionals &&\n (next.node.isIndex > prev.node.isIndex ||\n (next.node.isIndex === prev.node.isIndex &&\n next.depth > prev.depth)))))))\n )\n}\n"],"names":["start"],"mappings":";;;AAKO,MAAM,wBAAwB;AAC9B,MAAM,qBAAqB;AAC3B,MAAM,wBAAwB;AAC9B,MAAM,8BAA8B;AAQ3C,MAAM,0BACJ;AACF,MAAM,mCACJ;AACF,MAAM,6BAA6B;AAiC5B,SAAS,aAEd,MAEA,OAEA,SAAsB,IAAI,YAAY,CAAC,GACxB;AACf,QAAM,OAAO,KAAK,QAAQ,KAAK,KAAK;AACpC,QAAM,MAAM,SAAS,KAAK,KAAK,SAAS;AACxC,QAAM,OAAO,KAAK,UAAU,OAAO,GAAG;AAEtC,MAAI,CAAC,QAAQ,CAAC,KAAK,SAAS,GAAG,GAAG;AAEhC,WAAO,CAAC,IAAI;AACZ,WAAO,CAAC,IAAI;AACZ,WAAO,CAAC,IAAI;AACZ,WAAO,CAAC,IAAI;AACZ,WAAO,CA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KAAK;AAEpC;"}
|
|
@@ -64,7 +64,10 @@ function transformStreamWithRouter(router, appStream, opts) {
|
|
|
64
64
|
let stopListeningToInjectedHtml = void 0;
|
|
65
65
|
let timeoutHandle;
|
|
66
66
|
const finalPassThrough = createPassthrough(() => {
|
|
67
|
-
stopListeningToInjectedHtml
|
|
67
|
+
if (stopListeningToInjectedHtml) {
|
|
68
|
+
stopListeningToInjectedHtml();
|
|
69
|
+
stopListeningToInjectedHtml = void 0;
|
|
70
|
+
}
|
|
68
71
|
clearTimeout(timeoutHandle);
|
|
69
72
|
});
|
|
70
73
|
const textDecoder = new TextDecoder();
|
|
@@ -87,26 +90,28 @@ function transformStreamWithRouter(router, appStream, opts) {
|
|
|
87
90
|
}
|
|
88
91
|
const injectedHtmlDonePromise = createControlledPromise();
|
|
89
92
|
let processingCount = 0;
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
93
|
+
handleInjectedHtml();
|
|
94
|
+
stopListeningToInjectedHtml = router.subscribe(
|
|
95
|
+
"onInjectedHtml",
|
|
96
|
+
handleInjectedHtml
|
|
97
|
+
);
|
|
98
|
+
function handleInjectedHtml() {
|
|
99
|
+
router.serverSsr.injectedHtml.forEach((promise) => {
|
|
100
|
+
processingCount++;
|
|
101
|
+
promise.then((html) => {
|
|
102
|
+
if (isAppRendering) {
|
|
103
|
+
routerStreamBuffer += html;
|
|
104
|
+
} else {
|
|
105
|
+
finalPassThrough.write(html);
|
|
106
|
+
}
|
|
107
|
+
}).catch(injectedHtmlDonePromise.reject).finally(() => {
|
|
108
|
+
processingCount--;
|
|
109
|
+
if (!isAppRendering && processingCount === 0) {
|
|
110
|
+
injectedHtmlDonePromise.resolve();
|
|
111
|
+
}
|
|
112
|
+
});
|
|
109
113
|
});
|
|
114
|
+
router.serverSsr.injectedHtml = [];
|
|
110
115
|
}
|
|
111
116
|
injectedHtmlDonePromise.then(() => {
|
|
112
117
|
clearTimeout(timeoutHandle);
|
|
@@ -115,7 +120,12 @@ function transformStreamWithRouter(router, appStream, opts) {
|
|
|
115
120
|
}).catch((err) => {
|
|
116
121
|
console.error("Error reading routerStream:", err);
|
|
117
122
|
finalPassThrough.destroy(err);
|
|
118
|
-
}).finally(() =>
|
|
123
|
+
}).finally(() => {
|
|
124
|
+
if (stopListeningToInjectedHtml) {
|
|
125
|
+
stopListeningToInjectedHtml();
|
|
126
|
+
stopListeningToInjectedHtml = void 0;
|
|
127
|
+
}
|
|
128
|
+
});
|
|
119
129
|
readStream(appStream, {
|
|
120
130
|
onData: (chunk) => {
|
|
121
131
|
const text = decodeChunk(chunk.value);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transformStreamWithRouter.js","sources":["../../../src/ssr/transformStreamWithRouter.ts"],"sourcesContent":["import { ReadableStream } from 'node:stream/web'\nimport { Readable } from 'node:stream'\nimport { createControlledPromise } from '../utils'\nimport type { AnyRouter } from '../router'\n\nexport function transformReadableStreamWithRouter(\n router: AnyRouter,\n routerStream: ReadableStream,\n) {\n return transformStreamWithRouter(router, routerStream)\n}\n\nexport function transformPipeableStreamWithRouter(\n router: AnyRouter,\n routerStream: Readable,\n) {\n return Readable.fromWeb(\n transformStreamWithRouter(router, Readable.toWeb(routerStream)),\n )\n}\n\nexport const TSR_SCRIPT_BARRIER_ID = '$tsr-stream-barrier'\n\n// regex pattern for matching closing body and html tags\nconst patternBodyEnd = /(<\\/body>)/\nconst patternHtmlEnd = /(<\\/html>)/\n// regex pattern for matching closing tags\nconst patternClosingTag = /(<\\/[a-zA-Z][\\w:.-]*?>)/g\n\ntype ReadablePassthrough = {\n stream: ReadableStream\n write: (chunk: unknown) => void\n end: (chunk?: string) => void\n destroy: (error: unknown) => void\n destroyed: boolean\n}\n\nfunction createPassthrough(onCancel?: () => void) {\n let controller: ReadableStreamDefaultController<any>\n const encoder = new TextEncoder()\n const stream = new ReadableStream({\n start(c) {\n controller = c\n },\n cancel() {\n res.destroyed = true\n onCancel?.()\n },\n })\n\n const res: ReadablePassthrough = {\n stream,\n write: (chunk) => {\n if (typeof chunk === 'string') {\n controller.enqueue(encoder.encode(chunk))\n } else {\n controller.enqueue(chunk)\n }\n },\n end: (chunk) => {\n if (chunk) {\n res.write(chunk)\n }\n controller.close()\n res.destroyed = true\n },\n destroy: (error) => {\n controller.error(error)\n },\n destroyed: false,\n }\n\n return res\n}\n\nasync function readStream(\n stream: ReadableStream,\n opts: {\n onData?: (chunk: ReadableStreamReadValueResult<any>) => void\n onEnd?: () => void\n onError?: (error: unknown) => void\n },\n) {\n try {\n const reader = stream.getReader()\n let chunk\n while (!(chunk = await reader.read()).done) {\n opts.onData?.(chunk)\n }\n opts.onEnd?.()\n } catch (error) {\n opts.onError?.(error)\n }\n}\n\nexport function transformStreamWithRouter(\n router: AnyRouter,\n appStream: ReadableStream,\n opts?: {\n timeoutMs?: number\n },\n) {\n let stopListeningToInjectedHtml: (() => void) | undefined = undefined\n let timeoutHandle: NodeJS.Timeout\n\n const finalPassThrough = createPassthrough(() => {\n stopListeningToInjectedHtml?.()\n clearTimeout(timeoutHandle)\n })\n const textDecoder = new TextDecoder()\n\n let isAppRendering = true as boolean\n let routerStreamBuffer = ''\n let pendingClosingTags = ''\n let streamBarrierLifted = false as boolean\n let leftover = ''\n let leftoverHtml = ''\n\n function getBufferedRouterStream() {\n const html = routerStreamBuffer\n routerStreamBuffer = ''\n return html\n }\n\n function decodeChunk(chunk: unknown): string {\n if (chunk instanceof Uint8Array) {\n return textDecoder.decode(chunk, { stream: true })\n }\n return String(chunk)\n }\n\n const injectedHtmlDonePromise = createControlledPromise<void>()\n\n let processingCount = 0\n\n // Process any already-injected HTML\n router.serverSsr!.injectedHtml.forEach((promise) => {\n handleInjectedHtml(promise)\n })\n\n // Listen for any new injected HTML\n stopListeningToInjectedHtml = router.subscribe('onInjectedHtml', (e) => {\n handleInjectedHtml(e.promise)\n })\n\n function handleInjectedHtml(promise: Promise<string>) {\n processingCount++\n\n promise\n .then((html) => {\n if (isAppRendering) {\n routerStreamBuffer += html\n } else {\n finalPassThrough.write(html)\n }\n })\n .catch(injectedHtmlDonePromise.reject)\n .finally(() => {\n processingCount--\n\n if (!isAppRendering && processingCount === 0) {\n injectedHtmlDonePromise.resolve()\n }\n })\n }\n\n injectedHtmlDonePromise\n .then(() => {\n clearTimeout(timeoutHandle)\n const finalHtml =\n leftoverHtml + getBufferedRouterStream() + pendingClosingTags\n\n finalPassThrough.end(finalHtml)\n })\n .catch((err) => {\n console.error('Error reading routerStream:', err)\n finalPassThrough.destroy(err)\n })\n .finally(() => stopListeningToInjectedHtml?.())\n\n // Transform the appStream\n readStream(appStream, {\n onData: (chunk) => {\n const text = decodeChunk(chunk.value)\n const chunkString = leftover + text\n const bodyEndMatch = chunkString.match(patternBodyEnd)\n const htmlEndMatch = chunkString.match(patternHtmlEnd)\n\n if (!streamBarrierLifted) {\n const streamBarrierIdIncluded = chunkString.includes(\n TSR_SCRIPT_BARRIER_ID,\n )\n if (streamBarrierIdIncluded) {\n streamBarrierLifted = true\n router.serverSsr!.liftScriptBarrier()\n }\n }\n\n // If either the body end or html end is in the chunk,\n // We need to get all of our data in asap\n if (\n bodyEndMatch &&\n htmlEndMatch &&\n bodyEndMatch.index! < htmlEndMatch.index!\n ) {\n const bodyEndIndex = bodyEndMatch.index!\n pendingClosingTags = chunkString.slice(bodyEndIndex)\n\n finalPassThrough.write(\n chunkString.slice(0, bodyEndIndex) + getBufferedRouterStream(),\n )\n\n leftover = ''\n return\n }\n\n let result: RegExpExecArray | null\n let lastIndex = 0\n while ((result = patternClosingTag.exec(chunkString)) !== null) {\n lastIndex = result.index + result[0].length\n }\n\n if (lastIndex > 0) {\n const processed =\n chunkString.slice(0, lastIndex) +\n getBufferedRouterStream() +\n leftoverHtml\n\n finalPassThrough.write(processed)\n leftover = chunkString.slice(lastIndex)\n } else {\n leftover = chunkString\n leftoverHtml += getBufferedRouterStream()\n }\n },\n onEnd: () => {\n // Mark the app as done rendering\n isAppRendering = false\n router.serverSsr!.setRenderFinished()\n\n // If there are no pending promises, resolve the injectedHtmlDonePromise\n if (processingCount === 0) {\n injectedHtmlDonePromise.resolve()\n } else {\n const timeoutMs = opts?.timeoutMs ?? 60000\n timeoutHandle = setTimeout(() => {\n injectedHtmlDonePromise.reject(\n new Error('Injected HTML timeout after app render finished'),\n )\n }, timeoutMs)\n }\n },\n onError: (error) => {\n console.error('Error reading appStream:', error)\n finalPassThrough.destroy(error)\n injectedHtmlDonePromise.reject(error)\n },\n })\n\n return finalPassThrough.stream\n}\n"],"names":[],"mappings":";;;AAKO,SAAS,kCACd,QACA,cACA;AACA,SAAO,0BAA0B,QAAQ,YAAY;AACvD;AAEO,SAAS,kCACd,QACA,cACA;AACA,SAAO,SAAS;AAAA,IACd,0BAA0B,QAAQ,SAAS,MAAM,YAAY,CAAC;AAAA,EAAA;AAElE;AAEO,MAAM,wBAAwB;AAGrC,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AAEvB,MAAM,oBAAoB;AAU1B,SAAS,kBAAkB,UAAuB;AAChD,MAAI;AACJ,QAAM,UAAU,IAAI,YAAA;AACpB,QAAM,SAAS,IAAI,eAAe;AAAA,IAChC,MAAM,GAAG;AACP,mBAAa;AAAA,IACf;AAAA,IACA,SAAS;AACP,UAAI,YAAY;AAChB,iBAAA;AAAA,IACF;AAAA,EAAA,CACD;AAED,QAAM,MAA2B;AAAA,IAC/B;AAAA,IACA,OAAO,CAAC,UAAU;AAChB,UAAI,OAAO,UAAU,UAAU;AAC7B,mBAAW,QAAQ,QAAQ,OAAO,KAAK,CAAC;AAAA,MAC1C,OAAO;AACL,mBAAW,QAAQ,KAAK;AAAA,MAC1B;AAAA,IACF;AAAA,IACA,KAAK,CAAC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AQ,OAAO,CAAC,EAAE;AAAA,MACvC;AAEA,UAAI,YAAY,GAAG;AACjB,cAAM,YACJ,YAAY,MAAM,GAAG,SAAS,IAC9B,4BACA;AAEF,yBAAiB,MAAM,SAAS;AAChC,mBAAW,YAAY,MAAM,SAAS;AAAA,MACxC,OAAO;AACL,mBAAW;AACX,wBAAgB,wBAAA;AAAA,MAClB;AAAA,IACF;AAAA,IACA,OAAO,MAAM;AAEX,uBAAiB;AACjB,aAAO,UAAW,kBAAA;AAGlB,UAAI,oBAAoB,GAAG;AACzB,gCAAwB,QAAA;AAAA,MAC1B,OAAO;AACL,cAAM,YAAY,MAAM,aAAa;AACrC,wBAAgB,WAAW,MAAM;AAC/B,kCAAwB;AAAA,YACtB,IAAI,MAAM,iDAAiD;AAAA,UAAA;AAAA,QAE/D,GAAG,SAAS;AAAA,MACd;AAAA,IACF;AAAA,IACA,SAAS,CAAC,UAAU;AAClB,cAAQ,MAAM,4BAA4B,KAAK;AAC/C,uBAAiB,QAAQ,KAAK;AAC9B,8BAAwB,OAAO,KAAK;AAAA,IACtC;AAAA,EAAA,CACD;AAED,SAAO,iBAAiB;AAC1B;"}
|
|
1
|
+
{"version":3,"file":"transformStreamWithRouter.js","sources":["../../../src/ssr/transformStreamWithRouter.ts"],"sourcesContent":["import { ReadableStream } from 'node:stream/web'\nimport { Readable } from 'node:stream'\nimport { createControlledPromise } from '../utils'\nimport type { AnyRouter } from '../router'\n\nexport function transformReadableStreamWithRouter(\n router: AnyRouter,\n routerStream: ReadableStream,\n) {\n return transformStreamWithRouter(router, routerStream)\n}\n\nexport function transformPipeableStreamWithRouter(\n router: AnyRouter,\n routerStream: Readable,\n) {\n return Readable.fromWeb(\n transformStreamWithRouter(router, Readable.toWeb(routerStream)),\n )\n}\n\nexport const TSR_SCRIPT_BARRIER_ID = '$tsr-stream-barrier'\n\n// regex pattern for matching closing body and html tags\nconst patternBodyEnd = /(<\\/body>)/\nconst patternHtmlEnd = /(<\\/html>)/\n// regex pattern for matching closing tags\nconst patternClosingTag = /(<\\/[a-zA-Z][\\w:.-]*?>)/g\n\ntype ReadablePassthrough = {\n stream: ReadableStream\n write: (chunk: unknown) => void\n end: (chunk?: string) => void\n destroy: (error: unknown) => void\n destroyed: boolean\n}\n\nfunction createPassthrough(onCancel?: () => void) {\n let controller: ReadableStreamDefaultController<any>\n const encoder = new TextEncoder()\n const stream = new ReadableStream({\n start(c) {\n controller = c\n },\n cancel() {\n res.destroyed = true\n onCancel?.()\n },\n })\n\n const res: ReadablePassthrough = {\n stream,\n write: (chunk) => {\n if (typeof chunk === 'string') {\n controller.enqueue(encoder.encode(chunk))\n } else {\n controller.enqueue(chunk)\n }\n },\n end: (chunk) => {\n if (chunk) {\n res.write(chunk)\n }\n controller.close()\n res.destroyed = true\n },\n destroy: (error) => {\n controller.error(error)\n },\n destroyed: false,\n }\n\n return res\n}\n\nasync function readStream(\n stream: ReadableStream,\n opts: {\n onData?: (chunk: ReadableStreamReadValueResult<any>) => void\n onEnd?: () => void\n onError?: (error: unknown) => void\n },\n) {\n try {\n const reader = stream.getReader()\n let chunk\n while (!(chunk = await reader.read()).done) {\n opts.onData?.(chunk)\n }\n opts.onEnd?.()\n } catch (error) {\n opts.onError?.(error)\n }\n}\n\nexport function transformStreamWithRouter(\n router: AnyRouter,\n appStream: ReadableStream,\n opts?: {\n timeoutMs?: number\n },\n) {\n let stopListeningToInjectedHtml: (() => void) | undefined = undefined\n let timeoutHandle: NodeJS.Timeout\n\n const finalPassThrough = createPassthrough(() => {\n if (stopListeningToInjectedHtml) {\n stopListeningToInjectedHtml()\n stopListeningToInjectedHtml = undefined\n }\n clearTimeout(timeoutHandle)\n })\n const textDecoder = new TextDecoder()\n\n let isAppRendering = true as boolean\n let routerStreamBuffer = ''\n let pendingClosingTags = ''\n let streamBarrierLifted = false as boolean\n let leftover = ''\n let leftoverHtml = ''\n\n function getBufferedRouterStream() {\n const html = routerStreamBuffer\n routerStreamBuffer = ''\n return html\n }\n\n function decodeChunk(chunk: unknown): string {\n if (chunk instanceof Uint8Array) {\n return textDecoder.decode(chunk, { stream: true })\n }\n return String(chunk)\n }\n\n const injectedHtmlDonePromise = createControlledPromise<void>()\n\n let processingCount = 0\n\n // Process any already-injected HTML\n handleInjectedHtml()\n\n // Listen for any new injected HTML\n stopListeningToInjectedHtml = router.subscribe(\n 'onInjectedHtml',\n handleInjectedHtml,\n )\n\n function handleInjectedHtml() {\n router.serverSsr!.injectedHtml.forEach((promise) => {\n processingCount++\n\n promise\n .then((html) => {\n if (isAppRendering) {\n routerStreamBuffer += html\n } else {\n finalPassThrough.write(html)\n }\n })\n .catch(injectedHtmlDonePromise.reject)\n .finally(() => {\n processingCount--\n\n if (!isAppRendering && processingCount === 0) {\n injectedHtmlDonePromise.resolve()\n }\n })\n })\n router.serverSsr!.injectedHtml = []\n }\n\n injectedHtmlDonePromise\n .then(() => {\n clearTimeout(timeoutHandle)\n const finalHtml =\n leftoverHtml + getBufferedRouterStream() + pendingClosingTags\n\n finalPassThrough.end(finalHtml)\n })\n .catch((err) => {\n console.error('Error reading routerStream:', err)\n finalPassThrough.destroy(err)\n })\n .finally(() => {\n if (stopListeningToInjectedHtml) {\n stopListeningToInjectedHtml()\n stopListeningToInjectedHtml = undefined\n }\n })\n\n // Transform the appStream\n readStream(appStream, {\n onData: (chunk) => {\n const text = decodeChunk(chunk.value)\n const chunkString = leftover + text\n const bodyEndMatch = chunkString.match(patternBodyEnd)\n const htmlEndMatch = chunkString.match(patternHtmlEnd)\n\n if (!streamBarrierLifted) {\n const streamBarrierIdIncluded = chunkString.includes(\n TSR_SCRIPT_BARRIER_ID,\n )\n if (streamBarrierIdIncluded) {\n streamBarrierLifted = true\n router.serverSsr!.liftScriptBarrier()\n }\n }\n\n // If either the body end or html end is in the chunk,\n // We need to get all of our data in asap\n if (\n bodyEndMatch &&\n htmlEndMatch &&\n bodyEndMatch.index! < htmlEndMatch.index!\n ) {\n const bodyEndIndex = bodyEndMatch.index!\n pendingClosingTags = chunkString.slice(bodyEndIndex)\n\n finalPassThrough.write(\n chunkString.slice(0, bodyEndIndex) + getBufferedRouterStream(),\n )\n\n leftover = ''\n return\n }\n\n let result: RegExpExecArray | null\n let lastIndex = 0\n while ((result = patternClosingTag.exec(chunkString)) !== null) {\n lastIndex = result.index + result[0].length\n }\n\n if (lastIndex > 0) {\n const processed =\n chunkString.slice(0, lastIndex) +\n getBufferedRouterStream() +\n leftoverHtml\n\n finalPassThrough.write(processed)\n leftover = chunkString.slice(lastIndex)\n } else {\n leftover = chunkString\n leftoverHtml += getBufferedRouterStream()\n }\n },\n onEnd: () => {\n // Mark the app as done rendering\n isAppRendering = false\n router.serverSsr!.setRenderFinished()\n\n // If there are no pending promises, resolve the injectedHtmlDonePromise\n if (processingCount === 0) {\n injectedHtmlDonePromise.resolve()\n } else {\n const timeoutMs = opts?.timeoutMs ?? 60000\n timeoutHandle = setTimeout(() => {\n injectedHtmlDonePromise.reject(\n new Error('Injected HTML timeout after app render finished'),\n )\n }, timeoutMs)\n }\n },\n onError: (error) => {\n console.error('Error reading appStream:', error)\n finalPassThrough.destroy(error)\n injectedHtmlDonePromise.reject(error)\n },\n })\n\n return finalPassThrough.stream\n}\n"],"names":[],"mappings":";;;AAKO,SAAS,kCACd,QACA,cACA;AACA,SAAO,0BAA0B,QAAQ,YAAY;AACvD;AAEO,SAAS,kCACd,QACA,cACA;AACA,SAAO,SAAS;AAAA,IACd,0BAA0B,QAAQ,SAAS,MAAM,YAAY,CAAC;AAAA,EAAA;AAElE;AAEO,MAAM,wBAAwB;AAGrC,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AAEvB,MAAM,oBAAoB;AAU1B,SAAS,kBAAkB,UAAuB;AAChD,MAAI;AACJ,QAAM,UAAU,IAAI,YAAA;AACpB,QAAM,SAAS,IAAI,eAAe;AAAA,IAChC,MAAM,GAAG;AACP,mBAAa;AAAA,IACf;AAAA,IACA,SAAS;AACP,UAAI,YAAY;AAChB,iBAAA;AAAA,IACF;AAAA,E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pB;AAAA,MACF;AAIA,UACE,gBACA,gBACA,aAAa,QAAS,aAAa,OACnC;AACA,cAAM,eAAe,aAAa;AAClC,6BAAqB,YAAY,MAAM,YAAY;AAEnD,yBAAiB;AAAA,UACf,YAAY,MAAM,GAAG,YAAY,IAAI,wBAAA;AAAA,QAAwB;AAG/D,mBAAW;AACX;AAAA,MACF;AAEA,UAAI;AACJ,UAAI,YAAY;AAChB,cAAQ,SAAS,kBAAkB,KAAK,WAAW,OAAO,MAAM;AAC9D,oBAAY,OAAO,QAAQ,OAAO,CAAC,EAAE;AAAA,MACvC;AAEA,UAAI,YAAY,GAAG;AACjB,cAAM,YACJ,YAAY,MAAM,GAAG,SAAS,IAC9B,4BACA;AAEF,yBAAiB,MAAM,SAAS;AAChC,mBAAW,YAAY,MAAM,SAAS;AAAA,MACxC,OAAO;AACL,mBAAW;AACX,wBAAgB,wBAAA;AAAA,MAClB;AAAA,IACF;AAAA,IACA,OAAO,MAAM;AAEX,uBAAiB;AACjB,aAAO,UAAW,kBAAA;AAGlB,UAAI,oBAAoB,GAAG;AACzB,gCAAwB,QAAA;AAAA,MAC1B,OAAO;AACL,cAAM,YAAY,MAAM,aAAa;AACrC,wBAAgB,WAAW,MAAM;AAC/B,kCAAwB;AAAA,YACtB,IAAI,MAAM,iDAAiD;AAAA,UAAA;AAAA,QAE/D,GAAG,SAAS;AAAA,MACd;AAAA,IACF;AAAA,IACA,SAAS,CAAC,UAAU;AAClB,cAAQ,MAAM,4BAA4B,KAAK;AAC/C,uBAAiB,QAAQ,KAAK;AAC9B,8BAAwB,OAAO,KAAK;AAAA,IACtC;AAAA,EAAA,CACD;AAED,SAAO,iBAAiB;AAC1B;"}
|
package/package.json
CHANGED
|
@@ -1018,6 +1018,12 @@ function getNodeMatch<T extends RouteLike>(
|
|
|
1018
1018
|
}
|
|
1019
1019
|
}
|
|
1020
1020
|
|
|
1021
|
+
if (bestMatch && wildcardMatch) {
|
|
1022
|
+
return isFrameMoreSpecific(wildcardMatch, bestMatch)
|
|
1023
|
+
? bestMatch
|
|
1024
|
+
: wildcardMatch
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1021
1027
|
if (bestMatch) return bestMatch
|
|
1022
1028
|
|
|
1023
1029
|
if (wildcardMatch) return wildcardMatch
|
|
@@ -104,7 +104,10 @@ export function transformStreamWithRouter(
|
|
|
104
104
|
let timeoutHandle: NodeJS.Timeout
|
|
105
105
|
|
|
106
106
|
const finalPassThrough = createPassthrough(() => {
|
|
107
|
-
stopListeningToInjectedHtml
|
|
107
|
+
if (stopListeningToInjectedHtml) {
|
|
108
|
+
stopListeningToInjectedHtml()
|
|
109
|
+
stopListeningToInjectedHtml = undefined
|
|
110
|
+
}
|
|
108
111
|
clearTimeout(timeoutHandle)
|
|
109
112
|
})
|
|
110
113
|
const textDecoder = new TextDecoder()
|
|
@@ -134,34 +137,36 @@ export function transformStreamWithRouter(
|
|
|
134
137
|
let processingCount = 0
|
|
135
138
|
|
|
136
139
|
// Process any already-injected HTML
|
|
137
|
-
|
|
138
|
-
handleInjectedHtml(promise)
|
|
139
|
-
})
|
|
140
|
+
handleInjectedHtml()
|
|
140
141
|
|
|
141
142
|
// Listen for any new injected HTML
|
|
142
|
-
stopListeningToInjectedHtml = router.subscribe(
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
function handleInjectedHtml(promise: Promise<string>) {
|
|
147
|
-
processingCount++
|
|
148
|
-
|
|
149
|
-
promise
|
|
150
|
-
.then((html) => {
|
|
151
|
-
if (isAppRendering) {
|
|
152
|
-
routerStreamBuffer += html
|
|
153
|
-
} else {
|
|
154
|
-
finalPassThrough.write(html)
|
|
155
|
-
}
|
|
156
|
-
})
|
|
157
|
-
.catch(injectedHtmlDonePromise.reject)
|
|
158
|
-
.finally(() => {
|
|
159
|
-
processingCount--
|
|
143
|
+
stopListeningToInjectedHtml = router.subscribe(
|
|
144
|
+
'onInjectedHtml',
|
|
145
|
+
handleInjectedHtml,
|
|
146
|
+
)
|
|
160
147
|
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
148
|
+
function handleInjectedHtml() {
|
|
149
|
+
router.serverSsr!.injectedHtml.forEach((promise) => {
|
|
150
|
+
processingCount++
|
|
151
|
+
|
|
152
|
+
promise
|
|
153
|
+
.then((html) => {
|
|
154
|
+
if (isAppRendering) {
|
|
155
|
+
routerStreamBuffer += html
|
|
156
|
+
} else {
|
|
157
|
+
finalPassThrough.write(html)
|
|
158
|
+
}
|
|
159
|
+
})
|
|
160
|
+
.catch(injectedHtmlDonePromise.reject)
|
|
161
|
+
.finally(() => {
|
|
162
|
+
processingCount--
|
|
163
|
+
|
|
164
|
+
if (!isAppRendering && processingCount === 0) {
|
|
165
|
+
injectedHtmlDonePromise.resolve()
|
|
166
|
+
}
|
|
167
|
+
})
|
|
168
|
+
})
|
|
169
|
+
router.serverSsr!.injectedHtml = []
|
|
165
170
|
}
|
|
166
171
|
|
|
167
172
|
injectedHtmlDonePromise
|
|
@@ -176,7 +181,12 @@ export function transformStreamWithRouter(
|
|
|
176
181
|
console.error('Error reading routerStream:', err)
|
|
177
182
|
finalPassThrough.destroy(err)
|
|
178
183
|
})
|
|
179
|
-
.finally(() =>
|
|
184
|
+
.finally(() => {
|
|
185
|
+
if (stopListeningToInjectedHtml) {
|
|
186
|
+
stopListeningToInjectedHtml()
|
|
187
|
+
stopListeningToInjectedHtml = undefined
|
|
188
|
+
}
|
|
189
|
+
})
|
|
180
190
|
|
|
181
191
|
// Transform the appStream
|
|
182
192
|
readStream(appStream, {
|