@timber-js/app 0.2.0-alpha.230 → 0.2.0-alpha.232

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.
Files changed (98) hide show
  1. package/agent-skill.md +13 -0
  2. package/dist/_chunks/{actions-DHum77eH.js → actions-CYjRMpZI.js} +3 -2
  3. package/dist/_chunks/{actions-DHum77eH.js.map → actions-CYjRMpZI.js.map} +1 -1
  4. package/dist/_chunks/{cli-check-B-JZkpBD.js → cli-check-BAKOSTkg.js} +2 -2
  5. package/dist/_chunks/{cli-check-B-JZkpBD.js.map → cli-check-BAKOSTkg.js.map} +1 -1
  6. package/dist/_chunks/codec-registry-C8hOGmZo.js +13 -0
  7. package/dist/_chunks/codec-registry-C8hOGmZo.js.map +1 -0
  8. package/dist/_chunks/{codegen-B9oWkWGf.js → codegen-vaCyFyVN.js} +67 -17
  9. package/dist/_chunks/codegen-vaCyFyVN.js.map +1 -0
  10. package/dist/_chunks/{convention-lint-CrDKERHg.js → convention-lint-D54k6uUM.js} +2 -2
  11. package/dist/_chunks/{convention-lint-CrDKERHg.js.map → convention-lint-D54k6uUM.js.map} +1 -1
  12. package/dist/_chunks/href-BtspoNc9.js +164 -0
  13. package/dist/_chunks/href-BtspoNc9.js.map +1 -0
  14. package/dist/_chunks/href-validation-DNg-zV7u.js +102 -0
  15. package/dist/_chunks/href-validation-DNg-zV7u.js.map +1 -0
  16. package/dist/_chunks/merge-search-params-7o_5yX0L.js +111 -0
  17. package/dist/_chunks/merge-search-params-7o_5yX0L.js.map +1 -0
  18. package/dist/_chunks/{use-query-states-pkDV-jSg.js → use-query-states-D3MMl-KM.js} +12 -12
  19. package/dist/_chunks/use-query-states-D3MMl-KM.js.map +1 -0
  20. package/dist/cli.js +1 -1
  21. package/dist/client/index.d.ts +2 -1
  22. package/dist/client/index.d.ts.map +1 -1
  23. package/dist/client/index.js +4 -122
  24. package/dist/client/index.js.map +1 -1
  25. package/dist/client/internal.js +1 -1
  26. package/dist/client/link.d.ts +4 -25
  27. package/dist/client/link.d.ts.map +1 -1
  28. package/dist/client/nuqs-adapter.d.ts.map +1 -1
  29. package/dist/client/use-query-states.d.ts +1 -1
  30. package/dist/client/use-query-states.d.ts.map +1 -1
  31. package/dist/index.d.ts +2 -0
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +57 -1
  34. package/dist/index.js.map +1 -1
  35. package/dist/params/codec-registry.d.ts +21 -11
  36. package/dist/params/codec-registry.d.ts.map +1 -1
  37. package/dist/params/index.d.ts +0 -1
  38. package/dist/params/index.d.ts.map +1 -1
  39. package/dist/params/index.js +1 -2
  40. package/dist/params/index.js.map +1 -1
  41. package/dist/plugins/node-flight-builds.d.ts +38 -0
  42. package/dist/plugins/node-flight-builds.d.ts.map +1 -0
  43. package/dist/plugins/shims.d.ts.map +1 -1
  44. package/dist/routes/href.d.ts +124 -0
  45. package/dist/routes/href.d.ts.map +1 -0
  46. package/dist/routes/index.d.ts +4 -0
  47. package/dist/routes/index.d.ts.map +1 -0
  48. package/dist/routes/index.js +8 -0
  49. package/dist/routes/index.js.map +1 -0
  50. package/dist/routing/codegen.d.ts.map +1 -1
  51. package/dist/routing/index.js +1 -1
  52. package/dist/routing/link-codegen.d.ts +39 -8
  53. package/dist/routing/link-codegen.d.ts.map +1 -1
  54. package/dist/search-params/define.d.ts +37 -17
  55. package/dist/search-params/define.d.ts.map +1 -1
  56. package/dist/search-params/index.d.ts +1 -0
  57. package/dist/search-params/index.d.ts.map +1 -1
  58. package/dist/search-params/index.js +3 -2
  59. package/dist/search-params/index.js.map +1 -1
  60. package/dist/server/index.js +1 -1
  61. package/dist/server/internal.js +4 -6
  62. package/dist/server/internal.js.map +1 -1
  63. package/dist/server/param-coercion.d.ts +0 -7
  64. package/dist/server/param-coercion.d.ts.map +1 -1
  65. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  66. package/dist/shared/href.d.ts +88 -0
  67. package/dist/shared/href.d.ts.map +1 -0
  68. package/docs/api/31-api-client.mdx +1 -1
  69. package/docs/api/35-api-typescript.mdx +47 -15
  70. package/docs/learn/06-typed-params.mdx +33 -0
  71. package/docs/learn/07-typed-routes.mdx +75 -10
  72. package/package.json +6 -2
  73. package/src/client/browser-entry/index.ts +4 -4
  74. package/src/client/index.ts +3 -1
  75. package/src/client/link.tsx +5 -238
  76. package/src/client/nuqs-adapter.tsx +45 -2
  77. package/src/client/use-query-states.ts +27 -23
  78. package/src/index.ts +5 -0
  79. package/src/params/codec-registry.ts +24 -11
  80. package/src/params/index.ts +0 -1
  81. package/src/plugins/node-flight-builds.ts +94 -0
  82. package/src/plugins/shims.ts +10 -0
  83. package/src/routes/href.ts +171 -0
  84. package/src/routes/index.ts +10 -0
  85. package/src/routing/codegen.ts +8 -1
  86. package/src/routing/link-codegen.ts +103 -37
  87. package/src/search-params/define.ts +37 -17
  88. package/src/search-params/index.ts +10 -0
  89. package/src/server/param-coercion.ts +5 -23
  90. package/src/server/rsc-entry/index.ts +6 -3
  91. package/src/server/ssr-entry.ts +2 -2
  92. package/src/shared/href.ts +257 -0
  93. package/dist/_chunks/codec-registry-CPc6bjVl.js +0 -20
  94. package/dist/_chunks/codec-registry-CPc6bjVl.js.map +0 -1
  95. package/dist/_chunks/codegen-B9oWkWGf.js.map +0 -1
  96. package/dist/_chunks/href-validation-CEZy1V-k.js +0 -210
  97. package/dist/_chunks/href-validation-CEZy1V-k.js.map +0 -1
  98. package/dist/_chunks/use-query-states-pkDV-jSg.js.map +0 -1
@@ -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"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"codegen-B9oWkWGf.js","names":[],"sources":["../../src/routing/codegen-shared.ts","../../src/routing/link-codegen.ts","../../src/routing/codegen.ts"],"sourcesContent":["/**\n * Shared codegen helpers — import-path computation and codec chain type\n * builders.\n *\n * Extracted from `codegen.ts` so `link-codegen.ts` can use the same\n * helpers without a cyclic import.\n */\n\nimport { relative, posix } from 'node:path';\nimport type { ParamEntry } from './codegen-types.ts';\n\n/**\n * Compute a relative import specifier for a codec/page file, stripping\n * the .ts/.tsx extension and resolving against the codegen output dir.\n */\nexport function codecImportPath(codecFilePath: string, importBase: string | undefined): string {\n const absPath = codecFilePath.replace(/\\.(ts|tsx)$/, '');\n if (importBase) {\n return './' + relative(importBase, absPath).replace(/\\\\/g, '/');\n }\n return './' + posix.basename(absPath);\n}\n\n/**\n * Build a TypeScript type expression for a single param using the global\n * schema's InferCodecType. Falls back to the param's base type when\n * schema doesn't declare this param (schemas are opt-in per key).\n *\n * Uses `infer` to extract the codec value rather than direct indexing\n * because TypeScript doesn't narrow index validity inside a conditional\n * type's true branch — `typeof schema.segmentParams[K]` produces TS2538\n * even when the condition proves K is a valid key. In .d.ts files that\n * error is suppressed and the type silently becomes `any`.\n */\nexport function buildSchemaParamType(p: ParamEntry, fallback?: string): string {\n const key = JSON.stringify(p.bracketName);\n const fb = fallback ?? p.type;\n return `typeof schema['segmentParams'] extends Record<${key}, infer V> ? InferCodecType<V> : ${fb}`;\n}\n","/**\n * Typed `<Link>` codegen — interface augmentation generation.\n *\n * Extracted from `codegen.ts` to keep that file under the project's\n * 500-line cap. This module owns everything that emits the\n * `interface LinkFunction { ... }` augmentation blocks in the generated\n * `.timber/timber-routes.d.ts`.\n *\n * Two augmentation blocks are emitted:\n *\n * 1. **Per-route discriminated union** (`formatTypedLinkOverloads`) —\n * one call signature whose props is a union keyed on `href`. TS\n * narrows by literal href and reports prop errors against the\n * matched variant. See TIM-835 and `design/09-typescript.md`.\n *\n * 2. **Catch-all overloads** (`formatLinkCatchAllOverloads`) — external\n * href literals (`http://`, `mailto:`, etc.) and a computed-string\n * `<H extends string>` signature for runtime-computed paths.\n *\n * Block ordering is critical for error UX: per-route is emitted FIRST\n * so that, after TS's \"later overload set ordered first\" merge rule,\n * the discriminated union ends up LAST in resolution order — the\n * overload TS reports against on failure.\n */\n\nimport type { ParamEntry, RouteEntry } from './codegen-types.ts';\nimport { buildSchemaParamType } from './codegen-shared.ts';\nimport { classifyUrlSegment } from './segment-classify.ts';\n\n/**\n * The `searchParams` prop type, emitted identically on every Link variant\n * — per-route pattern, resolved template, and catch-all.\n *\n * TIM-1343: there is no per-route narrowing any more. `params.ts` is gone,\n * so codegen has no definition to read a `SearchParamsDefinition<T>` from.\n * Type safety moved to the value's construction site instead: callers write\n * `definition.buildSearchParams({ ... })`, which checks `Partial<T>` there\n * and returns a query STRING — the only shape that survives the RSC Flight\n * boundary. A plain record is the uncodec'd escape hatch. See `client/link.tsx` §\"searchParams prop shapes\".\n *\n * Declared once so the three emission sites cannot drift apart.\n */\nexport const SEARCH_PARAMS_PROP_TYPE = 'string | Record<string, unknown>';\n\n/** Shared Link base-props type literal used in every emitted call signature. */\nexport const LINK_BASE_PROPS_TYPE =\n \"Omit<import('react').AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> & { prefetch?: boolean; scroll?: boolean; preserveSearchParams?: true | string[]; onNavigate?: import('./client/link.js').OnNavigateHandler; children?: import('react').ReactNode }\";\n\n/**\n * Build a TypeScript template literal pattern for a dynamic route.\n * e.g. '/products/[id]' → '/products/${string}'\n * '/blog/[...slug]' → '/blog/${string}'\n * '/docs/[[...path]]' → '/docs/${string}' (also matches /docs)\n * '/[org]/[repo]' → '/${string}/${string}'\n */\nexport function buildResolvedPattern(route: RouteEntry): string | null {\n const parts = route.urlPath.split('/');\n const templateParts = parts.map((part) => {\n const seg = classifyUrlSegment(part);\n switch (seg.kind) {\n case 'catch-all':\n case 'optional-catch-all':\n // eslint-disable-next-line no-template-curly-in-string -- codegen output\n return '${string}';\n case 'dynamic': {\n const prefix = seg.prefix ?? '';\n const suffix = seg.suffix ?? '';\n // eslint-disable-next-line no-template-curly-in-string -- codegen output\n return `${prefix}\\${string}${suffix}`;\n }\n default:\n return part;\n }\n });\n return templateParts.join('/');\n}\n\n/**\n * Format the segmentParams type for Link overloads.\n *\n * Link params accept `string | number` for single dynamic segments\n * (convenience — values are stringified at runtime). Catch-all and\n * optional catch-all remain `string[]` / `string[] | undefined`.\n *\n * With a global schema, the schema codec's inferred type wins. Without\n * one, a URL segment is a raw string (widened to string | number for\n * Link convenience) — per-segment codec chains were deleted in TIM-1342.\n */\nexport function formatLinkParamsType(params: ParamEntry[], hasSchema?: boolean): string {\n if (params.length === 0) {\n return '{}';\n }\n\n const fields = params.map((p) => {\n const fallback = p.type === 'string' ? 'string | number' : p.type;\n const codecType = hasSchema ? buildSchemaParamType(p, fallback) : fallback;\n return `${p.name}: ${codecType}`;\n });\n return `{ ${fields.join('; ')} }`;\n}\n\n/**\n * Catch-all call signatures for `<Link>` — external hrefs and computed\n * `string` variables. Emitted from codegen in a SEPARATE\n * `declare module` block (declared AFTER the per-route block) so the TS\n * \"later overload set ordered first\" rule places these catch-all\n * signatures ahead of per-route in resolution order, leaving per-route\n * as the final overload whose error message is reported on failure.\n *\n * The conditional `string extends H ? ... : never` protection preserves\n * TIM-624's guarantee that unknown internal path literals don't match\n * the catch-all — typos like `<Link href=\"/typo\" />` still error.\n */\nexport function formatLinkCatchAllOverloads(): string[] {\n const lines: string[] = [];\n const baseProps = LINK_BASE_PROPS_TYPE;\n\n const catchAllSearchParams = SEARCH_PARAMS_PROP_TYPE;\n\n // ExternalHref inlined here rather than referenced as an exported\n // alias so the generated .d.ts stands alone without source imports.\n /* eslint-disable no-template-curly-in-string -- codegen output */\n const externalHref =\n '`http://${string}` | `https://${string}` | `mailto:${string}` | `tel:${string}` | `ftp://${string}` | `//${string}` | `#${string}` | `?${string}`';\n /* eslint-enable no-template-curly-in-string */\n\n lines.push(' // Typed Link overloads — catch-all (block 2 / emitted second)');\n lines.push(' interface LinkFunction {');\n\n // (1) External/literal-protocol hrefs.\n //\n // TIM-833: `segmentParams` is permissively typed as\n // `Record<string, unknown>` (not `never`) so generic wrappers that\n // forward a `LinkProps`-shaped object can compile when the wrapper\n // happens to bottom out at an external href. There are no dynamic\n // segments to interpolate for an external href, so this prop is\n // ignored at runtime — accepting an open-shape object instead of\n // forbidding it removes a footgun without changing behavior.\n lines.push(` (props: ${baseProps} & {`);\n lines.push(` href: ${externalHref}`);\n lines.push(` segmentParams?: Record<string, unknown>`);\n lines.push(` searchParams?: ${catchAllSearchParams}`);\n lines.push(` }): import('react').JSX.Element`);\n\n // (2) Computed/variable href — non-literal `string` only.\n //\n // `string extends H` is true only when H is the wide `string` type,\n // not a specific literal. For literal hrefs, this overload must NOT\n // be selectable so the per-route discriminated union (block 1) is\n // the resolution target.\n //\n // TIM-833 follow-up: the previous shape used `string extends H ? {...} : never`\n // on the WHOLE props type. For literal H, that collapsed `props` to\n // `never`, and JSX type inference then read `(never).children` as\n // `never` — producing the misleading\n // `'children' prop expects type 'never' which requires multiple\n // children, but only a single child was provided` (TS2745) error,\n // which buried the actual prop-mismatch message under a noise diagnostic.\n //\n // Fix: move the `: never` from the whole props onto just the `href`\n // field. The overload remains uncallable for literal H (since `\"/x\"`\n // is not assignable to `never`), but `children` retains its real\n // `ReactNode` type so JSX inference no longer collapses to never.\n // The diagnostic surface becomes: TS reports the per-route block's\n // error chain (the helpful \"Type 'number' is not assignable to type\n // 'string'\" message) WITHOUT a leading TS2745 noise line.\n lines.push(` <H extends string>(`);\n lines.push(` props: ${baseProps} & {`);\n lines.push(` href: string extends H ? H : never`);\n lines.push(` segmentParams?: Record<string, string | number | string[]>`);\n lines.push(` searchParams?: ${catchAllSearchParams}`);\n lines.push(` }`);\n lines.push(` ): import('react').JSX.Element`);\n\n lines.push(' }');\n return lines;\n}\n\n/**\n * Generate typed per-route Link call signatures via LinkFunction\n * interface merging.\n *\n * TIM-835: This emits a SINGLE call signature whose props is a\n * discriminated union keyed on `href`. TypeScript narrows the union by\n * the literal `href` at the call site, then checks the rest of the\n * props against the matched variant. When `segmentParams` or\n * `searchParams` is wrong, TS reports the error against the matched\n * variant — naming the user's actual `href` and the offending field.\n *\n * Before TIM-835, this function emitted N separate per-route overloads\n * (one per route, sometimes two for dynamic routes). When ALL overloads\n * failed, TS would pick an arbitrary failed overload (heuristically the\n * \"last tried\") to render the diagnostic, often pointing at a route\n * completely unrelated to the one the user wrote. The discriminated\n * union sidesteps overload-resolution heuristics entirely.\n *\n * Open property shapes (`Record<string, unknown>` instead of `never`)\n * for `segmentParams` on routes that don't declare them keep generic\n * `LinkProps`-spreading wrappers compiling. (Aligned with TIM-833.)\n *\n * TIM-832: this function still emits the per-route block FIRST and the\n * catch-all block follows, so per-route remains the LAST overload set in\n * resolution order — the one TS reports against on failure. With a\n * discriminated union there is only one call signature in this block,\n * so the resolved-template-vs-pattern ordering reduces to placing the\n * pattern variant before the resolved-template variant inside the union.\n */\nexport function formatTypedLinkOverloads(routes: RouteEntry[], hasSchema?: boolean): string[] {\n const lines: string[] = [];\n const baseProps = LINK_BASE_PROPS_TYPE;\n\n // Build the union variants. Each route contributes one variant for the\n // pattern href (e.g. '/products/[id]') and, for dynamic routes, an\n // additional variant for the resolved-template href (e.g.\n // `/products/${string}`).\n //\n // The PATTERN variant must be listed BEFORE the resolved-template\n // variant for the same route so that when the user writes the literal\n // pattern href (`<Link href=\"/products/[id]\" />`), TS narrows to the\n // pattern variant (which carries the typed `segmentParams` shape)\n // rather than the looser resolved-template variant. Without this\n // ordering, TS would silently match the resolved-template variant\n // first — swallowing typed-segmentParams type errors.\n const variants: string[] = [];\n for (const route of routes) {\n const hasDynamicParams = route.params.length > 0;\n // For routes with no dynamic params, accept an absent OR open-shape\n // segmentParams. `Record<string, unknown>` keeps generic spreads\n // compiling and gives a readable error if a non-object is passed.\n const paramsProp = hasDynamicParams\n ? `segmentParams: ${formatLinkParamsType(route.params, hasSchema)}`\n : 'segmentParams?: Record<string, unknown>';\n\n // TIM-1343: searchParams is no longer typed per-route. There is no\n // convention file to read a definition from, so codegen has nothing to\n // narrow with — the value is either a URLSearchParams built by\n // `definition.buildSearchParams()` (which type-checks its own\n // `Partial<T>` at that call) or a plain String()-coerced record.\n const searchParamsProp = `searchParams?: ${SEARCH_PARAMS_PROP_TYPE}`;\n\n // Pattern variant FIRST (more specific).\n variants.push(\n `${baseProps} & { href: '${route.urlPath}'; ${paramsProp}; ${searchParamsProp} }`\n );\n\n // Resolved-template variant SECOND (looser, matches interpolated hrefs).\n if (hasDynamicParams) {\n const templatePattern = buildResolvedPattern(route);\n if (templatePattern) {\n // TIM-835: `Record<string, never>` for segmentParams forbids ANY\n // provided keys on the resolved-template variant. Without this,\n // the resolved-template would shadow the pattern variant for\n // literal pattern hrefs (`<Link href=\"/products/[id]\" segmentParams={...} />`)\n // because both variants accept the literal `'/products/[id]'`\n // and the looser variant would silently swallow segmentParams\n // type errors.\n variants.push(\n `${baseProps} & { href: \\`${templatePattern}\\`; segmentParams?: Record<string, never>; ${searchParamsProp} }`\n );\n }\n }\n }\n\n lines.push(' interface LinkFunction {');\n if (variants.length === 0) {\n // No page routes — emit nothing. The catch-all block in the second\n // augmentation still provides external/computed-string signatures.\n lines.push(' }');\n return lines;\n }\n lines.push(' (');\n lines.push(' props:');\n for (const variant of variants) {\n lines.push(` | (${variant})`);\n }\n lines.push(` ): import('react').JSX.Element`);\n lines.push(' }');\n\n return lines;\n}\n","/**\n * Route map codegen.\n *\n * Walks the scanned RouteTree and generates a TypeScript declaration file\n * mapping every route to its params and searchParams shapes.\n *\n * This runs at build time and in dev (regenerated on file changes).\n * No runtime overhead — purely static type generation.\n */\n\nimport { existsSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport type { RouteTree, SegmentNode } from './types.ts';\nimport type { ParamEntry, RouteEntry } from './codegen-types.ts';\nimport { buildSchemaParamType } from './codegen-shared.ts';\nimport { effectiveUrlSegment, type UrlSegmentIdentity } from './segment-classify.ts';\nimport { formatLinkCatchAllOverloads, formatTypedLinkOverloads } from './link-codegen.ts';\n\n/** Options for route map generation. */\nexport interface CodegenOptions {\n /** Absolute path to the app/ directory. Required for page searchParams detection. */\n appDir?: string;\n /**\n * Absolute path to the directory where the .d.ts file will be written.\n * Used to compute correct relative import paths for page files.\n * Defaults to appDir when not provided (preserves backward compat for tests).\n */\n outputDir?: string;\n /**\n * Whether a global schema (app/schema.ts) exists.\n * Auto-detected from appDir when not explicitly set.\n */\n hasSchema?: boolean;\n}\n\n/**\n * Generate a TypeScript declaration file string from a scanned route tree.\n *\n * The output is a `declare module '@timber-js/app'` block containing the Routes\n * interface that maps every route path to its params and searchParams shape.\n */\nexport function generateRouteMap(tree: RouteTree, options: CodegenOptions = {}): string {\n // Auto-detect schema from appDir when not explicitly set\n const hasSchema = options.hasSchema ?? detectSchema(options.appDir);\n\n const routes: RouteEntry[] = [];\n collectRoutes(tree.root, [], '', routes, hasSchema, false);\n\n // Sort routes alphabetically for deterministic output\n routes.sort((a, b) => a.urlPath.localeCompare(b.urlPath));\n\n // When outputDir differs from appDir, import paths must be relative to outputDir\n const importBase = options.outputDir ?? options.appDir;\n\n return formatDeclarationFile(routes, importBase, hasSchema, options.appDir);\n}\n\n/** Schema file extensions to check, in priority order. */\nconst SCHEMA_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];\n\n/**\n * Detect whether app/schema.{ts,tsx,js,jsx} exists.\n */\nfunction detectSchema(appDir: string | undefined): boolean {\n if (!appDir) return false;\n return SCHEMA_EXTENSIONS.some((ext) => existsSync(join(appDir, `schema${ext}`)));\n}\n\n/**\n * Recursively walk the segment tree and collect route entries.\n *\n * A route entry is created for any segment that has a `page` or `route` file.\n * Params accumulate from ancestor dynamic segments.\n */\nfunction collectRoutes(\n node: SegmentNode,\n ancestorParams: ParamEntry[],\n parentTreePath: string,\n routes: RouteEntry[],\n hasSchema: boolean,\n insideSlot: boolean,\n insideIntercepting = false\n): void {\n // Build the tree path (includes groups, slots — uniquely identifies this segment).\n // Root node has empty segmentName, producing treePath = ''.\n const treePath = node.segmentName ? `${parentTreePath}/${node.segmentName}` : parentTreePath;\n // Accumulate params from this segment.\n //\n // The segment is read through `effectiveUrlSegment` for the same reason the\n // runtime coercer is: an intercepting node's own `segmentType` is\n // 'intercepting' and its `paramName` is unset — the param it binds lives in\n // the intercepted name (`(.)[albumSlug]` → `[albumSlug]`). Reading the node\n // directly emitted `{}` for a segment the router does bind and coerce, so\n // the types disagreed with the values for every intercepting page with a\n // dynamic intercepted segment, and for its descendants, which lost the\n // ancestor param too.\n const urlSegment = effectiveUrlSegment(node);\n const params = [...ancestorParams];\n if (urlSegment.paramName) {\n params.push({\n name: urlSegment.paramName,\n bracketName: bracketNameForSegment(urlSegment),\n type: paramTypeForSegment(urlSegment.segmentType),\n });\n }\n\n // Check if this segment is a leaf route (has page or route file)\n const isPage = !!node.page;\n const isApiRoute = !!node.route;\n\n // A segment that hosts code but is not itself addressable — a layout,\n // middleware, or access check above the leaf — still gets a `$segment`\n // module, so `getSegmentParams(SEGMENT_PATH)` is callable from it and needs\n // a matching typed overload. Emitting only leaves left those call sites on\n // the broad `Record<string, string | string[]>` signature, which since\n // TIM-1342 (which deleted `defineSegmentParams`) is their ONLY typed path.\n // design/41-global-params.md's Type Summary promises layouts and middleware\n // exact accumulated params.\n //\n // `isRoutable: false` keeps them out of the urlPath-keyed emissions — the\n // `Routes` interface and `<Link>` variants — where they would publish a URL\n // that no request can reach. They belong only to the segmentPath-keyed\n // APIs: `getSegmentParams`, `useSegmentParams`, `TimberSegmentParams`.\n const hostsCode = !!node.layout || !!node.middleware || !!node.access;\n\n if (isPage || isApiRoute || hostsCode) {\n const entry: RouteEntry = {\n urlPath: node.urlPath,\n segmentPath: treePath || '/',\n params,\n isApiRoute,\n isRoutable: isPage || isApiRoute,\n isSlotRoute: insideSlot,\n isInterceptingRoute: insideIntercepting,\n hasSchema,\n };\n\n routes.push(entry);\n }\n\n // Recurse into children. An intercepting subtree is flagged, and the flag is\n // sticky — the descendants are where the false URLs are. See\n // `RouteEntry.isInterceptingRoute` for what the flag drops and why dedupe\n // alone was not enough.\n for (const child of node.children) {\n const childIntercepting = insideIntercepting || child.segmentType === 'intercepting';\n collectRoutes(child, params, treePath, routes, hasSchema, insideSlot, childIntercepting);\n }\n\n // Recurse into slots (they share the parent's URL path, but may have their own pages)\n for (const slot of Object.values(node.slots)) {\n collectRoutes(slot, params, treePath, routes, hasSchema, true, insideIntercepting);\n }\n}\n\n/**\n * Dedupe route entries by urlPath for urlPath-keyed emissions (the Routes\n * interface and typed Link variants).\n *\n * Parallel-slot pages share their parent's urlPath; emitting one entry per\n * slot page produced duplicate interface keys (TS2300/TS2717 under\n * skipLibCheck:false) and duplicate overloads. The non-slot entry is the\n * canonical one; when only slot entries exist (parent has no page), the\n * lexicographically smallest segmentPath wins so output is independent of\n * slot scan order.\n *\n * The loser is discarded outright. It used to donate its `searchParams`\n * definition to the winner, because a slot could carry one the parent page\n * lacked; since TIM-1343 no route entry carries a searchParams definition at\n * all, there is nothing left to merge.\n *\n * segmentPath-keyed emissions (getSegmentParams, useSegmentParams,\n * TimberSegmentParams) must NOT use this — segmentPaths are already unique\n * and slot entries feed those APIs directly.\n */\nfunction dedupeRoutesByUrlPath(routes: RouteEntry[]): RouteEntry[] {\n const byPath = new Map<string, RouteEntry>();\n for (const route of routes) {\n const existing = byPath.get(route.urlPath);\n if (!existing) {\n byPath.set(route.urlPath, route);\n continue;\n }\n\n const routeWins =\n (existing.isSlotRoute && !route.isSlotRoute) ||\n (!!existing.isSlotRoute === !!route.isSlotRoute &&\n route.segmentPath.localeCompare(existing.segmentPath) < 0);\n byPath.set(route.urlPath, routeWins ? route : existing);\n }\n return [...byPath.values()];\n}\n\n/**\n * Determine the TypeScript type for a segment's param.\n */\n/**\n * Derive the bracket key for schema/codegen lookup.\n * For bare segments like `[id]` this is the segmentName itself.\n * For affixed segments like `img-[id].png` this is `[id]` — the bare bracket form.\n */\nfunction bracketNameForSegment(node: UrlSegmentIdentity): string {\n if (node.paramPrefix || node.paramSuffix) {\n return `[${node.paramName}]`;\n }\n return node.segmentName;\n}\n\nfunction paramTypeForSegment(segmentType: string): ParamEntry['type'] {\n switch (segmentType) {\n case 'catch-all':\n return 'string[]';\n case 'optional-catch-all':\n return 'string[] | undefined';\n default:\n return 'string';\n }\n}\n\n/**\n * Emit the schema-based type exports: TimberSegmentParams, TimberRoute,\n * AllSegmentParams, RoutesWithParams.\n *\n * These types use InferCodecType references so they stay in sync with\n * the schema without hardcoding resolved types.\n *\n * Design doc: design/41-global-params.md §Codegen Output\n */\nfunction formatSchemaTypes(routes: RouteEntry[]): string[] {\n const lines: string[] = [];\n\n lines.push('/** Union of all valid route patterns. */');\n lines.push('export type TimberRoute = keyof TimberSegmentParams;');\n lines.push('');\n lines.push('/** Maps each segment path to its accumulated segment params. */');\n lines.push('export interface TimberSegmentParams {');\n\n for (const route of routes) {\n if (route.params.length === 0) {\n lines.push(` '${route.segmentPath}': {};`);\n } else {\n lines.push(` '${route.segmentPath}': {`);\n for (const p of route.params) {\n lines.push(` ${p.name}: ${buildSchemaParamType(p)};`);\n }\n lines.push(' };');\n }\n }\n\n lines.push('}');\n lines.push('');\n\n // AllSegmentParams — flat union of all param types across all routes\n lines.push('/** All segment params (union of all route params). */');\n lines.push('export type AllSegmentParams = {');\n lines.push(\n ' [K in keyof TimberSegmentParams as TimberSegmentParams[K] extends Record<string, never>'\n );\n lines.push(' ? never');\n lines.push(' : K]: TimberSegmentParams[K];');\n lines.push('} extends infer U');\n lines.push(' ? { [K in keyof U[keyof U]]: U[keyof U][K] }');\n lines.push(' : never;');\n lines.push('');\n\n // RoutesWithParams — filter routes by required param keys\n lines.push(\n '/** Filters TimberRoute to routes whose accumulated params include all listed keys. */'\n );\n lines.push('export type RoutesWithParams<K extends keyof AllSegmentParams> = {');\n lines.push(' [R in TimberRoute]: K extends keyof TimberSegmentParams[R] ? R : never;');\n lines.push('}[TimberRoute];');\n\n return lines;\n}\n\n/**\n * Format the collected routes into a TypeScript declaration file.\n */\nfunction formatDeclarationFile(\n routes: RouteEntry[],\n importBase?: string,\n hasSchema?: boolean,\n appDir?: string\n): string {\n const lines: string[] = [];\n\n lines.push('// This file is auto-generated by timber.js route map codegen.');\n lines.push('// Do not edit manually. Regenerated on build and in dev mode.');\n lines.push('');\n // export {} makes this file a module, so all declare module blocks are\n // augmentations rather than ambient replacements. Without this, the\n // declare module blocks would replace the original module types entirely\n // (removing exports like bindUseQueryStates that aren't listed here).\n lines.push('export {};');\n lines.push('');\n\n if (hasSchema) {\n // Schema-based codegen: import schema and InferCodecType\n // Compute the schema import path relative to the output directory\n const schemaImport =\n appDir && importBase\n ? './' + relative(importBase, join(appDir, 'schema')).replace(/\\\\/g, '/')\n : '../app/schema';\n lines.push(`import type schema from '${schemaImport}';`);\n lines.push(\"import type { InferCodecType, SegmentParamCodec } from '@timber-js/app/params';\");\n lines.push('');\n // Collect all unique bracket keys from routes for key validation\n const allBracketKeys = new Set<string>();\n for (const route of routes) {\n for (const p of route.params) {\n allBracketKeys.add(p.bracketName);\n }\n }\n\n // Augment the ValidDynamicSegmentKeysRegistry so defineSchema constrains keys\n // to known filesystem segments. Unknown keys produce inline TS errors.\n if (allBracketKeys.size > 0) {\n lines.push(\"declare module '@timber-js/app/params' {\");\n lines.push(' interface ValidDynamicSegmentKeysRegistry {');\n for (const key of [...allBracketKeys].sort()) {\n lines.push(` ${JSON.stringify(key)}: true;`);\n }\n lines.push(' }');\n lines.push('}');\n lines.push('');\n }\n // Guard: detect when the schema or params imports silently degraded to\n // `any` because TypeScript could not resolve the import specifier.\n // In a .d.ts an unresolved import does NOT error — every downstream\n // type silently becomes `any`, which satisfies every assertion. Only\n // an explicit IsAny check catches it.\n lines.push('type _IsAny<T> = 0 extends 1 & T ? true : false;');\n lines.push('type _AssertSchemaNotAny<_T extends false = _IsAny<typeof schema>> = true;');\n lines.push('type _AssertCodecTypeNotAny<_T extends false = _IsAny<SegmentParamCodec>> = true;');\n lines.push('');\n // Type-level validation: each schema value must be a Codec or Standard Schema.\n // Running `pnpm run typecheck` will surface errors for invalid values.\n lines.push('type _AssertSchemaValues = {');\n lines.push(\n \" [K in keyof typeof schema['segmentParams']]: typeof schema['segmentParams'][K] extends SegmentParamCodec ? true : ['Error: value for', K, 'is not a valid Codec or Standard Schema'];\"\n );\n lines.push('};');\n // Generic constraint enforces that all values are `true` — if any value is\n // an error tuple, TS reports a real diagnostic instead of silently computing it.\n lines.push(\n 'type _EnforceSchemaValues<_T extends Record<string, true> = _AssertSchemaValues> = true;'\n );\n lines.push('');\n }\n\n // urlPath-keyed emissions use the deduped list (slot pages share their\n // parent's urlPath); segmentPath-keyed emissions below keep all entries.\n //\n // Intercepting subtrees are dropped outright rather than deduped: their\n // computed urlPath is not a route any request can reach, so a path that\n // happens NOT to collide with a real one would otherwise be published as a\n // real route. See `RouteEntry.isInterceptingRoute`.\n const uniqueByUrlPath = dedupeRoutesByUrlPath(\n routes.filter((r) => r.isRoutable && !r.isInterceptingRoute)\n );\n\n lines.push(\"declare module '@timber-js/app' {\");\n lines.push(' interface Routes {');\n\n // TIM-1343: no `searchParams` member. With `params.ts` gone there is no\n // convention file to read a definition from, so the framework has nothing\n // to type it with — and an always-`{}` member is a claim that every route\n // has no search params, which is false. Search-param types now come from\n // the definition object itself, wherever the app chooses to keep it.\n for (const route of uniqueByUrlPath) {\n const paramsType = formatParamsType(route.params, hasSchema);\n\n lines.push(` '${route.urlPath}': {`);\n lines.push(` segmentParams: ${paramsType}`);\n lines.push(` }`);\n }\n\n lines.push(' }');\n\n // When a global schema exists, emit segment param types inside the\n // @timber-js/app module augmentation so that declare module blocks\n // for @timber-js/app/server and @timber-js/app/client can reference\n // AllSegmentParams via `import type { AllSegmentParams } from '@timber-js/app'`.\n if (hasSchema) {\n lines.push('');\n lines.push(...formatSchemaTypes(routes).map((l) => ` ${l}`));\n }\n\n lines.push('}');\n lines.push('');\n\n // useQueryStates + typed Link are urlPath-keyed → deduped list.\n const pageRoutes = uniqueByUrlPath.filter((r) => !r.isApiRoute);\n // getSegmentParams / useSegmentParams are segmentPath-keyed → full list,\n // so slot segments keep their own typed overloads.\n const dynamicRoutes = routes.filter((r) => r.params.length > 0);\n\n // Generate @timber-js/app/server augmentation — typed getSegmentParams\n if (dynamicRoutes.length > 0) {\n lines.push(\"declare module '@timber-js/app/server' {\");\n if (hasSchema) {\n lines.push(\" import type { AllSegmentParams } from '@timber-js/app'\");\n }\n for (const route of dynamicRoutes) {\n const paramsType = formatParamsType(route.params, hasSchema);\n lines.push(\n ` export function getSegmentParams(segmentPath: '${route.segmentPath}'): ${paramsType}`\n );\n }\n lines.push(\n hasSchema\n ? ' export function getSegmentParams(): Partial<AllSegmentParams>'\n : ' export function getSegmentParams(): Record<string, string | string[]>'\n );\n lines.push('}');\n lines.push('');\n }\n\n // Generate overloads for @timber-js/app/client\n\n if (dynamicRoutes.length > 0 || pageRoutes.length > 0) {\n lines.push(\"declare module '@timber-js/app/client' {\");\n lines.push(\" import type { SearchParamsDefinition } from '@timber-js/app/search-params'\");\n if (hasSchema) {\n lines.push(\" import type { AllSegmentParams } from '@timber-js/app'\");\n }\n lines.push('');\n\n // useSegmentParams overloads\n if (dynamicRoutes.length > 0) {\n for (const route of dynamicRoutes) {\n const paramsType = formatParamsType(route.params, hasSchema);\n lines.push(\n ` export function useSegmentParams(segmentPath: '${route.segmentPath}'): ${paramsType}`\n );\n }\n lines.push(\n hasSchema\n ? ' export function useSegmentParams(): Partial<AllSegmentParams>'\n : ' export function useSegmentParams(): Record<string, string | string[]>'\n );\n lines.push('');\n }\n\n // Typed Link overloads — per-route with DIRECT types (no conditionals).\n // Direct types preserve TypeScript's excess property checking.\n //\n // TIM-832: per-route and catch-all are emitted as TWO separate\n // augmentation blocks. Per TS's merging rule \"later overload sets\n // ordered first\", the catch-all block (declared SECOND in this file)\n // ends up FIRST in the merged call-signature list at resolution time,\n // which puts the per-route block LAST — so its error message is the\n // one TypeScript reports when no overload matches. This gives users a\n // clear prop-mismatch error (e.g. \"'string | undefined' is not\n // assignable to 'string | number' on id\") instead of the old\n // confusing \"Type 'string' is not assignable to type 'never'\" cascade.\n if (pageRoutes.length > 0) {\n lines.push(' // Typed Link overloads — per-route (block 1 / emitted first)');\n lines.push(...formatTypedLinkOverloads(pageRoutes, hasSchema));\n lines.push('');\n }\n\n lines.push('}');\n lines.push('');\n }\n\n // TIM-832: catch-all block — emitted as a SEPARATE `declare module`\n // augmentation so TS's \"later overload set first\" rule orders it ahead\n // of the per-route block above at resolution time, leaving per-route as\n // the \"last overload\" whose error TypeScript reports.\n lines.push(\"declare module '@timber-js/app/client' {\");\n lines.push(\" import type { SearchParamsDefinition } from '@timber-js/app/search-params'\");\n lines.push('');\n lines.push(...formatLinkCatchAllOverloads());\n lines.push('}');\n lines.push('');\n\n return lines.join('\\n');\n}\n\n/**\n * Format the params type for a route entry.\n */\nfunction formatParamsType(params: ParamEntry[], hasSchema?: boolean): string {\n if (params.length === 0) {\n return '{}';\n }\n\n // Without a schema a URL segment is an uninterpreted string — that IS\n // its type. Per-segment codec chains used to narrow it here; TIM-1342\n // deleted them along with params.ts.\n const fields = params.map((p) => {\n const codecType = hasSchema ? buildSchemaParamType(p) : p.type;\n return `${p.name}: ${codecType}`;\n });\n return `{ ${fields.join('; ')} }`;\n}\n\n// TIM-1341: `useQueryStates` no longer has a route-string form, so the\n// generated `.d.ts` emits no overloads for it. Its source signature —\n// `useQueryStates(codecs, options?)` — is fully generic over the codec map\n// and needs no per-route augmentation. Reaching another route's codecs is\n// done by importing that route's `searchParams` definition from its\n// `params.ts` and calling `definition.useQueryStates()`, which is typed by\n// inference and cannot fail at runtime on an unpopulated registry.\n// See design/23-search-params.md §\"Client Access\".\n\n// Link overload formatters and helpers (`formatTypedLinkOverloads`,\n// `formatLinkCatchAllOverloads`, `formatLinkParamsType`,\n// `buildResolvedPattern`, `LINK_BASE_PROPS_TYPE`) were extracted to\n// `./link-codegen.ts` (TIM-835) to keep this file under the 500-line\n// cap. They are imported at the top of this file.\n"],"mappings":";;;;;;;;;;;;;;;AAkCA,SAAgB,qBAAqB,GAAe,UAA2B;CAG7E,OAAO,iDAFK,KAAK,UAAU,EAAE,WAE2B,EAAI,mCADjD,YAAY,EAAE;AAE3B;;;;;;;;;;;;;;;ACIA,IAAa,0BAA0B;;AAGvC,IAAa,uBACX;;;;;;;;AASF,SAAgB,qBAAqB,OAAkC;CAmBrE,OAlBc,MAAM,QAAQ,MAAM,GACZ,CAAA,CAAM,KAAK,SAAS;EACxC,MAAM,MAAM,mBAAmB,IAAI;EACnC,QAAQ,IAAI,MAAZ;GACE,KAAK;GACL,KAAK,sBAEH,OAAO;GACT,KAAK,WAIH,OAAO,GAHQ,IAAI,UAAU,GAGZ,YAFF,IAAI,UAAU;GAI/B,SACE,OAAO;EACX;CACF,CACO,CAAA,CAAc,KAAK,GAAG;AAC/B;;;;;;;;;;;;AAaA,SAAgB,qBAAqB,QAAsB,WAA6B;CACtF,IAAI,OAAO,WAAW,GACpB,OAAO;CAQT,OAAO,KALQ,OAAO,KAAK,MAAM;EAC/B,MAAM,WAAW,EAAE,SAAS,WAAW,oBAAoB,EAAE;EAC7D,MAAM,YAAY,YAAY,qBAAq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;CAUT,OAAO,KAJQ,OAAO,KAAK,MAAM;EAC/B,MAAM,YAAY,YAAY,qBAAqB,CAAC,IAAI,EAAE;EAC1D,OAAO,GAAG,EAAE,KAAK,IAAI;CACvB,CACY,CAAA,CAAO,KAAK,IAAI,EAAE;AAChC"}
@@ -1,210 +0,0 @@
1
- // src/shared/slot-params.ts
2
- /**
3
- * The params a slot sees: the main route's as a base, the slot's own on top.
4
- *
5
- * Params from segments *above* the slot are not re-derived by the slot's own
6
- * chain, so they have to come from the main route; params the slot does
7
- * re-derive may have a different type than the main route gave them, so the
8
- * slot's win.
9
- *
10
- * Null-prototype, like every other param record the framework hands out
11
- * (`coerceSegmentParams` installs one unconditionally). A spread literal would
12
- * inherit `Object.prototype`, so a lookup for a param the route does not
13
- * define would resolve to an inherited member — `params.constructor` returning
14
- * a function instead of `undefined` — in the one param record that was built
15
- * by merging. See design/13-security.md #36c.
16
- */
17
- function mergeSlotParams(mainParams, slotParams) {
18
- return Object.assign(Object.create(null), mainParams, slotParams);
19
- }
20
- /**
21
- * Resolve the params for a segment path against a published slot map.
22
- *
23
- * Returns the merge when `segmentPath` names a slot that published params,
24
- * and the main route's record otherwise — an ordinary (non-slot) segment
25
- * path, an unknown path, or a request with no slots at all. Mirrors the
26
- * server's `getSegmentParams(segmentPath)` branch exactly.
27
- *
28
- * `Object.hasOwn` rather than `in` or a truthiness test: the map arrives from
29
- * JSON, so a segment path of `constructor` or `toString` would otherwise
30
- * resolve to an inherited member of `Object.prototype`.
31
- */
32
- function resolveSegmentParams(mainParams, slotParams, segmentPath) {
33
- if (!segmentPath || !slotParams || !Object.hasOwn(slotParams, segmentPath)) return mainParams;
34
- return cachedMerge(mainParams, slotParams, segmentPath);
35
- }
36
- /**
37
- * The merged record for one (main record, slot map, path) triple, reused until
38
- * one of the three changes.
39
- *
40
- * `useSegmentParams(slotPath)` calls this on every render. Returning a fresh
41
- * object each time makes the hook's result change by reference on renders where
42
- * nothing navigated, so a component using it as a `useEffect` dependency
43
- * re-runs the effect — and re-renders in a loop if that effect sets state —
44
- * while memoized children below it lose their memoization.
45
- *
46
- * Keyed on the *identities* of the two records, not their contents: both are
47
- * replaced rather than mutated on every navigation (`ParamsProvider`'s memoized
48
- * value and the server's per-request store), so identity is the correct
49
- * equality here and a deep comparison would be slower and no more accurate.
50
- *
51
- * A `WeakMap` chain rather than a `Map`, so a superseded navigation's records
52
- * and their merges become collectable as soon as nothing else holds them.
53
- */
54
- var mergeCache = /* @__PURE__ */ new WeakMap();
55
- function cachedMerge(mainParams, slotParams, segmentPath) {
56
- let bySlotMap = mergeCache.get(mainParams);
57
- if (!bySlotMap) {
58
- bySlotMap = /* @__PURE__ */ new WeakMap();
59
- mergeCache.set(mainParams, bySlotMap);
60
- }
61
- let byPath = bySlotMap.get(slotParams);
62
- if (!byPath) {
63
- byPath = /* @__PURE__ */ new Map();
64
- bySlotMap.set(slotParams, byPath);
65
- }
66
- const cached = byPath.get(segmentPath);
67
- if (cached) return cached;
68
- const merged = mergeSlotParams(mainParams, slotParams[segmentPath]);
69
- byPath.set(segmentPath, merged);
70
- return merged;
71
- }
72
- // src/shared/merge-search-params.ts
73
- /**
74
- * Shared utility for merging preserved search params into a target URL.
75
- *
76
- * Used by both <Link> (client) and redirect() (server). Extracted to a shared
77
- * module to avoid importing client code ('use client') from server modules.
78
- */
79
- /**
80
- * Merge preserved search params from the current URL into a target href.
81
- *
82
- * When `preserve` is `true`, all current search params are merged.
83
- * When `preserve` is a `string[]`, only the named params are merged.
84
- *
85
- * The target href's own search params take precedence — preserved params
86
- * are only added if the target doesn't already define them.
87
- *
88
- * @param targetHref - The resolved target href (may already contain query string)
89
- * @param currentSearch - The current URL's search string (e.g. "?private=access&page=2")
90
- * @param preserve - `true` to preserve all, or `string[]` to preserve specific params
91
- * @returns The target href with preserved search params merged in
92
- */
93
- function mergePreservedSearchParams(targetHref, currentSearch, preserve) {
94
- const currentParams = new URLSearchParams(currentSearch);
95
- if (currentParams.size === 0) return targetHref;
96
- const hashIdx = targetHref.indexOf("#");
97
- const hrefWithoutHash = hashIdx >= 0 ? targetHref.slice(0, hashIdx) : targetHref;
98
- const hash = hashIdx >= 0 ? targetHref.slice(hashIdx) : "";
99
- const qIdx = hrefWithoutHash.indexOf("?");
100
- const targetPath = qIdx >= 0 ? hrefWithoutHash.slice(0, qIdx) : hrefWithoutHash;
101
- const targetParams = new URLSearchParams(qIdx >= 0 ? hrefWithoutHash.slice(qIdx + 1) : "");
102
- const merged = new URLSearchParams(targetParams);
103
- for (const [key, value] of currentParams) if (!targetParams.has(key)) {
104
- if (preserve === true || preserve.includes(key)) merged.append(key, value);
105
- }
106
- const qs = merged.toString();
107
- return (qs ? `${targetPath}?${qs}` : targetPath) + hash;
108
- }
109
- // src/shared/href-validation.ts
110
- /**
111
- * Shared href/URL validation for all navigation sinks.
112
- *
113
- * Used by <Link>, useRouter().push/replace, and redirectExternal().
114
- * Single source of truth for dangerous-scheme detection — prevents
115
- * control-character smuggling that bypasses naive regex checks.
116
- *
117
- * See design/13-security.md §"Link scheme injection" (test #9)
118
- * and design/07-routing.md §"<Link> Scheme Validation".
119
- */
120
- /**
121
- * All C0 control characters (U+0000–U+001F) that browsers strip during
122
- * URL preprocessing. Browsers and `new URL()` strip the full C0 range,
123
- * not just tab/LF/CR — so we must match that behavior to prevent
124
- * bypass vectors like `\x00javascript:alert(1)`.
125
- */
126
- var CONTROL_CHARS_RE = /[\x00-\x1f]/g;
127
- var DANGEROUS_SCHEMES = /* @__PURE__ */ new Set([
128
- "javascript:",
129
- "data:",
130
- "vbscript:"
131
- ]);
132
- /**
133
- * Strip C0 control chars and leading whitespace, then extract the scheme.
134
- * Returns the lowercase scheme (e.g. "javascript:") or null if no scheme.
135
- */
136
- function extractScheme(href) {
137
- const cleaned = href.replace(CONTROL_CHARS_RE, "").trimStart();
138
- const match = /^([a-z][a-z0-9+.-]*:)/i.exec(cleaned);
139
- return match ? match[1].toLowerCase() : null;
140
- }
141
- /**
142
- * Validate an href for navigation sinks (<Link>, useRouter, etc.).
143
- *
144
- * Rejects dangerous schemes (javascript:, data:, vbscript:) even when
145
- * control characters are embedded to bypass naive regex checks.
146
- * Also rejects protocol-relative URLs (//evil.com).
147
- *
148
- * Throws on rejection. Safe hrefs pass through silently.
149
- */
150
- function validateNavigationHref(href) {
151
- if (href.replace(CONTROL_CHARS_RE, "").trimStart().replaceAll("\\", "/").startsWith("//")) throw new Error(`Navigation received a protocol-relative or backslash-prefixed URL: "${href}". Use an absolute URL with an explicit scheme or a relative path.`);
152
- const scheme = extractScheme(href);
153
- if (scheme && DANGEROUS_SCHEMES.has(scheme)) throw new Error(`Navigation received a dangerous href: "${href}". javascript:, data:, and vbscript: URLs are not allowed.`);
154
- }
155
- /**
156
- * Check if an href is internal (same-origin navigation) or external.
157
- *
158
- * Strips control characters before checking so that "java\tscript:" is
159
- * correctly identified as having a scheme (and thus not internal).
160
- */
161
- function isInternalHref(href) {
162
- const cleaned = href.replace(CONTROL_CHARS_RE, "").trimStart().replaceAll("\\", "/");
163
- if (cleaned.startsWith("//")) return false;
164
- if (cleaned.startsWith("/") || cleaned.startsWith("#") || cleaned.startsWith("?")) return true;
165
- if (extractScheme(href)) return false;
166
- return true;
167
- }
168
- /** Pattern matching absolute URLs: any scheme (http:, javascript:, …) or protocol-relative // */
169
- var ABSOLUTE_URL_RE = /^(?:[a-zA-Z][a-zA-Z\d+\-.]*:|\/\/)/;
170
- /**
171
- * Assert that a redirect target is a relative path — rejects absolute and
172
- * protocol-relative URLs. Used by both the server `redirect()` primitive and
173
- * the client next/navigation shim so they enforce identical semantics.
174
- *
175
- * Normalizes for validation only: strips C0 controls, trims, then replaces
176
- * backslashes with forward slashes. Browsers normalize \ → / during URL
177
- * resolution, so "/\evil.com" becomes "//evil.com" (protocol-relative open
178
- * redirect). See design/13-security.md tests #8, #8a–#8c.
179
- */
180
- function assertRelativeRedirectPath(path) {
181
- const cleaned = path.replace(CONTROL_CHARS_RE, "").trimStart().replaceAll("\\", "/");
182
- if (ABSOLUTE_URL_RE.test(cleaned)) throw new Error(`redirect() only accepts relative URLs. Got absolute URL: "${path}". Use redirectExternal(url, allowList) for external redirects.`);
183
- if (/[\x00-\x1f]/.test(path)) throw new Error("redirect() received a path containing control characters (U+0000–U+001F). Sanitize user input before passing it to redirect().");
184
- }
185
- var SAFE_REDIRECT_SCHEMES = /* @__PURE__ */ new Set(["http:", "https:"]);
186
- /**
187
- * Validate and canonicalize an external redirect URL.
188
- *
189
- * Requires http: or https: scheme and checks origin against an allow-list.
190
- * Returns the parsed canonical URL string (from URL.href) to prevent
191
- * raw user input from reaching the Location header.
192
- *
193
- * @throws On invalid URL, dangerous scheme, or origin not in allow-list.
194
- */
195
- function validateExternalRedirectUrl(url, allowList) {
196
- const cleaned = url.replace(CONTROL_CHARS_RE, "").trimStart();
197
- if (cleaned.startsWith("//")) throw new Error(`redirectExternal() received a protocol-relative URL: "${url}". Use an absolute URL with http: or https: scheme.`);
198
- let parsed;
199
- try {
200
- parsed = new URL(cleaned);
201
- } catch {
202
- throw new Error(`redirectExternal() received an invalid URL: "${url}"`);
203
- }
204
- if (!SAFE_REDIRECT_SCHEMES.has(parsed.protocol)) throw new Error(`redirectExternal() received a non-http(s) URL: "${url}". Only http: and https: schemes are allowed for external redirects.`);
205
- if (!allowList.includes(parsed.origin)) throw new Error(`redirectExternal() target "${parsed.origin}" is not in the allow-list. Allowed: [${allowList.join(", ")}]`);
206
- return parsed.href;
207
- }
208
- export { mergePreservedSearchParams as a, validateNavigationHref as i, isInternalHref as n, resolveSegmentParams as o, validateExternalRedirectUrl as r, assertRelativeRedirectPath as t };
209
-
210
- //# sourceMappingURL=href-validation-CEZy1V-k.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"href-validation-CEZy1V-k.js","names":[],"sources":["../../src/shared/slot-params.ts","../../src/shared/merge-search-params.ts","../../src/shared/href-validation.ts"],"sourcesContent":["/**\n * Per-slot segment params — the one definition both halves of the API read.\n *\n * A parallel slot matches the URL through its *own* sub-tree, so it can derive\n * a param the main route never had, or derive the same name with a different\n * type (`[...year]` → `string[]` where the main route's `[year]` gave\n * `string`). The server answers `getSegmentParams(slotPath)` from a per-slot\n * map; the client answers `useSegmentParams(slotPath)` from the same map,\n * published on the RSC payload (TIM-1285).\n *\n * The merge lives here rather than in either half because the two must agree\n * about what \"the slot's params\" are — a divergence is invisible until\n * somebody reads a param of the wrong type, which is exactly the class of bug\n * this module closes.\n *\n * Isomorphic: no server or client imports.\n *\n * See design/41-global-params.md §\"Params in a parallel slot\".\n */\n\nimport type { CoercedParams } from './param-value.ts';\n\n/** Slot tree path → that slot's own coerced params. */\nexport type SlotParamsRecord = Record<string, CoercedParams>;\n\n/**\n * The params a slot sees: the main route's as a base, the slot's own on top.\n *\n * Params from segments *above* the slot are not re-derived by the slot's own\n * chain, so they have to come from the main route; params the slot does\n * re-derive may have a different type than the main route gave them, so the\n * slot's win.\n *\n * Null-prototype, like every other param record the framework hands out\n * (`coerceSegmentParams` installs one unconditionally). A spread literal would\n * inherit `Object.prototype`, so a lookup for a param the route does not\n * define would resolve to an inherited member — `params.constructor` returning\n * a function instead of `undefined` — in the one param record that was built\n * by merging. See design/13-security.md #36c.\n */\nexport function mergeSlotParams(\n mainParams: CoercedParams,\n slotParams: CoercedParams\n): CoercedParams {\n return Object.assign(Object.create(null), mainParams, slotParams);\n}\n\n/**\n * Resolve the params for a segment path against a published slot map.\n *\n * Returns the merge when `segmentPath` names a slot that published params,\n * and the main route's record otherwise — an ordinary (non-slot) segment\n * path, an unknown path, or a request with no slots at all. Mirrors the\n * server's `getSegmentParams(segmentPath)` branch exactly.\n *\n * `Object.hasOwn` rather than `in` or a truthiness test: the map arrives from\n * JSON, so a segment path of `constructor` or `toString` would otherwise\n * resolve to an inherited member of `Object.prototype`.\n */\nexport function resolveSegmentParams(\n mainParams: CoercedParams,\n slotParams: SlotParamsRecord | null | undefined,\n segmentPath: string | undefined\n): CoercedParams {\n if (!segmentPath || !slotParams || !Object.hasOwn(slotParams, segmentPath)) return mainParams;\n return cachedMerge(mainParams, slotParams, segmentPath);\n}\n\n/**\n * The merged record for one (main record, slot map, path) triple, reused until\n * one of the three changes.\n *\n * `useSegmentParams(slotPath)` calls this on every render. Returning a fresh\n * object each time makes the hook's result change by reference on renders where\n * nothing navigated, so a component using it as a `useEffect` dependency\n * re-runs the effect — and re-renders in a loop if that effect sets state —\n * while memoized children below it lose their memoization.\n *\n * Keyed on the *identities* of the two records, not their contents: both are\n * replaced rather than mutated on every navigation (`ParamsProvider`'s memoized\n * value and the server's per-request store), so identity is the correct\n * equality here and a deep comparison would be slower and no more accurate.\n *\n * A `WeakMap` chain rather than a `Map`, so a superseded navigation's records\n * and their merges become collectable as soon as nothing else holds them.\n */\nconst mergeCache = new WeakMap<object, WeakMap<object, Map<string, CoercedParams>>>();\n\nfunction cachedMerge(\n mainParams: CoercedParams,\n slotParams: SlotParamsRecord,\n segmentPath: string\n): CoercedParams {\n let bySlotMap = mergeCache.get(mainParams);\n if (!bySlotMap) {\n bySlotMap = new WeakMap();\n mergeCache.set(mainParams, bySlotMap);\n }\n let byPath = bySlotMap.get(slotParams);\n if (!byPath) {\n byPath = new Map();\n bySlotMap.set(slotParams, byPath);\n }\n const cached = byPath.get(segmentPath);\n if (cached) return cached;\n const merged = mergeSlotParams(mainParams, slotParams[segmentPath]);\n byPath.set(segmentPath, merged);\n return merged;\n}\n","/**\n * Shared utility for merging preserved search params into a target URL.\n *\n * Used by both <Link> (client) and redirect() (server). Extracted to a shared\n * module to avoid importing client code ('use client') from server modules.\n */\n\n/**\n * Merge preserved search params from the current URL into a target href.\n *\n * When `preserve` is `true`, all current search params are merged.\n * When `preserve` is a `string[]`, only the named params are merged.\n *\n * The target href's own search params take precedence — preserved params\n * are only added if the target doesn't already define them.\n *\n * @param targetHref - The resolved target href (may already contain query string)\n * @param currentSearch - The current URL's search string (e.g. \"?private=access&page=2\")\n * @param preserve - `true` to preserve all, or `string[]` to preserve specific params\n * @returns The target href with preserved search params merged in\n */\nexport function mergePreservedSearchParams(\n targetHref: string,\n currentSearch: string,\n preserve: true | string[]\n): string {\n const currentParams = new URLSearchParams(currentSearch);\n if (currentParams.size === 0) return targetHref;\n\n // Split hash fragment from target before processing query params.\n // Hash must come after query string: /path?query=value#hash\n const hashIdx = targetHref.indexOf('#');\n const hrefWithoutHash = hashIdx >= 0 ? targetHref.slice(0, hashIdx) : targetHref;\n const hash = hashIdx >= 0 ? targetHref.slice(hashIdx) : '';\n\n // Split target into path and existing query\n const qIdx = hrefWithoutHash.indexOf('?');\n const targetPath = qIdx >= 0 ? hrefWithoutHash.slice(0, qIdx) : hrefWithoutHash;\n const targetParams = new URLSearchParams(qIdx >= 0 ? hrefWithoutHash.slice(qIdx + 1) : '');\n\n // Collect params to preserve (that aren't already in the target)\n const merged = new URLSearchParams(targetParams);\n for (const [key, value] of currentParams) {\n // Only preserve if: (a) not already in target, and (b) included in preserve list\n if (!targetParams.has(key)) {\n if (preserve === true || preserve.includes(key)) {\n merged.append(key, value);\n }\n }\n }\n\n const qs = merged.toString();\n const pathWithQuery = qs ? `${targetPath}?${qs}` : targetPath;\n return pathWithQuery + hash;\n}\n","/**\n * Shared href/URL validation for all navigation sinks.\n *\n * Used by <Link>, useRouter().push/replace, and redirectExternal().\n * Single source of truth for dangerous-scheme detection — prevents\n * control-character smuggling that bypasses naive regex checks.\n *\n * See design/13-security.md §\"Link scheme injection\" (test #9)\n * and design/07-routing.md §\"<Link> Scheme Validation\".\n */\n\n/**\n * All C0 control characters (U+0000–U+001F) that browsers strip during\n * URL preprocessing. Browsers and `new URL()` strip the full C0 range,\n * not just tab/LF/CR — so we must match that behavior to prevent\n * bypass vectors like `\\x00javascript:alert(1)`.\n */\n// eslint-disable-next-line no-control-regex -- intentional: must match all C0 controls to prevent bypass\nconst CONTROL_CHARS_RE = /[\\x00-\\x1f]/g;\n\nconst DANGEROUS_SCHEMES = new Set(['javascript:', 'data:', 'vbscript:']);\n\n/**\n * Strip C0 control chars and leading whitespace, then extract the scheme.\n * Returns the lowercase scheme (e.g. \"javascript:\") or null if no scheme.\n */\nfunction extractScheme(href: string): string | null {\n const cleaned = href.replace(CONTROL_CHARS_RE, '').trimStart();\n const match = /^([a-z][a-z0-9+.-]*:)/i.exec(cleaned);\n return match ? match[1].toLowerCase() : null;\n}\n\n/**\n * Validate an href for navigation sinks (<Link>, useRouter, etc.).\n *\n * Rejects dangerous schemes (javascript:, data:, vbscript:) even when\n * control characters are embedded to bypass naive regex checks.\n * Also rejects protocol-relative URLs (//evil.com).\n *\n * Throws on rejection. Safe hrefs pass through silently.\n */\nexport function validateNavigationHref(href: string): void {\n // Normalize for validation: strip C0 controls, trim, then replace backslashes\n // with forward slashes. Browsers normalize \\ → / during URL resolution, so\n // \"/\\evil.com\" becomes \"//evil.com\" (protocol-relative open redirect).\n const cleaned = href.replace(CONTROL_CHARS_RE, '').trimStart().replaceAll('\\\\', '/');\n\n // Protocol-relative URLs can redirect to attacker-controlled origins\n if (cleaned.startsWith('//')) {\n throw new Error(\n `Navigation received a protocol-relative or backslash-prefixed URL: \"${href}\". ` +\n 'Use an absolute URL with an explicit scheme or a relative path.'\n );\n }\n\n const scheme = extractScheme(href);\n if (scheme && DANGEROUS_SCHEMES.has(scheme)) {\n throw new Error(\n `Navigation received a dangerous href: \"${href}\". ` +\n 'javascript:, data:, and vbscript: URLs are not allowed.'\n );\n }\n}\n\n/**\n * Check if an href is internal (same-origin navigation) or external.\n *\n * Strips control characters before checking so that \"java\\tscript:\" is\n * correctly identified as having a scheme (and thus not internal).\n */\nexport function isInternalHref(href: string): boolean {\n const cleaned = href.replace(CONTROL_CHARS_RE, '').trimStart().replaceAll('\\\\', '/');\n\n if (cleaned.startsWith('//')) return false;\n if (cleaned.startsWith('/') || cleaned.startsWith('#') || cleaned.startsWith('?')) return true;\n\n const scheme = extractScheme(href);\n if (scheme) return false;\n\n return true;\n}\n\n/** Pattern matching absolute URLs: any scheme (http:, javascript:, …) or protocol-relative // */\nconst ABSOLUTE_URL_RE = /^(?:[a-zA-Z][a-zA-Z\\d+\\-.]*:|\\/\\/)/;\n\n/**\n * Assert that a redirect target is a relative path — rejects absolute and\n * protocol-relative URLs. Used by both the server `redirect()` primitive and\n * the client next/navigation shim so they enforce identical semantics.\n *\n * Normalizes for validation only: strips C0 controls, trims, then replaces\n * backslashes with forward slashes. Browsers normalize \\ → / during URL\n * resolution, so \"/\\evil.com\" becomes \"//evil.com\" (protocol-relative open\n * redirect). See design/13-security.md tests #8, #8a–#8c.\n */\nexport function assertRelativeRedirectPath(path: string): void {\n const cleaned = path.replace(CONTROL_CHARS_RE, '').trimStart().replaceAll('\\\\', '/');\n\n if (ABSOLUTE_URL_RE.test(cleaned)) {\n throw new Error(\n `redirect() only accepts relative URLs. Got absolute URL: \"${path}\". ` +\n 'Use redirectExternal(url, allowList) for external redirects.'\n );\n }\n\n // eslint-disable-next-line no-control-regex -- intentional: must match C0 controls\n if (/[\\x00-\\x1f]/.test(path)) {\n throw new Error(\n `redirect() received a path containing control characters (U+0000–U+001F). ` +\n 'Sanitize user input before passing it to redirect().'\n );\n }\n}\n\nconst SAFE_REDIRECT_SCHEMES = new Set(['http:', 'https:']);\n\n/**\n * Validate and canonicalize an external redirect URL.\n *\n * Requires http: or https: scheme and checks origin against an allow-list.\n * Returns the parsed canonical URL string (from URL.href) to prevent\n * raw user input from reaching the Location header.\n *\n * @throws On invalid URL, dangerous scheme, or origin not in allow-list.\n */\nexport function validateExternalRedirectUrl(url: string, allowList: string[]): string {\n // Strip control chars before parsing to prevent scheme smuggling\n const cleaned = url.replace(CONTROL_CHARS_RE, '').trimStart();\n\n if (cleaned.startsWith('//')) {\n throw new Error(\n `redirectExternal() received a protocol-relative URL: \"${url}\". ` +\n 'Use an absolute URL with http: or https: scheme.'\n );\n }\n\n let parsed: URL;\n try {\n parsed = new URL(cleaned);\n } catch {\n throw new Error(`redirectExternal() received an invalid URL: \"${url}\"`);\n }\n\n if (!SAFE_REDIRECT_SCHEMES.has(parsed.protocol)) {\n throw new Error(\n `redirectExternal() received a non-http(s) URL: \"${url}\". ` +\n 'Only http: and https: schemes are allowed for external redirects.'\n );\n }\n\n if (!allowList.includes(parsed.origin)) {\n throw new Error(\n `redirectExternal() target \"${parsed.origin}\" is not in the allow-list. ` +\n `Allowed: [${allowList.join(', ')}]`\n );\n }\n\n return parsed.href;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAwCA,SAAgB,gBACd,YACA,YACe;CACf,OAAO,OAAO,OAAO,OAAO,OAAO,IAAI,GAAG,YAAY,UAAU;AAClE;;;;;;;;;;;;;AAcA,SAAgB,qBACd,YACA,YACA,aACe;CACf,IAAI,CAAC,eAAe,CAAC,cAAc,CAAC,OAAO,OAAO,YAAY,WAAW,GAAG,OAAO;CACnF,OAAO,YAAY,YAAY,YAAY,WAAW;AACxD;;;;;;;;;;;;;;;;;;;AAoBA,IAAM,6BAAa,IAAI,QAA6D;AAEpF,SAAS,YACP,YACA,YACA,aACe;CACf,IAAI,YAAY,WAAW,IAAI,UAAU;CACzC,IAAI,CAAC,WAAW;EACd,4BAAY,IAAI,QAAQ;EACxB,WAAW,IAAI,YAAY,SAAS;CACtC;CACA,IAAI,SAAS,UAAU,IAAI,UAAU;CACrC,IAAI,CAAC,QAAQ;EACX,yBAAS,IAAI,IAAI;EACjB,UAAU,IAAI,YAAY,MAAM;CAClC;CACA,MAAM,SAAS,OAAO,IAAI,WAAW;CACrC,IAAI,QAAQ,OAAO;CACnB,MAAM,SAAS,gBAAgB,YAAY,WAAW,YAAY;CAClE,OAAO,IAAI,aAAa,MAAM;CAC9B,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;ACvFA,SAAgB,2BACd,YACA,eACA,UACQ;CACR,MAAM,gBAAgB,IAAI,gBAAgB,aAAa;CACvD,IAAI,cAAc,SAAS,GAAG,OAAO;CAIrC,MAAM,UAAU,WAAW,QAAQ,GAAG;CACtC,MAAM,kBAAkB,WAAW,IAAI,WAAW,MAAM,GAAG,OAAO,IAAI;CACtE,MA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