@timber-js/app 0.2.0-alpha.205 → 0.2.0-alpha.207
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/_chunks/{chains-BjGKq9Je.js → chains-B4bgOl2g.js} +2 -2
- package/dist/_chunks/{chains-BjGKq9Je.js.map → chains-B4bgOl2g.js.map} +1 -1
- package/dist/_chunks/{cli-check-3WE_GyoL.js → cli-check-G8o30ldg.js} +3 -3
- package/dist/_chunks/{cli-check-3WE_GyoL.js.map → cli-check-G8o30ldg.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-D3iIZjku.js → cli-schema-sync--LZKs8Zn.js} +2 -2
- package/dist/_chunks/{cli-schema-sync-D3iIZjku.js.map → cli-schema-sync--LZKs8Zn.js.map} +1 -1
- package/dist/_chunks/{convention-lint-BnO5TyHD.js → convention-lint-5KzoMg_A.js} +35 -1
- package/dist/_chunks/convention-lint-5KzoMg_A.js.map +1 -0
- package/dist/_chunks/{dev-server-Dbdgx2dD.js → dev-server-BzBxgYAV.js} +3 -3
- package/dist/_chunks/{dev-server-Dbdgx2dD.js.map → dev-server-BzBxgYAV.js.map} +1 -1
- package/dist/_chunks/{live-graph-BM2UbbNx.js → live-graph-Bm5WTvcr.js} +3 -3
- package/dist/_chunks/{live-graph-BM2UbbNx.js.map → live-graph-Bm5WTvcr.js.map} +1 -1
- package/dist/_chunks/{poison-scan-g83aAXhs.js → poison-scan-DG5eI2_z.js} +2 -2
- package/dist/_chunks/{poison-scan-g83aAXhs.js.map → poison-scan-DG5eI2_z.js.map} +1 -1
- package/dist/_chunks/{scanner-BhNruzv0.js → scanner-BQ5sPIJ7.js} +2 -2
- package/dist/_chunks/{scanner-BhNruzv0.js.map → scanner-BQ5sPIJ7.js.map} +1 -1
- package/dist/_chunks/schema-bridge-C83xa9lT.js.map +1 -1
- package/dist/_chunks/{tree-match-CdbvYTBz.js → tree-match-6yihorhk.js} +49 -2
- package/dist/_chunks/tree-match-6yihorhk.js.map +1 -0
- package/dist/_chunks/{walkers-BNsswm-h.js → walkers-CN2N_bA-.js} +2 -2
- package/dist/_chunks/{walkers-BNsswm-h.js.map → walkers-CN2N_bA-.js.map} +1 -1
- package/dist/analyze/crawl-entry.js +2 -2
- package/dist/analyze/graph-command.js +2 -2
- package/dist/cli.js +3 -3
- package/dist/client/browser-entry/action-dispatch.d.ts.map +1 -1
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/dist/routing/convention-lint.d.ts.map +1 -1
- package/dist/routing/index.js +2 -2
- package/dist/schema-bridge.d.ts +2 -2
- package/dist/schema-bridge.d.ts.map +1 -1
- package/dist/server/action-client.d.ts +2 -2
- package/dist/server/action-client.d.ts.map +1 -1
- package/dist/server/index.js.map +1 -1
- package/dist/server/tree-match.d.ts +10 -0
- package/dist/server/tree-match.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/client/browser-entry/action-dispatch.ts +8 -2
- package/src/plugins/routing.ts +1 -1
- package/src/routing/convention-lint.ts +60 -0
- package/src/schema-bridge.ts +4 -2
- package/src/server/action-client.ts +4 -2
- package/src/server/route-matcher.ts +73 -20
- package/src/server/tree-match.ts +250 -18
- package/dist/_chunks/convention-lint-BnO5TyHD.js.map +0 -1
- package/dist/_chunks/tree-match-CdbvYTBz.js.map +0 -1
package/src/server/tree-match.ts
CHANGED
|
@@ -66,6 +66,27 @@ export function matchUrlParts<TFile>(
|
|
|
66
66
|
return null;
|
|
67
67
|
}
|
|
68
68
|
|
|
69
|
+
/**
|
|
70
|
+
* Yield every match for the given URL parts, in priority order.
|
|
71
|
+
*
|
|
72
|
+
* Same matching semantics as `matchUrlParts` — static > affixed-dynamic >
|
|
73
|
+
* bare-dynamic > catch-all > optional-catch-all — but instead of returning
|
|
74
|
+
* the first match, it yields all of them. Used by the metadata route matcher,
|
|
75
|
+
* which needs to try alternate owner segments when the first match doesn't
|
|
76
|
+
* own the requested metadata file.
|
|
77
|
+
*/
|
|
78
|
+
export function* matchUrlPartsAll<TFile>(
|
|
79
|
+
root: SegmentNode<TFile>,
|
|
80
|
+
parts: string[],
|
|
81
|
+
options?: TreeMatchOptions
|
|
82
|
+
): Generator<TreeMatchResult<TFile>> {
|
|
83
|
+
const chain: SegmentNode<TFile>[] = [];
|
|
84
|
+
const params: Record<string, string | string[]> = {};
|
|
85
|
+
const requireTerminal = options?.requireTerminal ?? true;
|
|
86
|
+
|
|
87
|
+
yield* matchNodeAll(root, parts, 0, chain, params, requireTerminal);
|
|
88
|
+
}
|
|
89
|
+
|
|
69
90
|
// ─── Internal ─────────────────────────────────────────────────────────────
|
|
70
91
|
|
|
71
92
|
/**
|
|
@@ -107,6 +128,59 @@ function isTerminal<TFile>(node: SegmentNode<TFile>): boolean {
|
|
|
107
128
|
return !!(node.page || node.route);
|
|
108
129
|
}
|
|
109
130
|
|
|
131
|
+
/**
|
|
132
|
+
* Specificity tier for a segment. Lower = more specific. Matches the
|
|
133
|
+
* priority order in `matchNode`: static > affixed-dynamic > bare-dynamic >
|
|
134
|
+
* catch-all > optional-catch-all.
|
|
135
|
+
*/
|
|
136
|
+
function segmentTier<TFile>(node: SegmentNode<TFile>): number {
|
|
137
|
+
if (node.segmentType === 'static') return 0;
|
|
138
|
+
if (node.segmentType === 'dynamic' && (node.paramPrefix || node.paramSuffix)) return 1;
|
|
139
|
+
if (node.segmentType === 'dynamic') return 2;
|
|
140
|
+
if (node.segmentType === 'catch-all') return 3;
|
|
141
|
+
if (node.segmentType === 'optional-catch-all') return 4;
|
|
142
|
+
return 2;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Score a bare-dynamic candidate by running `matchNode` against its subtree
|
|
147
|
+
* with the remaining URL parts, then reading the tier of each segment in
|
|
148
|
+
* the matched chain. Returns a tier array that is compared lexicographically
|
|
149
|
+
* — the candidate whose chain has a lower tier at the first differing
|
|
150
|
+
* position is more specific.
|
|
151
|
+
*
|
|
152
|
+
* Delegates entirely to `matchNode`, so every segment type and priority
|
|
153
|
+
* rule is inherited automatically — no second copy to drift.
|
|
154
|
+
*/
|
|
155
|
+
function subtreeMatchScore<TFile>(
|
|
156
|
+
node: SegmentNode<TFile>,
|
|
157
|
+
parts: string[],
|
|
158
|
+
index: number,
|
|
159
|
+
requireTerminal: boolean
|
|
160
|
+
): number[] {
|
|
161
|
+
const chain: SegmentNode<TFile>[] = [];
|
|
162
|
+
const params: Record<string, string | string[]> = {};
|
|
163
|
+
if (!matchNode(node, parts, index, chain, params, requireTerminal)) return [];
|
|
164
|
+
// Skip the first entry (the candidate node itself — it's the bare-dynamic
|
|
165
|
+
// we're scoring, which is the same tier for all candidates).
|
|
166
|
+
return chain.slice(1).map((seg) => segmentTier(seg));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Compare two tier arrays lexicographically. Negative means `a` is more
|
|
171
|
+
* specific (should be tried first).
|
|
172
|
+
*/
|
|
173
|
+
function compareTierArrays(a: number[], b: number[]): number {
|
|
174
|
+
const len = Math.max(a.length, b.length);
|
|
175
|
+
for (let i = 0; i < len; i++) {
|
|
176
|
+
// A shorter match is less specific — missing entries treated as worst tier.
|
|
177
|
+
const ta = i < a.length ? a[i] : 5;
|
|
178
|
+
const tb = i < b.length ? b[i] : 5;
|
|
179
|
+
if (ta !== tb) return ta - tb;
|
|
180
|
+
}
|
|
181
|
+
return 0;
|
|
182
|
+
}
|
|
183
|
+
|
|
110
184
|
/** Combined affix length for specificity ordering. */
|
|
111
185
|
function affixLength<TFile>(node: SegmentNode<TFile>): number {
|
|
112
186
|
return (node.paramPrefix?.length ?? 0) + (node.paramSuffix?.length ?? 0);
|
|
@@ -206,32 +280,177 @@ function matchNode<TFile>(
|
|
|
206
280
|
}
|
|
207
281
|
|
|
208
282
|
// 3. Bare dynamic segments ([param])
|
|
283
|
+
// When multiple bare dynamics compete (common with route groups that
|
|
284
|
+
// flatten into the same parent), sort by subtree specificity so a
|
|
285
|
+
// branch containing a static match for the NEXT URL part is tried
|
|
286
|
+
// first. Without this, the winner depends on children order and
|
|
287
|
+
// renaming a route group can flip it — the exact shape the collision
|
|
288
|
+
// validator exists to reject.
|
|
289
|
+
const bareDynamic = effective.filter(
|
|
290
|
+
({ child }) =>
|
|
291
|
+
child.segmentType === 'dynamic' && child.paramName && !child.paramPrefix && !child.paramSuffix
|
|
292
|
+
);
|
|
293
|
+
if (bareDynamic.length > 1 && index + 1 < parts.length) {
|
|
294
|
+
const scores = new Map<SegmentNode<TFile>, number[]>();
|
|
295
|
+
for (const { child } of bareDynamic) {
|
|
296
|
+
scores.set(child, subtreeMatchScore(child, parts, index + 1, requireTerminal));
|
|
297
|
+
}
|
|
298
|
+
bareDynamic.sort((a, b) => compareTierArrays(scores.get(a.child)!, scores.get(b.child)!));
|
|
299
|
+
}
|
|
300
|
+
for (const { child, groupChain } of bareDynamic) {
|
|
301
|
+
chain.push(...groupChain);
|
|
302
|
+
const prev = params[child.paramName!];
|
|
303
|
+
params[child.paramName!] = part;
|
|
304
|
+
if (matchNode(child, parts, index + 1, chain, params, requireTerminal)) {
|
|
305
|
+
return true;
|
|
306
|
+
}
|
|
307
|
+
// Backtrack
|
|
308
|
+
chain.length -= groupChain.length;
|
|
309
|
+
if (prev !== undefined) {
|
|
310
|
+
params[child.paramName!] = prev;
|
|
311
|
+
} else {
|
|
312
|
+
delete params[child.paramName!];
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// 4. Catch-all segments ([...param]) — must be terminal unless the
|
|
317
|
+
// caller passed requireTerminal:false (metadata route matching needs to
|
|
318
|
+
// find the owning segment even when it has no page).
|
|
209
319
|
for (const { child, groupChain } of effective) {
|
|
210
320
|
if (
|
|
211
|
-
child.segmentType === '
|
|
321
|
+
child.segmentType === 'catch-all' &&
|
|
212
322
|
child.paramName &&
|
|
213
|
-
!child
|
|
214
|
-
!child.paramSuffix
|
|
323
|
+
(!requireTerminal || isTerminal(child))
|
|
215
324
|
) {
|
|
216
|
-
chain.push(...groupChain);
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
325
|
+
chain.push(...groupChain, child);
|
|
326
|
+
params[child.paramName] = parts.slice(index);
|
|
327
|
+
return true;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// 5. Optional catch-all segments ([[...param]]) — same terminal rule
|
|
332
|
+
for (const { child, groupChain } of effective) {
|
|
333
|
+
if (
|
|
334
|
+
child.segmentType === 'optional-catch-all' &&
|
|
335
|
+
child.paramName &&
|
|
336
|
+
(!requireTerminal || isTerminal(child))
|
|
337
|
+
) {
|
|
338
|
+
chain.push(...groupChain, child);
|
|
339
|
+
params[child.paramName] = parts.slice(index);
|
|
340
|
+
return true;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
chain.pop();
|
|
345
|
+
return false;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Generator twin of `matchNode` — yields every match instead of returning
|
|
350
|
+
* the first. Each yield snapshots `chain` and `params` so the caller gets
|
|
351
|
+
* independent results. After yielding, backtracking continues to find the
|
|
352
|
+
* next match.
|
|
353
|
+
*/
|
|
354
|
+
function* matchNodeAll<TFile>(
|
|
355
|
+
node: SegmentNode<TFile>,
|
|
356
|
+
parts: string[],
|
|
357
|
+
index: number,
|
|
358
|
+
chain: SegmentNode<TFile>[],
|
|
359
|
+
params: Record<string, string | string[]>,
|
|
360
|
+
requireTerminal: boolean
|
|
361
|
+
): Generator<TreeMatchResult<TFile>> {
|
|
362
|
+
chain.push(node);
|
|
363
|
+
|
|
364
|
+
if (index >= parts.length) {
|
|
365
|
+
if (!requireTerminal || isTerminal(node)) {
|
|
366
|
+
yield { chain: [...chain], params: { ...params } };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
for (const child of node.children) {
|
|
370
|
+
if (child.segmentType === 'group') {
|
|
371
|
+
yield* matchNodeAll(child, parts, index, chain, params, requireTerminal);
|
|
221
372
|
}
|
|
222
|
-
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
const effective = collectEffectiveChildren(node);
|
|
376
|
+
for (const { child, groupChain } of effective) {
|
|
377
|
+
if (child.segmentType === 'optional-catch-all' && (!requireTerminal || isTerminal(child))) {
|
|
378
|
+
chain.push(...groupChain, child);
|
|
379
|
+
yield { chain: [...chain], params: { ...params } };
|
|
380
|
+
chain.length -= groupChain.length + 1;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
chain.pop();
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
const part = parts[index];
|
|
389
|
+
const effective = collectEffectiveChildren(node);
|
|
390
|
+
|
|
391
|
+
// 1. Static segments
|
|
392
|
+
for (const { child, groupChain } of effective) {
|
|
393
|
+
if (child.segmentType === 'static' && child.segmentName === part) {
|
|
394
|
+
chain.push(...groupChain);
|
|
395
|
+
yield* matchNodeAll(child, parts, index + 1, chain, params, requireTerminal);
|
|
396
|
+
chain.length -= groupChain.length;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// 2. Affixed dynamic segments
|
|
401
|
+
const affixed = effective.filter(
|
|
402
|
+
({ child }) =>
|
|
403
|
+
child.segmentType === 'dynamic' && child.paramName && (child.paramPrefix || child.paramSuffix)
|
|
404
|
+
);
|
|
405
|
+
affixed.sort((a, b) => affixLength(b.child) - affixLength(a.child));
|
|
406
|
+
for (const { child, groupChain } of affixed) {
|
|
407
|
+
const prefix = child.paramPrefix ?? '';
|
|
408
|
+
const suffix = child.paramSuffix ?? '';
|
|
409
|
+
if (
|
|
410
|
+
part.length > prefix.length + suffix.length &&
|
|
411
|
+
(!prefix || part.startsWith(prefix)) &&
|
|
412
|
+
(!suffix || part.endsWith(suffix))
|
|
413
|
+
) {
|
|
414
|
+
const value = part.slice(prefix.length, part.length - (suffix.length || 0));
|
|
415
|
+
chain.push(...groupChain);
|
|
416
|
+
const prev = params[child.paramName!];
|
|
417
|
+
params[child.paramName!] = value;
|
|
418
|
+
yield* matchNodeAll(child, parts, index + 1, chain, params, requireTerminal);
|
|
223
419
|
chain.length -= groupChain.length;
|
|
224
420
|
if (prev !== undefined) {
|
|
225
|
-
params[child.paramName] = prev;
|
|
421
|
+
params[child.paramName!] = prev;
|
|
226
422
|
} else {
|
|
227
|
-
delete params[child.paramName];
|
|
423
|
+
delete params[child.paramName!];
|
|
228
424
|
}
|
|
229
425
|
}
|
|
230
426
|
}
|
|
231
427
|
|
|
232
|
-
//
|
|
233
|
-
|
|
234
|
-
|
|
428
|
+
// 3. Bare dynamic segments
|
|
429
|
+
const bareDynamic = effective.filter(
|
|
430
|
+
({ child }) =>
|
|
431
|
+
child.segmentType === 'dynamic' && child.paramName && !child.paramPrefix && !child.paramSuffix
|
|
432
|
+
);
|
|
433
|
+
if (bareDynamic.length > 1 && index + 1 < parts.length) {
|
|
434
|
+
const scores = new Map<SegmentNode<TFile>, number[]>();
|
|
435
|
+
for (const { child } of bareDynamic) {
|
|
436
|
+
scores.set(child, subtreeMatchScore(child, parts, index + 1, requireTerminal));
|
|
437
|
+
}
|
|
438
|
+
bareDynamic.sort((a, b) => compareTierArrays(scores.get(a.child)!, scores.get(b.child)!));
|
|
439
|
+
}
|
|
440
|
+
for (const { child, groupChain } of bareDynamic) {
|
|
441
|
+
chain.push(...groupChain);
|
|
442
|
+
const prev = params[child.paramName!];
|
|
443
|
+
params[child.paramName!] = part;
|
|
444
|
+
yield* matchNodeAll(child, parts, index + 1, chain, params, requireTerminal);
|
|
445
|
+
chain.length -= groupChain.length;
|
|
446
|
+
if (prev !== undefined) {
|
|
447
|
+
params[child.paramName!] = prev;
|
|
448
|
+
} else {
|
|
449
|
+
delete params[child.paramName!];
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// 4. Catch-all segments
|
|
235
454
|
for (const { child, groupChain } of effective) {
|
|
236
455
|
if (
|
|
237
456
|
child.segmentType === 'catch-all' &&
|
|
@@ -239,12 +458,19 @@ function matchNode<TFile>(
|
|
|
239
458
|
(!requireTerminal || isTerminal(child))
|
|
240
459
|
) {
|
|
241
460
|
chain.push(...groupChain, child);
|
|
461
|
+
const prev = params[child.paramName];
|
|
242
462
|
params[child.paramName] = parts.slice(index);
|
|
243
|
-
|
|
463
|
+
yield { chain: [...chain], params: { ...params } };
|
|
464
|
+
chain.length -= groupChain.length + 1;
|
|
465
|
+
if (prev !== undefined) {
|
|
466
|
+
params[child.paramName] = prev;
|
|
467
|
+
} else {
|
|
468
|
+
delete params[child.paramName];
|
|
469
|
+
}
|
|
244
470
|
}
|
|
245
471
|
}
|
|
246
472
|
|
|
247
|
-
// 5. Optional catch-all segments
|
|
473
|
+
// 5. Optional catch-all segments
|
|
248
474
|
for (const { child, groupChain } of effective) {
|
|
249
475
|
if (
|
|
250
476
|
child.segmentType === 'optional-catch-all' &&
|
|
@@ -252,11 +478,17 @@ function matchNode<TFile>(
|
|
|
252
478
|
(!requireTerminal || isTerminal(child))
|
|
253
479
|
) {
|
|
254
480
|
chain.push(...groupChain, child);
|
|
481
|
+
const prev = params[child.paramName];
|
|
255
482
|
params[child.paramName] = parts.slice(index);
|
|
256
|
-
|
|
483
|
+
yield { chain: [...chain], params: { ...params } };
|
|
484
|
+
chain.length -= groupChain.length + 1;
|
|
485
|
+
if (prev !== undefined) {
|
|
486
|
+
params[child.paramName] = prev;
|
|
487
|
+
} else {
|
|
488
|
+
delete params[child.paramName];
|
|
489
|
+
}
|
|
257
490
|
}
|
|
258
491
|
}
|
|
259
492
|
|
|
260
493
|
chain.pop();
|
|
261
|
-
return false;
|
|
262
494
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"convention-lint-BnO5TyHD.js","names":[],"sources":["../../src/routing/segment-codegen.ts","../../src/routing/codegen-write.ts","../../src/routing/export-detect.ts","../../src/routing/convention-lint.ts"],"sourcesContent":["/**\n * $segment type generation and directory-to-route mapping.\n *\n * Generates per-route $segment.d.ts files in .timber/types/ that mirror\n * the app/ directory structure. TypeScript's rootDirs feature makes these\n * importable as './$segment' from route files.\n *\n * Design doc: design/41-global-params.md §The $segment Module\n */\n\nimport { writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { RouteTree, SegmentNode } from './types.ts';\n\n/** Info carried per directory for type generation. */\nexport interface SegmentInfo {\n /** The URL route pattern (groups and slots stripped). e.g. '/[artistSlug]/[year]' */\n route: string;\n /** The full tree path including groups and slots — uniquely identifies a segment.\n * e.g. '/(browse)/[artistSlug]/@shows/[year]' */\n segmentPath: string;\n}\n\n/**\n * Build a map of absolute filesystem directory → segment info.\n * Used by resolveId to map a $segment import's importer to the correct route,\n * and by writeSegmentTypes to generate per-route $segment.d.ts files.\n *\n * Walks every segment (not just leaves) so layouts and middleware\n * at any depth can import $segment.\n */\nexport function buildDirToRouteMap(tree: RouteTree, appDir: string): Map<string, SegmentInfo> {\n const map = new Map<string, SegmentInfo>();\n\n function walk(node: SegmentNode, fsPath: string, treePath: string): void {\n map.set(fsPath, {\n route: node.urlPath || '/',\n segmentPath: treePath || '/',\n });\n\n for (const child of node.children) {\n const childDir = join(fsPath, child.segmentName);\n const childTreePath = `${treePath}/${child.segmentName}`;\n walk(child, childDir, childTreePath);\n }\n for (const [slotName, slotNode] of Object.entries(node.slots)) {\n const slotDir = join(fsPath, `@${slotName}`);\n const slotTreePath = `${treePath}/@${slotName}`;\n walk(slotNode, slotDir, slotTreePath);\n }\n }\n\n walk(tree.root, appDir, '');\n return map;\n}\n\n/**\n * Generate the full $segment.d.ts content for a segment.\n */\nexport function generateSegmentDts(info: SegmentInfo): string {\n return [\n `export const ROUTE: '${info.route}';`,\n `export const SEGMENT_PATH: '${info.segmentPath}';`,\n '',\n ].join('\\n');\n}\n\n/**\n * Generate per-route $segment.d.ts files in .timber/types/ mirroring\n * the app/ directory structure. These files are importable via TypeScript's\n * rootDirs feature.\n */\nexport async function writeSegmentTypes(\n routeTree: RouteTree,\n appDir: string,\n root: string\n): Promise<void> {\n // Compute the relative prefix from project root to appDir.\n // e.g. if appDir is /project/src/app, relative is 'src/app'\n const relative = appDir.slice(root.length + 1);\n const typesBase = join(root, '.timber', 'types', relative);\n const map = buildDirToRouteMap(routeTree, appDir);\n\n const writes: Promise<void>[] = [];\n for (const [fsDir, info] of map) {\n // Mirror the app/ structure under .timber/types/\n const relDir = fsDir.slice(appDir.length); // e.g. '/[artistSlug]/[year]'\n const segmentDir = join(typesBase, relDir);\n const segmentFile = join(segmentDir, '$segment.d.ts');\n const content = generateSegmentDts(info);\n\n writes.push(\n mkdir(segmentDir, { recursive: true }).then(() => writeFile(segmentFile, content, 'utf-8'))\n );\n }\n\n await Promise.all(writes);\n}\n","/**\n * Route-map codegen writer.\n *\n * Materializes the generated route types on disk: `.timber/timber-routes.d.ts`,\n * `.timber/segment-types.d.ts` (via `writeSegmentTypes`), and the root\n * `timber-env.d.ts` that references them.\n *\n * Lives outside `plugins/routing.ts` because it has two callers with two\n * different failure policies: the dev/build plugin starts the write off the hot\n * path and logs failures, while `timber check` awaits it and treats a failure as\n * fatal — a type check run against absent or stale route types reports errors\n * about code that is fine. One implementation, two policies, so the bytes on\n * disk cannot drift between the two commands.\n *\n * Design docs: 09-typescript.md §\"Typed Routes\", 18-build-system.md\n */\n\nimport { writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { generateRouteMap } from './codegen.ts';\nimport { writeSegmentTypes } from './segment-codegen.ts';\nimport type { RouteTree } from './types.ts';\n\n/**\n * Path (relative to the project root) of the generated route map declaration\n * file, and the name of the root file that `/// <reference>`s it.\n *\n * Exported because `timber check` has to answer whether the user's tsconfig\n * pulls these into the program — a question about these exact paths. It derives\n * them from here rather than restating them, so a rename cannot leave the check\n * looking for a file nothing writes.\n */\nexport const CODEGEN_OUTPUT = '.timber/timber-routes.d.ts';\n\n/** Root-level file that references the generated declarations. */\nexport const ENV_DTS_FILENAME = 'timber-env.d.ts';\n\n/**\n * Content of the timber-env.d.ts file written to the project root.\n *\n * Uses a triple-slash reference so TypeScript auto-discovers the generated\n * route map without the user needing to edit tsconfig.json — same pattern\n * as Next.js's next-env.d.ts.\n *\n * Also references `vite/client` so side-effect imports like\n * `import './globals.css'` type-check without ts(2882), and so\n * `import.meta.env`, `import.meta.hot`, `import.meta.glob`, asset\n * imports (`*.png`, `*.svg`, …), CSS modules, and `?url`/`?raw`/\n * `?inline` query variants all resolve without the user editing\n * tsconfig.json themselves. Next.js's next-env.d.ts plays the same\n * role via `next/types/global`.\n *\n * `vite` is a peer dep of `@timber-js/app`, so the reference always\n * resolves in a correctly-installed project.\n */\nconst TIMBER_ENV_DTS = [\n '// This file is auto-generated by timber.js. Do not edit.',\n '// It ensures TypeScript picks up the generated route types and',\n '// Vite-provided ambient types (CSS, assets, import.meta.env, HMR).',\n '/* eslint-disable @typescript-eslint/triple-slash-reference */',\n '/// <reference path=\".timber/timber-routes.d.ts\" />',\n '/// <reference types=\"vite/client\" />',\n '/// <reference types=\"react/canary\" />',\n '/// <reference types=\"react-dom/canary\" />',\n '',\n].join('\\n');\n\n/**\n * Codegen writes that have been started but have not yet landed on disk.\n *\n * `writeRouteCodegen` is deliberately unawaited on the dev/build hot path,\n * which leaves that caller no way to know the files exist yet. Anything that\n * tears down the project root — a build process exiting, a test removing its\n * temp root — then races the writes: `rmSync` empties a directory that a\n * pending `mkdir` immediately recreates, and the removal fails with ENOTEMPTY.\n *\n * Every started write registers here and deregisters when it settles, so\n * `flushCodegenWrites()` can await them instead of guessing at a delay.\n */\nconst pendingCodegenWrites = new Set<Promise<void>>();\n\n/**\n * Resolve once every codegen write started so far has landed on disk.\n *\n * Safe to call at any time and from anywhere — writes are tracked per process,\n * not per plugin instance, so a caller does not need a handle on the plugin\n * that started them. Never rejects: the tracked copy of each write has its\n * rejection swallowed, so a failing write cannot turn a teardown barrier into\n * an unhandled rejection. Callers that care about failure await the promise\n * `writeRouteCodegen` returned instead.\n */\nexport async function flushCodegenWrites(): Promise<void> {\n // Loop rather than a single Promise.all: a write started while we were\n // awaiting would otherwise be missed, and the set would still be non-empty\n // on return.\n //\n // Each round drops what it awaited rather than trusting the per-write\n // `finally` to have run, so the two removal paths are independent — a\n // deregistration that stopped firing would leak memory in dev, but it can\n // never turn this into a spin.\n while (pendingCodegenWrites.size > 0) {\n const inFlight = [...pendingCodegenWrites];\n await Promise.all(inFlight);\n for (const write of inFlight) pendingCodegenWrites.delete(write);\n }\n}\n\n/**\n * Write the generated route map, segment types, and the timber-env.d.ts\n * reference file for `tree`.\n *\n * Returns a promise that **rejects** if any write fails. The dev/build plugin\n * does not await it (types are a developer convenience there, not a runtime\n * dependency) and logs instead; `timber check` awaits it and fails the command.\n * Either way the write is registered with `flushCodegenWrites()`.\n */\nexport function writeRouteCodegen(tree: RouteTree, appDir: string, root: string): Promise<void> {\n const timberDir = join(root, '.timber');\n const content = generateRouteMap(tree, { appDir, outputDir: timberDir });\n const routesPath = join(root, CODEGEN_OUTPUT);\n const envPath = join(root, ENV_DTS_FILENAME);\n\n const done = mkdir(timberDir, { recursive: true })\n .then(() =>\n Promise.all([\n writeFile(routesPath, content, 'utf-8'),\n writeFile(envPath, TIMBER_ENV_DTS, 'utf-8'),\n writeSegmentTypes(tree, appDir, root),\n ])\n )\n .then(() => undefined);\n\n // The tracked copy swallows rejection so `flushCodegenWrites` — a teardown\n // barrier — never rejects and never leaves an unhandled rejection behind.\n // The returned promise keeps its rejection for callers that want it.\n const tracked = done.catch(() => undefined);\n pendingCodegenWrites.add(tracked);\n void tracked.finally(() => pendingCodegenWrites.delete(tracked));\n\n return done;\n}\n","/**\n * AST-based export detection for route files.\n *\n * Uses Vite's `parseAst` (backed by oxc) to precisely detect named and\n * default exports, replacing the regex-based approach that was fragile\n * with TypeScript syntax (type exports, `as` aliases, comments, etc.).\n */\n\nimport { existsSync } from 'node:fs';\nimport { parseAst } from 'vite';\nimport { readFileCached } from './file-cache.ts';\n\ninterface AstNode {\n type: string;\n exportKind?: string;\n declaration?: AstNode;\n specifiers?: Array<{\n exported?: { name: string };\n local?: { name: string };\n exportKind?: string;\n }>;\n id?: { name: string };\n declarations?: Array<{ id?: { name: string }; init?: AstNode }>;\n /** Set on re-exports: `export { X } from './y'`. Absent on local exports. */\n source?: { value?: string } | null;\n /** Set on runtime-transparent wrappers: `X as T`, `X satisfies T`, `(X)`, `X!`. */\n expression?: AstNode;\n /** Set on `Identifier` nodes. */\n name?: string;\n}\n\ninterface ProgramNode {\n body: AstNode[];\n}\n\nfunction tryParse(source: string): ProgramNode | null {\n try {\n return parseAst(source, { lang: 'tsx' }) as unknown as ProgramNode;\n } catch {\n return null;\n }\n}\n\n/**\n * Collect all named export identifiers from a parsed program.\n * Handles: `export function X`, `export const X`, `export { X }`,\n * `export { X } from '...'`, `export { Y as X }`.\n */\nfunction collectNamedExports(program: ProgramNode): Set<string> {\n const names = new Set<string>();\n for (const stmt of program.body) {\n if (stmt.type !== 'ExportNamedDeclaration') continue;\n // Skip `export type ...` declarations — they're erased at runtime\n if (stmt.exportKind === 'type') continue;\n\n if (stmt.declaration) {\n if (stmt.declaration.id?.name) {\n names.add(stmt.declaration.id.name);\n }\n if (stmt.declaration.declarations) {\n for (const decl of stmt.declaration.declarations) {\n if (decl.id?.name) names.add(decl.id.name);\n }\n }\n }\n\n if (stmt.specifiers) {\n for (const spec of stmt.specifiers) {\n // Skip `export { type X }` — per-specifier type exports\n if (spec.exportKind === 'type') continue;\n if (spec.exported?.name && spec.exported.name !== 'default') {\n names.add(spec.exported.name);\n }\n }\n }\n }\n return names;\n}\n\n/**\n * The specifier exporting a *runtime* default from this statement, if any.\n *\n * Type-only exports erase, so they are not default exports at runtime — and\n * TypeScript spells that two ways, on two different nodes: `export type { X as\n * default }` marks the **statement**, `export { type X as default }` marks the\n * **specifier**. Both have to be checked, or a type alias reads as a component:\n * a status file whose only default is a type has nothing for the error boundary\n * to receive (the renderer's `mod?.default` skips it), so treating it as one\n * would fail a build over a file that cannot break anything.\n *\n * One implementation because two callers must agree on what \"has a default\n * export\" means: `hasDefaultExport` decides whether to warn that a page has\n * none, and `fileDefaultExportIsLocalValue` decides whether to fail the build.\n */\nfunction defaultSpecifier(stmt: AstNode): NonNullable<AstNode['specifiers']>[number] | null {\n if (stmt.type !== 'ExportNamedDeclaration' || !stmt.specifiers) return null;\n if (stmt.exportKind === 'type') return null;\n for (const spec of stmt.specifiers) {\n if (spec.exportKind === 'type') continue;\n if (spec.exported?.name === 'default') return spec;\n }\n return null;\n}\n\n/**\n * Check whether a program has a default export.\n * Handles: `export default ...`, `export { X as default }`,\n * `export { default } from '...'`. Type-only defaults do not count —\n * see `defaultSpecifier`.\n */\nfunction hasDefaultExport(program: ProgramNode): boolean {\n for (const stmt of program.body) {\n if (stmt.type === 'ExportDefaultDeclaration') return true;\n if (defaultSpecifier(stmt)) return true;\n }\n return false;\n}\n\n/**\n * Check whether a program has any bare `export * from '...'` declarations.\n * Excludes `export * as X from '...'` (namespace re-exports) since those\n * create a namespace object, not individual top-level exports.\n */\nfunction hasStarExport(program: ProgramNode): boolean {\n return program.body.some(\n (stmt) =>\n stmt.type === 'ExportAllDeclaration' && !(stmt as any).exported && stmt.exportKind !== 'type'\n );\n}\n\n/**\n * Check if a file exports a specific named export.\n * Returns false if the file doesn't exist or can't be parsed.\n */\nexport function fileHasExport(filePath: string, exportName: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n return collectNamedExports(program).has(exportName);\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a file has any of the given named exports.\n * Returns the set of matching export names.\n */\nexport function fileHasAnyExport(filePath: string, exportNames: readonly string[]): Set<string> {\n const matches = new Set<string>();\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return matches;\n const exports = collectNamedExports(program);\n for (const name of exportNames) {\n if (exports.has(name)) matches.add(name);\n }\n } catch {\n // Graceful fallback: return empty set\n }\n return matches;\n}\n\n/**\n * Check if a file has a default export.\n * Returns false if the file doesn't exist or can't be parsed.\n */\nexport function fileHasDefaultExport(filePath: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n return hasDefaultExport(program);\n } catch {\n return false;\n }\n}\n\n/** Node types whose value is unambiguously constructed by this module. */\nconst FUNCTION_LIKE = new Set([\n 'FunctionDeclaration',\n 'FunctionExpression',\n 'ArrowFunctionExpression',\n 'ClassDeclaration',\n 'ClassExpression',\n]);\n\n/**\n * Expression wrappers that erase at runtime and so cannot change where a value\n * was constructed: `X as T`, `X satisfies T`, `<T>X`, `X!`, `X<T>`, `(X)`.\n */\nconst TRANSPARENT_WRAPPERS = new Set([\n 'TSAsExpression',\n 'TSSatisfiesExpression',\n 'TSTypeAssertion',\n 'TSNonNullExpression',\n 'TSInstantiationExpression',\n 'ParenthesizedExpression',\n]);\n\n/**\n * Strip runtime-transparent wrappers so the node underneath can be classified.\n *\n * Without this, `(() => <h1 />) satisfies React.FC` reads as a\n * `TSSatisfiesExpression` rather than the arrow function it compiles to, and a\n * provably-local component is misread as one whose origin cannot be\n * determined — turning a build error into a warning.\n */\nfunction unwrapTransparent(node: AstNode): AstNode {\n let current = node;\n while (TRANSPARENT_WRAPPERS.has(current.type) && current.expression) {\n current = current.expression;\n }\n return current;\n}\n\n/**\n * Whether `name` is bound at module top level to a function or class written\n * in this file. An imported binding can never match: imports are\n * `ImportDeclaration` specifiers, not function/class/variable declarations,\n * and a module-level name cannot be both.\n */\nfunction bindsLocalFunction(program: ProgramNode, name: string): boolean {\n for (const stmt of program.body) {\n // `export function X() {}` binds X locally too — unwrap the export.\n const decl = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt;\n if (!decl) continue;\n if (\n (decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration') &&\n decl.id?.name === name\n ) {\n return true;\n }\n if (decl.type === 'VariableDeclaration') {\n for (const d of decl.declarations ?? []) {\n if (d.id?.name === name && d.init && FUNCTION_LIKE.has(unwrapTransparent(d.init).type)) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Whether the default export is *provably* a value constructed by this module:\n * `export default function/class/() => {}`, or a name bound to a function or\n * class declared here — whether it leaves via `export default Name` or\n * `export { Name as default }`. Both spellings are the same fact about where\n * the value was built, so both must answer the same way.\n *\n * This is the sound half of \"is this a server component?\". A file with no\n * `'use client'` directive whose default export is built here is a server\n * component, full stop. Everything else — `export { default } from\n * './client-thing'`, `export default Imported`, `export default memo(X)`,\n * an unparseable file — returns false, because the exported value may have\n * been minted in a module that *does* carry the directive. Callers must not\n * infer \"server component\" from a missing directive alone.\n */\nexport function fileDefaultExportIsLocalValue(filePath: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n for (const stmt of program.body) {\n if (stmt.type === 'ExportDefaultDeclaration') {\n const decl = stmt.declaration && unwrapTransparent(stmt.declaration);\n if (!decl) return false;\n if (FUNCTION_LIKE.has(decl.type)) return true;\n if (decl.type === 'Identifier' && decl.name) {\n return bindsLocalFunction(program, decl.name);\n }\n return false;\n }\n\n // `export { Name as default }` — the same default export by another\n // spelling. `hasDefaultExport` already counts it, so an analysis that\n // skipped it here would let the exact defect this powers slip through\n // as a warning.\n const spec = defaultSpecifier(stmt);\n if (spec) {\n // `export { X as default } from './client-thing'` re-exports another\n // module's value — the directive governing it lives over there.\n if (stmt.source) return false;\n return spec.local?.name ? bindsLocalFunction(program, spec.local.name) : false;\n }\n }\n return false;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a file has any `export * from '...'` declarations.\n * Returns false if the file doesn't exist or can't be parsed.\n */\nexport function fileHasStarExport(filePath: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n return hasStarExport(program);\n } catch {\n return false;\n }\n}\n\n/**\n * Parsed value of `export const prerender` from a route file.\n *\n * - `true` / `false` — literal boolean\n * - `{ ttl?, tags? }` — ISR options object (prerender: true is implied)\n * - `undefined` — no `export const prerender` found\n *\n * See design/45-cache-lifetimes.md §\"Route-Level Static\".\n */\nexport type PrerenderExportValue = boolean | { ttl?: number; tags?: string[] };\n\nfunction extractLiteralValue(node: AstNode): unknown {\n if (!node) return undefined;\n const n = node as any;\n if (n.type === 'Literal') return n.value;\n if (n.type === 'UnaryExpression' && n.operator === '-' && n.argument?.type === 'Literal') {\n return -(n.argument.value as number);\n }\n if (n.type === 'ArrayExpression') {\n const elements = n.elements as AstNode[] | undefined;\n if (!elements) return undefined;\n const result: unknown[] = [];\n for (const el of elements) {\n const v = extractLiteralValue(el);\n if (v === undefined) return undefined;\n result.push(v);\n }\n return result;\n }\n return undefined;\n}\n\nfunction extractObjectLiteral(node: AstNode): Record<string, unknown> | undefined {\n if ((node as any).type !== 'ObjectExpression') return undefined;\n const props = (node as any).properties as AstNode[] | undefined;\n if (!props) return undefined;\n const result: Record<string, unknown> = {};\n for (const prop of props) {\n const p = prop as any;\n if (p.type === 'SpreadElement') return undefined;\n if (p.type !== 'Property' || p.computed) return undefined;\n const key =\n p.key?.type === 'Identifier'\n ? p.key.name\n : p.key?.type === 'Literal'\n ? String(p.key.value)\n : undefined;\n if (!key) return undefined;\n const value = extractLiteralValue(p.value);\n if (value === undefined) return undefined;\n result[key] = value;\n }\n return result;\n}\n\n/**\n * Extract the value of `export const prerender` from a file.\n * Returns undefined if the file doesn't export `prerender` or can't be parsed.\n *\n * Supports:\n * export const prerender = true;\n * export const prerender = false;\n * export const prerender = { ttl: 3600, tags: ['docs'] };\n */\nexport function getPrerenderExport(filePath: string): PrerenderExportValue | undefined {\n if (!existsSync(filePath)) return undefined;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return undefined;\n\n for (const stmt of program.body) {\n if (stmt.type !== 'ExportNamedDeclaration') continue;\n if (stmt.exportKind === 'type') continue;\n if (!stmt.declaration) continue;\n const decl = stmt.declaration;\n if (decl.type !== 'VariableDeclaration') continue;\n const declarations = decl.declarations as\n | Array<{\n id?: { name?: string };\n init?: AstNode;\n }>\n | undefined;\n if (!declarations) continue;\n for (const d of declarations) {\n if (d.id?.name !== 'prerender' || !d.init) continue;\n const init = d.init as any;\n if (init.type === 'Literal' && typeof init.value === 'boolean') {\n return init.value;\n }\n if (init.type === 'ObjectExpression') {\n const obj = extractObjectLiteral(init);\n if (!obj) return undefined;\n const result: { ttl?: number; tags?: string[] } = {};\n if ('ttl' in obj && typeof obj.ttl === 'number') result.ttl = obj.ttl;\n if (\n 'tags' in obj &&\n Array.isArray(obj.tags) &&\n obj.tags.every((t: unknown) => typeof t === 'string')\n ) {\n result.tags = obj.tags as string[];\n }\n return result;\n }\n return undefined;\n }\n }\n return undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Check if a file starts with a specific directive (e.g. \"use client\").\n * Directives are string literal expression statements at the top of the file.\n */\nexport function fileHasDirective(filePath: string, directive: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n for (const stmt of program.body) {\n if (stmt.type !== 'ExpressionStatement') break;\n const expr = (stmt as any).expression;\n if (expr?.type !== 'Literal' || typeof expr.value !== 'string') break;\n if (expr.value === directive) return true;\n }\n return false;\n } catch {\n return false;\n }\n}\n","/**\n * Convention linter — validates common misconfigurations in the route tree.\n *\n * Runs at scan time (build and dev startup). Each check produces a warning\n * with the file path, what's wrong, and what to do about it.\n *\n * Most checks are warnings — they don't block the build. The goal is to catch\n * issues that would otherwise produce cryptic runtime behavior (silent 404s,\n * empty pages, confusing React errors).\n *\n * A check emits `level: 'error'` only when the misconfiguration is *proven*\n * (never inferred from an absence the analysis cannot see through) and fatal\n * to rendering. `plugins/routing.ts` turns those into a thrown build error,\n * so a false positive there refuses a working app — see\n * `classifyClientBoundaryFile` for how that bar is met.\n *\n * Design doc: 07-routing.md, 10-error-handling.md\n */\n\nimport { existsSync } from 'node:fs';\nimport type { RouteFile, RouteTree, SegmentNode } from './types.ts';\nimport { swallow } from '../server/logger.ts';\nimport {\n fileDefaultExportIsLocalValue,\n fileHasAnyExport,\n fileHasDefaultExport,\n fileHasDirective,\n fileHasStarExport,\n} from './export-detect.ts';\n\n// ─── Types ──────────────────────────────────────────────────────────────────\n\nexport interface ConventionWarning {\n /** Warning ID for deduplication and filtering. */\n id: string;\n /** Human-readable single-line summary. */\n summary: string;\n /** Multi-line details with file path and fix suggestion. */\n details: string;\n /** Severity: 'warn' for potential issues, 'error' for definite misconfigurations. */\n level: 'warn' | 'error';\n}\n\n// ─── Lint Rules ─────────────────────────────────────────────────────────────\n\n/**\n * Run all convention lint checks on a route tree.\n *\n * Returns an array of warnings. Empty array means everything looks good.\n */\nexport function lintConventions(tree: RouteTree, appDir: string): ConventionWarning[] {\n const warnings: ConventionWarning[] = [];\n\n // Check 1: app/ directory exists (caller should check before scanning,\n // but we validate the root has at least one routable file)\n checkEmptyApp(tree.root, appDir, warnings);\n\n // Check 2: route.ts without recognized HTTP method exports\n checkRouteExports(tree.root, warnings);\n\n // Check 3: Segments with layout but no page/route anywhere in subtree\n // (not a misconfiguration per se — layouts without pages are valid for\n // route groups. Skip this check.)\n\n // Check 4: Root segment has no layout.tsx (no HTML shell)\n checkRootLayout(tree.root, warnings);\n\n // Check 5: page.tsx / layout.tsx without default export\n checkDefaultExports(tree.root, warnings);\n\n // Check 6: Client layouts cannot suppress server children before Flight\n // serializes them. They remain valid UI boundaries, but not authorization\n // or data-hiding boundaries.\n checkClientLayouts(tree.root, warnings);\n\n // Check 7: error.tsx / 404.tsx / 4xx.tsx / … without 'use client' directive\n checkClientBoundaryFiles(tree.root, warnings);\n if (tree.globalError) {\n checkFileUseClientDirective(tree.globalError, 'global-error', warnings);\n }\n\n return warnings;\n}\n\nfunction checkClientLayouts(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.layout && isScriptExtension(node.layout.extension)) {\n try {\n const isClient = fileHasDirective(node.layout.filePath, 'use client');\n const isProvablyServer = fileDefaultExportIsLocalValue(node.layout.filePath);\n if (isClient || !isProvablyServer) {\n const certainty = isClient\n ? `This layout is a client component.`\n : `Timber cannot prove this layout is a server component because its default export comes from another module or an opaque expression.`;\n warnings.push({\n id: `CLIENT_LAYOUT_NOT_AUTH_BOUNDARY:${node.layout.filePath}`,\n summary: isClient\n ? `Client layout cannot securely suppress server children: ${node.layout.filePath}`\n : `Layout may resolve to a client component and cannot be trusted as an auth boundary: ${node.layout.filePath}`,\n details:\n ` File: ${node.layout.filePath}\\n\\n` +\n ` ${certainty}\\n` +\n ` React Flight resolves server content passed to a client layout before the layout runs in the browser.\\n` +\n ` Conditionally omitting children here does not prevent descendant server components from executing or being serialized.\\n\\n` +\n ` To fix: Put authorization in access.ts or a provably server layout with a locally defined default component, and keep client components inside that boundary.\\n`,\n level: 'warn',\n });\n }\n } catch (err) {\n swallow(err, `convention-lint: unreadable layout file ${node.layout.filePath}`);\n }\n }\n for (const child of node.children) checkClientLayouts(child, warnings);\n for (const slot of Object.values(node.slots)) checkClientLayouts(slot, warnings);\n}\n\n// ─── Check: Empty App ───────────────────────────────────────────────────────\n\n/**\n * Warn when the app/ directory has no routable files at all.\n *\n * This catches the \"I created app/ but didn't add any pages\" case where\n * every request silently 404s with no guidance.\n */\nfunction checkEmptyApp(root: SegmentNode, appDir: string, warnings: ConventionWarning[]): void {\n if (hasAnyRoutable(root)) return;\n\n warnings.push({\n id: 'EMPTY_APP',\n summary: 'No pages or route handlers found in app/',\n details:\n ` Directory: ${appDir}\\n\\n` +\n ' Your app/ directory has no page.tsx or route.ts files.\\n' +\n ' Every request will return 404.\\n\\n' +\n ' To fix: Create app/page.tsx with a default export:\\n\\n' +\n ' export default function Home() {\\n return <h1>Hello</h1>;\\n }\\n',\n level: 'warn',\n });\n}\n\n/**\n * Check if a segment tree has any routable files (page or route) anywhere.\n */\nfunction hasAnyRoutable(node: SegmentNode): boolean {\n if (node.page || node.route) return true;\n for (const child of node.children) {\n if (hasAnyRoutable(child)) return true;\n }\n for (const slot of Object.values(node.slots)) {\n if (hasAnyRoutable(slot)) return true;\n }\n return false;\n}\n\n/**\n * Check if a segment tree has any page files (not just route handlers).\n * Used by checkRootLayout to avoid false positives for API-only apps (TIM-794).\n * API-only apps (just route.ts handlers) don't need a root layout.\n */\nfunction hasAnyPage(node: SegmentNode): boolean {\n if (node.page) return true;\n for (const child of node.children) {\n if (hasAnyPage(child)) return true;\n }\n for (const slot of Object.values(node.slots)) {\n if (hasAnyPage(slot)) return true;\n }\n return false;\n}\n\n// ─── Check: Route Exports ───────────────────────────────────────────────────\n\n/** HTTP methods that route.ts can export. */\nconst HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'] as const;\n\n/**\n * Warn when a route.ts file doesn't appear to export any recognized HTTP methods.\n *\n * Uses AST-based detection via parseAst for precise matching.\n * Falls back silently when the file can't be parsed (syntax errors produce\n * no spurious warning — the TS compiler will catch those).\n */\nfunction checkRouteExports(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.route) {\n const filePath = node.route.filePath;\n try {\n const methods = fileHasAnyExport(filePath, HTTP_METHODS);\n if (methods.size === 0 && !fileHasStarExport(filePath)) {\n const hasDefault = fileHasDefaultExport(filePath);\n const hint = hasDefault\n ? ' It looks like you have a default export. route.ts uses named exports\\n' +\n ' for HTTP methods (GET, POST, etc.), not a default export.\\n'\n : '';\n\n warnings.push({\n id: 'ROUTE_NO_METHODS',\n summary: `route.ts has no HTTP method exports: ${filePath}`,\n details:\n ` File: ${filePath}\\n\\n` +\n ' route.ts files must export named HTTP method handlers.\\n' +\n ' Without them, the route matches but returns 405 Method Not Allowed.\\n\\n' +\n hint +\n ' Example:\\n\\n' +\n ' export function GET(ctx: RouteContext) {\\n' +\n \" return Response.json({ hello: 'world' });\\n\" +\n ' }\\n',\n level: 'warn',\n });\n }\n } catch (err) {\n swallow(err, `convention-lint: unreadable route.ts ${filePath}`);\n }\n }\n\n // Recurse\n for (const child of node.children) {\n checkRouteExports(child, warnings);\n }\n for (const slot of Object.values(node.slots)) {\n checkRouteExports(slot, warnings);\n }\n}\n\n// ─── Check: Root Layout ─────────────────────────────────────────────────────\n\n/**\n * Warn when the root segment has no layout.tsx.\n *\n * Without a root layout, there's no HTML shell (<html>, <body>).\n * The page will render but may have hydration issues or no proper document structure.\n */\nfunction checkRootLayout(root: SegmentNode, warnings: ConventionWarning[]): void {\n if (root.layout) return;\n\n // Only warn if there are pages — API-only apps (just route.ts handlers)\n // don't need a root layout (TIM-794).\n if (!hasAnyPage(root)) return;\n\n warnings.push({\n id: 'NO_ROOT_LAYOUT',\n summary: 'No root layout.tsx found',\n details:\n ' Your app has pages but no root layout.\\n' +\n ' Without app/layout.tsx, pages have no <html> or <body> wrapper.\\n\\n' +\n ' To fix: Create app/layout.tsx:\\n\\n' +\n ' export default function RootLayout({ children }: { children: React.ReactNode }) {\\n' +\n ' return (\\n' +\n ' <html lang=\"en\">\\n' +\n ' <body>{children}</body>\\n' +\n ' </html>\\n' +\n ' );\\n' +\n ' }\\n',\n level: 'warn',\n });\n}\n\n// ─── Check: Default Exports ───────────────────────────────────────────\n\n/**\n * Warn when page.tsx or layout.tsx files don't have a default export.\n *\n * Without a default export:\n * - page.tsx: the page renders nothing (empty content)\n * - layout.tsx: the layout module loads but has no component to render\n *\n * Uses AST-based detection via parseAst for precise matching. Falls back\n * silently when the file can't be parsed (no spurious warning on syntax errors).\n */\nfunction checkDefaultExports(node: SegmentNode, warnings: ConventionWarning[]): void {\n // Check page files (tsx/ts/jsx/js only — not mdx, which is default-exported by the mdx compiler)\n if (node.page && isScriptExtension(node.page.extension)) {\n checkFileDefaultExport(node.page.filePath, 'page', warnings);\n }\n\n // Check layout files\n if (node.layout && isScriptExtension(node.layout.extension)) {\n checkFileDefaultExport(node.layout.filePath, 'layout', warnings);\n }\n\n // Recurse\n for (const child of node.children) {\n checkDefaultExports(child, warnings);\n }\n for (const slot of Object.values(node.slots)) {\n checkDefaultExports(slot, warnings);\n }\n}\n\nfunction isScriptExtension(ext: string): boolean {\n return ext === 'tsx' || ext === 'ts' || ext === 'jsx' || ext === 'js';\n}\n\nfunction checkFileDefaultExport(\n filePath: string,\n fileType: string,\n warnings: ConventionWarning[]\n): void {\n try {\n if (!fileHasDefaultExport(filePath)) {\n warnings.push({\n id: `NO_DEFAULT_EXPORT:${filePath}`,\n summary: `${fileType}.tsx has no default export: ${filePath}`,\n details:\n ` File: ${filePath}\\n\\n` +\n ` ${fileType}.tsx files must export a default React component.\\n` +\n ` Without a default export, the ${fileType === 'page' ? 'page renders nothing' : 'layout has no component to wrap children'}.\\n\\n` +\n ` To fix: Add a default export:\\n\\n` +\n ` export default function My${fileType === 'page' ? 'Page' : 'Layout'}(${fileType === 'layout' ? '{ children }' : ''}) {\\n` +\n ` return ${fileType === 'layout' ? '<div>{children}</div>' : '<h1>Hello</h1>'};\\n` +\n ` }\\n`,\n level: 'warn',\n });\n }\n } catch (err) {\n swallow(err, `convention-lint: unreadable ${fileType} file ${filePath}`);\n }\n}\n\n// ─── Check: Client Boundary Directive ───────────────────────────────────────\n\n/**\n * Check every file the renderer hands to `TimberErrorBoundary` as a component\n * prop: `error.tsx`, `global-error.tsx`, and the status-code family\n * (`404.tsx`, `4xx.tsx`, `503.tsx`, …).\n *\n * `TimberErrorBoundary` is a client component, so a server component passed as\n * `fallbackComponent` is a function crossing the RSC → client boundary. React\n * Flight refuses to serialize it, and because the boundary wraps the segment's\n * *children*, the failure hits every page under that segment — not just the\n * error path. The raw message (\"Functions cannot be passed directly to Client\n * Components\") names neither the file nor the fix (TIM-1329).\n *\n * `.json` status files never reach React at all, and are not in `statusFiles`.\n */\nfunction checkClientBoundaryFiles(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.error) {\n checkFileUseClientDirective(node.error, 'error', warnings);\n }\n\n for (const [key, file] of Object.entries(node.statusFiles ?? {})) {\n checkFileUseClientDirective(file, key, warnings);\n }\n\n for (const child of node.children) {\n checkClientBoundaryFiles(child, warnings);\n }\n for (const slot of Object.values(node.slots)) {\n checkClientBoundaryFiles(slot, warnings);\n }\n}\n\n/**\n * `'client'` — carries the directive.\n * `'server'` — proven server component: no directive, and the default export is\n * a function or class built by this very module, so no other file's directive\n * can be governing it.\n * `'unknown'` — no directive, but the exported value may come from elsewhere\n * (`export { default } from './client-thing'`), or the file could not be\n * read or parsed. Never escalated to a build error.\n */\ntype ClientBoundaryVerdict = 'client' | 'server' | 'unknown';\n\nfunction classifyClientBoundaryFile(filePath: string): ClientBoundaryVerdict {\n if (fileHasDirective(filePath, 'use client')) return 'client';\n if (fileDefaultExportIsLocalValue(filePath)) return 'server';\n return 'unknown';\n}\n\n/** Example component name for the fix snippet, keyed by convention name. */\nfunction exampleComponentName(convention: string): string {\n if (convention === 'global-error') return 'GlobalError';\n if (convention === 'error') return 'ErrorBoundary';\n if (convention === '404') return 'NotFound';\n return 'StatusPage';\n}\n\n/**\n * @param file the route file (its extension decides whether the check applies)\n * @param convention the convention name — `error`, `global-error`, `404`, `4xx`, …\n */\nfunction checkFileUseClientDirective(\n file: RouteFile,\n convention: string,\n warnings: ConventionWarning[]\n): void {\n // Only script extensions need the 'use client' check — .json status files\n // never reach React at all, and are not in `statusFiles`.\n if (!isScriptExtension(file.extension)) return;\n\n const filePath = file.filePath;\n const label = `${convention}.${file.extension}`;\n let verdict: ClientBoundaryVerdict;\n try {\n verdict = classifyClientBoundaryFile(filePath);\n } catch (err) {\n swallow(err, `convention-lint: unreadable ${label} file ${filePath}`);\n return;\n }\n if (verdict === 'client') return;\n\n const isError = verdict === 'server';\n const name = exampleComponentName(convention);\n const props =\n convention === 'error' || convention === 'global-error' ? '{ error, reset }' : '{ status }';\n\n warnings.push({\n id: `NEEDS_USE_CLIENT:${filePath}`,\n summary: isError\n ? `${label} is a server component and must be a client component: ${filePath}`\n : `${label} may be missing 'use client': ${filePath}`,\n details:\n ` File: ${filePath}\\n\\n` +\n ` ${label} is handed to timber's error boundary — a client\\n` +\n ' component — as a prop. A server component cannot cross that boundary:\\n' +\n ' React fails with \"Functions cannot be passed directly to Client\\n' +\n ' Components\", and every page under this segment fails to render.\\n\\n' +\n (isError\n ? \" To fix: Add 'use client' as the first line of the file:\\n\\n\" +\n \" 'use client';\\n\\n\" +\n ` export default function ${name}(${props}) {\\n` +\n ' return <h1>…</h1>;\\n' +\n ' }\\n'\n : // The default export comes from somewhere this analysis cannot follow\n // — a re-export, an imported binding, a wrapper call. It may well\n // already be a client component, so say what was checked rather than\n // assert a break.\n \" This file has no 'use client' directive, and its default export\\n\" +\n ' comes from elsewhere, so timber cannot tell which it is. If the\\n' +\n \" module it re-exports starts with 'use client', nothing is wrong\\n\" +\n ' and you can ignore this. Otherwise add the directive there.\\n'),\n level: isError ? 'error' : 'warn',\n });\n}\n\n// ─── Check: App Directory Exists ────────────────────────────────────────────\n\n/**\n * Check if the app/ directory exists. Called before scanning.\n * Returns a warning if missing, or null if the directory exists.\n */\nexport function checkAppDirExists(appDir: string): ConventionWarning | null {\n if (existsSync(appDir)) return null;\n\n return {\n id: 'NO_APP_DIR',\n summary: 'No app/ directory found',\n details:\n ` Expected: ${appDir}\\n\\n` +\n ' timber.js requires an app/ directory for file-system routing.\\n' +\n ' Every request will return 404 until you create it.\\n\\n' +\n ' To fix: Create the app/ directory with a page:\\n\\n' +\n ' mkdir -p app\\n' +\n ' # Create app/layout.tsx and app/page.tsx\\n',\n level: 'error',\n };\n}\n\n// ─── Formatting ─────────────────────────────────────────────────────────────\n\nimport type { InspectColor } from 'node:util';\nimport { styleText } from 'node:util';\n\ntype Format = InspectColor | readonly InspectColor[];\nconst noValidate = { validateStream: false } as const;\n\nexport interface FormatOptions {\n /**\n * Emit ANSI escapes. Off when the text becomes an `Error` message —\n * whoever prints it decides its formatting, and colored escapes inside\n * an exception leak into logs and stack traces.\n */\n color?: boolean;\n}\n\n/**\n * Format warnings for terminal output.\n *\n * Groups by severity, uses colors, and includes fix suggestions.\n */\nexport function formatConventionWarnings(\n warnings: ConventionWarning[],\n options: FormatOptions = {}\n): string {\n const { color = true } = options;\n const style = (fmt: Format, text: string) => (color ? styleText(fmt, text, noValidate) : text);\n if (warnings.length === 0) return '';\n\n const errors = warnings.filter((w) => w.level === 'error');\n const warns = warnings.filter((w) => w.level === 'warn');\n\n const lines: string[] = [];\n\n if (errors.length > 0) {\n lines.push(\n `${style(['red', 'bold'], '[timber]')} ${style('red', `${errors.length} configuration error${errors.length !== 1 ? 's' : ''}:`)}`\n );\n for (const e of errors) {\n lines.push('');\n lines.push(` ${style('red', '✗')} ${e.summary}`);\n lines.push(style('dim', e.details));\n }\n }\n\n if (warns.length > 0) {\n if (errors.length > 0) lines.push('');\n lines.push(\n `${style(['yellow', 'bold'], '[timber]')} ${style('yellow', `${warns.length} configuration warning${warns.length !== 1 ? 's' : ''}:`)}`\n );\n for (const w of warns) {\n lines.push('');\n lines.push(` ${style('yellow', '⚠')} ${w.summary}`);\n lines.push(style('dim', w.details));\n }\n }\n\n return lines.join('\\n');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,mBAAmB,MAAiB,QAA0C;CAC5F,MAAM,sBAAM,IAAI,IAAyB;CAEzC,SAAS,KAAK,MAAmB,QAAgB,UAAwB;EACvE,IAAI,IAAI,QAAQ;GACd,OAAO,KAAK,WAAW;GACvB,aAAa,YAAY;EAC3B,CAAC;EAED,KAAK,MAAM,SAAS,KAAK,UAGvB,KAAK,OAFY,KAAK,QAAQ,MAAM,WAExB,GAAU,GADG,SAAS,GAAG,MAAM,aACR;EAErC,KAAK,MAAM,CAAC,UAAU,aAAa,OAAO,QAAQ,KAAK,KAAK,GAG1D,KAAK,UAFW,KAAK,QAAQ,IAAI,UAElB,GAAS,GADA,SAAS,IAAI,UACD;CAExC;CAEA,KAAK,KAAK,MAAM,QAAQ,EAAE;CAC1B,OAAO;AACT;;;;AAKA,SAAgB,mBAAmB,MAA2B;CAC5D,OAAO;EACL,wBAAwB,KAAK,MAAM;EACnC,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,OAAO,CAAC;EACpC;CACF;CAEA,OAAO,MAAM,KAAK,IAAI;AACxB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"tree-match-CdbvYTBz.js","names":[],"sources":["../../src/server/tree-match.ts"],"sourcesContent":["/**\n * Shared URL-matching tree walker for segment trees.\n *\n * Both the main route matcher (`route-matcher.ts`) and slot resolver\n * (`slot-resolver.ts`) need to walk a SegmentNode tree, matching URL\n * parts against children with the same priority semantics:\n *\n * static > dynamic > catch-all > optional-catch-all\n *\n * Before this module, each had its own walker with subtle divergences\n * (different group handling, missing backtracking, incomplete\n * optional-catch-all support). This shared walker is the single\n * source of truth for URL-to-segment matching.\n *\n * See design/07-routing.md §\"Request Lifecycle\" and TIM-940.\n */\n\nimport type { SegmentNode } from '../routing/types.ts';\n\n// ─── Public API ───────────────────────────────────────────────────────────\n\n/** Result of matching URL parts against a segment tree. */\nexport interface TreeMatchResult<TFile> {\n /** Matched segment chain from root to leaf, inclusive. */\n chain: SegmentNode<TFile>[];\n /** Collected params, keyed by param name. Catch-all params are string[]. */\n params: Record<string, string | string[]>;\n}\n\nexport interface TreeMatchOptions {\n /**\n * When true (default), only match if the leaf node has a page or route\n * handler. Set to false for metadata route matching, where we just need\n * to find the owning segment regardless of whether it has a page.\n */\n requireTerminal?: boolean;\n}\n\n/**\n * Match URL path parts against a segment tree.\n *\n * Walks the tree depth-first with backtracking, applying priority\n * ordering globally across group boundaries. Returns the matched\n * segment chain and collected params, or null if no route matches.\n *\n * By default, a match requires a terminal node (one with `page` or\n * `route`) at the leaf. Pass `{ requireTerminal: false }` to match\n * any segment (used by metadata route matching).\n *\n * @param root The root segment node to start matching from.\n * @param parts URL path parts (e.g. ['blog', 'hello-world']).\n * Empty array matches the root itself (if terminal).\n */\nexport function matchUrlParts<TFile>(\n root: SegmentNode<TFile>,\n parts: string[],\n options?: TreeMatchOptions\n): TreeMatchResult<TFile> | null {\n const chain: SegmentNode<TFile>[] = [];\n const params: Record<string, string | string[]> = {};\n const requireTerminal = options?.requireTerminal ?? true;\n\n if (matchNode(root, parts, 0, chain, params, requireTerminal)) {\n return { chain, params };\n }\n return null;\n}\n\n// ─── Internal ─────────────────────────────────────────────────────────────\n\n/**\n * A child node flattened through group segments, along with the\n * chain of group nodes that must appear in the segment chain\n * before the child to preserve the tree path.\n */\ninterface EffectiveChild<TFile> {\n child: SegmentNode<TFile>;\n groupChain: SegmentNode<TFile>[];\n}\n\n/**\n * Flatten children through group segments.\n *\n * Groups are transparent for URL matching — their non-group descendants\n * are returned with the chain of group nodes leading to them. This lets\n * the caller apply priority ordering (static > dynamic > catch-all >\n * optional-catch-all) across all groups uniformly instead of per-group.\n */\nfunction collectEffectiveChildren<TFile>(\n node: SegmentNode<TFile>,\n groupChain: SegmentNode<TFile>[] = []\n): EffectiveChild<TFile>[] {\n const result: EffectiveChild<TFile>[] = [];\n for (const child of node.children) {\n if (child.segmentType === 'group') {\n const nested = collectEffectiveChildren(child, [...groupChain, child]);\n result.push(...nested);\n } else {\n result.push({ child, groupChain });\n }\n }\n return result;\n}\n\n/** A node is terminal if it can serve a response (has a page or route handler). */\nfunction isTerminal<TFile>(node: SegmentNode<TFile>): boolean {\n return !!(node.page || node.route);\n}\n\n/** Combined affix length for specificity ordering. */\nfunction affixLength<TFile>(node: SegmentNode<TFile>): number {\n return (node.paramPrefix?.length ?? 0) + (node.paramSuffix?.length ?? 0);\n}\n\n/**\n * Recursive depth-first matcher with backtracking.\n *\n * Mutates `chain` and `params` in place for performance; backtracks\n * (restores previous state) when a candidate doesn't lead to a match.\n */\nfunction matchNode<TFile>(\n node: SegmentNode<TFile>,\n parts: string[],\n index: number,\n chain: SegmentNode<TFile>[],\n params: Record<string, string | string[]>,\n requireTerminal: boolean\n): boolean {\n chain.push(node);\n\n // All parts consumed — check if this node is terminal (or any node if !requireTerminal)\n if (index >= parts.length) {\n if (!requireTerminal || isTerminal(node)) return true;\n\n // Groups don't consume URL segments, so a group child's page can\n // match at the same URL depth. Recurse into groups transparently.\n for (const child of node.children) {\n if (child.segmentType === 'group') {\n if (matchNode(child, parts, index, chain, params, requireTerminal)) {\n return true;\n }\n }\n }\n\n // Optional catch-all with zero segments (direct and through groups).\n // The param is NOT set — matching Next.js semantics for [[...slug]]\n // with no path segments.\n const effective = collectEffectiveChildren(node);\n for (const { child, groupChain } of effective) {\n if (child.segmentType === 'optional-catch-all' && (!requireTerminal || isTerminal(child))) {\n chain.push(...groupChain, child);\n return true;\n }\n }\n\n chain.pop();\n return false;\n }\n\n const part = parts[index];\n\n // Flatten children through groups so priority ordering applies globally.\n const effective = collectEffectiveChildren(node);\n\n // 1. Static segments (exact name match)\n for (const { child, groupChain } of effective) {\n if (child.segmentType === 'static' && child.segmentName === part) {\n chain.push(...groupChain);\n if (matchNode(child, parts, index + 1, chain, params, requireTerminal)) {\n return true;\n }\n chain.length -= groupChain.length;\n }\n }\n\n // 2. Affixed dynamic segments (e.g. img-[id].png) — more specific than bare dynamic.\n // Sorted by specificity: longer combined prefix+suffix wins.\n const affixed = effective.filter(\n ({ child }) =>\n child.segmentType === 'dynamic' && child.paramName && (child.paramPrefix || child.paramSuffix)\n );\n affixed.sort((a, b) => affixLength(b.child) - affixLength(a.child));\n for (const { child, groupChain } of affixed) {\n const prefix = child.paramPrefix ?? '';\n const suffix = child.paramSuffix ?? '';\n if (\n part.length > prefix.length + suffix.length &&\n (!prefix || part.startsWith(prefix)) &&\n (!suffix || part.endsWith(suffix))\n ) {\n const value = part.slice(prefix.length, part.length - (suffix.length || 0));\n chain.push(...groupChain);\n const prev = params[child.paramName!];\n params[child.paramName!] = value;\n if (matchNode(child, parts, index + 1, chain, params, requireTerminal)) {\n return true;\n }\n // Backtrack\n chain.length -= groupChain.length;\n if (prev !== undefined) {\n params[child.paramName!] = prev;\n } else {\n delete params[child.paramName!];\n }\n }\n }\n\n // 3. Bare dynamic segments ([param])\n for (const { child, groupChain } of effective) {\n if (\n child.segmentType === 'dynamic' &&\n child.paramName &&\n !child.paramPrefix &&\n !child.paramSuffix\n ) {\n chain.push(...groupChain);\n const prev = params[child.paramName];\n params[child.paramName] = part;\n if (matchNode(child, parts, index + 1, chain, params, requireTerminal)) {\n return true;\n }\n // Backtrack\n chain.length -= groupChain.length;\n if (prev !== undefined) {\n params[child.paramName] = prev;\n } else {\n delete params[child.paramName];\n }\n }\n }\n\n // 4. Catch-all segments ([...param]) — must be terminal unless the\n // caller passed requireTerminal:false (metadata route matching needs to\n // find the owning segment even when it has no page).\n for (const { child, groupChain } of effective) {\n if (\n child.segmentType === 'catch-all' &&\n child.paramName &&\n (!requireTerminal || isTerminal(child))\n ) {\n chain.push(...groupChain, child);\n params[child.paramName] = parts.slice(index);\n return true;\n }\n }\n\n // 5. Optional catch-all segments ([[...param]]) — same terminal rule\n for (const { child, groupChain } of effective) {\n if (\n child.segmentType === 'optional-catch-all' &&\n child.paramName &&\n (!requireTerminal || isTerminal(child))\n ) {\n chain.push(...groupChain, child);\n params[child.paramName] = parts.slice(index);\n return true;\n }\n }\n\n chain.pop();\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqDA,SAAgB,cACd,MACA,OACA,SAC+B;CAC/B,MAAM,QAA8B,CAAC;CACrC,MAAM,SAA4C,CAAC;CAGnD,IAAI,UAAU,MAAM,OAAO,GAAG,OAAO,QAFb,SAAS,mBAAmB,IAEQ,GAC1D,OAAO;EAAE;EAAO;CAAO;CAEzB,OAAO;AACT;;;;;;;;;AAsBA,SAAS,yBACP,MACA,aAAmC,CAAC,GACX;CACzB,MAAM,SAAkC,CAAC;CACzC,KAAK,MAAM,SAAS,KAAK,UACvB,IAAI,MAAM,gBAAgB,SAAS;EACjC,MAAM,SAAS,yBAAyB,OAAO,CAAC,GAAG,YAAY,KAAK,CAAC;EACrE,OAAO,KAAK,GAAG,MAAM;CACvB,OACE,OAAO,KAAK;EAAE;EAAO;CAAW,CAAC;CAGrC,OAAO;AACT;;AAGA,SAAS,WAAkB,MAAmC;CAC5D,OAAO,CAAC,EA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