Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions src/_match.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,7 @@ export function normalizePath(path: string): string {
* segments. Empty segments are kept: `/a/` is `["a", ""]` (#209).
*/
export function splitPath(path: string): string[] {
const s = path.split("/");
s.shift();
return s;
return path.split("/").slice(1);
}

/**
Expand Down Expand Up @@ -120,18 +118,35 @@ export function getMatchParams(
paramsMap: ParamsIndexMap,
suffix?: [number, number],
slash?: boolean,
path?: string,
catchAllOffset?: number,
): MatchedRoute["params"] {
const params = new NullProtoObj();
if (paramsMap.length === 1 && !suffix) {
const map = paramsMap[0];
const index = map[0];
if (index >= 0 && typeof map[1] === "string" && !map[2] && !map[5]) {
params[map[1]] = segments[index];
return params;
}
}
// Segments after a `**` are counted from the end of the path
const end = suffix ? segments.length - suffix[1] : segments.length;
for (const [index, name, optional, , , join] of paramsMap) {
for (let p = 0; p < paramsMap.length; p++) {
const map = paramsMap[p];
const index = map[0];
const name = map[1];
const optional = map[2];
const join = map[5];
// A bare `**` (`~index` is where it starts; negative for the other
// params) over zero segments is unset; a trailing `*` there too, unless
// the lookup path had a trailing slash (`slash`): `""`
if (~index >= end && (optional || !slash)) continue;
const segment =
index < 0
? segments.slice(~index, end).join("/")
? catchAllOffset !== undefined && path !== undefined
? path.slice(catchAllOffset)
: segments.slice(~index, end).join("/")
: segments[suffix && index > suffix[0] ? index - suffix[0] - 1 + end : index];
if (typeof name === "string") {
setParam(params, name, segment, join);
Expand Down
3 changes: 2 additions & 1 deletion src/context.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { createNode } from "./node.ts";
import { NullProtoObj } from "./object.ts";
import type { RouterContext } from "./types.ts";

Expand All @@ -6,7 +7,7 @@ import type { RouterContext } from "./types.ts";
*/
export function createRouter<T = unknown>(): RouterContext<T> {
const ctx: RouterContext<T> = {
root: { key: "" },
root: createNode<T>(""),
static: new NullProtoObj(),
};
return ctx;
Expand Down
15 changes: 15 additions & 0 deletions src/node.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { Node } from "./types.ts";

/** All fields are set so nodes keep one hidden class. */
export function createNode<T>(key: string): Node<T> {
return {
key,
static: undefined,
param: undefined,
wildcard: undefined,
suffix: undefined,
hasSuffix: undefined,
hasRegexParam: undefined,
methods: undefined,
};
}
21 changes: 15 additions & 6 deletions src/operations/add.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
} from "../_pattern.ts";
import { getParamRegexp, linearRegExp } from "../_segment-regexp.ts";
import { createRouter } from "../context.ts";
import { createNode } from "../node.ts";
import { NullProtoObj } from "../object.ts";
import type { Node, RouterContext, ParamsIndexMap } from "../types.ts";

Expand Down Expand Up @@ -211,6 +212,9 @@ function _insert<T>(
let wildcardIndex = -1;
// Nodes on the way to the catch-all, flagged `hasSuffix` for a suffix route
const trail: Node<T>[] | undefined = star ? [] : undefined;
// Catch-all value offset when its prefix is static (see `getMatchParams`)
let catchAllOffset = -1;
let prefixLength = 1;

for (let i = 0; i < segments.length; i++) {
let segment = segments[i];
Expand All @@ -223,7 +227,7 @@ function _insert<T>(
}
trail?.push(node);
if (!node.wildcard) {
node.wildcard = { key: "**" };
node.wildcard = createNode<T>("**");
}
node = node.wildcard;
// A `*` takes one segment or more (or, last, none: see `matchesZero`),
Expand All @@ -236,6 +240,9 @@ function _insert<T>(
// `getMatchParams`), so that name is taken. The `**` of a split `*` is
// part of its capture: its number (taken by the piece before it, if
// any), no `_` alias.
if (join === -1 && i === segments.length - 1 && paramsMap.length === 0) {
catchAllOffset = prefixLength;
}
paramsMap.push([
-(i + 1),
i === join
Expand Down Expand Up @@ -268,7 +275,7 @@ function _insert<T>(
} else {
trail?.push(node);
if (!node.param) {
node.param = { key: "*" };
node.param = createNode<T>("*");
}
node = node.param;
}
Expand Down Expand Up @@ -315,12 +322,13 @@ function _insert<T>(
suffix.push(segment);
continue;
}
prefixLength += segment.length + 1;
trail?.push(node);
const child = node.static?.[segment];
if (child) {
node = child;
} else {
const staticNode = { key: segment };
const staticNode = createNode<T>(segment);
if (!node.static) {
node.static = new NullProtoObj();
}
Expand All @@ -333,13 +341,13 @@ function _insert<T>(
for (const n of trail!) {
n.hasSuffix = true;
}
node = node.suffix ??= { key: "" };
node = node.suffix ??= createNode<T>("");
for (let j = suffix.length - 1; j >= 0; j--) {
const edge = suffix[j];
if (edge === 1) {
node = node.param ??= { key: "*" };
node = node.param ??= createNode<T>("*");
} else {
node = (node.static ??= new NullProtoObj())[edge] ??= { key: edge };
node = (node.static ??= new NullProtoObj())[edge] ??= createNode<T>(edge);
}
}
}
Expand All @@ -354,6 +362,7 @@ function _insert<T>(
paramsMap: hasParams ? paramsMap : undefined,
route: route ?? key,
suffix: suffix && [wildcardIndex, suffix.length],
catchAllOffset: catchAllOffset >= 0 ? catchAllOffset : undefined,
variants,
// Within half a weight point (`getParamRegexp` ranks a segment by
// +-2^31 at most)
Expand Down
5 changes: 4 additions & 1 deletion src/operations/find-all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,10 @@ export function findAllRoutes<T>(
const params = opts?.params !== false;
return matches.map((m) =>
params && m.paramsMap
? { data: m.data, params: getMatchParams(segments, m.paramsMap, m.suffix, slash) }
? {
data: m.data,
params: getMatchParams(segments, m.paramsMap, m.suffix, slash, path, m.catchAllOffset),
}
: { data: m.data },
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/operations/find.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export function findRoute<T = unknown>(
return {
data: match.data,
params: match.paramsMap
? getMatchParams(segments, match.paramsMap, match.suffix, slash)
? getMatchParams(segments, match.paramsMap, match.suffix, slash, path, match.catchAllOffset)
: undefined,
};
}
Expand Down
5 changes: 5 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ export type MethodData<T = unknown> = {
* the path.
*/
suffix?: [wildcard: number, length: number];
/**
* Set on a trailing catch-all whose prefix is static: where its value starts
* in the lookup path (leading `/` included).
*/
catchAllOffset?: number;
/**
* Set on every entry (variant) of an `addRoute` call that registers several
* (optional syntax, a `*` inside a segment): a token they share (identity
Expand Down
7 changes: 5 additions & 2 deletions test/bench/bundle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,8 +248,11 @@ describe("benchmark", () => {
// +0B raw / +12B gzip: `src/` regrouped by concept (`_pattern.ts`,
// `_match.ts`, `_segment-regexp.ts`); the same code in another module
// order.
expect(bytes).toBeLessThanOrEqual(15099); // <15.10kb
expect(gzipSize).toBeLessThanOrEqual(6501); // <6.51kb
// +441B raw / +180B gzip: interpreter perf pass (catch-all path slicing,
// `splitPath` without `shift`, stable node shapes, indexed params with a
// single-param fast path). Compiled lookup is unchanged.
expect(bytes).toBeLessThanOrEqual(15560); // <15.56kb
expect(gzipSize).toBeLessThanOrEqual(6700); // <6.70kb
});

it("unused exports of the single-file build leave no code behind", async () => {
Expand Down