Documentation menuMenu da documentação

$ cat docs/router.md

Radix routerRoteador Radix

The Radix Tree router keeps one tree per method and matches paths without allocating on the hot path.O roteador Radix Tree guarda uma árvore por método e casa caminhos sem alocar no hot path.

UsageUso

  • insert(method, path, value) registers static routes, parameters and wildcards.
  • matchInto(method, path, state) reuses the state from createState(): zero allocations per lookup.
  • match(method, path) is the convenience variant that allocates a { value, params }.
  • A CLOCK second-chance cache (cacheSize, default 1024) speeds up repeated paths.
  • insert(method, path, value) registra rotas estáticas, parâmetros e wildcards.
  • matchInto(method, path, state) reusa o estado criado por createState(): zero alocação por lookup.
  • match(method, path) é a variante de conveniência que aloca um { value, params }.
  • Um cache CLOCK de segunda chance (cacheSize, padrão 1024) acelera caminhos repetidos.
router.ts
import { RadixRouter } from '@tupik/core';

const router = new RadixRouter<string>({ cacheSize: 1024 });
router.insert('GET', '/users', 'list');
router.insert('GET', '/users/:id', 'detail');

const state = router.createState();
if (router.matchInto('GET', '/users/42', state)) {
  console.log(state.value); // 'detail'
  console.log(state.param('id')); // '42'
}

ParametersParâmetros

:name segments capture a whole segment; state.param('id') returns the decoded value and state.params() builds the full object. Duplicate or conflicting names at the same position throw on insert.

Segmentos :nome capturam um segmento inteiro; state.param('id') devolve o valor decodificado e state.params() monta o objeto completo. Nomes duplicados ou conflitantes na mesma posição geram erro no insert.

Wildcards

*name (or just *) captures the rest of the path, and also matches the bare prefix with an empty value. Encoded slashes stay as %2F in the value (use state.rawParam() for the raw capture). Priority: static > parameter > wildcard.

*nome (ou só *) captura o restante do caminho e também casa com o prefixo sozinho, com valor vazio. Barras codificadas ficam como %2F no valor (use state.rawParam() para a captura crua). Prioridade: estático > parâmetro > wildcard.

wildcard.ts
router.insert('GET', '/static/*path', 'files');
router.insert('GET', '/static/logo.svg', 'logo');

router.match('GET', '/static/logo.svg')?.value; // 'logo' (static wins)
router.match('GET', '/static/css/site.css')?.params; // { path: 'css/site.css' }
router.match('GET', '/static')?.params; // { path: '' }
router.match('GET', '/static/..%2Fetc')?.params; // { path: '..%2Fetc' } (%2F stays encoded)
router.insert('GET', '/static/*path', 'files');
router.insert('GET', '/static/logo.svg', 'logo');

router.match('GET', '/static/logo.svg')?.value; // 'logo' (estático vence)
router.match('GET', '/static/css/site.css')?.params; // { path: 'css/site.css' }
router.match('GET', '/static')?.params; // { path: '' }
router.match('GET', '/static/..%2Fetc')?.params; // { path: '..%2Fetc' } (%2F continua codificado)

HEAD fallback

head.ts
router.insert('GET', '/health', 'ok');

// When no HEAD route matches the path, HEAD uses the GET tree.
router.match('HEAD', '/health')?.value; // 'ok'

// In the app, HEAD keeps status and headers, without a body.
router.insert('GET', '/health', 'ok');

// Quando nenhuma rota HEAD casa com o caminho, HEAD usa a árvore de GET.
router.match('HEAD', '/health')?.value; // 'ok'

// No app, a resposta de HEAD mantém status e headers, sem corpo.

PerformanceDesempenho

Every value below was measured on Node 24.21.0 on 2026-12-01 on the same machine. The command, the route kinds and the sample size stay in the row, so the number can be reproduced.

Todo valor abaixo foi medido no Node 24.21.0 em 2026-12-01 na mesma máquina. O comando, os tipos de rota e o tamanho da amostra ficam na própria linha, para o número ser reproduzível.

MeasurementMedição ResultResultado ConditionCondição
matchInto(), static → parametric 54.6 to 82.4 ns Node 24.21.0 · pnpm bench (match.bench.ts, 2,000,000 iterations per route kind, reusable state) · 2026-12-01
match(), worst gated route kind 85.0 ns Node 24.21.0 · pnpm bench:ci (router.ci.ts, best of 5 samples of 1,000,000, static/parametric/wildcard) · 2026-12-01, after the performance work
match(), mixed suite 175.6 ns Node 24.21.0 · pnpm bench (router.bench.ts, 200,000 iterations, static/parametric/wildcard plus root and miss) · 2026-12-01

The 175.6 ns mixed-suite result is above the 150 ns target. The 85.0 ns number is the CI gate measurement: it samples only matched route kinds and keeps the best of five runs, so it is lower than the mixed suite. The gate limit is a separate number from the target. The router is a small part of a request; see performance for the HTTP numbers.

O resultado de 175,6 ns da suíte mista fica acima da meta de 150 ns. O número de 85,0 ns é a medição do gate de CI: ele amostra apenas tipos de rota que casam e mantém o melhor de cinco execuções, por isso é menor que a suíte mista. O limite do gate é um número separado da meta. O roteador é uma parte pequena da requisição; veja desempenho para os números HTTP.

Targets, not results: Metas, não resultados: 150 ns per lookup (target)por lookup (meta) 200 ns CI gate limit (fails above it)limite do gate de CI (falha acima dele)