@timber-js/app 0.2.0-alpha.216 → 0.2.0-alpha.218
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-CUh3cClk.js.map +1 -1
- package/dist/_chunks/cloudflare-Byxl8FWP.js.map +1 -1
- package/dist/_chunks/dev-server-B8zsT-ee.js.map +1 -1
- package/dist/_chunks/dist-DtrJyBbw.js.map +1 -1
- package/dist/_chunks/graph-cache-CYiUS2aS.js.map +1 -1
- package/dist/_chunks/use-query-states-I3JMng6J.js.map +1 -1
- package/dist/adapters/cloudflare.js +1 -2
- package/dist/adapters/nitro-immutable-assets.d.ts +47 -0
- package/dist/adapters/nitro-immutable-assets.d.ts.map +1 -0
- package/dist/adapters/nitro-preview.d.ts +3 -2
- package/dist/adapters/nitro-preview.d.ts.map +1 -1
- package/dist/adapters/nitro.d.ts +16 -2
- package/dist/adapters/nitro.d.ts.map +1 -1
- package/dist/adapters/nitro.js +130 -10
- package/dist/adapters/nitro.js.map +1 -1
- package/dist/analyze/graph-command.js.map +1 -1
- package/dist/client/error-boundary.js +1 -2
- package/dist/cookies/index.js.map +1 -1
- package/dist/index.js +29 -26
- package/dist/index.js.map +1 -1
- package/dist/plugins/build-manifest.d.ts.map +1 -1
- package/dist/search-params/index.js.map +1 -1
- package/dist/server/internal.js +11 -2
- package/dist/server/internal.js.map +1 -1
- package/dist/server/pipeline-metadata.d.ts +9 -0
- package/dist/server/pipeline-metadata.d.ts.map +1 -1
- package/dist/server/pipeline-phases.d.ts.map +1 -1
- package/dist/server/sitemap-handler.d.ts.map +1 -1
- package/docs/api/34-api-config.mdx +1 -1
- package/package.json +8 -8
- package/src/adapters/nitro-immutable-assets.ts +142 -0
- package/src/adapters/nitro-preview.ts +12 -3
- package/src/adapters/nitro.ts +31 -17
- package/src/client/browser-entry/index.ts +7 -1
- package/src/plugins/build-manifest.ts +12 -27
- package/src/server/pipeline-metadata.ts +11 -1
- package/src/server/pipeline-phases.ts +9 -2
- package/src/server/sitemap-handler.ts +14 -21
|
@@ -6,6 +6,15 @@
|
|
|
6
6
|
*
|
|
7
7
|
* See design/16-metadata.md §"Metadata Routes"
|
|
8
8
|
*/
|
|
9
|
+
/**
|
|
10
|
+
* Cache-Control the framework sets on metadata route responses it produces:
|
|
11
|
+
* static files, serialized handler results (sitemap, robots, manifest) and
|
|
12
|
+
* the auto-generated sitemap. A Response a handler returns is sent with its
|
|
13
|
+
* own headers only — the framework adds no default to it.
|
|
14
|
+
*
|
|
15
|
+
* See design/16-metadata.md §"Caching" (under "Metadata Routes")
|
|
16
|
+
*/
|
|
17
|
+
export declare const METADATA_CACHE_CONTROL = "public, max-age=14400, must-revalidate";
|
|
9
18
|
/**
|
|
10
19
|
* Serve a static metadata file by reading it from disk.
|
|
11
20
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pipeline-metadata.d.ts","sourceRoot":"","sources":["../../src/server/pipeline-metadata.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;
|
|
1
|
+
{"version":3,"file":"pipeline-metadata.d.ts","sourceRoot":"","sources":["../../src/server/pipeline-metadata.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH;;;;;;;GAOG;AACH,eAAO,MAAM,sBAAsB,2CAA2C,CAAC;AAc/E;;;;;;;;GAQG;AACH,wBAAsB,uBAAuB,CAC3C,SAAS,EAAE,OAAO,oBAAoB,EAAE,kBAAkB,GACzD,OAAO,CAAC,QAAQ,CAAC,CAanB;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,KAAK,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;IACZ,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,CAAC,GACD,MAAM,CAoBR;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,WAAW,EAAE,MAAM,EAAE,GAAG,MAAM,CAMnE;AAED,qCAAqC;AACrC,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAO7C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pipeline-phases.d.ts","sourceRoot":"","sources":["../../src/server/pipeline-phases.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;
|
|
1
|
+
{"version":3,"file":"pipeline-phases.d.ts","sourceRoot":"","sources":["../../src/server/pipeline-phases.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AA0BH,OAAO,EAKL,KAAK,aAAa,EACnB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAoC,KAAK,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAC5F,OAAO,KAAK,EAAE,mBAAmB,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAMrF,UAAU,aAAa;IACrB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,mBAAmB,CAAC;CACpC;AAID;;;;;;;;GAQG;AACH,wBAAsB,aAAa,CACjC,MAAM,EAAE,cAAc,EACtB,QAAQ,EAAE,aAAa,EACvB,GAAG,EAAE,OAAO,EACZ,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,MAAM,OAAO,CAAC,QAAQ,CAAC,GAC7B,OAAO,CAAC,YAAY,CAAC,CAavB;AAID;;;;GAIG;AACH,wBAAsB,kBAAkB,CACtC,MAAM,EAAE,cAAc,EACtB,GAAG,EAAE,OAAO,EACZ,KAAK,EAAE,UAAU,EACjB,eAAe,EAAE,OAAO,EACxB,aAAa,EAAE,aAAa,GAC3B,OAAO,CAAC,YAAY,CAAC,CAsDvB;AAID;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,cAAc,CAClC,MAAM,EAAE,cAAc,EACtB,GAAG,EAAE,OAAO,EACZ,KAAK,EAAE,UAAU,EACjB,eAAe,EAAE,OAAO,EACxB,EAAE,iBAAiB,EAAE,YAAY,EAAE,EAAE,aAAa,GACjD,OAAO,CAAC,YAAY,CAAC,CAYvB;AAID;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,aAAa,CACjC,MAAM,EAAE,cAAc,EACtB,GAAG,EAAE,OAAO,EACZ,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,eAAe,CAAC,EAAE,OAAO,GACxB,OAAO,CAAC,QAAQ,CAAC,CA0RnB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sitemap-handler.d.ts","sourceRoot":"","sources":["../../src/server/sitemap-handler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;
|
|
1
|
+
{"version":3,"file":"sitemap-handler.d.ts","sourceRoot":"","sources":["../../src/server/sitemap-handler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAUH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAevD;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CACtC,IAAI,EAAE,WAAW,EACjB,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GACrC,CAAC,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAAC,GAAG,SAAS,CAuG9D"}
|
|
@@ -356,4 +356,4 @@ type BuildArtifacts =
|
|
|
356
356
|
};
|
|
357
357
|
```
|
|
358
358
|
|
|
359
|
-
Every path is absolute. `prebuilt` and `manifestInit` are absent when the build did not produce them, so check the field rather than whether a directory exists on disk. `immutableDirs` lists the directories of the served site whose file names are content-hashed — such as `assets`, `_timber/fonts`, and a static build's `_rsc` — relative to the site root, without a leading slash or the deployment `base`. Give those a long-lived `immutable` cache
|
|
359
|
+
Every path is absolute. `prebuilt` and `manifestInit` are absent when the build did not produce them, so check the field rather than whether a directory exists on disk. `immutableDirs` lists the directories of the served site whose file names are content-hashed — such as `assets`, `_timber/fonts`, and a static build's `_rsc` — relative to the site root, without a leading slash or the deployment `base`. Give the files in those directories a long-lived `immutable` cache header instead of hard-coding the paths. Set it only on a response that served a file. A rule that matches by path alone also covers the 404 for a file that is missing, for example during a rolling deploy when one server has a new asset and another does not. A CDN would then cache that 404 for a year. `preview()` runs in a separate process after the build, so instead of `BuildArtifacts` it receives the build output directory and the configured `output` mode.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@timber-js/app",
|
|
3
|
-
"version": "0.2.0-alpha.
|
|
3
|
+
"version": "0.2.0-alpha.218",
|
|
4
4
|
"description": "Vite-native React framework built for Servers and Serverless Platforms — correct HTTP semantics, real status codes, pages that work without JavaScript",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare-workers",
|
|
@@ -152,13 +152,13 @@
|
|
|
152
152
|
},
|
|
153
153
|
"dependencies": {
|
|
154
154
|
"@opentelemetry/api": "^1.9.1",
|
|
155
|
-
"@opentelemetry/context-async-hooks": "^2.
|
|
156
|
-
"@opentelemetry/sdk-trace-base": "^2.
|
|
155
|
+
"@opentelemetry/context-async-hooks": "^2.12.0",
|
|
156
|
+
"@opentelemetry/sdk-trace-base": "^2.12.0",
|
|
157
157
|
"cookie": "^2.0.1",
|
|
158
158
|
"jsonc-parser": "^3.3.1",
|
|
159
|
-
"magic-string": "^1.4.
|
|
159
|
+
"magic-string": "^1.4.3",
|
|
160
160
|
"nitro": "3.0.260903-beta",
|
|
161
|
-
"oxc-transform-react": "^0.
|
|
161
|
+
"oxc-transform-react": "^0.153.0",
|
|
162
162
|
"srvx": "^1.0.5"
|
|
163
163
|
},
|
|
164
164
|
"peerDependencies": {
|
|
@@ -167,10 +167,10 @@
|
|
|
167
167
|
"@content-collections/vite": "^0.2.0 || ^0.3.0",
|
|
168
168
|
"@typescript/native-preview": "^7.0.0-dev.0",
|
|
169
169
|
"@vitejs/plugin-react": "^6.1.0",
|
|
170
|
-
"@vitejs/plugin-rsc": "
|
|
170
|
+
"@vitejs/plugin-rsc": "^0.5.35",
|
|
171
171
|
"nuqs": "^2.0.0",
|
|
172
|
-
"react": "
|
|
173
|
-
"react-dom": "
|
|
172
|
+
"react": "19.3.0",
|
|
173
|
+
"react-dom": "19.3.0",
|
|
174
174
|
"satteri": "^0.9.5",
|
|
175
175
|
"vite": "8.3.0",
|
|
176
176
|
"vite-plugin-satteri": "^0.2.15",
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// Immutable caching for the build's content-hashed directories on Nitro.
|
|
2
|
+
//
|
|
3
|
+
// A one-year `immutable` Cache-Control is correct only on a response that
|
|
4
|
+
// served a file. Nitro route rules cannot tell a hit from a miss — their
|
|
5
|
+
// headers land on every response under the path, the 404 for a file that is
|
|
6
|
+
// not there included — so a CDN in front of a pod that lacked the file mid
|
|
7
|
+
// rollout cached that 404 for a year (TIM-1578). Nitro's public-asset `maxAge`
|
|
8
|
+
// option is a route rule underneath, with the same reach.
|
|
9
|
+
//
|
|
10
|
+
// Instead, three pieces, all keyed by one generated path matcher:
|
|
11
|
+
//
|
|
12
|
+
// - Each directory is its own non-fallthrough public-asset directory. Where
|
|
13
|
+
// Nitro serves files itself, a GET or HEAD miss there is a 404 from its
|
|
14
|
+
// static handler; Vercel and Netlify route such misses to a platform 404
|
|
15
|
+
// instead of the function.
|
|
16
|
+
// - timber's Nitro entry answers any request under those directories that
|
|
17
|
+
// still reaches it with a plain `no-store` 404, before the app runs. Nothing
|
|
18
|
+
// else answers there: a preset without Nitro's static handler (aws-lambda),
|
|
19
|
+
// a method the static handler ignores, or a path it does not claim
|
|
20
|
+
// (`/assets/`) gets the 404 rather than a page.
|
|
21
|
+
// - A Nitro runtime plugin sets Cache-Control from the outcome. Since only a
|
|
22
|
+
// served file can succeed under those directories, a successful GET or HEAD
|
|
23
|
+
// is a hit.
|
|
24
|
+
//
|
|
25
|
+
// See design/25-production-deployments.md §"Hashed assets".
|
|
26
|
+
|
|
27
|
+
import { writeFile } from 'node:fs/promises';
|
|
28
|
+
import { join } from 'node:path';
|
|
29
|
+
import { IMMUTABLE_CACHE } from './shared.ts';
|
|
30
|
+
|
|
31
|
+
/** The generated module, written beside the Nitro entry that imports it. */
|
|
32
|
+
const IMMUTABLE_ASSETS_MODULE = '_immutable-assets.mjs';
|
|
33
|
+
|
|
34
|
+
/** One Nitro `publicAssets` entry. */
|
|
35
|
+
interface NitroPublicAssetDir {
|
|
36
|
+
dir: string;
|
|
37
|
+
baseURL: string;
|
|
38
|
+
fallthrough: false;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The Nitro config that serves `immutableDirs` from `<nitroDir>/public`. */
|
|
42
|
+
export interface ImmutableAssetsNitroConfig {
|
|
43
|
+
publicAssets: NitroPublicAssetDir[];
|
|
44
|
+
plugins: string[];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Write the generated module into `nitroDir` and return the Nitro config that
|
|
49
|
+
* serves the build's content-hashed directories from `<nitroDir>/public`.
|
|
50
|
+
*
|
|
51
|
+
* No `maxAge`: Nitro would turn it into a route rule (see the module header),
|
|
52
|
+
* and Vercel already gives a non-fallthrough directory a one-year immutable
|
|
53
|
+
* header on hits and `no-store` on misses by default.
|
|
54
|
+
*/
|
|
55
|
+
export async function prepareImmutableAssets(
|
|
56
|
+
nitroDir: string,
|
|
57
|
+
immutableDirs: readonly string[]
|
|
58
|
+
): Promise<ImmutableAssetsNitroConfig> {
|
|
59
|
+
if (immutableDirs.length === 0) return { publicAssets: [], plugins: [] };
|
|
60
|
+
const plugin = join(nitroDir, IMMUTABLE_ASSETS_MODULE);
|
|
61
|
+
await writeFile(plugin, generateImmutableAssetsModule(immutableDirs));
|
|
62
|
+
return {
|
|
63
|
+
publicAssets: immutableDirs.map((dir) => ({
|
|
64
|
+
dir: join(nitroDir, 'public', dir),
|
|
65
|
+
baseURL: `/${dir}`,
|
|
66
|
+
fallthrough: false,
|
|
67
|
+
})),
|
|
68
|
+
plugins: [plugin],
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The lines timber's Nitro entry needs to answer a request under the
|
|
74
|
+
* content-hashed directories itself: an import, and a guard to run before
|
|
75
|
+
* the handler, with the h3 event in scope as `event`. Empty when the build
|
|
76
|
+
* has no such directories, which also means `prepareImmutableAssets()`
|
|
77
|
+
* writes no module to import.
|
|
78
|
+
*/
|
|
79
|
+
export function immutableAssetsEntryGuard(immutableDirs: readonly string[]): {
|
|
80
|
+
imports: string;
|
|
81
|
+
guard: string;
|
|
82
|
+
} {
|
|
83
|
+
if (immutableDirs.length === 0) return { imports: '', guard: '' };
|
|
84
|
+
return {
|
|
85
|
+
imports: `import { isImmutableAssetPath } from './${IMMUTABLE_ASSETS_MODULE}'\n`,
|
|
86
|
+
guard: ` // Under a content-hashed directory only a served file may answer; the
|
|
87
|
+
// static handler already sent any file there is. A no-store 404, never a
|
|
88
|
+
// page — see _immutable-assets.mjs.
|
|
89
|
+
if (isImmutableAssetPath(event.url.pathname)) {
|
|
90
|
+
return new Response('Not Found', {
|
|
91
|
+
status: 404,
|
|
92
|
+
headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },
|
|
93
|
+
})
|
|
94
|
+
}
|
|
95
|
+
`,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Generate the module shared by the Nitro entry and runtime: the path matcher
|
|
101
|
+
* for the content-hashed directories, and the runtime plugin that owns
|
|
102
|
+
* Cache-Control under them — `IMMUTABLE_CACHE` on a GET or HEAD that served
|
|
103
|
+
* the file (200, or 304 revalidating it), `no-store` on everything else.
|
|
104
|
+
*
|
|
105
|
+
* Status is a sound signal only because the entry answers everything else
|
|
106
|
+
* under these directories with a 404 (see `immutableAssetsEntryGuard`). The
|
|
107
|
+
* prefixes are matched against the decoded path, the one Nitro's static
|
|
108
|
+
* handler looks the file up by.
|
|
109
|
+
*
|
|
110
|
+
* @internal Exported for testing.
|
|
111
|
+
*/
|
|
112
|
+
export function generateImmutableAssetsModule(immutableDirs: readonly string[]): string {
|
|
113
|
+
const prefixes = immutableDirs.map((dir) => `/${dir}/`);
|
|
114
|
+
return `// Generated by @timber-js/app — Cache-Control for content-hashed directories.
|
|
115
|
+
// Do not edit — this file is regenerated on each build.
|
|
116
|
+
|
|
117
|
+
const PREFIXES = ${JSON.stringify(prefixes)};
|
|
118
|
+
const IMMUTABLE_CACHE = ${JSON.stringify(IMMUTABLE_CACHE)};
|
|
119
|
+
|
|
120
|
+
export function isImmutableAssetPath(pathname) {
|
|
121
|
+
let path = pathname;
|
|
122
|
+
try {
|
|
123
|
+
path = decodeURI(pathname);
|
|
124
|
+
} catch {
|
|
125
|
+
// Malformed escapes: match the path as received.
|
|
126
|
+
}
|
|
127
|
+
return PREFIXES.some((prefix) => path.startsWith(prefix));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export default function immutableAssets(nitroApp) {
|
|
131
|
+
// Hooks are off only if a user's nitroConfig disables them; files then go
|
|
132
|
+
// without the long-lived header rather than failing every request.
|
|
133
|
+
nitroApp.hooks?.hook('response', (res, event) => {
|
|
134
|
+
if (!isImmutableAssetPath(event.url.pathname)) return;
|
|
135
|
+
const method = event.req.method;
|
|
136
|
+
const served =
|
|
137
|
+
(method === 'GET' || method === 'HEAD') && (res.status === 200 || res.status === 304);
|
|
138
|
+
res.headers.set('Cache-Control', served ? IMMUTABLE_CACHE : 'no-store');
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
`;
|
|
142
|
+
}
|
|
@@ -74,8 +74,9 @@ export type PreviewScriptOptions = StaticPreviewScriptOptions | ServerPreviewScr
|
|
|
74
74
|
|
|
75
75
|
interface PreviewScriptOptionsBase {
|
|
76
76
|
/**
|
|
77
|
-
* `BuildArtifacts.immutableDirs` — served with a one-year
|
|
78
|
-
* `Cache-Control`, every other file with a revalidating one.
|
|
77
|
+
* `BuildArtifacts.immutableDirs` — files there are served with a one-year
|
|
78
|
+
* immutable `Cache-Control`, every other file with a revalidating one. In
|
|
79
|
+
* a server build, a miss there is a plain `no-store` 404.
|
|
79
80
|
*/
|
|
80
81
|
immutableDirs: readonly string[];
|
|
81
82
|
/**
|
|
@@ -167,7 +168,15 @@ const { sendNodeResponse } = await import('./_send-response.mjs');
|
|
|
167
168
|
res.writeHead(404, { 'Content-Type': 'text/plain' });
|
|
168
169
|
res.end('Not Found');
|
|
169
170
|
`
|
|
170
|
-
: `
|
|
171
|
+
: ` // A request under a content-hashed directory that names no file is a
|
|
172
|
+
// plain no-store 404, never a render of the app — as timber's Nitro entry
|
|
173
|
+
// answers it in production (TIM-1578).
|
|
174
|
+
if (pathname !== null && IMMUTABLE_PREFIXES.some((prefix) => pathname.startsWith(prefix))) {
|
|
175
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
176
|
+
res.end('Not Found');
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
await handleDynamic(req, res, url);
|
|
171
180
|
`;
|
|
172
181
|
|
|
173
182
|
const dynamicHandler =
|
package/src/adapters/nitro.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import { existsSync } from 'node:fs';
|
|
9
9
|
import { cp, glob, readFile, writeFile } from 'node:fs/promises';
|
|
10
10
|
import { basename, dirname, join, relative, sep } from 'node:path';
|
|
11
|
+
import type { NitroConfig } from 'nitro/types';
|
|
11
12
|
import {
|
|
12
13
|
buildStaticDirectoryOutput,
|
|
13
14
|
runSharedBuildSteps,
|
|
@@ -15,13 +16,14 @@ import {
|
|
|
15
16
|
} from './build-output-helper.ts';
|
|
16
17
|
import { generateCompressModule } from './compress-module.ts';
|
|
17
18
|
import { generateCanonicalizeModule } from './canonicalize-module.ts';
|
|
19
|
+
import { immutableAssetsEntryGuard, prepareImmutableAssets } from './nitro-immutable-assets.ts';
|
|
18
20
|
import { LOCALLY_PREVIEWABLE, PRESET_CONFIGS, type NitroPreset } from './nitro-presets.ts';
|
|
19
21
|
import {
|
|
20
22
|
generatePreviewScript,
|
|
21
23
|
generateSendResponseModule,
|
|
22
24
|
spawnNitroPreview,
|
|
23
25
|
} from './nitro-preview.ts';
|
|
24
|
-
import { adapterBase
|
|
26
|
+
import { adapterBase } from './shared.ts';
|
|
25
27
|
import type {
|
|
26
28
|
BuildArtifacts,
|
|
27
29
|
PreviewTarget,
|
|
@@ -80,7 +82,7 @@ export interface NitroAdapterOptions {
|
|
|
80
82
|
* Additional Nitro configuration to merge into the generated config.
|
|
81
83
|
* Overrides default values for the selected preset.
|
|
82
84
|
*/
|
|
83
|
-
nitroConfig?:
|
|
85
|
+
nitroConfig?: NitroConfig;
|
|
84
86
|
}
|
|
85
87
|
|
|
86
88
|
// ─── Adapter ─────────────────────────────────────────────────────────────────
|
|
@@ -206,7 +208,7 @@ export function nitro(options: NitroAdapterOptions = {}): TimberPlatformAdapter
|
|
|
206
208
|
}
|
|
207
209
|
|
|
208
210
|
// Generate the Nitro entry point (imports from ./rsc/ within nitro dir)
|
|
209
|
-
const entry = generateNitroEntry(preset, compress);
|
|
211
|
+
const entry = generateNitroEntry(preset, compress, artifacts.immutableDirs);
|
|
210
212
|
await writeFile(join(outDir, 'entry.ts'), entry);
|
|
211
213
|
|
|
212
214
|
// Run the Nitro build to produce a production-ready server bundle.
|
|
@@ -283,7 +285,11 @@ function importSpecifier(fromDir: string, file: string): string {
|
|
|
283
285
|
// ─── Entry Generation ────────────────────────────────────────────────────────
|
|
284
286
|
|
|
285
287
|
/** @internal Exported for testing. */
|
|
286
|
-
export function generateNitroEntry(
|
|
288
|
+
export function generateNitroEntry(
|
|
289
|
+
preset: NitroPreset,
|
|
290
|
+
compress = true,
|
|
291
|
+
immutableDirs: readonly string[] = []
|
|
292
|
+
): string {
|
|
287
293
|
// The RSC entry is the main request handler — it exports the fetch handler as default.
|
|
288
294
|
// rsc/ is copied into the nitro dir so the import is local.
|
|
289
295
|
// The manifest init is prepended to rsc/index.js before the nitro build,
|
|
@@ -344,12 +350,13 @@ export function generateNitroEntry(preset: NitroPreset, compress = true): string
|
|
|
344
350
|
|
|
345
351
|
const compressImport = compress ? "import { compressResponse } from './_compress.mjs'\n" : '';
|
|
346
352
|
const compressCall = compress ? 'compressResponse(webRequest, webResponse)' : 'webResponse';
|
|
353
|
+
const immutableAssets = immutableAssetsEntryGuard(immutableDirs);
|
|
347
354
|
|
|
348
355
|
return `// Generated by @timber-js/app/adapters/nitro
|
|
349
356
|
// Do not edit — this file is regenerated on each build.
|
|
350
357
|
|
|
351
358
|
import handler, { runWithEarlyHintsSender${waitUntilImport} } from '${serverEntryRelative}'
|
|
352
|
-
${compressImport}
|
|
359
|
+
${compressImport}${immutableAssets.imports}
|
|
353
360
|
// Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.
|
|
354
361
|
// See design/25-production-deployments.md §"TIMBER_RUNTIME".
|
|
355
362
|
process.env.TIMBER_RUNTIME = '${runtimeName}'
|
|
@@ -360,7 +367,7 @@ process.env.TIMBER_RUNTIME = '${runtimeName}'
|
|
|
360
367
|
// Nitro bundles h3 into its internal _libs/ directory but doesn't make
|
|
361
368
|
// it available as a bare specifier in the output's node_modules.
|
|
362
369
|
export default async function timberHandler(event) {
|
|
363
|
-
// h3 v2: event.req is the Web Request
|
|
370
|
+
${immutableAssets.guard} // h3 v2: event.req is the Web Request
|
|
364
371
|
const webRequest = event.req
|
|
365
372
|
${handlerCall}
|
|
366
373
|
return ${compressCall}
|
|
@@ -452,24 +459,27 @@ export function getPostBuildHint(preset: NitroPreset): string | null {
|
|
|
452
459
|
: null;
|
|
453
460
|
}
|
|
454
461
|
|
|
462
|
+
interface NitroBuildResult {
|
|
463
|
+
/** Resolved output.serverDir — where the server bundle + _chunks/ live. */
|
|
464
|
+
serverDir: string;
|
|
465
|
+
}
|
|
466
|
+
|
|
455
467
|
/**
|
|
456
468
|
* Run the Nitro production build using the programmatic API.
|
|
457
469
|
* Uses dynamic import so nitro is only loaded at build time.
|
|
458
470
|
* Externalizes the timber RSC/SSR output — those files are pre-built
|
|
459
471
|
* by timber and have internal references that nitro's bundler can't follow.
|
|
472
|
+
*
|
|
473
|
+
* @internal Exported for testing.
|
|
460
474
|
*/
|
|
461
|
-
|
|
462
|
-
/** Resolved output.serverDir — where the server bundle + _chunks/ live. */
|
|
463
|
-
serverDir: string;
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
async function runNitroBuild(
|
|
475
|
+
export async function runNitroBuild(
|
|
467
476
|
nitroDir: string,
|
|
468
477
|
preset: NitroPreset,
|
|
469
478
|
immutableDirs: readonly string[],
|
|
470
|
-
userConfig?:
|
|
479
|
+
userConfig?: NitroConfig
|
|
471
480
|
): Promise<NitroBuildResult> {
|
|
472
481
|
const presetConfig = PRESET_CONFIGS[preset];
|
|
482
|
+
const immutableAssets = await prepareImmutableAssets(nitroDir, immutableDirs);
|
|
473
483
|
const {
|
|
474
484
|
createNitro,
|
|
475
485
|
build: nitroBuild,
|
|
@@ -485,10 +495,6 @@ async function runNitroBuild(
|
|
|
485
495
|
// Using `entry` directly would bypass the Nitro server runtime.
|
|
486
496
|
renderer: { handler: join(nitroDir, 'entry.ts') },
|
|
487
497
|
output: { dir: join(nitroDir, presetConfig.outputDir) },
|
|
488
|
-
// One rule per content-hashed directory the build recorded.
|
|
489
|
-
routeRules: Object.fromEntries(
|
|
490
|
-
immutableDirs.map((dir) => [`/${dir}/**`, { headers: { 'Cache-Control': IMMUTABLE_CACHE } }])
|
|
491
|
-
),
|
|
492
498
|
// Don't bundle the timber RSC/SSR build output — it has its own
|
|
493
499
|
// internal file references that nitro's bundler can't follow.
|
|
494
500
|
// Mark them as external so rollup leaves the imports as-is.
|
|
@@ -497,6 +503,14 @@ async function runNitroBuild(
|
|
|
497
503
|
},
|
|
498
504
|
...presetConfig.extraConfig,
|
|
499
505
|
...userConfig,
|
|
506
|
+
// The content-hashed directories the build recorded: immutable on a hit,
|
|
507
|
+
// a no-store 404 on a miss. Not route rules, which cannot tell the two
|
|
508
|
+
// apart (TIM-1578) — see nitro-immutable-assets.ts. Set after the user's
|
|
509
|
+
// config, which may add public-asset directories and plugins but not drop
|
|
510
|
+
// these: without them a handler could answer 200 under a hashed directory
|
|
511
|
+
// and be marked immutable.
|
|
512
|
+
publicAssets: [...immutableAssets.publicAssets, ...(userConfig?.publicAssets ?? [])],
|
|
513
|
+
plugins: [...immutableAssets.plugins, ...(userConfig?.plugins ?? [])],
|
|
500
514
|
});
|
|
501
515
|
|
|
502
516
|
// Drop nitro's `npx nitro preview` / `npx nitro deploy` hints —
|
|
@@ -78,7 +78,13 @@ function bootstrap(runtimeConfig: typeof config, formState: ReactFormState | nul
|
|
|
78
78
|
|
|
79
79
|
// Static mode: fetch _rsc/*.rsc files instead of route URLs with
|
|
80
80
|
// Accept headers. Static hosts ignore Accept headers (TIM-1243).
|
|
81
|
-
|
|
81
|
+
// Only for built output — the .rsc files exist only after static
|
|
82
|
+
// generation, and `timber dev` renders route URLs on request like
|
|
83
|
+
// server mode, so dev keeps the Accept-header fetch path.
|
|
84
|
+
if (
|
|
85
|
+
(runtimeConfig as Record<string, unknown>).output === 'static' &&
|
|
86
|
+
!(runtimeConfig as Record<string, unknown>).dev
|
|
87
|
+
) {
|
|
82
88
|
setStaticMode(true);
|
|
83
89
|
}
|
|
84
90
|
|
|
@@ -22,7 +22,6 @@ import type { Plugin, ResolvedConfig } from 'vite';
|
|
|
22
22
|
import type { PluginContext } from '../plugin-context.ts';
|
|
23
23
|
import { EMPTY_BUILD_MANIFEST, type BuildManifest } from '../server/build-manifest.ts';
|
|
24
24
|
import type { SegmentNode, RouteFile } from '../routing/types.ts';
|
|
25
|
-
import { isDynamicMetadataExtension } from '../server/metadata-routes.ts';
|
|
26
25
|
|
|
27
26
|
// Rollup types used by generateBundle hook — imported from vite which re-exports them.
|
|
28
27
|
// We define minimal interfaces here to avoid a direct 'rollup' dependency.
|
|
@@ -217,36 +216,22 @@ function collectTransitiveBundleDeps(
|
|
|
217
216
|
}
|
|
218
217
|
|
|
219
218
|
/**
|
|
220
|
-
* Walk the route tree and compute short content hashes for metadata route
|
|
221
|
-
*
|
|
222
|
-
*
|
|
219
|
+
* Walk the route tree and compute short content hashes for metadata route
|
|
220
|
+
* files, used to cache-bust the auto-linked opengraph-image URL in <head>.
|
|
221
|
+
* A dynamic handler (.ts/.tsx) is hashed by its source: its output can depend
|
|
222
|
+
* on runtime data too, but the source is the best build-time signal there is.
|
|
223
|
+
* An unreadable file gets no hash, and the link falls back to the per-startup
|
|
224
|
+
* nonce.
|
|
223
225
|
*/
|
|
224
226
|
function computeMetadataRouteHashes(node: SegmentNode<RouteFile>): Record<string, string> {
|
|
225
227
|
const hashes: Record<string, string> = {};
|
|
226
228
|
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
const hash = createHash('sha256').update(content).digest('hex').slice(0, 8);
|
|
234
|
-
hashes[file.filePath] = hash;
|
|
235
|
-
} catch {
|
|
236
|
-
// File unreadable — skip hash, DEV_NONCE fallback applies
|
|
237
|
-
}
|
|
238
|
-
} else {
|
|
239
|
-
// For dynamic files (.ts/.tsx), hash the source file as a reasonable
|
|
240
|
-
// approximation — the output depends on runtime data too, but the
|
|
241
|
-
// source change is the best build-time signal we have.
|
|
242
|
-
try {
|
|
243
|
-
const content = readFileSync(file.filePath);
|
|
244
|
-
const hash = createHash('sha256').update(content).digest('hex').slice(0, 8);
|
|
245
|
-
hashes[file.filePath] = hash;
|
|
246
|
-
} catch {
|
|
247
|
-
// File unreadable — skip
|
|
248
|
-
}
|
|
249
|
-
}
|
|
229
|
+
for (const file of Object.values(node.metadataRoutes ?? {})) {
|
|
230
|
+
try {
|
|
231
|
+
const content = readFileSync(file.filePath);
|
|
232
|
+
hashes[file.filePath] = createHash('sha256').update(content).digest('hex').slice(0, 8);
|
|
233
|
+
} catch {
|
|
234
|
+
// File unreadable — skip hash, dev nonce fallback applies
|
|
250
235
|
}
|
|
251
236
|
}
|
|
252
237
|
|
|
@@ -9,6 +9,16 @@
|
|
|
9
9
|
|
|
10
10
|
import { readFile } from 'node:fs/promises';
|
|
11
11
|
|
|
12
|
+
/**
|
|
13
|
+
* Cache-Control the framework sets on metadata route responses it produces:
|
|
14
|
+
* static files, serialized handler results (sitemap, robots, manifest) and
|
|
15
|
+
* the auto-generated sitemap. A Response a handler returns is sent with its
|
|
16
|
+
* own headers only — the framework adds no default to it.
|
|
17
|
+
*
|
|
18
|
+
* See design/16-metadata.md §"Caching" (under "Metadata Routes")
|
|
19
|
+
*/
|
|
20
|
+
export const METADATA_CACHE_CONTROL = 'public, max-age=14400, must-revalidate';
|
|
21
|
+
|
|
12
22
|
/**
|
|
13
23
|
* Content types that are text-based and should include charset=utf-8.
|
|
14
24
|
* Binary formats (images) should not include charset.
|
|
@@ -41,7 +51,7 @@ export async function serveStaticMetadataFile(
|
|
|
41
51
|
const headers: Record<string, string> = {
|
|
42
52
|
'Content-Type': isText ? `${contentType}; charset=utf-8` : contentType,
|
|
43
53
|
'Content-Length': String(body.byteLength),
|
|
44
|
-
'Cache-Control':
|
|
54
|
+
'Cache-Control': METADATA_CACHE_CONTROL,
|
|
45
55
|
};
|
|
46
56
|
|
|
47
57
|
return new Response(body, { status: 200, headers });
|
|
@@ -28,7 +28,11 @@ import { logRenderError } from './logger.ts';
|
|
|
28
28
|
import { isDenySignal, isRedirectSignal } from './signal-identity.ts';
|
|
29
29
|
import { ParamCoercionError } from './param-coercion.ts';
|
|
30
30
|
import { checkVersionSkew, applyReloadHeaders } from './version-skew.ts';
|
|
31
|
-
import {
|
|
31
|
+
import {
|
|
32
|
+
METADATA_CACHE_CONTROL,
|
|
33
|
+
serveStaticMetadataFile,
|
|
34
|
+
serializeSitemap,
|
|
35
|
+
} from './pipeline-metadata.ts';
|
|
32
36
|
import { loadModule } from './safe-load.ts';
|
|
33
37
|
import { resolveInterceptedRoute } from './pipeline-interception.ts';
|
|
34
38
|
import { isApiRouteChain } from './route-matcher.ts';
|
|
@@ -271,6 +275,9 @@ export async function handleRequest(
|
|
|
271
275
|
// If the handler returns a Response, normalize headers so the
|
|
272
276
|
// outer Server-Timing writer can append without hitting an
|
|
273
277
|
// immutable header bag (e.g. user returns Response.redirect()).
|
|
278
|
+
// No default Cache-Control here: the handler runs in the request
|
|
279
|
+
// context and may vary on cookies or headers, so a public default
|
|
280
|
+
// could serve one user's response to another (#1064).
|
|
274
281
|
if (handlerResult instanceof Response) {
|
|
275
282
|
return cloneWithMutableHeaders(handlerResult);
|
|
276
283
|
}
|
|
@@ -294,7 +301,7 @@ export async function handleRequest(
|
|
|
294
301
|
status: 200,
|
|
295
302
|
headers: {
|
|
296
303
|
'Content-Type': `${contentType}; charset=utf-8`,
|
|
297
|
-
'Cache-Control':
|
|
304
|
+
'Cache-Control': METADATA_CACHE_CONTROL,
|
|
298
305
|
},
|
|
299
306
|
});
|
|
300
307
|
} catch (error) {
|
|
@@ -17,8 +17,19 @@ import {
|
|
|
17
17
|
type SitemapResult,
|
|
18
18
|
} from './sitemap-generator.ts';
|
|
19
19
|
import { loadModule } from './safe-load.ts';
|
|
20
|
+
import { METADATA_CACHE_CONTROL } from './pipeline-metadata.ts';
|
|
20
21
|
import type { SegmentNode } from '../routing/types.ts';
|
|
21
22
|
|
|
23
|
+
function xmlResponse(xml: string): Response {
|
|
24
|
+
return new Response(xml, {
|
|
25
|
+
status: 200,
|
|
26
|
+
headers: {
|
|
27
|
+
'Content-Type': 'application/xml; charset=utf-8',
|
|
28
|
+
'Cache-Control': METADATA_CACHE_CONTROL,
|
|
29
|
+
},
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
22
33
|
/** Regex to match /sitemap/N.xml where N is a non-negative integer. */
|
|
23
34
|
const SITEMAP_PAGE_PATTERN = /^\/sitemap\/(\d+)\.xml$/;
|
|
24
35
|
|
|
@@ -109,13 +120,7 @@ export function createAutoSitemapHandler(
|
|
|
109
120
|
if (pathname === '/sitemap.xml') {
|
|
110
121
|
const result = await getOrGenerateSitemap();
|
|
111
122
|
const xml = result.type === 'single' ? result.xml : result.indexXml;
|
|
112
|
-
return
|
|
113
|
-
status: 200,
|
|
114
|
-
headers: {
|
|
115
|
-
'Content-Type': 'application/xml; charset=utf-8',
|
|
116
|
-
'Cache-Control': 'public, max-age=14400, must-revalidate',
|
|
117
|
-
},
|
|
118
|
-
});
|
|
123
|
+
return xmlResponse(xml);
|
|
119
124
|
}
|
|
120
125
|
|
|
121
126
|
// Handle /sitemap/N.xml (paginated sub-sitemaps)
|
|
@@ -126,13 +131,7 @@ export function createAutoSitemapHandler(
|
|
|
126
131
|
// No pagination — only page 0 is valid for a single sitemap
|
|
127
132
|
const pageIndex = parseInt(pageMatch[1], 10);
|
|
128
133
|
if (pageIndex === 0) {
|
|
129
|
-
return
|
|
130
|
-
status: 200,
|
|
131
|
-
headers: {
|
|
132
|
-
'Content-Type': 'application/xml; charset=utf-8',
|
|
133
|
-
'Cache-Control': 'public, max-age=14400, must-revalidate',
|
|
134
|
-
},
|
|
135
|
-
});
|
|
134
|
+
return xmlResponse(result.xml);
|
|
136
135
|
}
|
|
137
136
|
return new Response(null, { status: 404 });
|
|
138
137
|
}
|
|
@@ -142,13 +141,7 @@ export function createAutoSitemapHandler(
|
|
|
142
141
|
if (!pageXml) {
|
|
143
142
|
return new Response(null, { status: 404 });
|
|
144
143
|
}
|
|
145
|
-
return
|
|
146
|
-
status: 200,
|
|
147
|
-
headers: {
|
|
148
|
-
'Content-Type': 'application/xml; charset=utf-8',
|
|
149
|
-
'Cache-Control': 'public, max-age=14400, must-revalidate',
|
|
150
|
-
},
|
|
151
|
-
});
|
|
144
|
+
return xmlResponse(pageXml);
|
|
152
145
|
}
|
|
153
146
|
|
|
154
147
|
// Not a sitemap URL — pass through
|