@timber-js/app 0.2.0-alpha.230 → 0.2.0-alpha.231
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/agent-skill.md +13 -0
- package/dist/_chunks/{actions-DHum77eH.js → actions-CYjRMpZI.js} +3 -2
- package/dist/_chunks/{actions-DHum77eH.js.map → actions-CYjRMpZI.js.map} +1 -1
- package/dist/_chunks/{cli-check-B-JZkpBD.js → cli-check-BAKOSTkg.js} +2 -2
- package/dist/_chunks/{cli-check-B-JZkpBD.js.map → cli-check-BAKOSTkg.js.map} +1 -1
- package/dist/_chunks/codec-registry-C8hOGmZo.js +13 -0
- package/dist/_chunks/codec-registry-C8hOGmZo.js.map +1 -0
- package/dist/_chunks/{codegen-B9oWkWGf.js → codegen-vaCyFyVN.js} +67 -17
- package/dist/_chunks/codegen-vaCyFyVN.js.map +1 -0
- package/dist/_chunks/{convention-lint-CrDKERHg.js → convention-lint-D54k6uUM.js} +2 -2
- package/dist/_chunks/{convention-lint-CrDKERHg.js.map → convention-lint-D54k6uUM.js.map} +1 -1
- package/dist/_chunks/href-BtspoNc9.js +164 -0
- package/dist/_chunks/href-BtspoNc9.js.map +1 -0
- package/dist/_chunks/href-validation-DNg-zV7u.js +102 -0
- package/dist/_chunks/href-validation-DNg-zV7u.js.map +1 -0
- package/dist/_chunks/merge-search-params-7o_5yX0L.js +111 -0
- package/dist/_chunks/merge-search-params-7o_5yX0L.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/client/index.d.ts +2 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +3 -121
- package/dist/client/index.js.map +1 -1
- package/dist/client/link.d.ts +4 -25
- package/dist/client/link.d.ts.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/params/codec-registry.d.ts +21 -11
- package/dist/params/codec-registry.d.ts.map +1 -1
- package/dist/params/index.d.ts +0 -1
- package/dist/params/index.d.ts.map +1 -1
- package/dist/params/index.js +1 -2
- package/dist/params/index.js.map +1 -1
- package/dist/plugins/shims.d.ts.map +1 -1
- package/dist/routes/href.d.ts +124 -0
- package/dist/routes/href.d.ts.map +1 -0
- package/dist/routes/index.d.ts +4 -0
- package/dist/routes/index.d.ts.map +1 -0
- package/dist/routes/index.js +8 -0
- package/dist/routes/index.js.map +1 -0
- package/dist/routing/codegen.d.ts.map +1 -1
- package/dist/routing/index.js +1 -1
- package/dist/routing/link-codegen.d.ts +39 -8
- package/dist/routing/link-codegen.d.ts.map +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/internal.js +4 -6
- package/dist/server/internal.js.map +1 -1
- package/dist/server/param-coercion.d.ts +0 -7
- package/dist/server/param-coercion.d.ts.map +1 -1
- package/dist/server/rsc-entry/index.d.ts.map +1 -1
- package/dist/shared/href.d.ts +88 -0
- package/dist/shared/href.d.ts.map +1 -0
- package/docs/api/31-api-client.mdx +1 -1
- package/docs/api/35-api-typescript.mdx +47 -15
- package/docs/learn/07-typed-routes.mdx +75 -10
- package/package.json +5 -1
- package/src/client/browser-entry/index.ts +4 -4
- package/src/client/index.ts +3 -1
- package/src/client/link.tsx +5 -238
- package/src/index.ts +3 -0
- package/src/params/codec-registry.ts +24 -11
- package/src/params/index.ts +0 -1
- package/src/plugins/shims.ts +10 -0
- package/src/routes/href.ts +171 -0
- package/src/routes/index.ts +10 -0
- package/src/routing/codegen.ts +8 -1
- package/src/routing/link-codegen.ts +103 -37
- package/src/server/param-coercion.ts +5 -23
- package/src/server/rsc-entry/index.ts +6 -3
- package/src/server/ssr-entry.ts +2 -2
- package/src/shared/href.ts +257 -0
- package/dist/_chunks/codec-registry-CPc6bjVl.js +0 -20
- package/dist/_chunks/codec-registry-CPc6bjVl.js.map +0 -1
- package/dist/_chunks/codegen-B9oWkWGf.js.map +0 -1
- package/dist/_chunks/href-validation-CEZy1V-k.js +0 -210
- package/dist/_chunks/href-validation-CEZy1V-k.js.map +0 -1
|
@@ -42,37 +42,92 @@ import { classifyUrlSegment } from './segment-classify.ts';
|
|
|
42
42
|
*/
|
|
43
43
|
export const SEARCH_PARAMS_PROP_TYPE = 'string | Record<string, unknown>';
|
|
44
44
|
|
|
45
|
-
/**
|
|
46
|
-
|
|
47
|
-
|
|
45
|
+
/**
|
|
46
|
+
* Link base props in every emitted call signature: the real `LinkBaseProps`
|
|
47
|
+
* from `@timber-js/app/client`, by reference.
|
|
48
|
+
*
|
|
49
|
+
* Until TIM-1621 this was an inline copy of the type. It drifted —
|
|
50
|
+
* `replace` and `transitionTypes` were never added, so typed `<Link>`
|
|
51
|
+
* rejected both — and its `onNavigate` came from `./client/link.js`, a
|
|
52
|
+
* path relative to `.timber/` that never resolved, so that prop was
|
|
53
|
+
* silently `any`. A reference cannot drift.
|
|
54
|
+
*/
|
|
55
|
+
export const LINK_BASE_PROPS_TYPE = "import('@timber-js/app/client').LinkBaseProps";
|
|
56
|
+
|
|
57
|
+
// eslint-disable-next-line no-template-curly-in-string -- codegen output
|
|
58
|
+
const DOLLAR_STRING = '${string}';
|
|
48
59
|
|
|
49
60
|
/**
|
|
50
|
-
* Build
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
61
|
+
* Build the TypeScript type of every URL a route resolves to — a type
|
|
62
|
+
* EXPRESSION, ready to drop into a declaration:
|
|
63
|
+
*
|
|
64
|
+
* '/venues' → '/venues'
|
|
65
|
+
* '/products/[id]' → `/products/${string}`
|
|
66
|
+
* '/img-[id].png' → `/img-${string}.png`
|
|
67
|
+
* '/blog/[...slug]' → `/blog/${string}`
|
|
68
|
+
* '/docs/[[...path]]' → '/docs' | `/docs/${string}`
|
|
69
|
+
* '/[[...path]]' → '/' | `/${string}`
|
|
70
|
+
*
|
|
71
|
+
* An optional catch-all that is omitted drops its segment AND its slash
|
|
72
|
+
* (`interpolateParams('/docs/[[...path]]', {})` is `/docs`), and
|
|
73
|
+
* `/docs/${string}` does not match `/docs` — so a trailing optional
|
|
74
|
+
* catch-all needs the bare prefix as a second member. Before TIM-1621 this
|
|
75
|
+
* emitted only the template, and `<Link href="/docs">` matched no route.
|
|
76
|
+
*
|
|
77
|
+
* Emitted once per route as `Routes[P]['href']` — the type `href()`
|
|
78
|
+
* returns — and reused for `<Link>`'s resolved-template variants, so the
|
|
79
|
+
* two cannot disagree about what a route's URLs look like.
|
|
55
80
|
*/
|
|
56
|
-
export function buildResolvedPattern(route: RouteEntry): string
|
|
81
|
+
export function buildResolvedPattern(route: RouteEntry): string {
|
|
82
|
+
return resolvedMembers(route)
|
|
83
|
+
.map((m) => (m.includes(DOLLAR_STRING) ? `\`${m}\`` : `'${m}'`))
|
|
84
|
+
.join(' | ');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* `<Link>`'s query-bearing href type: each member of `buildResolvedPattern`
|
|
89
|
+
* that ends in a static part, with `?${string}` appended. `href(pattern,
|
|
90
|
+
* params, search)` can return such a value, and a `/venues?${string}` is
|
|
91
|
+
* not wide `string`, so without this it would match no Link overload.
|
|
92
|
+
* `null` when every member ends in `${string}` (which already matches a query).
|
|
93
|
+
*/
|
|
94
|
+
export function buildResolvedPatternWithQuery(route: RouteEntry): string | null {
|
|
95
|
+
// A member ending in `${string}` already matches any query, so it needs no
|
|
96
|
+
// `?` form — emitting one anyway doubled the union and pushed real routes
|
|
97
|
+
// out of the truncated "not assignable to" list in diagnostics.
|
|
98
|
+
const members = resolvedMembers(route).filter((m) => !m.endsWith(DOLLAR_STRING));
|
|
99
|
+
if (members.length === 0) return null;
|
|
100
|
+
return members.map((m) => `\`${m}?${DOLLAR_STRING}\``).join(' | ');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Template-literal bodies (no delimiters) of a route's URLs: one per
|
|
105
|
+
* route, plus the bare prefix for a trailing optional catch-all.
|
|
106
|
+
*/
|
|
107
|
+
function resolvedMembers(route: RouteEntry): string[] {
|
|
57
108
|
const parts = route.urlPath.split('/');
|
|
58
|
-
|
|
109
|
+
let omittedAt: number | null = null;
|
|
110
|
+
const templateParts = parts.map((part, i) => {
|
|
59
111
|
const seg = classifyUrlSegment(part);
|
|
60
112
|
switch (seg.kind) {
|
|
61
|
-
case 'catch-all':
|
|
62
113
|
case 'optional-catch-all':
|
|
63
|
-
//
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
114
|
+
// Only a trailing optional catch-all is valid; omitted, it takes the
|
|
115
|
+
// slash before it along.
|
|
116
|
+
if (i === parts.length - 1) omittedAt = i;
|
|
117
|
+
return DOLLAR_STRING;
|
|
118
|
+
case 'catch-all':
|
|
119
|
+
return DOLLAR_STRING;
|
|
120
|
+
case 'dynamic':
|
|
121
|
+
return `${seg.prefix ?? ''}${DOLLAR_STRING}${seg.suffix ?? ''}`;
|
|
71
122
|
default:
|
|
72
123
|
return part;
|
|
73
124
|
}
|
|
74
125
|
});
|
|
75
|
-
|
|
126
|
+
const template = templateParts.join('/');
|
|
127
|
+
if (omittedAt === null) return [template];
|
|
128
|
+
// Built from the TEMPLATE parts, so a dynamic ancestor stays a placeholder:
|
|
129
|
+
// `/[org]/[[...path]]` omitted is `/${string}`, not the literal `/[org]`.
|
|
130
|
+
return [templateParts.slice(0, omittedAt).join('/') || '/', template];
|
|
76
131
|
}
|
|
77
132
|
|
|
78
133
|
/**
|
|
@@ -210,9 +265,9 @@ export function formatTypedLinkOverloads(routes: RouteEntry[], hasSchema?: boole
|
|
|
210
265
|
const baseProps = LINK_BASE_PROPS_TYPE;
|
|
211
266
|
|
|
212
267
|
// Build the union variants. Each route contributes one variant for the
|
|
213
|
-
// pattern href (e.g. '/products/[id]')
|
|
214
|
-
//
|
|
215
|
-
// `/
|
|
268
|
+
// pattern href (e.g. '/products/[id]'); for dynamic routes, a variant for
|
|
269
|
+
// the resolved-template href (e.g. `/products/${string}`); and, when its
|
|
270
|
+
// URL can end in a static part, a query-bearing variant (`/venues?${string}`).
|
|
216
271
|
//
|
|
217
272
|
// The PATTERN variant must be listed BEFORE the resolved-template
|
|
218
273
|
// variant for the same route so that when the user writes the literal
|
|
@@ -233,7 +288,7 @@ export function formatTypedLinkOverloads(routes: RouteEntry[], hasSchema?: boole
|
|
|
233
288
|
|
|
234
289
|
// TIM-1343: searchParams is no longer typed per-route. There is no
|
|
235
290
|
// convention file to read a definition from, so codegen has nothing to
|
|
236
|
-
// narrow with — the value is either a
|
|
291
|
+
// narrow with — the value is either a query string built by
|
|
237
292
|
// `definition.buildSearchParams()` (which type-checks its own
|
|
238
293
|
// `Partial<T>` at that call) or a plain String()-coerced record.
|
|
239
294
|
const searchParamsProp = `searchParams?: ${SEARCH_PARAMS_PROP_TYPE}`;
|
|
@@ -244,20 +299,31 @@ export function formatTypedLinkOverloads(routes: RouteEntry[], hasSchema?: boole
|
|
|
244
299
|
);
|
|
245
300
|
|
|
246
301
|
// Resolved-template variant SECOND (looser, matches interpolated hrefs).
|
|
302
|
+
// TIM-835: `Record<string, never>` for segmentParams forbids ANY
|
|
303
|
+
// provided keys on the resolved-template variant. Without this, the
|
|
304
|
+
// resolved-template would shadow the pattern variant for literal pattern
|
|
305
|
+
// hrefs (`<Link href="/products/[id]" segmentParams={...} />`) because
|
|
306
|
+
// both variants accept the literal '/products/[id]' and the looser
|
|
307
|
+
// variant would silently swallow segmentParams type errors.
|
|
247
308
|
if (hasDynamicParams) {
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
309
|
+
variants.push(
|
|
310
|
+
`${baseProps} & { href: ${buildResolvedPattern(route)}; segmentParams?: Record<string, never>; ${searchParamsProp} }`
|
|
311
|
+
);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// Query-bearing variant LAST (TIM-1621): what `href(pattern, params,
|
|
315
|
+
// search)` returns, and any literal href with an inline query, for URLs
|
|
316
|
+
// that end in a static part (`/venues?…`, `/docs?…`). It forbids both
|
|
317
|
+
// props: the params are already interpolated and the query is already in
|
|
318
|
+
// the string. A template ending in `${string}` already matches a query,
|
|
319
|
+
// so those routes get no `?` variant — and their template variant still
|
|
320
|
+
// accepts `searchParams`, which template types cannot prevent. That
|
|
321
|
+
// combination throws in `resolveHref` at render instead.
|
|
322
|
+
const queryPattern = buildResolvedPatternWithQuery(route);
|
|
323
|
+
if (queryPattern) {
|
|
324
|
+
variants.push(
|
|
325
|
+
`${baseProps} & { href: ${queryPattern}; segmentParams?: Record<string, never>; searchParams?: never }`
|
|
326
|
+
);
|
|
261
327
|
}
|
|
262
328
|
}
|
|
263
329
|
|
|
@@ -12,10 +12,10 @@
|
|
|
12
12
|
* See design/07-routing.md §"Where Coercion Runs".
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
|
-
import type { Codec } from '../codec.ts';
|
|
16
15
|
import type { SegmentType } from '../routing/types.ts';
|
|
17
16
|
import { effectiveUrlSegment } from '../routing/segment-classify.ts';
|
|
18
17
|
import { toBracketKey } from '../params/resolve-schema.ts';
|
|
18
|
+
import { getSchemaCodec, hasSchemaCodecs } from '../params/codec-registry.ts';
|
|
19
19
|
import type { RouteMatch } from './pipeline.ts';
|
|
20
20
|
import { normalizeParamValue, type CoercedParams } from '../shared/param-value.ts';
|
|
21
21
|
/**
|
|
@@ -52,22 +52,6 @@ export function warnParamCoercionFailure(
|
|
|
52
52
|
}
|
|
53
53
|
import { isDebug } from './debug.ts';
|
|
54
54
|
|
|
55
|
-
// ---------------------------------------------------------------------------
|
|
56
|
-
// Module-level global codec store (TIM-931)
|
|
57
|
-
// ---------------------------------------------------------------------------
|
|
58
|
-
|
|
59
|
-
/** Global schema codecs, set once at startup from virtual:timber-schema. */
|
|
60
|
-
let _globalCodecs: Record<string, Codec<unknown>> | null = null;
|
|
61
|
-
|
|
62
|
-
/**
|
|
63
|
-
* Register the global schema codecs. Called once from the RSC entry
|
|
64
|
-
* at server startup when app/schema.ts provides segment param codecs.
|
|
65
|
-
* @internal
|
|
66
|
-
*/
|
|
67
|
-
export function setGlobalSchemaCodecs(codecs: Record<string, Codec<unknown>> | null): void {
|
|
68
|
-
_globalCodecs = codecs;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
55
|
/**
|
|
72
56
|
* Coerce raw slot params through global schema codecs.
|
|
73
57
|
*
|
|
@@ -97,8 +81,7 @@ export function coerceSlotParams(
|
|
|
97
81
|
}>,
|
|
98
82
|
rawParams: Record<string, string | string[]>
|
|
99
83
|
): CoercedParams {
|
|
100
|
-
|
|
101
|
-
if (!globalCodecs) return rawParams;
|
|
84
|
+
if (!hasSchemaCodecs()) return rawParams;
|
|
102
85
|
|
|
103
86
|
const result: CoercedParams = Object.create(null);
|
|
104
87
|
for (const key of Object.keys(rawParams)) {
|
|
@@ -109,7 +92,7 @@ export function coerceSlotParams(
|
|
|
109
92
|
const segment = effectiveUrlSegment(node);
|
|
110
93
|
if (!segment.paramName) continue;
|
|
111
94
|
const bracketKey = toBracketKey(segment.segmentType, segment.paramName);
|
|
112
|
-
const codec =
|
|
95
|
+
const codec = getSchemaCodec(bracketKey);
|
|
113
96
|
if (!codec) continue;
|
|
114
97
|
|
|
115
98
|
const key = segment.paramName;
|
|
@@ -166,7 +149,6 @@ export function coerceSlotParams(
|
|
|
166
149
|
*/
|
|
167
150
|
// eslint-disable-next-line @typescript-eslint/require-await -- see above
|
|
168
151
|
export async function coerceSegmentParams(match: RouteMatch): Promise<CoercedParams> {
|
|
169
|
-
const globalCodecs = _globalCodecs;
|
|
170
152
|
// Always a null-prototype record, whether or not any segment has a codec.
|
|
171
153
|
const mergeTarget: CoercedParams = Object.create(null);
|
|
172
154
|
for (const key of Object.keys(match.rawSegmentParams)) {
|
|
@@ -179,7 +161,7 @@ export async function coerceSegmentParams(match: RouteMatch): Promise<CoercedPar
|
|
|
179
161
|
// instead of per-segment params.ts files. The global codec map is keyed
|
|
180
162
|
// by bracket name (e.g. '[id]', '[...slug]') to avoid collisions between
|
|
181
163
|
// distinct segment types that share a param name.
|
|
182
|
-
if (
|
|
164
|
+
if (hasSchemaCodecs()) {
|
|
183
165
|
for (const node of match.segments) {
|
|
184
166
|
// Read through `effectiveUrlSegment` for the same reason
|
|
185
167
|
// `coerceSlotParams` does: an intercepting node's own `segmentType` is
|
|
@@ -193,7 +175,7 @@ export async function coerceSegmentParams(match: RouteMatch): Promise<CoercedPar
|
|
|
193
175
|
const segment = effectiveUrlSegment(node);
|
|
194
176
|
if (!segment.paramName) continue;
|
|
195
177
|
const bracketKey = toBracketKey(segment.segmentType, segment.paramName);
|
|
196
|
-
const codec =
|
|
178
|
+
const codec = getSchemaCodec(bracketKey);
|
|
197
179
|
if (!codec) continue; // no codec in schema → keep raw string
|
|
198
180
|
|
|
199
181
|
const key = segment.paramName;
|
|
@@ -48,7 +48,8 @@ import { collectEarlyHintHeaders } from '../early-hints.ts';
|
|
|
48
48
|
import { buildClientScripts } from '../html-injectors.ts';
|
|
49
49
|
import type { InterceptionContext, PipelineConfig, RouteMatch } from '../pipeline.ts';
|
|
50
50
|
import { createPipeline } from '../pipeline.ts';
|
|
51
|
-
import { coerceSegmentParams
|
|
51
|
+
import { coerceSegmentParams } from '../param-coercion.ts';
|
|
52
|
+
import { setSchemaCodecs } from '../../params/codec-registry.ts';
|
|
52
53
|
import { createMetadataRouteMatcher, createRouteMatcher } from '../route-matcher.ts';
|
|
53
54
|
import { createInterceptedRouteMatcher } from '../children-interception.ts';
|
|
54
55
|
import { initDevTracing } from '../tracing.ts';
|
|
@@ -516,8 +517,10 @@ export function __timber_generateStaticSite(
|
|
|
516
517
|
}
|
|
517
518
|
|
|
518
519
|
// Schema codecs are needed by both the capture path (param coercion) and
|
|
519
|
-
// the request handler, so register them unconditionally.
|
|
520
|
-
|
|
520
|
+
// the request handler, so register them unconditionally. The same store
|
|
521
|
+
// serves URL construction (`href()`, server-rendered `<Link>`), so codecs
|
|
522
|
+
// serialize here exactly as they do in SSR and the browser (TIM-1621).
|
|
523
|
+
setSchemaCodecs(globalSchemaCodecs);
|
|
521
524
|
|
|
522
525
|
// Singleflight timeout protects against deadlocked cache calls — needed
|
|
523
526
|
// in both capture mode (components may call timber.cache) and normal mode.
|
package/src/server/ssr-entry.ts
CHANGED
|
@@ -18,8 +18,8 @@ import config from 'virtual:timber-config';
|
|
|
18
18
|
// use codec.serialize() instead of String() fallback for URL interpolation.
|
|
19
19
|
// @ts-expect-error — virtual module provided by timber-routing plugin
|
|
20
20
|
import schemaCodecs from 'virtual:timber-schema';
|
|
21
|
-
import {
|
|
22
|
-
|
|
21
|
+
import { setSchemaCodecs } from '../params/codec-registry.ts';
|
|
22
|
+
setSchemaCodecs(schemaCodecs);
|
|
23
23
|
import { createFromReadableStream, createFromNodeStream } from '../rsc-runtime/ssr.ts';
|
|
24
24
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
25
25
|
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Route-pattern interpolation and query serialization — the runtime behind
|
|
3
|
+
* `<Link segmentParams searchParams>` and `href()` from `@timber-js/app/routes`.
|
|
4
|
+
*
|
|
5
|
+
* Directive-free and isomorphic: no `'use client'`, no React, no ALS. It
|
|
6
|
+
* lived in `client/link.tsx` until TIM-1621, where the `'use client'`
|
|
7
|
+
* directive turned every import from a server component, middleware or
|
|
8
|
+
* action into a client-reference stub — so nothing on the server could
|
|
9
|
+
* build a URL with it.
|
|
10
|
+
*
|
|
11
|
+
* Segment values serialize through the app/schema.ts codecs registered in
|
|
12
|
+
* `params/codec-registry.ts`. Every entry (RSC, SSR, browser) registers
|
|
13
|
+
* them, so a URL built here is the same in every environment.
|
|
14
|
+
*
|
|
15
|
+
* Design docs: design/09-typescript.md §"Typed Routes",
|
|
16
|
+
* design/41-global-params.md §"Link Component".
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { classifyUrlSegment, type UrlSegment } from '../routing/segment-classify.ts';
|
|
20
|
+
import { getSchemaCodec } from '../params/codec-registry.ts';
|
|
21
|
+
import { validateNavigationHref } from './href-validation.ts';
|
|
22
|
+
|
|
23
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
24
|
+
export type ParamValue = string | number | string[] | { toString(): string; [key: string]: any };
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* A query, in one of two shapes discriminated by `typeof === 'string'`:
|
|
28
|
+
*
|
|
29
|
+
* 1. Codec-aware (preferred) — the string `definition.buildSearchParams()`
|
|
30
|
+
* returns. It applies each codec, honours `withUrlKey` aliases, and omits
|
|
31
|
+
* values equal to their default. Passed through untouched.
|
|
32
|
+
*
|
|
33
|
+
* 2. Plain record (escape hatch) — every value is String()-coerced, arrays
|
|
34
|
+
* repeat their key, null/undefined are skipped. No codecs, no aliases, so
|
|
35
|
+
* it must not carry keys a definition owns: `{ search: 'x' }` emits
|
|
36
|
+
* `?search=x` where the definition would emit `?q=x`.
|
|
37
|
+
*
|
|
38
|
+
* Why a STRING and not a URLSearchParams: a Link is routinely rendered by a
|
|
39
|
+
* Server Component, so this value crosses the RSC Flight boundary before the
|
|
40
|
+
* client Link runs. `URLSearchParams` is iterable, and React serializes any
|
|
41
|
+
* iterable as an array — so the prop arrived as `[['pg','2'], …]`, fell into
|
|
42
|
+
* the plain-object branch, and rendered `?0=pg&0=2`. Strings survive Flight
|
|
43
|
+
* unchanged. (Codex P1 on PR #1021; reproduced against a live dev server.)
|
|
44
|
+
*
|
|
45
|
+
* See design/23-search-params.md §"Link Integration".
|
|
46
|
+
*/
|
|
47
|
+
export type SearchParamsArg = string | Record<string, unknown>;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Parse a route pattern's path portion into classified segments.
|
|
51
|
+
* Uses the shared character-based classifier.
|
|
52
|
+
*/
|
|
53
|
+
export function parseSegments(pattern: string): UrlSegment[] {
|
|
54
|
+
return pattern.split('/').filter(Boolean).map(classifyUrlSegment);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Encode a codec's path-shaped output (it may contain '/') segment by segment.
|
|
59
|
+
*/
|
|
60
|
+
function encodePath(serialized: string): string {
|
|
61
|
+
return serialized.split('/').map(encodeURIComponent).join('/');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Resolve a single classified segment into its string representation.
|
|
66
|
+
* Returns null for optional catch-all with no value (filtered out before join).
|
|
67
|
+
*
|
|
68
|
+
* When schema codecs are registered (from virtual:timber-schema), uses
|
|
69
|
+
* codec.serialize() for URL construction instead of plain String().
|
|
70
|
+
*/
|
|
71
|
+
function resolveSegment(
|
|
72
|
+
seg: UrlSegment,
|
|
73
|
+
params: Record<string, ParamValue>,
|
|
74
|
+
pattern: string
|
|
75
|
+
): string | null {
|
|
76
|
+
switch (seg.kind) {
|
|
77
|
+
case 'static':
|
|
78
|
+
return seg.value;
|
|
79
|
+
|
|
80
|
+
case 'optional-catch-all': {
|
|
81
|
+
const value = params[seg.name];
|
|
82
|
+
if (value === undefined || (Array.isArray(value) && value.length === 0)) {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
const codec = getSchemaCodec(`[[...${seg.name}]]`);
|
|
86
|
+
if (codec) {
|
|
87
|
+
const serialized = codec.serialize(value);
|
|
88
|
+
return serialized ? encodePath(serialized) : null;
|
|
89
|
+
}
|
|
90
|
+
const segments = Array.isArray(value) ? value : [value];
|
|
91
|
+
return segments.map(encodeURIComponent).join('/');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
case 'catch-all': {
|
|
95
|
+
const value = params[seg.name];
|
|
96
|
+
if (value === undefined) {
|
|
97
|
+
throw new Error(
|
|
98
|
+
`Missing required catch-all segment param "${seg.name}" for pattern "${pattern}".`
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
const codec = getSchemaCodec(`[...${seg.name}]`);
|
|
102
|
+
if (codec) {
|
|
103
|
+
const serialized = codec.serialize(value);
|
|
104
|
+
if (!serialized) {
|
|
105
|
+
throw new Error(
|
|
106
|
+
`Catch-all segment param "${seg.name}" codec returned null for pattern "${pattern}".`
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
return encodePath(serialized);
|
|
110
|
+
}
|
|
111
|
+
const segments = Array.isArray(value) ? value : [value];
|
|
112
|
+
if (segments.length === 0) {
|
|
113
|
+
throw new Error(
|
|
114
|
+
`Catch-all segment param "${seg.name}" must have at least one segment for pattern "${pattern}".`
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
return segments.map(encodeURIComponent).join('/');
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
case 'dynamic': {
|
|
121
|
+
const value = params[seg.name];
|
|
122
|
+
if (value === undefined) {
|
|
123
|
+
throw new Error(`Missing required segment param "${seg.name}" for pattern "${pattern}".`);
|
|
124
|
+
}
|
|
125
|
+
if (Array.isArray(value)) {
|
|
126
|
+
throw new Error(
|
|
127
|
+
`Segment param "${seg.name}" expected a string but received an array for pattern "${pattern}".`
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
const codec = getSchemaCodec(`[${seg.name}]`);
|
|
131
|
+
const str = codec ? (codec.serialize(value) ?? String(value)) : String(value);
|
|
132
|
+
return (seg.prefix ?? '') + encodeURIComponent(str) + (seg.suffix ?? '');
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Split a URL pattern into the path portion and any trailing ?query/#hash suffix.
|
|
139
|
+
* Uses URL parsing for correctness rather than manual index arithmetic.
|
|
140
|
+
*/
|
|
141
|
+
function splitPatternSuffix(pattern: string): [path: string, suffix: string] {
|
|
142
|
+
if (!pattern.includes('?') && !pattern.includes('#')) {
|
|
143
|
+
return [pattern, ''];
|
|
144
|
+
}
|
|
145
|
+
const url = new URL(pattern, 'http://x');
|
|
146
|
+
const suffix = url.search + url.hash;
|
|
147
|
+
const path = pattern.slice(0, pattern.length - suffix.length);
|
|
148
|
+
return [path, suffix];
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Interpolate dynamic segments in a route pattern with actual values.
|
|
153
|
+
* e.g. interpolateParams("/products/[id]", { id: "123" }) → "/products/123"
|
|
154
|
+
*
|
|
155
|
+
* Supports:
|
|
156
|
+
* - [param] → single segment (with optional static prefix/suffix)
|
|
157
|
+
* - [...param] → catch-all (joined with /)
|
|
158
|
+
* - [[...param]] → optional catch-all (omitted if undefined/empty)
|
|
159
|
+
*
|
|
160
|
+
* Every value is percent-encoded per segment; catch-all elements are encoded
|
|
161
|
+
* individually, so a value can never introduce a path separator of its own.
|
|
162
|
+
*/
|
|
163
|
+
export function interpolateParams(pattern: string, params: Record<string, ParamValue>): string {
|
|
164
|
+
const [pathPart, suffix] = splitPatternSuffix(pattern);
|
|
165
|
+
|
|
166
|
+
const resolved = parseSegments(pathPart)
|
|
167
|
+
.map((seg) => resolveSegment(seg, params, pattern))
|
|
168
|
+
.filter((s): s is string => s !== null);
|
|
169
|
+
return ('/' + resolved.join('/') || '/') + suffix;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Tolerate a leading '?'. `buildSearchParams()` never emits one, but callers
|
|
174
|
+
* hand-rolling a query string reasonably might, and silently producing
|
|
175
|
+
* `?%3Fa=b` for it would be a worse failure than accepting both.
|
|
176
|
+
*/
|
|
177
|
+
function stripLeadingQuestionMark(qs: string): string {
|
|
178
|
+
return qs.startsWith('?') ? qs.slice(1) : qs;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Escape-hatch serialization for a plain object: String()-coerce every
|
|
183
|
+
* value, append arrays as repeated keys, skip null/undefined.
|
|
184
|
+
*
|
|
185
|
+
* Deliberately codec-free and alias-free — see `SearchParamsArg`.
|
|
186
|
+
*/
|
|
187
|
+
function coerceToQueryString(values: Record<string, unknown>): string {
|
|
188
|
+
const usp = new URLSearchParams();
|
|
189
|
+
for (const [key, val] of Object.entries(values)) {
|
|
190
|
+
if (val === undefined || val === null) continue;
|
|
191
|
+
if (Array.isArray(val)) {
|
|
192
|
+
for (const item of val) usp.append(key, String(item));
|
|
193
|
+
} else {
|
|
194
|
+
usp.set(key, String(val));
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return usp.toString();
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Resolve an href from a pattern, its segment params and a query.
|
|
202
|
+
*
|
|
203
|
+
* - `params` given → the href is interpolated as a pattern
|
|
204
|
+
* - `searchParams` given → serialized and appended (an empty query appends
|
|
205
|
+
* nothing, not a bare `?`)
|
|
206
|
+
* - a query in both `href` and `searchParams` throws: they are exclusive
|
|
207
|
+
*
|
|
208
|
+
* Does not validate the result; callers that hand it to a navigation sink
|
|
209
|
+
* run `validateNavigationHref` on it.
|
|
210
|
+
*/
|
|
211
|
+
export function resolveHref(
|
|
212
|
+
href: string,
|
|
213
|
+
params?: Record<string, ParamValue>,
|
|
214
|
+
searchParams?: SearchParamsArg
|
|
215
|
+
): string {
|
|
216
|
+
const resolvedPath = params ? interpolateParams(href, params) : href;
|
|
217
|
+
if (!searchParams) return resolvedPath;
|
|
218
|
+
|
|
219
|
+
if (resolvedPath.includes('?')) {
|
|
220
|
+
throw new Error(
|
|
221
|
+
`Received both searchParams and a query string in href "${resolvedPath}". ` +
|
|
222
|
+
'These are mutually exclusive — use one or the other.'
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// `typeof` is the only discriminator that survives the RSC Flight
|
|
227
|
+
// boundary — see `SearchParamsArg`.
|
|
228
|
+
const qs =
|
|
229
|
+
typeof searchParams === 'string'
|
|
230
|
+
? stripLeadingQuestionMark(searchParams)
|
|
231
|
+
: coerceToQueryString(searchParams);
|
|
232
|
+
|
|
233
|
+
return qs ? `${resolvedPath}?${qs}` : resolvedPath;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* The runtime of `href()` (@timber-js/app/routes), untyped: the typed
|
|
238
|
+
* surface lives in `routes/href.ts` and only narrows what may be passed.
|
|
239
|
+
*
|
|
240
|
+
* A pattern with no dynamic segment is already its URL. One with any —
|
|
241
|
+
* including a lone optional catch-all called with no params — is
|
|
242
|
+
* interpolated, or `/docs/[[...path]]` would come back verbatim. The query
|
|
243
|
+
* is appended exactly as `<Link searchParams>` appends it, and the result is
|
|
244
|
+
* validated like every navigation sink: segment values that would make a
|
|
245
|
+
* protocol-relative URL (`/[...slug]` with `['', 'evil.com']` →
|
|
246
|
+
* `//evil.com`) throw instead of returning an open redirect.
|
|
247
|
+
*/
|
|
248
|
+
export function buildHref(
|
|
249
|
+
pattern: string,
|
|
250
|
+
segmentParams?: Record<string, ParamValue>,
|
|
251
|
+
searchParams?: SearchParamsArg
|
|
252
|
+
): string {
|
|
253
|
+
const dynamic = parseSegments(pattern).some((seg) => seg.kind !== 'static');
|
|
254
|
+
const result = resolveHref(pattern, dynamic ? (segmentParams ?? {}) : undefined, searchParams);
|
|
255
|
+
validateNavigationHref(result);
|
|
256
|
+
return result;
|
|
257
|
+
}
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
// src/params/codec-registry.ts
|
|
2
|
-
var _codecs = null;
|
|
3
|
-
/**
|
|
4
|
-
* Register the resolved schema codecs for use by Link's URL interpolation.
|
|
5
|
-
* Called once at startup from the browser entry or RSC entry.
|
|
6
|
-
* @internal
|
|
7
|
-
*/
|
|
8
|
-
function setLinkCodecs(codecs) {
|
|
9
|
-
_codecs = codecs;
|
|
10
|
-
}
|
|
11
|
-
/**
|
|
12
|
-
* Look up a codec by bracket key (e.g. '[id]', '[...slug]').
|
|
13
|
-
* Returns undefined if no schema is registered or the key has no codec.
|
|
14
|
-
*/
|
|
15
|
-
function getLinkCodec(bracketKey) {
|
|
16
|
-
return _codecs?.[bracketKey] ?? void 0;
|
|
17
|
-
}
|
|
18
|
-
export { setLinkCodecs as n, getLinkCodec as t };
|
|
19
|
-
|
|
20
|
-
//# sourceMappingURL=codec-registry-CPc6bjVl.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"codec-registry-CPc6bjVl.js","names":[],"sources":["../../src/params/codec-registry.ts"],"sourcesContent":["/**\n * Client-side registry for schema segment param codecs.\n *\n * The Link component uses codec `serialize` functions to convert typed\n * segment param values back to URL-safe strings. Without this registry,\n * Link falls back to `String(value)` — which works for simple types\n * but breaks for custom codecs (e.g., Date → '2026-04-10').\n *\n * Populated at startup by the browser entry importing `virtual:timber-schema`.\n * Also usable on the server (isomorphic).\n *\n * Design doc: design/41-global-params.md §\"Link Component\"\n */\n\nimport type { Codec } from '../codec.ts';\n\nlet _codecs: Record<string, Codec<unknown>> | null = null;\n\n/**\n * Register the resolved schema codecs for use by Link's URL interpolation.\n * Called once at startup from the browser entry or RSC entry.\n * @internal\n */\nexport function setLinkCodecs(codecs: Record<string, Codec<unknown>> | null): void {\n _codecs = codecs;\n}\n\n/**\n * Look up a codec by bracket key (e.g. '[id]', '[...slug]').\n * Returns undefined if no schema is registered or the key has no codec.\n */\nexport function getLinkCodec(bracketKey: string): Codec<unknown> | undefined {\n return _codecs?.[bracketKey] ?? undefined;\n}\n"],"mappings":";AAgBA,IAAI,UAAiD;;;;;;AAOrD,SAAgB,cAAc,QAAqD;CACjF,UAAU;AACZ;;;;;AAMA,SAAgB,aAAa,YAAgD;CAC3E,OAAO,UAAU,eAAe,KAAA;AAClC"}
|