@timber-js/app 0.2.0-alpha.164 → 0.2.0-alpha.165
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/adapters/nitro.d.ts +29 -0
- package/dist/adapters/nitro.d.ts.map +1 -1
- package/dist/adapters/nitro.js +57 -10
- package/dist/adapters/nitro.js.map +1 -1
- package/package.json +1 -1
- package/src/adapters/nitro.ts +106 -4
package/dist/adapters/nitro.d.ts
CHANGED
|
@@ -12,6 +12,12 @@ interface PresetConfig {
|
|
|
12
12
|
nitroPreset: string;
|
|
13
13
|
/** Output directory name within the build dir. */
|
|
14
14
|
outputDir: string;
|
|
15
|
+
/**
|
|
16
|
+
* Path to the server bundle directory relative to outputDir.
|
|
17
|
+
* Nitro places the bundled server entry + _chunks/ here.
|
|
18
|
+
* Most presets use `server`; Vercel uses `functions/__server.func`.
|
|
19
|
+
*/
|
|
20
|
+
serverBundleDir: string;
|
|
15
21
|
/** Whether the runtime supports waitUntil. */
|
|
16
22
|
supportsWaitUntil: boolean;
|
|
17
23
|
/** Whether the runtime supports application-level 103 Early Hints. */
|
|
@@ -102,5 +108,28 @@ export declare function generateSendResponseModule(): string;
|
|
|
102
108
|
* @internal Exported for testing.
|
|
103
109
|
*/
|
|
104
110
|
export declare function getPresetConfig(preset: NitroPreset): PresetConfig;
|
|
111
|
+
/**
|
|
112
|
+
* Resolve the destination path for prebuilt flight payloads in the Nitro
|
|
113
|
+
* output directory. The RSC entry resolves `../prebuilt/` relative to its
|
|
114
|
+
* bundled chunk location (`<serverBundleDir>/_chunks/`), so prebuilt/ must
|
|
115
|
+
* live at `<serverBundleDir>/prebuilt/`.
|
|
116
|
+
*
|
|
117
|
+
* The serverBundleDir varies by preset — Nitro's Vercel preset uses
|
|
118
|
+
* `functions/__server.func` while most others use `server`.
|
|
119
|
+
*
|
|
120
|
+
* @internal Exported for testing.
|
|
121
|
+
*/
|
|
122
|
+
export declare function resolvePrebuiltOutputPath(outDir: string, preset: NitroPreset): string;
|
|
123
|
+
/**
|
|
124
|
+
* Copy prebuilt payloads into cloned Vercel function directories.
|
|
125
|
+
*
|
|
126
|
+
* When users configure `vercel.functionRules`, Nitro's compiled hook clones
|
|
127
|
+
* the base __server.func to per-route .func directories. These clones are
|
|
128
|
+
* created during `runNitroBuild()` — before our post-build prebuilt copy.
|
|
129
|
+
* Each clone resolves `../prebuilt` independently, so they each need a copy.
|
|
130
|
+
*
|
|
131
|
+
* @internal Exported for testing.
|
|
132
|
+
*/
|
|
133
|
+
export declare function copyPrebuiltToVercelFuncClones(functionsDir: string, prebuiltSrc: string, baseFuncName: string): Promise<void>;
|
|
105
134
|
export {};
|
|
106
135
|
//# sourceMappingURL=nitro.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nitro.d.ts","sourceRoot":"","sources":["../../src/adapters/nitro.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,qBAAqB,EAAgB,MAAM,SAAS,CAAC;AAOnE;;;;;GAKG;AACH,MAAM,MAAM,WAAW,GACnB,QAAQ,GACR,aAAa,GACb,SAAS,GACT,cAAc,GACd,YAAY,GACZ,aAAa,GACb,iBAAiB,GACjB,aAAa,GACb,KAAK,CAAC;AAEV,2CAA2C;AAC3C,UAAU,YAAY;IACpB,mDAAmD;IACnD,WAAW,EAAE,MAAM,CAAC;IACpB,kDAAkD;IAClD,SAAS,EAAE,MAAM,CAAC;IAClB,8CAA8C;IAC9C,iBAAiB,EAAE,OAAO,CAAC;IAC3B,sEAAsE;IACtE,kBAAkB,EAAE,OAAO,CAAC;IAC5B,iFAAiF;IACjF,WAAW,EAAE,MAAM,CAAC;IACpB,sDAAsD;IACtD,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;
|
|
1
|
+
{"version":3,"file":"nitro.d.ts","sourceRoot":"","sources":["../../src/adapters/nitro.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EA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AAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;CACb;AAED,sCAAsC;AACtC,wBAAgB,2BAA2B,CACzC,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,WAAW,GAClB,mBAAmB,GAAG,IAAI,CAY5B;AA4ED;;;;;;;;;GASG;AACH,wBAAgB,0BAA0B,IAAI,MAAM,CAuDnD;AAID;;;GAGG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,WAAW,GAAG,YAAY,CAEjE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,MAAM,CAGrF;AAED;;;;;;;;;GASG;AACH,wBAAsB,8BAA8B,CAClD,YAAY,EAAE,MAAM,EACpB,WAAW,EAAE,MAAM,EACnB,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,IAAI,CAAC,CAoBf"}
|
package/dist/adapters/nitro.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { n as IMMUTABLE_CACHE, t as runSharedBuildSteps } from "../_chunks/build-output-helper-DF5uScqS.js";
|
|
2
|
-
import { join, relative } from "node:path";
|
|
3
|
-
import { readFile, writeFile } from "node:fs/promises";
|
|
2
|
+
import { basename, dirname, join, relative } from "node:path";
|
|
3
|
+
import { cp, glob, readFile, writeFile } from "node:fs/promises";
|
|
4
4
|
import { transformWithOxc } from "vite";
|
|
5
5
|
import { execFile } from "node:child_process";
|
|
6
6
|
//#region src/server/compress.ts?raw
|
|
@@ -25,6 +25,7 @@ var PRESET_CONFIGS = {
|
|
|
25
25
|
"vercel": {
|
|
26
26
|
nitroPreset: "vercel",
|
|
27
27
|
outputDir: ".vercel/output",
|
|
28
|
+
serverBundleDir: "functions/__server.func",
|
|
28
29
|
supportsWaitUntil: true,
|
|
29
30
|
supportsEarlyHints: false,
|
|
30
31
|
runtimeName: "vercel",
|
|
@@ -33,6 +34,7 @@ var PRESET_CONFIGS = {
|
|
|
33
34
|
"vercel-edge": {
|
|
34
35
|
nitroPreset: "vercel-edge",
|
|
35
36
|
outputDir: ".vercel/output",
|
|
37
|
+
serverBundleDir: "functions/__server.func",
|
|
36
38
|
supportsWaitUntil: true,
|
|
37
39
|
supportsEarlyHints: false,
|
|
38
40
|
runtimeName: "vercel-edge"
|
|
@@ -40,6 +42,7 @@ var PRESET_CONFIGS = {
|
|
|
40
42
|
"netlify": {
|
|
41
43
|
nitroPreset: "netlify",
|
|
42
44
|
outputDir: ".netlify/functions-internal",
|
|
45
|
+
serverBundleDir: "server",
|
|
43
46
|
supportsWaitUntil: false,
|
|
44
47
|
supportsEarlyHints: false,
|
|
45
48
|
runtimeName: "netlify"
|
|
@@ -47,6 +50,7 @@ var PRESET_CONFIGS = {
|
|
|
47
50
|
"netlify-edge": {
|
|
48
51
|
nitroPreset: "netlify-edge",
|
|
49
52
|
outputDir: ".netlify/edge-functions",
|
|
53
|
+
serverBundleDir: "server",
|
|
50
54
|
supportsWaitUntil: true,
|
|
51
55
|
supportsEarlyHints: false,
|
|
52
56
|
runtimeName: "netlify-edge"
|
|
@@ -54,6 +58,7 @@ var PRESET_CONFIGS = {
|
|
|
54
58
|
"aws-lambda": {
|
|
55
59
|
nitroPreset: "aws-lambda",
|
|
56
60
|
outputDir: ".output",
|
|
61
|
+
serverBundleDir: "server",
|
|
57
62
|
supportsWaitUntil: false,
|
|
58
63
|
supportsEarlyHints: false,
|
|
59
64
|
runtimeName: "aws-lambda"
|
|
@@ -61,6 +66,7 @@ var PRESET_CONFIGS = {
|
|
|
61
66
|
"deno-deploy": {
|
|
62
67
|
nitroPreset: "deno-deploy",
|
|
63
68
|
outputDir: ".output",
|
|
69
|
+
serverBundleDir: "server",
|
|
64
70
|
supportsWaitUntil: true,
|
|
65
71
|
supportsEarlyHints: false,
|
|
66
72
|
runtimeName: "deno-deploy"
|
|
@@ -68,6 +74,7 @@ var PRESET_CONFIGS = {
|
|
|
68
74
|
"azure-functions": {
|
|
69
75
|
nitroPreset: "azure-functions",
|
|
70
76
|
outputDir: ".output",
|
|
77
|
+
serverBundleDir: "server",
|
|
71
78
|
supportsWaitUntil: false,
|
|
72
79
|
supportsEarlyHints: false,
|
|
73
80
|
runtimeName: "azure-functions"
|
|
@@ -75,6 +82,7 @@ var PRESET_CONFIGS = {
|
|
|
75
82
|
"node-server": {
|
|
76
83
|
nitroPreset: "node-server",
|
|
77
84
|
outputDir: ".output",
|
|
85
|
+
serverBundleDir: "server",
|
|
78
86
|
supportsWaitUntil: true,
|
|
79
87
|
supportsEarlyHints: false,
|
|
80
88
|
runtimeName: "node-server"
|
|
@@ -82,6 +90,7 @@ var PRESET_CONFIGS = {
|
|
|
82
90
|
"bun": {
|
|
83
91
|
nitroPreset: "bun",
|
|
84
92
|
outputDir: ".output",
|
|
93
|
+
serverBundleDir: "server",
|
|
85
94
|
supportsWaitUntil: true,
|
|
86
95
|
supportsEarlyHints: false,
|
|
87
96
|
runtimeName: "bun"
|
|
@@ -126,7 +135,12 @@ function nitro(options = {}) {
|
|
|
126
135
|
}
|
|
127
136
|
const entry = generateNitroEntry(buildDir, outDir, preset, compress);
|
|
128
137
|
await writeFile(join(outDir, "entry.ts"), entry);
|
|
129
|
-
await runNitroBuild(outDir, preset, options.nitroConfig);
|
|
138
|
+
const { serverDir } = await runNitroBuild(outDir, preset, options.nitroConfig);
|
|
139
|
+
const prebuiltSrc = join(buildDir, "prebuilt");
|
|
140
|
+
await cp(prebuiltSrc, join(serverDir, "prebuilt"), { recursive: true }).catch((e) => {
|
|
141
|
+
if (e.code !== "ENOENT") throw e;
|
|
142
|
+
});
|
|
143
|
+
if (preset === "vercel" || preset === "vercel-edge") await copyPrebuiltToVercelFuncClones(dirname(serverDir), prebuiltSrc, basename(serverDir));
|
|
130
144
|
},
|
|
131
145
|
preview: LOCALLY_PREVIEWABLE.has(preset) ? async (_config, buildDir) => {
|
|
132
146
|
const previewScript = generatePreviewScript(buildDir, preset);
|
|
@@ -434,12 +448,6 @@ function generateNitroPreviewCommand(buildDir, preset) {
|
|
|
434
448
|
cwd: nitroDir
|
|
435
449
|
};
|
|
436
450
|
}
|
|
437
|
-
/**
|
|
438
|
-
* Run the Nitro production build using the programmatic API.
|
|
439
|
-
* Uses dynamic import so nitro is only loaded at build time.
|
|
440
|
-
* Externalizes the timber RSC/SSR output — those files are pre-built
|
|
441
|
-
* by timber and have internal references that nitro's bundler can't follow.
|
|
442
|
-
*/
|
|
443
451
|
async function runNitroBuild(nitroDir, preset, userConfig) {
|
|
444
452
|
const presetConfig = PRESET_CONFIGS[preset];
|
|
445
453
|
const { createNitro, build: nitroBuild, prepare, copyPublicAssets } = await import("nitro/builder");
|
|
@@ -456,10 +464,13 @@ async function runNitroBuild(nitroDir, preset, userConfig) {
|
|
|
456
464
|
...presetConfig.extraConfig,
|
|
457
465
|
...userConfig
|
|
458
466
|
});
|
|
467
|
+
const raw = nitro.options.output.serverDir;
|
|
468
|
+
const serverDir = raw.endsWith("/") ? raw.slice(0, -1) : raw;
|
|
459
469
|
await prepare(nitro);
|
|
460
470
|
await copyPublicAssets(nitro);
|
|
461
471
|
await nitroBuild(nitro);
|
|
462
472
|
await nitro.close();
|
|
473
|
+
return { serverDir };
|
|
463
474
|
}
|
|
464
475
|
/** Spawn a Nitro preview process and pipe stdio. */
|
|
465
476
|
function spawnNitroPreview(command, args, cwd) {
|
|
@@ -545,7 +556,43 @@ export function sendNodeResponse(nodeRes, webRes) {
|
|
|
545
556
|
function getPresetConfig(preset) {
|
|
546
557
|
return PRESET_CONFIGS[preset];
|
|
547
558
|
}
|
|
559
|
+
/**
|
|
560
|
+
* Resolve the destination path for prebuilt flight payloads in the Nitro
|
|
561
|
+
* output directory. The RSC entry resolves `../prebuilt/` relative to its
|
|
562
|
+
* bundled chunk location (`<serverBundleDir>/_chunks/`), so prebuilt/ must
|
|
563
|
+
* live at `<serverBundleDir>/prebuilt/`.
|
|
564
|
+
*
|
|
565
|
+
* The serverBundleDir varies by preset — Nitro's Vercel preset uses
|
|
566
|
+
* `functions/__server.func` while most others use `server`.
|
|
567
|
+
*
|
|
568
|
+
* @internal Exported for testing.
|
|
569
|
+
*/
|
|
570
|
+
function resolvePrebuiltOutputPath(outDir, preset) {
|
|
571
|
+
const presetConfig = PRESET_CONFIGS[preset];
|
|
572
|
+
return join(outDir, presetConfig.outputDir, presetConfig.serverBundleDir, "prebuilt");
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* Copy prebuilt payloads into cloned Vercel function directories.
|
|
576
|
+
*
|
|
577
|
+
* When users configure `vercel.functionRules`, Nitro's compiled hook clones
|
|
578
|
+
* the base __server.func to per-route .func directories. These clones are
|
|
579
|
+
* created during `runNitroBuild()` — before our post-build prebuilt copy.
|
|
580
|
+
* Each clone resolves `../prebuilt` independently, so they each need a copy.
|
|
581
|
+
*
|
|
582
|
+
* @internal Exported for testing.
|
|
583
|
+
*/
|
|
584
|
+
async function copyPrebuiltToVercelFuncClones(functionsDir, prebuiltSrc, baseFuncName) {
|
|
585
|
+
const funcDirs = [];
|
|
586
|
+
try {
|
|
587
|
+
for await (const match of glob("**/*.func", { cwd: functionsDir })) if (!match.endsWith(baseFuncName)) funcDirs.push(join(functionsDir, match));
|
|
588
|
+
} catch {
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
await Promise.all(funcDirs.map((dir) => cp(prebuiltSrc, join(dir, "prebuilt"), { recursive: true }).catch((e) => {
|
|
592
|
+
if (e.code !== "ENOENT") throw e;
|
|
593
|
+
})));
|
|
594
|
+
}
|
|
548
595
|
//#endregion
|
|
549
|
-
export { generateNitroEntry, generateNitroPreviewCommand, generatePreviewScript, generateSendResponseModule, getPresetConfig, nitro };
|
|
596
|
+
export { copyPrebuiltToVercelFuncClones, generateNitroEntry, generateNitroPreviewCommand, generatePreviewScript, generateSendResponseModule, getPresetConfig, nitro, resolvePrebuiltOutputPath };
|
|
550
597
|
|
|
551
598
|
//# sourceMappingURL=nitro.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nitro.js","names":[],"sources":["../../src/adapters/compress-module.ts","../../src/adapters/nitro.ts"],"sourcesContent":["// Compiles server/compress.ts into a standalone ESM module (_compress.mjs)\n// for self-hosted deployments. The adapter writes this to the build output\n// during buildOutput(). It's imported by the Nitro entry and preview server\n// at runtime.\n//\n// By compiling the actual TypeScript source rather than maintaining a\n// hand-written string template, any fix to server/compress.ts automatically\n// flows to the production module. See design/18-build-system.md (\"entry\n// modules are real TypeScript files, not codegen strings\").\n\nimport { transformWithOxc } from 'vite';\n// Vite's ?raw import embeds the file as a string at build time — works\n// in both dev (Vite resolves the TS source) and the published package\n// (the string is inlined into the compiled adapter entry).\nimport compressSource from '../server/compress.ts?raw';\n\n/**\n * Compile server/compress.ts into a standalone ESM module.\n *\n * Uses Vite's OXC transform to strip TypeScript types from the\n * embedded source. The result is written to `_compress.mjs` during\n * buildOutput.\n *\n * @internal Exported for testing.\n */\nexport async function generateCompressModule(): Promise<string> {\n const result = await transformWithOxc(compressSource, 'compress.ts', {\n lang: 'ts',\n });\n\n return (\n '// Generated by @timber-js/app — compiled from server/compress.ts.\\n' +\n '// Do not edit — this file is regenerated on each build.\\n' +\n result.code\n );\n}\n","// Nitro adapter — multi-platform deployment\n//\n// Covers everything except Cloudflare Workers: Node.js, Bun, Vercel,\n// Netlify, AWS Lambda, Deno Deploy, Azure Functions. Nitro handles\n// compression, graceful shutdown, static file serving, and platform quirks.\n// See design/11-platform.md and design/25-production-deployments.md.\n\nimport { writeFile, readFile } from 'node:fs/promises';\nimport { execFile } from 'node:child_process';\nimport { join, relative } from 'node:path';\nimport type { TimberPlatformAdapter, TimberConfig } from './types';\nimport { generateCompressModule } from './compress-module.js';\nimport { IMMUTABLE_CACHE } from './shared.js';\nimport { runSharedBuildSteps } from './build-output-helper.js';\n\n// ─── Presets ─────────────────────────────────────────────────────────────────\n\n/**\n * Supported Nitro deployment presets.\n *\n * Each preset maps to a Nitro deployment target. The adapter generates\n * the appropriate configuration and entry point for the selected platform.\n */\nexport type NitroPreset =\n | 'vercel'\n | 'vercel-edge'\n | 'netlify'\n | 'netlify-edge'\n | 'aws-lambda'\n | 'deno-deploy'\n | 'azure-functions'\n | 'node-server'\n | 'bun';\n\n/** Preset-specific Nitro configuration. */\ninterface PresetConfig {\n /** Nitro preset name passed to the Nitro build. */\n nitroPreset: string;\n /** Output directory name within the build dir. */\n outputDir: string;\n /** Whether the runtime supports waitUntil. */\n supportsWaitUntil: boolean;\n /** Whether the runtime supports application-level 103 Early Hints. */\n supportsEarlyHints: boolean;\n /** Value for TIMBER_RUNTIME env var. See design/25-production-deployments.md. */\n runtimeName: string;\n /** Additional nitro.config fields for this preset. */\n extraConfig?: Record<string, unknown>;\n}\n\nconst PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {\n 'vercel': {\n nitroPreset: 'vercel',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel',\n extraConfig: { vercel: { functions: { maxDuration: 30 } } },\n },\n 'vercel-edge': {\n nitroPreset: 'vercel-edge',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel-edge',\n },\n 'netlify': {\n nitroPreset: 'netlify',\n outputDir: '.netlify/functions-internal',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'netlify',\n },\n 'netlify-edge': {\n nitroPreset: 'netlify-edge',\n outputDir: '.netlify/edge-functions',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'netlify-edge',\n },\n 'aws-lambda': {\n nitroPreset: 'aws-lambda',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'aws-lambda',\n },\n 'deno-deploy': {\n nitroPreset: 'deno-deploy',\n outputDir: '.output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'deno-deploy',\n },\n 'azure-functions': {\n nitroPreset: 'azure-functions',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'azure-functions',\n },\n 'node-server': {\n nitroPreset: 'node-server',\n outputDir: '.output',\n supportsWaitUntil: true,\n // Disabled by default: most node-server deployments sit behind a\n // reverse proxy (nginx, caddy, traefik) that doesn't support 103\n // Early Hints over HTTP/1.1. Sending 103 causes nginx to intermittently\n // treat the response as an error and retry after proxy_connect_timeout\n // (~5s stalls on ~23% of requests). Link headers on the 200 response\n // are the safe fallback — Cloudflare and other CDNs convert them to\n // 103 automatically at the edge (over HTTP/2+ to the browser).\n supportsEarlyHints: false,\n runtimeName: 'node-server',\n },\n 'bun': {\n nitroPreset: 'bun',\n outputDir: '.output',\n supportsWaitUntil: true,\n // Disabled for same reason as node-server — reverse proxies choke on 103.\n // Link headers on the 200 response are converted to 103 by CDNs.\n supportsEarlyHints: false,\n runtimeName: 'bun',\n },\n};\n\n// ─── Options ─────────────────────────────────────────────────────────────────\n\n/** Options for the Nitro adapter. */\nexport interface NitroAdapterOptions {\n /**\n * Deployment preset. Determines the target platform.\n * @default 'node-server'\n */\n preset?: NitroPreset;\n\n /**\n * Enable application-level gzip compression for HTML and RSC responses.\n *\n * When `true` (default), the origin compresses responses using the Web\n * `CompressionStream` API. This is useful for self-hosted deployments\n * where no reverse proxy or CDN handles compression.\n *\n * Set to `false` when deploying behind a reverse proxy (nginx, caddy)\n * or CDN (Cloudflare, Fastly, Vercel) that compresses at the edge.\n * Disabling origin compression saves CPU on the Node.js event loop —\n * compressing 1MB+ streaming HTML responses takes 10-15ms of main\n * thread time per request, directly reducing throughput under load.\n *\n * @default true\n */\n compress?: boolean;\n\n /**\n * Additional Nitro configuration to merge into the generated config.\n * Overrides default values for the selected preset.\n */\n nitroConfig?: Record<string, unknown>;\n}\n\n// ─── Adapter ─────────────────────────────────────────────────────────────────\n\n/**\n * Create a Nitro-based adapter for multi-platform deployment.\n *\n * Nitro abstracts deployment targets — the same timber.js app can deploy\n * to Vercel, Netlify, AWS, Deno Deploy, or Azure by changing the preset.\n *\n * @example\n * ```ts\n * import { nitro } from '@timber-js/app/adapters/nitro'\n *\n * export default {\n * output: 'server',\n * adapter: nitro({ preset: 'vercel' }),\n * }\n * ```\n */\nexport function nitro(options: NitroAdapterOptions = {}): TimberPlatformAdapter {\n const preset = options.preset ?? 'node-server';\n const compress = options.compress ?? true;\n const presetConfig = PRESET_CONFIGS[preset];\n return {\n name: `nitro-${preset}`,\n\n async buildOutput(config: TimberConfig, buildDir: string) {\n const outDir = join(buildDir, 'nitro');\n\n // Steps 1–5: shared across all adapters (mkdir, copy client/rsc/ssr,\n // write _headers, write manifest-init).\n await runSharedBuildSteps({\n config,\n buildDir,\n outDir,\n publicDirName: 'public',\n });\n\n // Write runtime helper modules used by the preview server.\n // See design/25-production-deployments.md — self-hosted deployments\n // need application-level compression (Cloudflare handles it at the edge).\n await writeFile(join(outDir, '_compress.mjs'), await generateCompressModule());\n\n // Web→Node response bridge with backpressure. See TIM-1154.\n await writeFile(join(outDir, '_send-response.mjs'), generateSendResponseModule());\n\n // Prepend the manifest assignment directly into the RSC entry so\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set before any module reads it.\n // This must be top-level code, not an import, because rollup tree-shakes\n // side-effect-only globalThis assignments from imported modules.\n if (config.manifestInit) {\n const rscEntry = join(outDir, 'rsc', 'index.js');\n const rscContent = await readFile(rscEntry, 'utf-8');\n await writeFile(rscEntry, `${config.manifestInit}\\n${rscContent}`);\n }\n\n // Generate the Nitro entry point (imports from ./rsc/ within nitro dir)\n const entry = generateNitroEntry(buildDir, outDir, preset, compress);\n await writeFile(join(outDir, 'entry.ts'), entry);\n\n // Run the Nitro build to produce a production-ready server bundle.\n // The output goes to dist/nitro/.output/server/index.mjs (for node-server preset).\n // Config is passed programmatically — no nitro.config.ts file needed.\n await runNitroBuild(outDir, preset, options.nitroConfig);\n },\n\n // Only presets that produce a locally-runnable server get preview().\n // Serverless presets (vercel, netlify, aws-lambda, etc.) have no\n // local runtime — Vite's built-in preview is the fallback.\n preview: LOCALLY_PREVIEWABLE.has(preset)\n ? async (_config: TimberConfig, buildDir: string) => {\n // Generate a standalone preview server that uses Node's built-in\n // HTTP server. The Nitro entry.ts can't be run directly because\n // it imports h3 (a Nitro dependency not available at runtime).\n const previewScript = generatePreviewScript(buildDir, preset);\n const scriptPath = join(buildDir, 'nitro', '_preview-server.mjs');\n await writeFile(scriptPath, previewScript);\n\n const command = preset === 'bun' ? 'bun' : 'node';\n await spawnNitroPreview(command, [scriptPath], join(buildDir, 'nitro'));\n }\n : undefined,\n };\n}\n\n// ─── Entry Generation ────────────────────────────────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateNitroEntry(\n buildDir: string,\n outDir: string,\n preset: NitroPreset,\n compress = true\n): string {\n // The RSC entry is the main request handler — it exports the fetch handler as default.\n // rsc/ is copied into the nitro dir so the import is local.\n // The manifest init is prepended to rsc/index.js before the nitro build,\n // so globalThis.__TIMBER_BUILD_MANIFEST__ is set before any code reads it.\n const serverEntryRelative = './rsc/index.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n const earlyHints = PRESET_CONFIGS[preset].supportsEarlyHints;\n const supportsWaitUntil = PRESET_CONFIGS[preset].supportsWaitUntil;\n\n // On node-server and bun, wrap the handler with ALS so the pipeline\n // can send 103 Early Hints via res.writeEarlyHints(). Other presets\n // either don't support 103 or handle it at the CDN level.\n //\n // For presets that support waitUntil, bridge h3's event.waitUntil()\n // to timber's waitUntil() primitive via the ALS bridge.\n // See design/11-platform.md §\"waitUntil()\".\n let handlerCall: string;\n if (earlyHints && supportsWaitUntil) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const callHandler = () => handler(webRequest)\n let wrappedHandler = earlyHintsSender\n ? () => runWithEarlyHintsSender(earlyHintsSender, callHandler)\n : callHandler\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, wrappedHandler)\n : await wrappedHandler()`;\n } else if (earlyHints) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const webResponse = earlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest)`;\n } else if (supportsWaitUntil) {\n handlerCall = ` const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, () => handler(webRequest))\n : await handler(webRequest)`;\n } else {\n handlerCall = ` const webResponse = await handler(webRequest)`;\n }\n\n // Import runWithWaitUntil only when the preset supports it.\n const waitUntilImport = supportsWaitUntil ? ', runWithWaitUntil' : '';\n\n const compressImport = compress ? \"import { compressResponse } from './_compress.mjs'\\n\" : '';\n const compressCall = compress ? 'compressResponse(webRequest, webResponse)' : 'webResponse';\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\nimport handler, { runWithEarlyHintsSender${waitUntilImport} } from '${serverEntryRelative}'\n${compressImport}\n// Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nprocess.env.TIMBER_RUNTIME = '${runtimeName}'\n\n// Nitro's index.mjs wraps this import with defineLazyEventHandler, which\n// already handles the event handler protocol. We export a plain async\n// function — no defineEventHandler wrapper needed.\n// Nitro bundles h3 into its internal _libs/ directory but doesn't make\n// it available as a bare specifier in the output's node_modules.\nexport default async function timberHandler(event) {\n // h3 v2: event.req is the Web Request\n const webRequest = event.req\n${handlerCall}\n return ${compressCall}\n}\n`;\n}\n\n// ─── Preview ─────────────────────────────────────────────────────────────────\n\n/** Presets that produce a locally-runnable server entry. */\nconst LOCALLY_PREVIEWABLE = new Set<NitroPreset>(['node-server', 'bun']);\n\n/**\n * Generate a standalone preview server script that uses Node's built-in\n * HTTP server. This bypasses Nitro entirely — the Nitro entry.ts imports\n * h3 which isn't available outside a Nitro build. For local preview we\n * just need to serve static files and route requests to the RSC handler.\n *\n * @internal Exported for testing.\n */\nexport function generatePreviewScript(buildDir: string, preset: NitroPreset): string {\n const rscEntryRelative = relative(join(buildDir, 'nitro'), join(buildDir, 'rsc', 'index.js'));\n const rscEntry = rscEntryRelative.startsWith('.') ? rscEntryRelative : './' + rscEntryRelative;\n const publicDir = './public';\n const manifestInitPath = './_timber-manifest-init.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n\n return `// Generated by @timber-js/app — standalone preview server.\n// Uses Node's built-in HTTP server to serve static assets and route\n// dynamic requests through the RSC handler. No Nitro/h3 dependency.\n\nimport { createServer } from 'node:http';\nimport { readFile, stat } from 'node:fs/promises';\nimport { join, extname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { existsSync } from 'node:fs';\n\n// Set runtime before importing the handler.\nprocess.env.TIMBER_RUNTIME = '${runtimeName}';\n\n// Load the build manifest if it exists.\nconst __dirname = fileURLToPath(new URL('.', import.meta.url));\nconst manifestPath = join(__dirname, '${manifestInitPath}');\nif (existsSync(manifestPath)) {\n await import('${manifestInitPath}');\n}\n\n// Import the RSC handler (default export is the fetch-like handler).\nconst { default: handler, runWithEarlyHintsSender } = await import('${rscEntry}');\n\n// Import compression helper for self-hosted response compression.\nconst { compressResponse } = await import('./_compress.mjs');\n\n// Web→Node response bridge with backpressure (TIM-1154).\nconst { sendNodeResponse } = await import('./_send-response.mjs');\n\nconst MIME_TYPES = {\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.mjs': 'application/javascript',\n '.css': 'text/css',\n '.json': 'application/json',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.otf': 'font/otf',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.webm': 'video/webm',\n '.mp4': 'video/mp4',\n '.txt': 'text/plain',\n '.xml': 'application/xml',\n '.wasm': 'application/wasm',\n};\n\nconst publicDir = join(__dirname, '${publicDir}');\n\n// Port resolution (TIM-842):\n// - Default to 3000\n// - If PORT env var is set, honor it strictly (fail loudly on conflict)\n// - Otherwise auto-bump from 3000 until a free port is found\n// Mirrors the dev server behavior so timber dev/preview/production all\n// behave the same way around port selection.\nconst envPort = process.env.PORT ? parseInt(process.env.PORT, 10) : null;\nconst portIsExplicit = envPort != null && Number.isFinite(envPort) && envPort > 0;\nconst startPort = portIsExplicit ? envPort : 3000;\nconst host = process.env.HOST || 'localhost';\n\n// Set after listenWithBump() resolves so request handlers can build\n// absolute URLs from the actual bound port (which may differ from\n// startPort after an auto-bump).\nlet boundPort = startPort;\n\nconst server = createServer(async (req, res) => {\n // Scheme from the socket's TLS state — a hardcoded http:// breaks CSRF\n // origin comparison and absolute-URL construction when TLS is terminated\n // at this server (TIM-1073; mirrors the dev-server fix in TIM-1067).\n // X-Forwarded-Proto is intentionally not consulted here: on a direct\n // connection it would be attacker-controlled. The CSRF layer honors it\n // separately for reverse-proxy deployments.\n const scheme = req.socket?.encrypted ? 'https' : 'http';\n const url = new URL(req.url || '/', \\`\\${scheme}://\\${host}:\\${boundPort}\\`);\n\n // Try serving static files from the public directory first.\n const filePath = join(publicDir, url.pathname);\n // Prevent path traversal.\n if (filePath.startsWith(publicDir)) {\n try {\n const fileStat = await stat(filePath);\n if (fileStat.isFile()) {\n const ext = extname(filePath);\n const contentType = MIME_TYPES[ext] || 'application/octet-stream';\n const body = await readFile(filePath);\n // Hashed assets get immutable cache, others get short cache.\n const isImmutable =\n url.pathname.startsWith('/assets/') || url.pathname.startsWith('/_timber/fonts/');\n const cacheControl = isImmutable\n ? 'public, max-age=31536000, immutable'\n : 'public, max-age=3600, must-revalidate';\n res.writeHead(200, {\n 'Content-Type': contentType,\n 'Content-Length': body.length,\n 'Cache-Control': cacheControl,\n });\n res.end(body);\n return;\n }\n } catch {\n // File not found — fall through to the RSC handler.\n }\n }\n\n // Convert Node request to Web Request.\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n }\n\n let body = undefined;\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n body = await new Promise((resolve) => {\n const chunks = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n });\n }\n\n const webRequest = new Request(url.href, {\n method: req.method,\n headers,\n body,\n duplex: body ? 'half' : undefined,\n });\n\n try {\n // Support 103 Early Hints when available.\n const earlyHintsSender = (typeof res.writeEarlyHints === 'function')\n ? (links) => { try { res.writeEarlyHints({ link: links }); } catch {} }\n : undefined;\n\n const rawResponse = earlyHintsSender && runWithEarlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest);\n\n // Compress the response for self-hosted deployments.\n const webResponse = compressResponse(webRequest, rawResponse);\n\n // Write the response to Node's ServerResponse. sendNodeResponse handles\n // status, headers (including Set-Cookie splitting via [...headers]),\n // body streaming with backpressure, and client disconnect cleanup.\n // See TIM-1154.\n await sendNodeResponse(res, webResponse);\n } catch (err) {\n console.error('[timber preview] Request error:', err);\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n }\n res.end('Internal Server Error');\n }\n});\n\nfunction listenWithBump(port, attempt = 0) {\n return new Promise((resolveListen, rejectListen) => {\n const onError = (err) => {\n server.removeListener('listening', onListening);\n if (err && err.code === 'EADDRINUSE' && !portIsExplicit && attempt < 100) {\n if (attempt === 0) {\n console.log(\\` [timber] Port \\${port} in use, trying \\${port + 1}...\\`);\n }\n listenWithBump(port + 1, attempt + 1).then(resolveListen, rejectListen);\n return;\n }\n rejectListen(err);\n };\n const onListening = () => {\n server.removeListener('error', onError);\n resolveListen(port);\n };\n server.once('error', onError);\n server.once('listening', onListening);\n server.listen(port, host);\n });\n}\n\ntry {\n boundPort = await listenWithBump(startPort);\n if (boundPort !== startPort) {\n console.log();\n console.log(\\` [timber] Port \\${startPort} in use, using \\${boundPort}\\`);\n }\n console.log();\n console.log(' ⚡ timber preview server running at:');\n console.log();\n console.log(\\` ➜ http://\\${host}:\\${boundPort}\\`);\n console.log();\n} catch (err) {\n if (err && err.code === 'EADDRINUSE') {\n console.error(\\`[timber] Port \\${startPort} is already in use. \\` +\n 'Set PORT to a free port, or unset PORT to auto-pick.');\n } else {\n console.error('[timber] Failed to start preview server:', err);\n }\n process.exit(1);\n}\n`;\n}\n\n/** Command descriptor for Nitro preview — testable without spawning. */\nexport interface NitroPreviewCommand {\n command: string;\n args: string[];\n cwd: string;\n}\n\n/** @internal Exported for testing. */\nexport function generateNitroPreviewCommand(\n buildDir: string,\n preset: NitroPreset\n): NitroPreviewCommand | null {\n if (!LOCALLY_PREVIEWABLE.has(preset)) return null;\n\n const nitroDir = join(buildDir, 'nitro');\n const entryPath = join(nitroDir, 'entry.ts');\n\n const command = preset === 'bun' ? 'bun' : 'node';\n return {\n command,\n args: [entryPath],\n cwd: nitroDir,\n };\n}\n\n/**\n * Run the Nitro production build using the programmatic API.\n * Uses dynamic import so nitro is only loaded at build time.\n * Externalizes the timber RSC/SSR output — those files are pre-built\n * by timber and have internal references that nitro's bundler can't follow.\n */\nasync function runNitroBuild(\n nitroDir: string,\n preset: NitroPreset,\n userConfig?: Record<string, unknown>\n): Promise<void> {\n const presetConfig = PRESET_CONFIGS[preset];\n const {\n createNitro,\n build: nitroBuild,\n prepare,\n copyPublicAssets,\n } = await import('nitro/builder');\n\n const nitro = await createNitro({\n rootDir: nitroDir,\n preset: presetConfig.nitroPreset,\n // Use renderer.entry so Nitro wraps our handler with its server runtime\n // (HTTP server, static file serving, graceful shutdown, etc.).\n // Using `entry` directly would bypass the Nitro server runtime.\n renderer: { handler: join(nitroDir, 'entry.ts') },\n output: { dir: join(nitroDir, presetConfig.outputDir) },\n routeRules: {\n '/assets/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n '/_timber/fonts/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n },\n // Don't bundle the timber RSC/SSR build output — it has its own\n // internal file references that nitro's bundler can't follow.\n // Mark them as external so rollup leaves the imports as-is.\n rollupConfig: {\n external: [/\\.\\.\\/rsc\\//],\n },\n ...presetConfig.extraConfig,\n ...userConfig,\n });\n\n await prepare(nitro);\n await copyPublicAssets(nitro);\n await nitroBuild(nitro);\n await nitro.close();\n}\n\n/** Spawn a Nitro preview process and pipe stdio. */\nfunction spawnNitroPreview(command: string, args: string[], cwd: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const child = execFile(command, args, { cwd }, (err) => {\n if (err) reject(err);\n else resolve();\n });\n child.stdout?.pipe(process.stdout);\n child.stderr?.pipe(process.stderr);\n });\n}\n\n// ─── Send Response Module ───────────────────────────────────────────────────\n\n/**\n * Generate a standalone ESM module that exports sendNodeResponse.\n *\n * Mirrors srvx/node's sendNodeResponse: status + headers via writeHead,\n * body streaming with backpressure (waits for drain on write() === false),\n * and client disconnect cleanup. Written to `_send-response.mjs` during\n * buildOutput for use by the preview server script. See TIM-1154.\n *\n * @internal Exported for testing.\n */\nexport function generateSendResponseModule(): string {\n return `// Generated by @timber-js/app — Web→Node response bridge.\n// Do not edit — this file is regenerated on each build.\n// Mirrors srvx/node's sendNodeResponse with backpressure support.\n\nexport function sendNodeResponse(nodeRes, webRes) {\n if (!webRes) {\n nodeRes.statusCode = 500;\n return new Promise((resolve) => nodeRes.end(resolve));\n }\n const rawHeaders = [...webRes.headers];\n const writeHeaders = rawHeaders.flat();\n if (!nodeRes.headersSent) {\n if (nodeRes.req?.httpVersion === '2.0') {\n nodeRes.writeHead(webRes.status, writeHeaders);\n } else {\n nodeRes.writeHead(webRes.status, webRes.statusText, writeHeaders);\n }\n }\n if (!webRes.body) {\n return new Promise((resolve) => nodeRes.end(resolve));\n }\n // Stream with backpressure: pause reading when the kernel buffer is\n // full (write() returns false) and resume on 'drain'.\n if (nodeRes.destroyed) {\n webRes.body.cancel();\n return;\n }\n const reader = webRes.body.getReader();\n function streamCancel(error) {\n reader.cancel(error).catch(() => {});\n if (error) nodeRes.destroy(error);\n }\n function streamHandle({ done, value }) {\n try {\n if (done) {\n nodeRes.end();\n } else if (nodeRes.write(value)) {\n reader.read().then(streamHandle, streamCancel);\n } else {\n nodeRes.once('drain', () => reader.read().then(streamHandle, streamCancel));\n }\n } catch (error) {\n streamCancel(error instanceof Error ? error : undefined);\n }\n }\n nodeRes.on('close', streamCancel);\n nodeRes.on('error', streamCancel);\n reader.read().then(streamHandle, streamCancel);\n return reader.closed.catch(streamCancel).finally(() => {\n nodeRes.off('close', streamCancel);\n nodeRes.off('error', streamCancel);\n });\n}\n`;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\n/**\n * Get the preset configuration for a given preset name.\n * @internal Exported for testing.\n */\nexport function getPresetConfig(preset: NitroPreset): PresetConfig {\n return PRESET_CONFIGS[preset];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyBA,eAAsB,yBAA0C;CAK9D,OACE,oIAEA,MAPmB,iBAAiB,kBAAgB,eAAe,EACnE,MAAM,KACR,CAAC,EAAA,CAKQ;AAEX;;;ACeA,IAAM,iBAAoD;CACxD,UAAU;EACR,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACb,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE,aAAa,GAAG,EAAE,EAAE;CAC5D;CACA,eAAe;EACb,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;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EAAE,IAAI,IAAI,QAAQ;GACtD,IAAI,KAAK,OAAO,GAAG;QACd,QAAQ;EACf,CAAC;EACD,MAAM,QAAQ,KAAK,QAAQ,MAAM;EACjC,MAAM,QAAQ,KAAK,QAAQ,MAAM;CACnC,CAAC;AACH;;;;;;;;;;;AAcA,SAAgB,6BAAqC;CACnD,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDT;;;;;AAQA,SAAgB,gBAAgB,QAAmC;CACjE,OAAO,eAAe;AACxB"}
|
|
1
|
+
{"version":3,"file":"nitro.js","names":[],"sources":["../../src/adapters/compress-module.ts","../../src/adapters/nitro.ts"],"sourcesContent":["// Compiles server/compress.ts into a standalone ESM module (_compress.mjs)\n// for self-hosted deployments. The adapter writes this to the build output\n// during buildOutput(). It's imported by the Nitro entry and preview server\n// at runtime.\n//\n// By compiling the actual TypeScript source rather than maintaining a\n// hand-written string template, any fix to server/compress.ts automatically\n// flows to the production module. See design/18-build-system.md (\"entry\n// modules are real TypeScript files, not codegen strings\").\n\nimport { transformWithOxc } from 'vite';\n// Vite's ?raw import embeds the file as a string at build time — works\n// in both dev (Vite resolves the TS source) and the published package\n// (the string is inlined into the compiled adapter entry).\nimport compressSource from '../server/compress.ts?raw';\n\n/**\n * Compile server/compress.ts into a standalone ESM module.\n *\n * Uses Vite's OXC transform to strip TypeScript types from the\n * embedded source. The result is written to `_compress.mjs` during\n * buildOutput.\n *\n * @internal Exported for testing.\n */\nexport async function generateCompressModule(): Promise<string> {\n const result = await transformWithOxc(compressSource, 'compress.ts', {\n lang: 'ts',\n });\n\n return (\n '// Generated by @timber-js/app — compiled from server/compress.ts.\\n' +\n '// Do not edit — this file is regenerated on each build.\\n' +\n result.code\n );\n}\n","// Nitro adapter — multi-platform deployment\n//\n// Covers everything except Cloudflare Workers: Node.js, Bun, Vercel,\n// Netlify, AWS Lambda, Deno Deploy, Azure Functions. Nitro handles\n// compression, graceful shutdown, static file serving, and platform quirks.\n// See design/11-platform.md and design/25-production-deployments.md.\n\nimport { writeFile, readFile, cp, glob } from 'node:fs/promises';\nimport { execFile } from 'node:child_process';\nimport { join, relative, dirname, basename } from 'node:path';\nimport type { TimberPlatformAdapter, TimberConfig } from './types';\nimport { generateCompressModule } from './compress-module.js';\nimport { IMMUTABLE_CACHE } from './shared.js';\nimport { runSharedBuildSteps } from './build-output-helper.js';\n\n// ─── Presets ─────────────────────────────────────────────────────────────────\n\n/**\n * Supported Nitro deployment presets.\n *\n * Each preset maps to a Nitro deployment target. The adapter generates\n * the appropriate configuration and entry point for the selected platform.\n */\nexport type NitroPreset =\n | 'vercel'\n | 'vercel-edge'\n | 'netlify'\n | 'netlify-edge'\n | 'aws-lambda'\n | 'deno-deploy'\n | 'azure-functions'\n | 'node-server'\n | 'bun';\n\n/** Preset-specific Nitro configuration. */\ninterface PresetConfig {\n /** Nitro preset name passed to the Nitro build. */\n nitroPreset: string;\n /** Output directory name within the build dir. */\n outputDir: string;\n /**\n * Path to the server bundle directory relative to outputDir.\n * Nitro places the bundled server entry + _chunks/ here.\n * Most presets use `server`; Vercel uses `functions/__server.func`.\n */\n serverBundleDir: string;\n /** Whether the runtime supports waitUntil. */\n supportsWaitUntil: boolean;\n /** Whether the runtime supports application-level 103 Early Hints. */\n supportsEarlyHints: boolean;\n /** Value for TIMBER_RUNTIME env var. See design/25-production-deployments.md. */\n runtimeName: string;\n /** Additional nitro.config fields for this preset. */\n extraConfig?: Record<string, unknown>;\n}\n\nconst PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {\n 'vercel': {\n nitroPreset: 'vercel',\n outputDir: '.vercel/output',\n serverBundleDir: 'functions/__server.func',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel',\n extraConfig: { vercel: { functions: { maxDuration: 30 } } },\n },\n 'vercel-edge': {\n nitroPreset: 'vercel-edge',\n outputDir: '.vercel/output',\n serverBundleDir: 'functions/__server.func',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel-edge',\n },\n 'netlify': {\n nitroPreset: 'netlify',\n outputDir: '.netlify/functions-internal',\n serverBundleDir: 'server',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'netlify',\n },\n 'netlify-edge': {\n nitroPreset: 'netlify-edge',\n outputDir: '.netlify/edge-functions',\n serverBundleDir: 'server',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'netlify-edge',\n },\n 'aws-lambda': {\n nitroPreset: 'aws-lambda',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'aws-lambda',\n },\n 'deno-deploy': {\n nitroPreset: 'deno-deploy',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'deno-deploy',\n },\n 'azure-functions': {\n nitroPreset: 'azure-functions',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'azure-functions',\n },\n 'node-server': {\n nitroPreset: 'node-server',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: true,\n // Disabled by default: most node-server deployments sit behind a\n // reverse proxy (nginx, caddy, traefik) that doesn't support 103\n // Early Hints over HTTP/1.1. Sending 103 causes nginx to intermittently\n // treat the response as an error and retry after proxy_connect_timeout\n // (~5s stalls on ~23% of requests). Link headers on the 200 response\n // are the safe fallback — Cloudflare and other CDNs convert them to\n // 103 automatically at the edge (over HTTP/2+ to the browser).\n supportsEarlyHints: false,\n runtimeName: 'node-server',\n },\n 'bun': {\n nitroPreset: 'bun',\n outputDir: '.output',\n serverBundleDir: 'server',\n supportsWaitUntil: true,\n // Disabled for same reason as node-server — reverse proxies choke on 103.\n // Link headers on the 200 response are converted to 103 by CDNs.\n supportsEarlyHints: false,\n runtimeName: 'bun',\n },\n};\n\n// ─── Options ─────────────────────────────────────────────────────────────────\n\n/** Options for the Nitro adapter. */\nexport interface NitroAdapterOptions {\n /**\n * Deployment preset. Determines the target platform.\n * @default 'node-server'\n */\n preset?: NitroPreset;\n\n /**\n * Enable application-level gzip compression for HTML and RSC responses.\n *\n * When `true` (default), the origin compresses responses using the Web\n * `CompressionStream` API. This is useful for self-hosted deployments\n * where no reverse proxy or CDN handles compression.\n *\n * Set to `false` when deploying behind a reverse proxy (nginx, caddy)\n * or CDN (Cloudflare, Fastly, Vercel) that compresses at the edge.\n * Disabling origin compression saves CPU on the Node.js event loop —\n * compressing 1MB+ streaming HTML responses takes 10-15ms of main\n * thread time per request, directly reducing throughput under load.\n *\n * @default true\n */\n compress?: boolean;\n\n /**\n * Additional Nitro configuration to merge into the generated config.\n * Overrides default values for the selected preset.\n */\n nitroConfig?: Record<string, unknown>;\n}\n\n// ─── Adapter ─────────────────────────────────────────────────────────────────\n\n/**\n * Create a Nitro-based adapter for multi-platform deployment.\n *\n * Nitro abstracts deployment targets — the same timber.js app can deploy\n * to Vercel, Netlify, AWS, Deno Deploy, or Azure by changing the preset.\n *\n * @example\n * ```ts\n * import { nitro } from '@timber-js/app/adapters/nitro'\n *\n * export default {\n * output: 'server',\n * adapter: nitro({ preset: 'vercel' }),\n * }\n * ```\n */\nexport function nitro(options: NitroAdapterOptions = {}): TimberPlatformAdapter {\n const preset = options.preset ?? 'node-server';\n const compress = options.compress ?? true;\n const presetConfig = PRESET_CONFIGS[preset];\n return {\n name: `nitro-${preset}`,\n\n async buildOutput(config: TimberConfig, buildDir: string) {\n const outDir = join(buildDir, 'nitro');\n\n // Steps 1–5: shared across all adapters (mkdir, copy client/rsc/ssr,\n // write _headers, write manifest-init).\n await runSharedBuildSteps({\n config,\n buildDir,\n outDir,\n publicDirName: 'public',\n });\n\n // Write runtime helper modules used by the preview server.\n // See design/25-production-deployments.md — self-hosted deployments\n // need application-level compression (Cloudflare handles it at the edge).\n await writeFile(join(outDir, '_compress.mjs'), await generateCompressModule());\n\n // Web→Node response bridge with backpressure. See TIM-1154.\n await writeFile(join(outDir, '_send-response.mjs'), generateSendResponseModule());\n\n // Prepend the manifest assignment directly into the RSC entry so\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set before any module reads it.\n // This must be top-level code, not an import, because rollup tree-shakes\n // side-effect-only globalThis assignments from imported modules.\n if (config.manifestInit) {\n const rscEntry = join(outDir, 'rsc', 'index.js');\n const rscContent = await readFile(rscEntry, 'utf-8');\n await writeFile(rscEntry, `${config.manifestInit}\\n${rscContent}`);\n }\n\n // Generate the Nitro entry point (imports from ./rsc/ within nitro dir)\n const entry = generateNitroEntry(buildDir, outDir, preset, compress);\n await writeFile(join(outDir, 'entry.ts'), entry);\n\n // Run the Nitro build to produce a production-ready server bundle.\n // The output goes to dist/nitro/.output/server/index.mjs (for node-server preset).\n // Config is passed programmatically — no nitro.config.ts file needed.\n const { serverDir } = await runNitroBuild(outDir, preset, options.nitroConfig);\n\n // Copy prebuilt flight payloads from the canonical build source\n // (buildDir/prebuilt, cleaned by the prebuilt plugin each build) into\n // the Nitro output. The RSC entry resolves `../prebuilt/` relative to\n // its bundled chunk (<serverDir>/_chunks/), so prebuilt/ must live at\n // <serverDir>/prebuilt/. serverDir is the resolved path from Nitro\n // (honors user overrides via nitroConfig.output.serverDir).\n const prebuiltSrc = join(buildDir, 'prebuilt');\n await cp(prebuiltSrc, join(serverDir, 'prebuilt'), {\n recursive: true,\n }).catch((e: NodeJS.ErrnoException) => {\n if (e.code !== 'ENOENT') throw e;\n });\n\n // Vercel with functionRules clones __server.func to per-route .func\n // directories during the Nitro build. Copy prebuilt into those clones\n // so requests routed to them also resolve ../prebuilt correctly.\n if (preset === 'vercel' || preset === 'vercel-edge') {\n const functionsDir = dirname(serverDir);\n const baseFuncName = basename(serverDir);\n await copyPrebuiltToVercelFuncClones(functionsDir, prebuiltSrc, baseFuncName);\n }\n },\n\n // Only presets that produce a locally-runnable server get preview().\n // Serverless presets (vercel, netlify, aws-lambda, etc.) have no\n // local runtime — Vite's built-in preview is the fallback.\n preview: LOCALLY_PREVIEWABLE.has(preset)\n ? async (_config: TimberConfig, buildDir: string) => {\n // Generate a standalone preview server that uses Node's built-in\n // HTTP server. The Nitro entry.ts can't be run directly because\n // it imports h3 (a Nitro dependency not available at runtime).\n const previewScript = generatePreviewScript(buildDir, preset);\n const scriptPath = join(buildDir, 'nitro', '_preview-server.mjs');\n await writeFile(scriptPath, previewScript);\n\n const command = preset === 'bun' ? 'bun' : 'node';\n await spawnNitroPreview(command, [scriptPath], join(buildDir, 'nitro'));\n }\n : undefined,\n };\n}\n\n// ─── Entry Generation ────────────────────────────────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateNitroEntry(\n buildDir: string,\n outDir: string,\n preset: NitroPreset,\n compress = true\n): string {\n // The RSC entry is the main request handler — it exports the fetch handler as default.\n // rsc/ is copied into the nitro dir so the import is local.\n // The manifest init is prepended to rsc/index.js before the nitro build,\n // so globalThis.__TIMBER_BUILD_MANIFEST__ is set before any code reads it.\n const serverEntryRelative = './rsc/index.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n const earlyHints = PRESET_CONFIGS[preset].supportsEarlyHints;\n const supportsWaitUntil = PRESET_CONFIGS[preset].supportsWaitUntil;\n\n // On node-server and bun, wrap the handler with ALS so the pipeline\n // can send 103 Early Hints via res.writeEarlyHints(). Other presets\n // either don't support 103 or handle it at the CDN level.\n //\n // For presets that support waitUntil, bridge h3's event.waitUntil()\n // to timber's waitUntil() primitive via the ALS bridge.\n // See design/11-platform.md §\"waitUntil()\".\n let handlerCall: string;\n if (earlyHints && supportsWaitUntil) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const callHandler = () => handler(webRequest)\n let wrappedHandler = earlyHintsSender\n ? () => runWithEarlyHintsSender(earlyHintsSender, callHandler)\n : callHandler\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, wrappedHandler)\n : await wrappedHandler()`;\n } else if (earlyHints) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const webResponse = earlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest)`;\n } else if (supportsWaitUntil) {\n handlerCall = ` const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, () => handler(webRequest))\n : await handler(webRequest)`;\n } else {\n handlerCall = ` const webResponse = await handler(webRequest)`;\n }\n\n // Import runWithWaitUntil only when the preset supports it.\n const waitUntilImport = supportsWaitUntil ? ', runWithWaitUntil' : '';\n\n const compressImport = compress ? \"import { compressResponse } from './_compress.mjs'\\n\" : '';\n const compressCall = compress ? 'compressResponse(webRequest, webResponse)' : 'webResponse';\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\nimport handler, { runWithEarlyHintsSender${waitUntilImport} } from '${serverEntryRelative}'\n${compressImport}\n// Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nprocess.env.TIMBER_RUNTIME = '${runtimeName}'\n\n// Nitro's index.mjs wraps this import with defineLazyEventHandler, which\n// already handles the event handler protocol. We export a plain async\n// function — no defineEventHandler wrapper needed.\n// Nitro bundles h3 into its internal _libs/ directory but doesn't make\n// it available as a bare specifier in the output's node_modules.\nexport default async function timberHandler(event) {\n // h3 v2: event.req is the Web Request\n const webRequest = event.req\n${handlerCall}\n return ${compressCall}\n}\n`;\n}\n\n// ─── Preview ─────────────────────────────────────────────────────────────────\n\n/** Presets that produce a locally-runnable server entry. */\nconst LOCALLY_PREVIEWABLE = new Set<NitroPreset>(['node-server', 'bun']);\n\n/**\n * Generate a standalone preview server script that uses Node's built-in\n * HTTP server. This bypasses Nitro entirely — the Nitro entry.ts imports\n * h3 which isn't available outside a Nitro build. For local preview we\n * just need to serve static files and route requests to the RSC handler.\n *\n * @internal Exported for testing.\n */\nexport function generatePreviewScript(buildDir: string, preset: NitroPreset): string {\n const rscEntryRelative = relative(join(buildDir, 'nitro'), join(buildDir, 'rsc', 'index.js'));\n const rscEntry = rscEntryRelative.startsWith('.') ? rscEntryRelative : './' + rscEntryRelative;\n const publicDir = './public';\n const manifestInitPath = './_timber-manifest-init.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n\n return `// Generated by @timber-js/app — standalone preview server.\n// Uses Node's built-in HTTP server to serve static assets and route\n// dynamic requests through the RSC handler. No Nitro/h3 dependency.\n\nimport { createServer } from 'node:http';\nimport { readFile, stat } from 'node:fs/promises';\nimport { join, extname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { existsSync } from 'node:fs';\n\n// Set runtime before importing the handler.\nprocess.env.TIMBER_RUNTIME = '${runtimeName}';\n\n// Load the build manifest if it exists.\nconst __dirname = fileURLToPath(new URL('.', import.meta.url));\nconst manifestPath = join(__dirname, '${manifestInitPath}');\nif (existsSync(manifestPath)) {\n await import('${manifestInitPath}');\n}\n\n// Import the RSC handler (default export is the fetch-like handler).\nconst { default: handler, runWithEarlyHintsSender } = await import('${rscEntry}');\n\n// Import compression helper for self-hosted response compression.\nconst { compressResponse } = await import('./_compress.mjs');\n\n// Web→Node response bridge with backpressure (TIM-1154).\nconst { sendNodeResponse } = await import('./_send-response.mjs');\n\nconst MIME_TYPES = {\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.mjs': 'application/javascript',\n '.css': 'text/css',\n '.json': 'application/json',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.otf': 'font/otf',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.webm': 'video/webm',\n '.mp4': 'video/mp4',\n '.txt': 'text/plain',\n '.xml': 'application/xml',\n '.wasm': 'application/wasm',\n};\n\nconst publicDir = join(__dirname, '${publicDir}');\n\n// Port resolution (TIM-842):\n// - Default to 3000\n// - If PORT env var is set, honor it strictly (fail loudly on conflict)\n// - Otherwise auto-bump from 3000 until a free port is found\n// Mirrors the dev server behavior so timber dev/preview/production all\n// behave the same way around port selection.\nconst envPort = process.env.PORT ? parseInt(process.env.PORT, 10) : null;\nconst portIsExplicit = envPort != null && Number.isFinite(envPort) && envPort > 0;\nconst startPort = portIsExplicit ? envPort : 3000;\nconst host = process.env.HOST || 'localhost';\n\n// Set after listenWithBump() resolves so request handlers can build\n// absolute URLs from the actual bound port (which may differ from\n// startPort after an auto-bump).\nlet boundPort = startPort;\n\nconst server = createServer(async (req, res) => {\n // Scheme from the socket's TLS state — a hardcoded http:// breaks CSRF\n // origin comparison and absolute-URL construction when TLS is terminated\n // at this server (TIM-1073; mirrors the dev-server fix in TIM-1067).\n // X-Forwarded-Proto is intentionally not consulted here: on a direct\n // connection it would be attacker-controlled. The CSRF layer honors it\n // separately for reverse-proxy deployments.\n const scheme = req.socket?.encrypted ? 'https' : 'http';\n const url = new URL(req.url || '/', \\`\\${scheme}://\\${host}:\\${boundPort}\\`);\n\n // Try serving static files from the public directory first.\n const filePath = join(publicDir, url.pathname);\n // Prevent path traversal.\n if (filePath.startsWith(publicDir)) {\n try {\n const fileStat = await stat(filePath);\n if (fileStat.isFile()) {\n const ext = extname(filePath);\n const contentType = MIME_TYPES[ext] || 'application/octet-stream';\n const body = await readFile(filePath);\n // Hashed assets get immutable cache, others get short cache.\n const isImmutable =\n url.pathname.startsWith('/assets/') || url.pathname.startsWith('/_timber/fonts/');\n const cacheControl = isImmutable\n ? 'public, max-age=31536000, immutable'\n : 'public, max-age=3600, must-revalidate';\n res.writeHead(200, {\n 'Content-Type': contentType,\n 'Content-Length': body.length,\n 'Cache-Control': cacheControl,\n });\n res.end(body);\n return;\n }\n } catch {\n // File not found — fall through to the RSC handler.\n }\n }\n\n // Convert Node request to Web Request.\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n }\n\n let body = undefined;\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n body = await new Promise((resolve) => {\n const chunks = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n });\n }\n\n const webRequest = new Request(url.href, {\n method: req.method,\n headers,\n body,\n duplex: body ? 'half' : undefined,\n });\n\n try {\n // Support 103 Early Hints when available.\n const earlyHintsSender = (typeof res.writeEarlyHints === 'function')\n ? (links) => { try { res.writeEarlyHints({ link: links }); } catch {} }\n : undefined;\n\n const rawResponse = earlyHintsSender && runWithEarlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest);\n\n // Compress the response for self-hosted deployments.\n const webResponse = compressResponse(webRequest, rawResponse);\n\n // Write the response to Node's ServerResponse. sendNodeResponse handles\n // status, headers (including Set-Cookie splitting via [...headers]),\n // body streaming with backpressure, and client disconnect cleanup.\n // See TIM-1154.\n await sendNodeResponse(res, webResponse);\n } catch (err) {\n console.error('[timber preview] Request error:', err);\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n }\n res.end('Internal Server Error');\n }\n});\n\nfunction listenWithBump(port, attempt = 0) {\n return new Promise((resolveListen, rejectListen) => {\n const onError = (err) => {\n server.removeListener('listening', onListening);\n if (err && err.code === 'EADDRINUSE' && !portIsExplicit && attempt < 100) {\n if (attempt === 0) {\n console.log(\\` [timber] Port \\${port} in use, trying \\${port + 1}...\\`);\n }\n listenWithBump(port + 1, attempt + 1).then(resolveListen, rejectListen);\n return;\n }\n rejectListen(err);\n };\n const onListening = () => {\n server.removeListener('error', onError);\n resolveListen(port);\n };\n server.once('error', onError);\n server.once('listening', onListening);\n server.listen(port, host);\n });\n}\n\ntry {\n boundPort = await listenWithBump(startPort);\n if (boundPort !== startPort) {\n console.log();\n console.log(\\` [timber] Port \\${startPort} in use, using \\${boundPort}\\`);\n }\n console.log();\n console.log(' ⚡ timber preview server running at:');\n console.log();\n console.log(\\` ➜ http://\\${host}:\\${boundPort}\\`);\n console.log();\n} catch (err) {\n if (err && err.code === 'EADDRINUSE') {\n console.error(\\`[timber] Port \\${startPort} is already in use. \\` +\n 'Set PORT to a free port, or unset PORT to auto-pick.');\n } else {\n console.error('[timber] Failed to start preview server:', err);\n }\n process.exit(1);\n}\n`;\n}\n\n/** Command descriptor for Nitro preview — testable without spawning. */\nexport interface NitroPreviewCommand {\n command: string;\n args: string[];\n cwd: string;\n}\n\n/** @internal Exported for testing. */\nexport function generateNitroPreviewCommand(\n buildDir: string,\n preset: NitroPreset\n): NitroPreviewCommand | null {\n if (!LOCALLY_PREVIEWABLE.has(preset)) return null;\n\n const nitroDir = join(buildDir, 'nitro');\n const entryPath = join(nitroDir, 'entry.ts');\n\n const command = preset === 'bun' ? 'bun' : 'node';\n return {\n command,\n args: [entryPath],\n cwd: nitroDir,\n };\n}\n\n/**\n * Run the Nitro production build using the programmatic API.\n * Uses dynamic import so nitro is only loaded at build time.\n * Externalizes the timber RSC/SSR output — those files are pre-built\n * by timber and have internal references that nitro's bundler can't follow.\n */\ninterface NitroBuildResult {\n /** Resolved output.serverDir — where the server bundle + _chunks/ live. */\n serverDir: string;\n}\n\nasync function runNitroBuild(\n nitroDir: string,\n preset: NitroPreset,\n userConfig?: Record<string, unknown>\n): Promise<NitroBuildResult> {\n const presetConfig = PRESET_CONFIGS[preset];\n const {\n createNitro,\n build: nitroBuild,\n prepare,\n copyPublicAssets,\n } = await import('nitro/builder');\n\n const nitro = await createNitro({\n rootDir: nitroDir,\n preset: presetConfig.nitroPreset,\n // Use renderer.entry so Nitro wraps our handler with its server runtime\n // (HTTP server, static file serving, graceful shutdown, etc.).\n // Using `entry` directly would bypass the Nitro server runtime.\n renderer: { handler: join(nitroDir, 'entry.ts') },\n output: { dir: join(nitroDir, presetConfig.outputDir) },\n routeRules: {\n '/assets/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n '/_timber/fonts/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n },\n // Don't bundle the timber RSC/SSR build output — it has its own\n // internal file references that nitro's bundler can't follow.\n // Mark them as external so rollup leaves the imports as-is.\n rollupConfig: {\n external: [/\\.\\.\\/rsc\\//],\n },\n ...presetConfig.extraConfig,\n ...userConfig,\n });\n\n // Read the resolved serverDir AFTER config merging — userConfig may\n // override output.dir or output.serverDir. Nitro appends a trailing\n // slash during resolution; strip it for join() compatibility.\n const raw = nitro.options.output.serverDir;\n const serverDir = raw.endsWith('/') ? raw.slice(0, -1) : raw;\n\n await prepare(nitro);\n await copyPublicAssets(nitro);\n await nitroBuild(nitro);\n await nitro.close();\n\n return { serverDir };\n}\n\n/** Spawn a Nitro preview process and pipe stdio. */\nfunction spawnNitroPreview(command: string, args: string[], cwd: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const child = execFile(command, args, { cwd }, (err) => {\n if (err) reject(err);\n else resolve();\n });\n child.stdout?.pipe(process.stdout);\n child.stderr?.pipe(process.stderr);\n });\n}\n\n// ─── Send Response Module ───────────────────────────────────────────────────\n\n/**\n * Generate a standalone ESM module that exports sendNodeResponse.\n *\n * Mirrors srvx/node's sendNodeResponse: status + headers via writeHead,\n * body streaming with backpressure (waits for drain on write() === false),\n * and client disconnect cleanup. Written to `_send-response.mjs` during\n * buildOutput for use by the preview server script. See TIM-1154.\n *\n * @internal Exported for testing.\n */\nexport function generateSendResponseModule(): string {\n return `// Generated by @timber-js/app — Web→Node response bridge.\n// Do not edit — this file is regenerated on each build.\n// Mirrors srvx/node's sendNodeResponse with backpressure support.\n\nexport function sendNodeResponse(nodeRes, webRes) {\n if (!webRes) {\n nodeRes.statusCode = 500;\n return new Promise((resolve) => nodeRes.end(resolve));\n }\n const rawHeaders = [...webRes.headers];\n const writeHeaders = rawHeaders.flat();\n if (!nodeRes.headersSent) {\n if (nodeRes.req?.httpVersion === '2.0') {\n nodeRes.writeHead(webRes.status, writeHeaders);\n } else {\n nodeRes.writeHead(webRes.status, webRes.statusText, writeHeaders);\n }\n }\n if (!webRes.body) {\n return new Promise((resolve) => nodeRes.end(resolve));\n }\n // Stream with backpressure: pause reading when the kernel buffer is\n // full (write() returns false) and resume on 'drain'.\n if (nodeRes.destroyed) {\n webRes.body.cancel();\n return;\n }\n const reader = webRes.body.getReader();\n function streamCancel(error) {\n reader.cancel(error).catch(() => {});\n if (error) nodeRes.destroy(error);\n }\n function streamHandle({ done, value }) {\n try {\n if (done) {\n nodeRes.end();\n } else if (nodeRes.write(value)) {\n reader.read().then(streamHandle, streamCancel);\n } else {\n nodeRes.once('drain', () => reader.read().then(streamHandle, streamCancel));\n }\n } catch (error) {\n streamCancel(error instanceof Error ? error : undefined);\n }\n }\n nodeRes.on('close', streamCancel);\n nodeRes.on('error', streamCancel);\n reader.read().then(streamHandle, streamCancel);\n return reader.closed.catch(streamCancel).finally(() => {\n nodeRes.off('close', streamCancel);\n nodeRes.off('error', streamCancel);\n });\n}\n`;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\n/**\n * Get the preset configuration for a given preset name.\n * @internal Exported for testing.\n */\nexport function getPresetConfig(preset: NitroPreset): PresetConfig {\n return PRESET_CONFIGS[preset];\n}\n\n/**\n * Resolve the destination path for prebuilt flight payloads in the Nitro\n * output directory. The RSC entry resolves `../prebuilt/` relative to its\n * bundled chunk location (`<serverBundleDir>/_chunks/`), so prebuilt/ must\n * live at `<serverBundleDir>/prebuilt/`.\n *\n * The serverBundleDir varies by preset — Nitro's Vercel preset uses\n * `functions/__server.func` while most others use `server`.\n *\n * @internal Exported for testing.\n */\nexport function resolvePrebuiltOutputPath(outDir: string, preset: NitroPreset): string {\n const presetConfig = PRESET_CONFIGS[preset];\n return join(outDir, presetConfig.outputDir, presetConfig.serverBundleDir, 'prebuilt');\n}\n\n/**\n * Copy prebuilt payloads into cloned Vercel function directories.\n *\n * When users configure `vercel.functionRules`, Nitro's compiled hook clones\n * the base __server.func to per-route .func directories. These clones are\n * created during `runNitroBuild()` — before our post-build prebuilt copy.\n * Each clone resolves `../prebuilt` independently, so they each need a copy.\n *\n * @internal Exported for testing.\n */\nexport async function copyPrebuiltToVercelFuncClones(\n functionsDir: string,\n prebuiltSrc: string,\n baseFuncName: string\n): Promise<void> {\n const funcDirs: string[] = [];\n try {\n for await (const match of glob('**/*.func', { cwd: functionsDir })) {\n if (!match.endsWith(baseFuncName)) {\n funcDirs.push(join(functionsDir, match));\n }\n }\n } catch {\n return;\n }\n await Promise.all(\n funcDirs.map((dir) =>\n cp(prebuiltSrc, join(dir, 'prebuilt'), { recursive: true }).catch(\n (e: NodeJS.ErrnoException) => {\n if (e.code !== 'ENOENT') throw e;\n }\n )\n )\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyBA,eAAsB,yBAA0C;CAK9D,OACE,oIAEA,MAPmB,iBAAiB,kBAAgB,eAAe,EACnE,MAAM,KACR,CAAC,EAAA,CAKQ;AAEX;;;ACqBA,IAAM,iBAAoD;CACxD,UAAU;EACR,aAAa;EACb,WAAW;EACX,iBAAiB;EACjB,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACb,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE,aAAa,GAAG,EAAE,EAAE;CAC5D;CACA,eAAe;EACb,aAAa;EACb,WAAW;EACX,iBAAiB;EACjB,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;CACf;CACA,WAAW;EACT,aAAa;EACb,WAAW;EACX,iBAAiB;EACjB,mBAAmB;EACnB,oB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,GAAG,aAAa,KAAK,KAAK,UAAU,GAAG,EAAE,WAAW,KAAK,CAAC,CAAC,CAAC,OACzD,MAA6B;EAC5B,IAAI,EAAE,SAAS,UAAU,MAAM;CACjC,CACF,CACF,CACF;AACF"}
|
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.165",
|
|
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",
|
package/src/adapters/nitro.ts
CHANGED
|
@@ -5,9 +5,9 @@
|
|
|
5
5
|
// compression, graceful shutdown, static file serving, and platform quirks.
|
|
6
6
|
// See design/11-platform.md and design/25-production-deployments.md.
|
|
7
7
|
|
|
8
|
-
import { writeFile, readFile } from 'node:fs/promises';
|
|
8
|
+
import { writeFile, readFile, cp, glob } from 'node:fs/promises';
|
|
9
9
|
import { execFile } from 'node:child_process';
|
|
10
|
-
import { join, relative } from 'node:path';
|
|
10
|
+
import { join, relative, dirname, basename } from 'node:path';
|
|
11
11
|
import type { TimberPlatformAdapter, TimberConfig } from './types';
|
|
12
12
|
import { generateCompressModule } from './compress-module.js';
|
|
13
13
|
import { IMMUTABLE_CACHE } from './shared.js';
|
|
@@ -38,6 +38,12 @@ interface PresetConfig {
|
|
|
38
38
|
nitroPreset: string;
|
|
39
39
|
/** Output directory name within the build dir. */
|
|
40
40
|
outputDir: string;
|
|
41
|
+
/**
|
|
42
|
+
* Path to the server bundle directory relative to outputDir.
|
|
43
|
+
* Nitro places the bundled server entry + _chunks/ here.
|
|
44
|
+
* Most presets use `server`; Vercel uses `functions/__server.func`.
|
|
45
|
+
*/
|
|
46
|
+
serverBundleDir: string;
|
|
41
47
|
/** Whether the runtime supports waitUntil. */
|
|
42
48
|
supportsWaitUntil: boolean;
|
|
43
49
|
/** Whether the runtime supports application-level 103 Early Hints. */
|
|
@@ -52,6 +58,7 @@ const PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {
|
|
|
52
58
|
'vercel': {
|
|
53
59
|
nitroPreset: 'vercel',
|
|
54
60
|
outputDir: '.vercel/output',
|
|
61
|
+
serverBundleDir: 'functions/__server.func',
|
|
55
62
|
supportsWaitUntil: true,
|
|
56
63
|
supportsEarlyHints: false,
|
|
57
64
|
runtimeName: 'vercel',
|
|
@@ -60,6 +67,7 @@ const PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {
|
|
|
60
67
|
'vercel-edge': {
|
|
61
68
|
nitroPreset: 'vercel-edge',
|
|
62
69
|
outputDir: '.vercel/output',
|
|
70
|
+
serverBundleDir: 'functions/__server.func',
|
|
63
71
|
supportsWaitUntil: true,
|
|
64
72
|
supportsEarlyHints: false,
|
|
65
73
|
runtimeName: 'vercel-edge',
|
|
@@ -67,6 +75,7 @@ const PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {
|
|
|
67
75
|
'netlify': {
|
|
68
76
|
nitroPreset: 'netlify',
|
|
69
77
|
outputDir: '.netlify/functions-internal',
|
|
78
|
+
serverBundleDir: 'server',
|
|
70
79
|
supportsWaitUntil: false,
|
|
71
80
|
supportsEarlyHints: false,
|
|
72
81
|
runtimeName: 'netlify',
|
|
@@ -74,6 +83,7 @@ const PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {
|
|
|
74
83
|
'netlify-edge': {
|
|
75
84
|
nitroPreset: 'netlify-edge',
|
|
76
85
|
outputDir: '.netlify/edge-functions',
|
|
86
|
+
serverBundleDir: 'server',
|
|
77
87
|
supportsWaitUntil: true,
|
|
78
88
|
supportsEarlyHints: false,
|
|
79
89
|
runtimeName: 'netlify-edge',
|
|
@@ -81,6 +91,7 @@ const PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {
|
|
|
81
91
|
'aws-lambda': {
|
|
82
92
|
nitroPreset: 'aws-lambda',
|
|
83
93
|
outputDir: '.output',
|
|
94
|
+
serverBundleDir: 'server',
|
|
84
95
|
supportsWaitUntil: false,
|
|
85
96
|
supportsEarlyHints: false,
|
|
86
97
|
runtimeName: 'aws-lambda',
|
|
@@ -88,6 +99,7 @@ const PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {
|
|
|
88
99
|
'deno-deploy': {
|
|
89
100
|
nitroPreset: 'deno-deploy',
|
|
90
101
|
outputDir: '.output',
|
|
102
|
+
serverBundleDir: 'server',
|
|
91
103
|
supportsWaitUntil: true,
|
|
92
104
|
supportsEarlyHints: false,
|
|
93
105
|
runtimeName: 'deno-deploy',
|
|
@@ -95,6 +107,7 @@ const PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {
|
|
|
95
107
|
'azure-functions': {
|
|
96
108
|
nitroPreset: 'azure-functions',
|
|
97
109
|
outputDir: '.output',
|
|
110
|
+
serverBundleDir: 'server',
|
|
98
111
|
supportsWaitUntil: false,
|
|
99
112
|
supportsEarlyHints: false,
|
|
100
113
|
runtimeName: 'azure-functions',
|
|
@@ -102,6 +115,7 @@ const PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {
|
|
|
102
115
|
'node-server': {
|
|
103
116
|
nitroPreset: 'node-server',
|
|
104
117
|
outputDir: '.output',
|
|
118
|
+
serverBundleDir: 'server',
|
|
105
119
|
supportsWaitUntil: true,
|
|
106
120
|
// Disabled by default: most node-server deployments sit behind a
|
|
107
121
|
// reverse proxy (nginx, caddy, traefik) that doesn't support 103
|
|
@@ -116,6 +130,7 @@ const PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {
|
|
|
116
130
|
'bun': {
|
|
117
131
|
nitroPreset: 'bun',
|
|
118
132
|
outputDir: '.output',
|
|
133
|
+
serverBundleDir: 'server',
|
|
119
134
|
supportsWaitUntil: true,
|
|
120
135
|
// Disabled for same reason as node-server — reverse proxies choke on 103.
|
|
121
136
|
// Link headers on the 200 response are converted to 103 by CDNs.
|
|
@@ -220,7 +235,29 @@ export function nitro(options: NitroAdapterOptions = {}): TimberPlatformAdapter
|
|
|
220
235
|
// Run the Nitro build to produce a production-ready server bundle.
|
|
221
236
|
// The output goes to dist/nitro/.output/server/index.mjs (for node-server preset).
|
|
222
237
|
// Config is passed programmatically — no nitro.config.ts file needed.
|
|
223
|
-
await runNitroBuild(outDir, preset, options.nitroConfig);
|
|
238
|
+
const { serverDir } = await runNitroBuild(outDir, preset, options.nitroConfig);
|
|
239
|
+
|
|
240
|
+
// Copy prebuilt flight payloads from the canonical build source
|
|
241
|
+
// (buildDir/prebuilt, cleaned by the prebuilt plugin each build) into
|
|
242
|
+
// the Nitro output. The RSC entry resolves `../prebuilt/` relative to
|
|
243
|
+
// its bundled chunk (<serverDir>/_chunks/), so prebuilt/ must live at
|
|
244
|
+
// <serverDir>/prebuilt/. serverDir is the resolved path from Nitro
|
|
245
|
+
// (honors user overrides via nitroConfig.output.serverDir).
|
|
246
|
+
const prebuiltSrc = join(buildDir, 'prebuilt');
|
|
247
|
+
await cp(prebuiltSrc, join(serverDir, 'prebuilt'), {
|
|
248
|
+
recursive: true,
|
|
249
|
+
}).catch((e: NodeJS.ErrnoException) => {
|
|
250
|
+
if (e.code !== 'ENOENT') throw e;
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
// Vercel with functionRules clones __server.func to per-route .func
|
|
254
|
+
// directories during the Nitro build. Copy prebuilt into those clones
|
|
255
|
+
// so requests routed to them also resolve ../prebuilt correctly.
|
|
256
|
+
if (preset === 'vercel' || preset === 'vercel-edge') {
|
|
257
|
+
const functionsDir = dirname(serverDir);
|
|
258
|
+
const baseFuncName = basename(serverDir);
|
|
259
|
+
await copyPrebuiltToVercelFuncClones(functionsDir, prebuiltSrc, baseFuncName);
|
|
260
|
+
}
|
|
224
261
|
},
|
|
225
262
|
|
|
226
263
|
// Only presets that produce a locally-runnable server get preview().
|
|
@@ -598,11 +635,16 @@ export function generateNitroPreviewCommand(
|
|
|
598
635
|
* Externalizes the timber RSC/SSR output — those files are pre-built
|
|
599
636
|
* by timber and have internal references that nitro's bundler can't follow.
|
|
600
637
|
*/
|
|
638
|
+
interface NitroBuildResult {
|
|
639
|
+
/** Resolved output.serverDir — where the server bundle + _chunks/ live. */
|
|
640
|
+
serverDir: string;
|
|
641
|
+
}
|
|
642
|
+
|
|
601
643
|
async function runNitroBuild(
|
|
602
644
|
nitroDir: string,
|
|
603
645
|
preset: NitroPreset,
|
|
604
646
|
userConfig?: Record<string, unknown>
|
|
605
|
-
): Promise<
|
|
647
|
+
): Promise<NitroBuildResult> {
|
|
606
648
|
const presetConfig = PRESET_CONFIGS[preset];
|
|
607
649
|
const {
|
|
608
650
|
createNitro,
|
|
@@ -633,10 +675,18 @@ async function runNitroBuild(
|
|
|
633
675
|
...userConfig,
|
|
634
676
|
});
|
|
635
677
|
|
|
678
|
+
// Read the resolved serverDir AFTER config merging — userConfig may
|
|
679
|
+
// override output.dir or output.serverDir. Nitro appends a trailing
|
|
680
|
+
// slash during resolution; strip it for join() compatibility.
|
|
681
|
+
const raw = nitro.options.output.serverDir;
|
|
682
|
+
const serverDir = raw.endsWith('/') ? raw.slice(0, -1) : raw;
|
|
683
|
+
|
|
636
684
|
await prepare(nitro);
|
|
637
685
|
await copyPublicAssets(nitro);
|
|
638
686
|
await nitroBuild(nitro);
|
|
639
687
|
await nitro.close();
|
|
688
|
+
|
|
689
|
+
return { serverDir };
|
|
640
690
|
}
|
|
641
691
|
|
|
642
692
|
/** Spawn a Nitro preview process and pipe stdio. */
|
|
@@ -729,3 +779,55 @@ export function sendNodeResponse(nodeRes, webRes) {
|
|
|
729
779
|
export function getPresetConfig(preset: NitroPreset): PresetConfig {
|
|
730
780
|
return PRESET_CONFIGS[preset];
|
|
731
781
|
}
|
|
782
|
+
|
|
783
|
+
/**
|
|
784
|
+
* Resolve the destination path for prebuilt flight payloads in the Nitro
|
|
785
|
+
* output directory. The RSC entry resolves `../prebuilt/` relative to its
|
|
786
|
+
* bundled chunk location (`<serverBundleDir>/_chunks/`), so prebuilt/ must
|
|
787
|
+
* live at `<serverBundleDir>/prebuilt/`.
|
|
788
|
+
*
|
|
789
|
+
* The serverBundleDir varies by preset — Nitro's Vercel preset uses
|
|
790
|
+
* `functions/__server.func` while most others use `server`.
|
|
791
|
+
*
|
|
792
|
+
* @internal Exported for testing.
|
|
793
|
+
*/
|
|
794
|
+
export function resolvePrebuiltOutputPath(outDir: string, preset: NitroPreset): string {
|
|
795
|
+
const presetConfig = PRESET_CONFIGS[preset];
|
|
796
|
+
return join(outDir, presetConfig.outputDir, presetConfig.serverBundleDir, 'prebuilt');
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
* Copy prebuilt payloads into cloned Vercel function directories.
|
|
801
|
+
*
|
|
802
|
+
* When users configure `vercel.functionRules`, Nitro's compiled hook clones
|
|
803
|
+
* the base __server.func to per-route .func directories. These clones are
|
|
804
|
+
* created during `runNitroBuild()` — before our post-build prebuilt copy.
|
|
805
|
+
* Each clone resolves `../prebuilt` independently, so they each need a copy.
|
|
806
|
+
*
|
|
807
|
+
* @internal Exported for testing.
|
|
808
|
+
*/
|
|
809
|
+
export async function copyPrebuiltToVercelFuncClones(
|
|
810
|
+
functionsDir: string,
|
|
811
|
+
prebuiltSrc: string,
|
|
812
|
+
baseFuncName: string
|
|
813
|
+
): Promise<void> {
|
|
814
|
+
const funcDirs: string[] = [];
|
|
815
|
+
try {
|
|
816
|
+
for await (const match of glob('**/*.func', { cwd: functionsDir })) {
|
|
817
|
+
if (!match.endsWith(baseFuncName)) {
|
|
818
|
+
funcDirs.push(join(functionsDir, match));
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
} catch {
|
|
822
|
+
return;
|
|
823
|
+
}
|
|
824
|
+
await Promise.all(
|
|
825
|
+
funcDirs.map((dir) =>
|
|
826
|
+
cp(prebuiltSrc, join(dir, 'prebuilt'), { recursive: true }).catch(
|
|
827
|
+
(e: NodeJS.ErrnoException) => {
|
|
828
|
+
if (e.code !== 'ENOENT') throw e;
|
|
829
|
+
}
|
|
830
|
+
)
|
|
831
|
+
)
|
|
832
|
+
);
|
|
833
|
+
}
|