@timber-js/app 0.2.0-alpha.213 → 0.2.0-alpha.215
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_chunks/{actions-CEootpB1.js → actions-CUh3cClk.js} +2 -2
- package/dist/_chunks/{actions-CEootpB1.js.map → actions-CUh3cClk.js.map} +1 -1
- package/dist/_chunks/{canonicalize-CgHoscYO.js → canonicalize-BAWkWiKK.js} +28 -2
- package/dist/_chunks/{canonicalize-CgHoscYO.js.map → canonicalize-BAWkWiKK.js.map} +1 -1
- package/dist/_chunks/{chains-BfoPFraI.js → chains-CjK1Eu6a.js} +2 -2
- package/dist/_chunks/{chains-BfoPFraI.js.map → chains-CjK1Eu6a.js.map} +1 -1
- package/dist/_chunks/{classify-BT66U83D.js → classify-GAdt6aiA.js} +2 -2
- package/dist/_chunks/{classify-BT66U83D.js.map → classify-GAdt6aiA.js.map} +1 -1
- package/dist/_chunks/{cli-check-BfQ54-UJ.js → cli-check-DOzjlycg.js} +3 -3
- package/dist/_chunks/{cli-check-BfQ54-UJ.js.map → cli-check-DOzjlycg.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-czh2dsLs.js → cli-schema-sync-B9wDaQvW.js} +2 -2
- package/dist/_chunks/{cli-schema-sync-czh2dsLs.js.map → cli-schema-sync-B9wDaQvW.js.map} +1 -1
- package/dist/_chunks/{client-dep-entries-CQwpb8dI.js → client-dep-entries-DEp8ZHce.js} +47 -3
- package/dist/_chunks/client-dep-entries-DEp8ZHce.js.map +1 -0
- package/dist/_chunks/{convention-lint-BEVW4EID.js → convention-lint-B3QEGJX7.js} +2 -2
- package/dist/_chunks/{convention-lint-BEVW4EID.js.map → convention-lint-B3QEGJX7.js.map} +1 -1
- package/dist/_chunks/{dev-server-FKxptbnI.js → dev-server-_9L4KWC-.js} +3 -3
- package/dist/_chunks/{dev-server-FKxptbnI.js.map → dev-server-_9L4KWC-.js.map} +1 -1
- package/dist/_chunks/{error-boundary-9g_Lb2na.js → error-boundary-xxxLtXt6.js} +38 -5
- package/dist/_chunks/{error-boundary-9g_Lb2na.js.map → error-boundary-xxxLtXt6.js.map} +1 -1
- package/dist/_chunks/{live-graph-C_4v-fHv.js → live-graph-Cd3YHvrH.js} +4 -4
- package/dist/_chunks/{live-graph-C_4v-fHv.js.map → live-graph-Cd3YHvrH.js.map} +1 -1
- package/dist/_chunks/{poison-scan-C92liMAr.js → poison-scan-BnJjBOkn.js} +2 -2
- package/dist/_chunks/{poison-scan-C92liMAr.js.map → poison-scan-BnJjBOkn.js.map} +1 -1
- package/dist/_chunks/{scanner-CQt12vE2.js → scanner-CKAT5gRx.js} +2 -2
- package/dist/_chunks/{scanner-CQt12vE2.js.map → scanner-CKAT5gRx.js.map} +1 -1
- package/dist/_chunks/{walkers-DAT4avhZ.js → walkers-DwCXEyRu.js} +3 -3
- package/dist/_chunks/{walkers-DAT4avhZ.js.map → walkers-DwCXEyRu.js.map} +1 -1
- package/dist/adapters/nitro-preview.d.ts.map +1 -1
- package/dist/adapters/nitro.js +11 -2
- package/dist/adapters/nitro.js.map +1 -1
- package/dist/adapters/types.d.ts +3 -1
- package/dist/adapters/types.d.ts.map +1 -1
- package/dist/analyze/crawl-entry.js +3 -3
- package/dist/analyze/graph-command.js +2 -2
- package/dist/cli.d.ts +5 -5
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +15 -14
- package/dist/cli.js.map +1 -1
- package/dist/client/error-boundary.js +1 -1
- package/dist/client/internal.js +22 -7
- package/dist/client/internal.js.map +1 -1
- package/dist/client/router-effects.d.ts +70 -12
- package/dist/client/router-effects.d.ts.map +1 -1
- package/dist/client/router.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +27 -52
- package/dist/index.js.map +1 -1
- package/dist/plugins/client-dep-entries.d.ts +36 -0
- package/dist/plugins/client-dep-entries.d.ts.map +1 -1
- package/dist/routing/index.js +2 -2
- package/dist/server/canonicalize.d.ts +22 -0
- package/dist/server/canonicalize.d.ts.map +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/internal.js +54 -3
- package/dist/server/internal.js.map +1 -1
- package/dist/server/pipeline-helpers.d.ts +31 -0
- package/dist/server/pipeline-helpers.d.ts.map +1 -1
- package/dist/server/pipeline.d.ts.map +1 -1
- package/dist/server/port-resolution.d.ts +3 -12
- package/dist/server/port-resolution.d.ts.map +1 -1
- package/docs/api/36-cli.mdx +8 -4
- package/docs/learn/13-deploying.mdx +2 -0
- package/package.json +1 -1
- package/src/adapters/nitro-preview.ts +10 -1
- package/src/adapters/types.ts +3 -1
- package/src/cli.ts +18 -16
- package/src/client/router-effects.ts +99 -14
- package/src/client/router.ts +29 -13
- package/src/index.ts +48 -71
- package/src/plugins/client-dep-entries.ts +46 -0
- package/src/server/canonicalize.ts +29 -0
- package/src/server/pipeline-helpers.ts +61 -0
- package/src/server/pipeline.ts +13 -1
- package/src/server/port-resolution.ts +6 -16
- package/dist/_chunks/client-dep-entries-CQwpb8dI.js.map +0 -1
package/src/index.ts
CHANGED
|
@@ -270,6 +270,19 @@ export function timber(config?: TimberUserConfig): PluginOption[] {
|
|
|
270
270
|
api: { getContext: () => ctx } satisfies TimberPluginApi,
|
|
271
271
|
|
|
272
272
|
async config(userConfig, { command, isPreview }) {
|
|
273
|
+
// `vite preview` serves Vite's build.outDir as static files, and timber
|
|
274
|
+
// sets that to the whole build directory (below): the rsc/ and ssr/
|
|
275
|
+
// server bundles, with no root index.html in either output mode. Refuse
|
|
276
|
+
// it rather than expose the server code. `timber preview` resolves the
|
|
277
|
+
// project under `build`, so it never lands here. TIM-1565, design/25.
|
|
278
|
+
if (isPreview) {
|
|
279
|
+
throw new Error(
|
|
280
|
+
'[timber] `vite preview` cannot serve a timber build: it would serve the build ' +
|
|
281
|
+
'directory, server bundles included, as static files. Run `timber preview`, ' +
|
|
282
|
+
"which runs your adapter's preview()."
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
|
|
273
286
|
// ── Load timber.config.ts from the correct root ───────────────
|
|
274
287
|
// Vite's `config` hook fires before `configResolved`. The user's
|
|
275
288
|
// `root` option (if set) tells us where the project lives.
|
|
@@ -319,23 +332,12 @@ export function timber(config?: TimberUserConfig): PluginOption[] {
|
|
|
319
332
|
// production jsx-runtime doesn't export jsxDEV). The oxc.jsx
|
|
320
333
|
// override below fixes Vite's native path; plugin-react's compiler
|
|
321
334
|
// plugin is handled by patchReactCompilerForProdJsx above.
|
|
322
|
-
// ── Resolve dev
|
|
335
|
+
// ── Resolve dev port (TIM-842) ───────────────────────────────
|
|
323
336
|
// Default port is 3000. Vite handles conflicts and honors server.strictPort.
|
|
324
|
-
//
|
|
325
|
-
// For dev (`command === 'serve' && !isPreview`) we start the
|
|
326
|
-
// holding server on the requested port when available.
|
|
327
|
-
//
|
|
328
|
-
// For `vite preview` (`command === 'serve' && isPreview`) we
|
|
329
|
-
// resolve the config/env port but delegate the actual bind +
|
|
330
|
-
// auto-bump to Vite's own preview server. Starting the holding
|
|
331
|
-
// server in preview mode would self-conflict because the dev
|
|
332
|
-
// plugin's `configureServer` handoff does not run for preview;
|
|
333
|
-
// the holding server would keep the port occupied while Vite's
|
|
334
|
-
// preview tried to bind the same port.
|
|
337
|
+
// We start the holding server on the requested port when available.
|
|
335
338
|
//
|
|
336
339
|
// See design/21-dev-server.md §"Default Port and Auto-Bump".
|
|
337
340
|
let resolvedDevPort: number | null = null;
|
|
338
|
-
let resolvedDevPortExplicit = false;
|
|
339
341
|
// Middleware-mode embeddings (the analyze crawl, custom servers)
|
|
340
342
|
// never bind a port, and the dev-server plugin's listen() handoff
|
|
341
343
|
// that closes the holding server never runs — starting it would
|
|
@@ -351,39 +353,20 @@ export function timber(config?: TimberUserConfig): PluginOption[] {
|
|
|
351
353
|
: userConfig.server?.host === true
|
|
352
354
|
? undefined
|
|
353
355
|
: 'localhost';
|
|
354
|
-
if (command === 'serve' && !
|
|
355
|
-
const start = resolveStartPort({
|
|
356
|
-
configPort: userConfig.server?.port,
|
|
357
|
-
envPort: process.env.PORT,
|
|
358
|
-
});
|
|
356
|
+
if (command === 'serve' && !isMiddlewareMode) {
|
|
359
357
|
// Vite owns port selection and remembers its bound port on restart.
|
|
360
358
|
// Never forward a probed/bumped port: replacement config runs while
|
|
361
359
|
// the old listener still owns the port. The holding page is optional.
|
|
362
|
-
resolvedDevPort =
|
|
363
|
-
|
|
364
|
-
|
|
360
|
+
resolvedDevPort = resolveStartPort({
|
|
361
|
+
configPort: userConfig.server?.port,
|
|
362
|
+
envPort: process.env.PORT,
|
|
363
|
+
});
|
|
364
|
+
if (resolvedDevPort !== 0) {
|
|
365
365
|
ctx.holdingServer = createHoldingServer();
|
|
366
|
-
await ctx.holdingServer.listen(
|
|
366
|
+
await ctx.holdingServer.listen(resolvedDevPort, resolvedHost).catch(() => {
|
|
367
367
|
ctx.holdingServer = null;
|
|
368
368
|
});
|
|
369
369
|
}
|
|
370
|
-
} else if (command === 'serve' && isPreview) {
|
|
371
|
-
// Preview mode: resolve the starting port from config/env/
|
|
372
|
-
// default but do NOT probe. Vite's preview server handles the
|
|
373
|
-
// bind itself, with `preview.strictPort` controlling whether
|
|
374
|
-
// an in-use port auto-bumps (implicit) or errors (explicit).
|
|
375
|
-
const previewConfigPort =
|
|
376
|
-
typeof userConfig.preview?.port === 'number'
|
|
377
|
-
? userConfig.preview.port
|
|
378
|
-
: typeof userConfig.server?.port === 'number'
|
|
379
|
-
? userConfig.server.port
|
|
380
|
-
: undefined;
|
|
381
|
-
const start = resolveStartPort({
|
|
382
|
-
configPort: previewConfigPort,
|
|
383
|
-
envPort: process.env.PORT,
|
|
384
|
-
});
|
|
385
|
-
resolvedDevPort = start.port;
|
|
386
|
-
resolvedDevPortExplicit = start.explicit;
|
|
387
370
|
}
|
|
388
371
|
|
|
389
372
|
// Derive relative buildOutDir from the absolute buildDir (set above)
|
|
@@ -429,32 +412,20 @@ export function timber(config?: TimberUserConfig): PluginOption[] {
|
|
|
429
412
|
};
|
|
430
413
|
}
|
|
431
414
|
|
|
432
|
-
// Dev
|
|
433
|
-
//
|
|
415
|
+
// Dev mode: set outDir so dev-time references are consistent, and
|
|
416
|
+
// surface the resolved port to Vite.
|
|
434
417
|
//
|
|
435
418
|
// Dev auto-bumps unless the user sets server.strictPort.
|
|
436
419
|
// Always forward the requested port so Vite can recognize unchanged
|
|
437
420
|
// config and reuse its actual bound port across restarts (TIM-1456).
|
|
438
|
-
//
|
|
439
|
-
// For `vite preview`, we set `preview.strictPort` based on
|
|
440
|
-
// whether the user explicitly set the port. Implicit (default)
|
|
441
|
-
// preview uses strictPort: false so Vite's preview server can
|
|
442
|
-
// auto-bump from 3000. Explicit preview uses strictPort: true
|
|
443
|
-
// so conflicts fail loudly, matching the dev behavior and the
|
|
444
|
-
// TIM-842 spec.
|
|
445
421
|
const serverConfig: {
|
|
446
422
|
port?: number;
|
|
447
423
|
strictPort?: boolean;
|
|
448
424
|
forwardConsole?: boolean | { unhandledErrors?: boolean; logLevels?: string[] };
|
|
449
425
|
} = {};
|
|
450
|
-
const previewConfig: { port?: number; strictPort?: boolean } = {};
|
|
451
426
|
if (resolvedDevPort != null) {
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
serverConfig.strictPort = resolvedDevPortExplicit;
|
|
455
|
-
}
|
|
456
|
-
previewConfig.port = resolvedDevPort;
|
|
457
|
-
previewConfig.strictPort = resolvedDevPortExplicit;
|
|
427
|
+
serverConfig.port = resolvedDevPort;
|
|
428
|
+
serverConfig.strictPort = userConfig.server?.strictPort ?? false;
|
|
458
429
|
}
|
|
459
430
|
|
|
460
431
|
// Enable Vite 8's built-in browser→terminal console forwarding.
|
|
@@ -476,29 +447,35 @@ export function timber(config?: TimberUserConfig): PluginOption[] {
|
|
|
476
447
|
// Seed the client optimizer's startup crawl with every 'use client'
|
|
477
448
|
// file so client-only packages are pre-bundled before the first
|
|
478
449
|
// request, not discovered mid-load (which full-reloads the page).
|
|
479
|
-
// Vite concatenates these with any entries the user sets.
|
|
450
|
+
// Vite concatenates these with any entries the user sets. The scan
|
|
451
|
+
// plugin keeps that crawl out of 'use server' modules, whose imports
|
|
452
|
+
// the browser never loads; Vite's mergeConfig concatenates it with any
|
|
453
|
+
// user or plugin-rsc rolldownOptions.plugins rather than replacing them. Its per-file
|
|
454
|
+
// cost lands inside Vite's own scan, not in client-deps-scan.
|
|
480
455
|
// See design/21-dev-server.md §"Client Dependency Pre-Bundling".
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
ctx.timer.end('client-deps-scan');
|
|
489
|
-
environments = {
|
|
490
|
-
...envOutDirs,
|
|
491
|
-
client: { ...envOutDirs.client, optimizeDeps: { entries } },
|
|
492
|
-
};
|
|
493
|
-
}
|
|
456
|
+
ctx.timer.start('client-deps-scan');
|
|
457
|
+
// Loaded lazily: directive detection pulls in @vitejs/plugin-rsc's
|
|
458
|
+
// transforms, which builds never need.
|
|
459
|
+
const { clientOptimizeDepsEntries, skipUseServerScanPlugin } =
|
|
460
|
+
await import('./plugins/client-dep-entries.ts');
|
|
461
|
+
const entries = await clientOptimizeDepsEntries(resolvedRoot, BROWSER_ENTRY_FILE, buildDir);
|
|
462
|
+
ctx.timer.end('client-deps-scan');
|
|
494
463
|
|
|
495
464
|
return {
|
|
496
465
|
build: { outDir: buildOutDir },
|
|
497
|
-
environments
|
|
466
|
+
environments: {
|
|
467
|
+
...envOutDirs,
|
|
468
|
+
client: {
|
|
469
|
+
...envOutDirs.client,
|
|
470
|
+
optimizeDeps: {
|
|
471
|
+
entries,
|
|
472
|
+
rolldownOptions: { plugins: [skipUseServerScanPlugin()] },
|
|
473
|
+
},
|
|
474
|
+
},
|
|
475
|
+
},
|
|
498
476
|
optimizeDeps: { exclude: timberOptimizeDepsExclude },
|
|
499
477
|
customLogger,
|
|
500
478
|
server: serverConfig,
|
|
501
|
-
preview: previewConfig,
|
|
502
479
|
};
|
|
503
480
|
},
|
|
504
481
|
configResolved(resolved) {
|
|
@@ -18,6 +18,14 @@
|
|
|
18
18
|
* the browser entry is listed too. Files that gain the directive after
|
|
19
19
|
* startup still fall back to Vite's late discovery.
|
|
20
20
|
*
|
|
21
|
+
* The crawl follows those entries' imports into `'use server'` modules
|
|
22
|
+
* too, because Vite's scanner does not run plugin-rsc's transforms — at
|
|
23
|
+
* runtime the browser only ever sees server references in their place.
|
|
24
|
+
* Without help the optimizer pre-bundles the actions' server-only
|
|
25
|
+
* packages (database clients, cloud SDKs) for the browser, slowing cold
|
|
26
|
+
* start or failing the whole client optimizer when one cannot bundle.
|
|
27
|
+
* `skipUseServerScanPlugin` stubs those modules out of the crawl.
|
|
28
|
+
*
|
|
21
29
|
* Design docs: 21-dev-server.md §"Client Dependency Pre-Bundling".
|
|
22
30
|
*/
|
|
23
31
|
|
|
@@ -53,6 +61,44 @@ export async function findUseClientFiles(root: string, excludeDir?: string): Pro
|
|
|
53
61
|
return matches.filter((file): file is string => file !== null);
|
|
54
62
|
}
|
|
55
63
|
|
|
64
|
+
/**
|
|
65
|
+
* The scanner's replacement for an app source file whose directive
|
|
66
|
+
* prologue holds `'use server'`: an empty module, so the crawl stops
|
|
67
|
+
* there. Returns null (load normally) for every other file. A
|
|
68
|
+
* `'use server'` inside a function body (an inline action in a server
|
|
69
|
+
* component) is not a module directive and leaves the file alone.
|
|
70
|
+
*/
|
|
71
|
+
export async function useServerScanStub(id: string): Promise<string | null> {
|
|
72
|
+
const file = normalizeSlashes(id);
|
|
73
|
+
if (file.includes('/node_modules/') || !PARSEABLE_EXTENSIONS.test(file)) return null;
|
|
74
|
+
const code = await readFile(id, 'utf8').catch(() => null);
|
|
75
|
+
if (code === null || !code.includes('use server')) return null;
|
|
76
|
+
return detectDirective(code, file) === 'use server' ? 'export {}' : null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* A rolldown plugin for the client environment's
|
|
81
|
+
* `optimizeDeps.rolldownOptions.plugins`. Vite's scanner runs these
|
|
82
|
+
* before its own scan plugin, so this `load` hook decides what the crawl
|
|
83
|
+
* sees of each app source file (Vite has no JS load hook of its own
|
|
84
|
+
* there; rolldown reads the file).
|
|
85
|
+
*
|
|
86
|
+
* Vite also runs these plugins in the optimizer's bundle step. That step
|
|
87
|
+
* bundles the discovered dependencies, which live in node_modules, so the
|
|
88
|
+
* node_modules guard makes the hook a no-op there. The exception is a
|
|
89
|
+
* linked package outside node_modules listed in `optimizeDeps.include`
|
|
90
|
+
* with a module-level `'use server'` file: named imports from the stub
|
|
91
|
+
* fail that bundle (MISSING_EXPORT). Unstubbed, it would ship the server
|
|
92
|
+
* code to the browser instead, so such a package must not be
|
|
93
|
+
* pre-bundled either way.
|
|
94
|
+
*/
|
|
95
|
+
export function skipUseServerScanPlugin(): {
|
|
96
|
+
name: string;
|
|
97
|
+
load: (id: string) => Promise<string | null>;
|
|
98
|
+
} {
|
|
99
|
+
return { name: 'timber:client-deps-skip-use-server', load: useServerScanStub };
|
|
100
|
+
}
|
|
101
|
+
|
|
56
102
|
/**
|
|
57
103
|
* Escape a path for use as an `optimizeDeps.entries` pattern. Vite globs
|
|
58
104
|
* entries, and route directories are full of glob syntax: `(group)`,
|
|
@@ -91,3 +91,32 @@ export function canonicalize(rawPathname: string, stripTrailingSlash = true): Ca
|
|
|
91
91
|
|
|
92
92
|
return { ok: true, pathname };
|
|
93
93
|
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The path a safe request for `rawPathname` should be redirected to — or
|
|
97
|
+
* `rawPathname` itself when it is already canonical.
|
|
98
|
+
*
|
|
99
|
+
* Applies the structural steps of `canonicalize()` — collapse `//` (step 3)
|
|
100
|
+
* and strip the trailing slash (step 5) — to the **encoded** path, without
|
|
101
|
+
* decoding. That is what the browser will send back, so the redirect is
|
|
102
|
+
* idempotent: `/%61dmin` differs from its canonical form `/admin` only by
|
|
103
|
+
* percent-encoding, and redirecting it to `/admin` would compare against the
|
|
104
|
+
* decoded form forever. Decoding cannot introduce a `/` (`%2f` is rejected),
|
|
105
|
+
* so the structure is the same before and after decoding.
|
|
106
|
+
*
|
|
107
|
+
* Dot segments are not handled here: the request URL is parsed by the WHATWG
|
|
108
|
+
* URL parser, which has already resolved `.`, `..` and their encoded forms.
|
|
109
|
+
*
|
|
110
|
+
* Only meaningful for a path `canonicalize()` accepted. The collapse also
|
|
111
|
+
* means the result can never start with `//`, so it is never a
|
|
112
|
+
* protocol-relative redirect target.
|
|
113
|
+
*
|
|
114
|
+
* See design/07-routing.md §"Non-Canonical URLs Redirect"
|
|
115
|
+
*/
|
|
116
|
+
export function canonicalRequestPath(rawPathname: string, stripTrailingSlash = true): string {
|
|
117
|
+
let pathname = rawPathname.replace(/\/\/+/g, '/');
|
|
118
|
+
if (stripTrailingSlash && pathname.length > 1 && pathname.endsWith('/')) {
|
|
119
|
+
pathname = pathname.slice(0, -1);
|
|
120
|
+
}
|
|
121
|
+
return pathname;
|
|
122
|
+
}
|
|
@@ -28,6 +28,9 @@ import { isApiRouteChain, isCsrfExemptRoute, type ManifestSegmentNode } from './
|
|
|
28
28
|
import type { ProxyConfig, RouteMatcher } from './pipeline.ts';
|
|
29
29
|
import { csrfRejectionResponse, validateCsrf, type CsrfConfig } from './csrf.ts';
|
|
30
30
|
import type { PhaseName } from './pipeline-outcome.ts';
|
|
31
|
+
import { canonicalRequestPath } from './canonicalize.ts';
|
|
32
|
+
import { isRscRequest } from '../shared/rsc-media-type.ts';
|
|
33
|
+
import { appVisibleSearch } from '../shared/rsc-cache-key.ts';
|
|
31
34
|
|
|
32
35
|
// ─── Prototype-Pollution-Safe Sanitizer ────────────────────────────────────
|
|
33
36
|
|
|
@@ -66,6 +69,64 @@ export function csrfGate(
|
|
|
66
69
|
return exempt ? null : csrfRejectionResponse(req, result);
|
|
67
70
|
}
|
|
68
71
|
|
|
72
|
+
// ─── Canonical Redirect ────────────────────────────────────────────────────
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The redirect for a safe request whose URL is not canonical, or null to
|
|
76
|
+
* serve it.
|
|
77
|
+
*
|
|
78
|
+
* A GET for `/admin/` used to render with a 200 at that URL. The server
|
|
79
|
+
* rendered with the canonical `/admin` while the browser hydrated with the
|
|
80
|
+
* raw `/admin/`, so anything branching on `usePathname()` hydrated
|
|
81
|
+
* mismatched (TIM-1571). Redirecting makes the address bar — the client's
|
|
82
|
+
* copy of the URL — the canonical one, and leaves one URL per page for
|
|
83
|
+
* caches and crawlers.
|
|
84
|
+
*
|
|
85
|
+
* Only GET and HEAD are redirected. Every other method — an action's POST,
|
|
86
|
+
* a CORS preflight — is served at the canonical path, as before: a
|
|
87
|
+
* redirected POST is re-sent by the browser, which an action must not
|
|
88
|
+
* depend on.
|
|
89
|
+
*
|
|
90
|
+
* Runs inside proxy.ts's `next()`, not before it, so proxy.ts still runs
|
|
91
|
+
* on every request and its headers land on the redirect. A cross-origin
|
|
92
|
+
* `GET /api/items/` needs proxy.ts's CORS headers on the 308 itself:
|
|
93
|
+
* browsers apply the CORS check to a redirect response.
|
|
94
|
+
*
|
|
95
|
+
* A document request gets a relative 308 (never built from `Host`). A page
|
|
96
|
+
* navigation gets the router's soft redirect, decided exactly as for a
|
|
97
|
+
* `redirect()` outcome: an RSC request that does not match a route.ts
|
|
98
|
+
* handler (`buildRedirectResponse`). The framework's `_rsc` cache key is
|
|
99
|
+
* dropped from the soft target; the router appends a fresh one when it
|
|
100
|
+
* fetches the canonical URL.
|
|
101
|
+
*
|
|
102
|
+
* See design/07-routing.md §"Non-Canonical URLs Redirect".
|
|
103
|
+
*/
|
|
104
|
+
export function canonicalRedirect(
|
|
105
|
+
req: Request,
|
|
106
|
+
canonicalPath: string,
|
|
107
|
+
stripTrailingSlash: boolean,
|
|
108
|
+
matchRoute: RouteMatcher
|
|
109
|
+
): Response | null {
|
|
110
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return null;
|
|
111
|
+
const url = new URL(req.url);
|
|
112
|
+
const target = canonicalRequestPath(url.pathname, stripTrailingSlash);
|
|
113
|
+
if (target === url.pathname) return null;
|
|
114
|
+
const navigation = isRscRequest(req) && !isApiRoutePath(canonicalPath, matchRoute);
|
|
115
|
+
const search = navigation ? appVisibleSearch(url).search : url.search;
|
|
116
|
+
return buildRedirectResponse(new RedirectSignal(target + search, 308), new Headers(), navigation);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Whether `path` matches a route.ts handler. A matcher that throws: no. */
|
|
120
|
+
function isApiRoutePath(path: string, matchRoute: RouteMatcher): boolean {
|
|
121
|
+
try {
|
|
122
|
+
const match = matchRoute(path);
|
|
123
|
+
return match !== null && isApiRouteChain(match.segments);
|
|
124
|
+
} catch (err) {
|
|
125
|
+
swallow(err, 'canonical redirect: route match for route.ts lookup threw');
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
69
130
|
// ─── Proxy Resolver ────────────────────────────────────────────────────────
|
|
70
131
|
|
|
71
132
|
/**
|
package/src/server/pipeline.ts
CHANGED
|
@@ -32,7 +32,7 @@ import {
|
|
|
32
32
|
import { logRequestReceived, logRequestCompleted, logSlowRequest } from './logger.ts';
|
|
33
33
|
import { DenySignal } from './primitives.ts';
|
|
34
34
|
import type { ManifestSegmentNode } from './route-matcher.ts';
|
|
35
|
-
import { csrfGate, makeProxyResolver } from './pipeline-helpers.ts';
|
|
35
|
+
import { canonicalRedirect, csrfGate, makeProxyResolver } from './pipeline-helpers.ts';
|
|
36
36
|
import type { CsrfConfig } from './csrf.ts';
|
|
37
37
|
import { handleRequest, runProxyPhase } from './pipeline-phases.ts';
|
|
38
38
|
import { outcomeToResponse } from './pipeline-outcome.ts';
|
|
@@ -402,6 +402,18 @@ export function createPipeline(config: PipelineConfig): (req: Request) => Promis
|
|
|
402
402
|
// TIM-1213: action dispatch is now INSIDE the pipeline so
|
|
403
403
|
// proxy.ts runs on every request, including action POSTs.
|
|
404
404
|
const innerHandler = async (): Promise<Response> => {
|
|
405
|
+
// A safe request for a non-canonical URL (`/x/`, `/a//b`) is
|
|
406
|
+
// redirected to the canonical one instead of served, so the
|
|
407
|
+
// client hydrates with the pathname the server renders with
|
|
408
|
+
// (TIM-1571). Inside proxy.ts's next(), so proxy.ts still runs
|
|
409
|
+
// on every request and its headers (CORS) reach the redirect.
|
|
410
|
+
const redirect = canonicalRedirect(
|
|
411
|
+
req,
|
|
412
|
+
canonicalPath,
|
|
413
|
+
stripTrailingSlash,
|
|
414
|
+
config.matchRoute
|
|
415
|
+
);
|
|
416
|
+
if (redirect) return redirect;
|
|
405
417
|
if (config.dispatchAction) {
|
|
406
418
|
const actionResult = await config.dispatchAction(
|
|
407
419
|
canonicalReq,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
/** Port input precedence for dev
|
|
1
|
+
/** Port input precedence for dev. Vite owns binding and restart reuse. */
|
|
2
2
|
|
|
3
|
-
/** Default port used by `timber dev
|
|
3
|
+
/** Default port used by `timber dev`. */
|
|
4
4
|
export const DEFAULT_PORT = 3000;
|
|
5
5
|
|
|
6
6
|
// ── Pure resolution ────────────────────────────────────────────────────
|
|
@@ -18,36 +18,26 @@ export interface ResolvePortInput {
|
|
|
18
18
|
defaultPort?: number;
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
export interface ResolvedPortInput {
|
|
22
|
-
/** Port to start binding from. */
|
|
23
|
-
port: number;
|
|
24
|
-
/**
|
|
25
|
-
* `true` if the port came from an explicit user override (config or
|
|
26
|
-
* env). Preview uses this to default to strict port binding.
|
|
27
|
-
*/
|
|
28
|
-
explicit: boolean;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
21
|
/**
|
|
32
22
|
* Pure: compute the starting port from config / env / defaults.
|
|
33
23
|
*
|
|
34
24
|
* Performs no I/O.
|
|
35
25
|
*/
|
|
36
|
-
export function resolveStartPort(input: ResolvePortInput):
|
|
26
|
+
export function resolveStartPort(input: ResolvePortInput): number {
|
|
37
27
|
const defaultPort = input.defaultPort ?? DEFAULT_PORT;
|
|
38
28
|
|
|
39
29
|
// `configPort` wins over `envPort`. This matches Vite's behavior:
|
|
40
30
|
// `vite --port 4000` overrides `PORT=5000` in the environment.
|
|
41
31
|
if (typeof input.configPort === 'number' && Number.isFinite(input.configPort)) {
|
|
42
|
-
return
|
|
32
|
+
return input.configPort;
|
|
43
33
|
}
|
|
44
34
|
|
|
45
35
|
if (input.envPort != null && input.envPort !== '') {
|
|
46
36
|
const parsed = Number(input.envPort);
|
|
47
37
|
if (Number.isFinite(parsed) && parsed > 0) {
|
|
48
|
-
return
|
|
38
|
+
return parsed;
|
|
49
39
|
}
|
|
50
40
|
}
|
|
51
41
|
|
|
52
|
-
return
|
|
42
|
+
return defaultPort;
|
|
53
43
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"client-dep-entries-CQwpb8dI.js","names":[],"sources":["../../src/plugins/client-dep-entries.ts"],"sourcesContent":["/**\n * client-dep-entries — seed the client dep optimizer's startup scan with\n * the app's `'use client'` modules.\n *\n * Vite's dev optimizer discovers bare imports by crawling from its\n * entries before the first request. With no `optimizeDeps.entries`, the\n * client environment crawls its build input — timber's browser entry —\n * and nothing more: every `'use client'` module is reached only through\n * the RSC payload at runtime, never through a static import the crawl\n * can follow. A package imported only from client components is then\n * found on the first browser request, re-optimized mid-load, and the\n * page full-reloads (\"optimized dependencies changed. reloading\"). That\n * reload can leave react and react-dom from two optimizer runs in the\n * browser (duplicate React → \"Invalid hook call\").\n *\n * Listing the `'use client'` files as entries lets the startup crawl see\n * those imports. Setting `entries` replaces the build-input default, so\n * the browser entry is listed too. Files that gain the directive after\n * startup still fall back to Vite's late discovery.\n *\n * Design docs: 21-dev-server.md §\"Client Dependency Pre-Bundling\".\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { sep } from 'node:path';\nimport { detectDirective, PARSEABLE_EXTENSIONS } from '../analyze/classify.ts';\nimport { normalizeSlashes, scanProjectSourceFiles } from '../analyze/scan.ts';\n\n/**\n * Every project source file under `root` whose directive prologue holds\n * `'use client'`. Uses the same walker as `timber graph` (node_modules,\n * root-level dot dirs and build outputs skipped) and the same AST\n * directive check the RSC plugin applies. Files under `excludeDir` (the\n * build output) are skipped.\n */\nexport async function findUseClientFiles(root: string, excludeDir?: string): Promise<string[]> {\n const files: string[] = [];\n // An unreadable directory only means its client deps are discovered\n // late, through Vite's normal fallback — never fatal for dev startup.\n await scanProjectSourceFiles(root, files, () => {}, 0, PARSEABLE_EXTENSIONS);\n const excludePrefix = excludeDir ? excludeDir + sep : undefined;\n const candidates = excludePrefix ? files.filter((f) => !f.startsWith(excludePrefix)) : files;\n\n const matches = await Promise.all(\n candidates.map(async (file) => {\n const code = await readFile(file, 'utf8').catch(() => null);\n // Cheap text gate before parsing: a directive is a literal\n // without escapes, so a file lacking the text cannot carry it.\n if (code === null || !code.includes('use client')) return null;\n return detectDirective(code, file) === 'use client' ? file : null;\n })\n );\n return matches.filter((file): file is string => file !== null);\n}\n\n/**\n * Escape a path for use as an `optimizeDeps.entries` pattern. Vite globs\n * entries, and route directories are full of glob syntax: `(group)`,\n * `[slug]`, `[[...catchAll]]`, `@slot`. Slashes are normalized first, so\n * the only backslashes left are literal (POSIX) ones, which are escaped\n * too.\n */\nexport function escapeGlobPath(path: string): string {\n return normalizeSlashes(path).replace(/[\\\\()[\\]{}*?|!+@]/g, '\\\\$&');\n}\n\n/**\n * The client environment's `optimizeDeps.entries`: timber's browser\n * entry plus every `'use client'` file in the project.\n */\nexport async function clientOptimizeDepsEntries(\n root: string,\n browserEntryFile: string,\n buildDir: string\n): Promise<string[]> {\n const clientFiles = await findUseClientFiles(root, buildDir);\n return [browserEntryFile, ...clientFiles].map(escapeGlobPath);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,eAAsB,mBAAmB,MAAc,YAAwC;CAC7F,MAAM,QAAkB,CAAC;CAGzB,MAAM,uBAAuB,MAAM,aAAa,CAAC,GAAG,GAAG,oBAAoB;CAC3E,MAAM,gBAAgB,aAAa,aAAa,MAAM,KAAA;CACtD,MAAM,aAAa,gBAAgB,MAAM,QAAQ,MAAM,CAAC,EAAE,WAAW,aAAa,CAAC,IAAI;CAWvF,QAAO,MATe,QAAQ,IAC5B,WAAW,IAAI,OAAO,SAAS;EAC7B,MAAM,OAAO,MAAM,SAAS,MAAM,MAAM,CAAC,CAAC,YAAY,IAAI;EAG1D,IAAI,SAAS,QAAQ,CAAC,KAAK,SAAS,YAAY,GAAG,OAAO;EAC1D,OAAO,gBAAgB,MAAM,IAAI,MAAM,eAAe,OAAO;CAC/D,CAAC,CACH,EAAA,CACe,QAAQ,SAAyB,SAAS,IAAI;AAC/D;;;;;;;;AASA,SAAgB,eAAe,MAAsB;CACnD,OAAO,iBAAiB,IAAI,CAAC,CAAC,QAAQ,sBAAsB,MAAM;AACpE;;;;;AAMA,eAAsB,0BACpB,MACA,kBACA,UACmB;CAEnB,OAAO,CAAC,kBAAkB,GAAG,MADH,mBAAmB,MAAM,QAAQ,CACnB,CAAC,CAAC,IAAI,cAAc;AAC9D"}
|