@ngrok/app-server 0.4.1 → 0.5.1
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/README.md +223 -64
- package/dist/brotli-only-BVAagKt3.js +63 -0
- package/dist/build-id-CwMbED1n.js +245 -0
- package/dist/{build-manifest-DBMWe3Lx.js → build-manifest-CoBztw_6.js} +13 -4
- package/dist/bun-BCz6K_Xv.js +1 -2
- package/dist/check-count-DQl5z_qe.js +17 -0
- package/dist/cli.js +9 -6
- package/dist/client-browser.d.ts +2 -3
- package/dist/client-browser.js +1 -1
- package/dist/client.d.ts +5 -4
- package/dist/client.js +9 -6
- package/dist/{compress-Cp5NfXCC.js → compress-2w3jqBh7.js} +2 -3
- package/dist/{compression-CT2mWlKM.js → compression-uJxu0JVb.js} +32 -5
- package/dist/content-types-Le-5BNEC.js +10 -0
- package/dist/{create-server-Bp1yILQk.js → create-server-DVTZun6D.js} +617 -306
- package/dist/create-server-PA0qniaK.js +3 -0
- package/dist/{create-server-X2GR-U6t.d.ts → create-server-UVsHFQyK.d.ts} +116 -54
- package/dist/deno-aqhikNMG.js +1 -2
- package/dist/{entry-BoxCqc6w.js → entry-CMhX3yf8.js} +85 -65
- package/dist/entry-CvZ4U0ia.js +3 -0
- package/dist/{entry-DZTCaL3d.d.ts → entry-DBq_3s8X.d.ts} +10 -36
- package/dist/entry-protocol-C30UPXzy.js +14 -0
- package/dist/entry-source-DSE5NAJu.js +70 -0
- package/dist/entry-source-SHoE-DUP.js +3 -0
- package/dist/exit-Hh-O3gp4.js +83 -0
- package/dist/{header-hook-Vzw9J9BY.js → header-hook-JfqaTt34.js} +69 -23
- package/dist/{index-B8LsM6Mh.d.ts → index-gzGs53Ue.d.ts} +43 -38
- package/dist/index.d.ts +88 -44
- package/dist/index.js +216 -84
- package/dist/listen-options-7TaXjyrk.js +1 -2
- package/dist/{load-entry-CCPWbsrj.js → load-entry-Bgq1_HDV.js} +11 -12
- package/dist/{log-DQAS5gGT.js → log-DfC9D5_T.js} +70 -49
- package/dist/{node-D6m6e6EI.js → node-DQPrMFyc.js} +20 -8
- package/dist/node-DyKDFII0.js +263 -0
- package/dist/node-vite.d.ts +2 -3
- package/dist/node-vite.js +1 -1
- package/dist/node.d.ts +41 -64
- package/dist/node.js +3 -3
- package/dist/react-router-vite.d.ts +2 -3
- package/dist/react-router-vite.js +1 -1
- package/dist/react-router.d.ts +6 -17
- package/dist/react-router.js +9 -14
- package/dist/request-context-Cslbrscf.js +163 -0
- package/dist/{response-edge-CU8ZvL_F.js → response-edge-Ow5Pi5qF.js} +13 -10
- package/dist/{response-writer-D7KHfr8n.js → response-writer-Dd4Ey99f.js} +57 -21
- package/dist/{script-hashes-CU7P9oZU.js → script-hashes-BdvJ0QI_.js} +2 -3
- package/dist/serve-AatMo9k6.js +26 -0
- package/dist/{stale-build-navigation-rg5xxmTr.js → stale-build-navigation-Qf_Lem39.js} +4 -5
- package/dist/{stale-build-navigation-ypV7Ow4o.d.ts → stale-build-navigation-WjhD8zHi.d.ts} +4 -4
- package/dist/start-DYFyGKsM.js +470 -0
- package/dist/static-files-BdTPam5b.js +438 -0
- package/dist/static-pages-6IBHdYQc.d.ts +30 -0
- package/dist/tanstack-start-vite.d.ts +2 -3
- package/dist/tanstack-start-vite.js +1 -1
- package/dist/tanstack-start.d.ts +3 -4
- package/dist/tanstack-start.js +2 -3
- package/dist/tcp-3v4pmnYU.js +58 -0
- package/dist/testing.d.ts +8 -6
- package/dist/testing.js +19 -17
- package/dist/{trailing-slash-D2QWKWEu.d.ts → trailing-slash-C-yBKCib.d.ts} +2 -3
- package/dist/{types-MgFtkNQW.d.ts → types-KsKRDwAv.d.ts} +97 -46
- package/dist/vercel-pages.d.ts +3 -16
- package/dist/vercel-pages.js +1 -2
- package/dist/vercel-vite.d.ts +4 -5
- package/dist/vercel-vite.js +48 -44
- package/dist/vercel.d.ts +13 -10
- package/dist/vercel.js +48 -35
- package/dist/{vite-D4hfj3ph.js → vite-Brb8YR9I.js} +2 -7
- package/dist/{vite-B-GfswoH.js → vite-CHppJWp_.js} +5 -7
- package/dist/{vite-DyrhyKEr.js → vite-DjlHdyTM.js} +2 -7
- package/dist/vite.d.ts +2 -2
- package/dist/vite.js +885 -2
- package/package.json +13 -12
- package/dist/brotli-only-DrA29Ecw.js +0 -97
- package/dist/brotli-only-DrA29Ecw.js.map +0 -1
- package/dist/build-id-B0448vZH.js +0 -151
- package/dist/build-id-B0448vZH.js.map +0 -1
- package/dist/build-manifest-DBMWe3Lx.js.map +0 -1
- package/dist/bun-BCz6K_Xv.js.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/client.js.map +0 -1
- package/dist/compress-Cp5NfXCC.js.map +0 -1
- package/dist/compression-CT2mWlKM.js.map +0 -1
- package/dist/create-server-Bp1yILQk.js.map +0 -1
- package/dist/deno-aqhikNMG.js.map +0 -1
- package/dist/entry-BoxCqc6w.js.map +0 -1
- package/dist/header-hook-Vzw9J9BY.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/listen-options-7TaXjyrk.js.map +0 -1
- package/dist/load-entry-CCPWbsrj.js.map +0 -1
- package/dist/log-DQAS5gGT.js.map +0 -1
- package/dist/node-CVVdk2N6.js +0 -334
- package/dist/node-CVVdk2N6.js.map +0 -1
- package/dist/node-D6m6e6EI.js.map +0 -1
- package/dist/react-router.js.map +0 -1
- package/dist/request-context-Bxdbk5P1.js +0 -80
- package/dist/request-context-Bxdbk5P1.js.map +0 -1
- package/dist/response-edge-CU8ZvL_F.js.map +0 -1
- package/dist/response-writer-D7KHfr8n.js.map +0 -1
- package/dist/script-hashes-CU7P9oZU.js.map +0 -1
- package/dist/serve-W4WacdOw.js +0 -29
- package/dist/serve-W4WacdOw.js.map +0 -1
- package/dist/stale-build-navigation-rg5xxmTr.js.map +0 -1
- package/dist/start-j0VlxeiI.js +0 -324
- package/dist/start-j0VlxeiI.js.map +0 -1
- package/dist/static-files-C2ea8KQ6.js +0 -310
- package/dist/static-files-C2ea8KQ6.js.map +0 -1
- package/dist/tanstack-start.js.map +0 -1
- package/dist/tcp-BgDXbjOG.js +0 -42
- package/dist/tcp-BgDXbjOG.js.map +0 -1
- package/dist/testing.js.map +0 -1
- package/dist/vercel-pages.js.map +0 -1
- package/dist/vercel-vite.js.map +0 -1
- package/dist/vercel.js.map +0 -1
- package/dist/vite-B-GfswoH.js.map +0 -1
- package/dist/vite-D4hfj3ph.js.map +0 -1
- package/dist/vite-DPiSKHDn.js +0 -870
- package/dist/vite-DPiSKHDn.js.map +0 -1
- package/dist/vite-DyrhyKEr.js.map +0 -1
package/dist/vite-DPiSKHDn.js
DELETED
|
@@ -1,870 +0,0 @@
|
|
|
1
|
-
import { n as DEFAULT_ASSETS_PATH, r as manifestKey, t as BUILD_MANIFEST_FILE } from "./build-manifest-DBMWe3Lx.js";
|
|
2
|
-
import { a as isCompressible, n as MIN_COMPRESS_BYTES, r as copyName } from "./compression-CT2mWlKM.js";
|
|
3
|
-
import { t as contentType } from "./static-files-C2ea8KQ6.js";
|
|
4
|
-
import { n as scriptHashesOf } from "./script-hashes-CU7P9oZU.js";
|
|
5
|
-
import { t as node } from "./vite-D4hfj3ph.js";
|
|
6
|
-
import { t as reactRouterAdapter } from "./vite-B-GfswoH.js";
|
|
7
|
-
import { t as tanstackStartAdapter } from "./vite-DyrhyKEr.js";
|
|
8
|
-
import { isBuiltin } from "node:module";
|
|
9
|
-
import { getPath } from "hono/utils/url";
|
|
10
|
-
import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
11
|
-
import { basename, dirname, extname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
|
|
12
|
-
import { brotliCompressSync, constants as constants$1, gzipSync } from "node:zlib";
|
|
13
|
-
import { createHash } from "node:crypto";
|
|
14
|
-
import { nodeFileTrace } from "@vercel/nft";
|
|
15
|
-
|
|
16
|
-
// src/vite/standalone.ts
|
|
17
|
-
/**
|
|
18
|
-
* A package name: an optional scope and a name, each with no `/` or `\` and
|
|
19
|
-
* no `.` at the start. Why: a name such as `..` or `../x` in a manifest must
|
|
20
|
-
* not move a copy out of `node_modules`.
|
|
21
|
-
*/
|
|
22
|
-
const PACKAGE_NAME = /^(?:@[^./\\][^/\\]*\/)?[^./\\][^/\\]*$/u;
|
|
23
|
-
/**
|
|
24
|
-
* The package names in the dependency `fields` of the `package.json` in
|
|
25
|
-
* `directory`. It skips a key that is not a package name.
|
|
26
|
-
*
|
|
27
|
-
* @example
|
|
28
|
-
* dependencyNames("/app/node_modules/react-dom", ["peerDependencies"]); // => ["react"]
|
|
29
|
-
*/
|
|
30
|
-
function dependencyNames(directory, fields) {
|
|
31
|
-
const manifest = JSON.parse(readFileSync(join(directory, "package.json"), "utf8"));
|
|
32
|
-
const names = fields.flatMap((field) => {
|
|
33
|
-
const value = typeof manifest === "object" && manifest != null ? Reflect.get(manifest, field) : void 0;
|
|
34
|
-
return typeof value === "object" && value != null ? Object.keys(value).filter((name) => PACKAGE_NAME.test(name)) : [];
|
|
35
|
-
});
|
|
36
|
-
return [...new Set(names)];
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* The package name of a bare import.
|
|
40
|
-
*
|
|
41
|
-
* @example
|
|
42
|
-
* packageName("@scope/name/sub/path"); // => "@scope/name"
|
|
43
|
-
*/
|
|
44
|
-
function packageName(specifier) {
|
|
45
|
-
return specifier.split("/").slice(0, specifier.startsWith("@") ? 2 : 1).join("/");
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* Code that finds a file next to its own module: a relative `new URL()` on
|
|
49
|
-
* `import.meta.url`, `fileURLToPath(import.meta.url)`, or
|
|
50
|
-
* `import.meta.dirname`.
|
|
51
|
-
*/
|
|
52
|
-
const OWN_FILE = /new\s+URL\(\s*(?<quote>["'`])\.{1,2}\/[^"'`]*\k<quote>\s*,\s*import\.meta\.url\s*\)|fileURLToPath\(\s*import\.meta\.url\s*\)|import\.meta\.(?:dirname|filename)\b/u;
|
|
53
|
-
/**
|
|
54
|
-
* Whether the module `file` finds a file next to itself, such as
|
|
55
|
-
* `@vercel/og`, which reads `resvg.wasm` through
|
|
56
|
-
* `new URL("./resvg.wasm", import.meta.url)`. Why: in the bundle,
|
|
57
|
-
* `import.meta.url` is the URL of the bundle, so the file is not there.
|
|
58
|
-
*
|
|
59
|
-
* @example
|
|
60
|
-
* readsOwnFiles("/app/node_modules/@vercel/og/dist/index.node.js"); // => true
|
|
61
|
-
*/
|
|
62
|
-
function readsOwnFiles(file) {
|
|
63
|
-
return OWN_FILE.test(readFileSync(file, "utf8"));
|
|
64
|
-
}
|
|
65
|
-
/**
|
|
66
|
-
* The real path of the directory of package `name`, as Node finds it from the
|
|
67
|
-
* directory `from`: in each `node_modules` directory above `from`. Else
|
|
68
|
-
* `undefined`. The real path follows the symbolic links of pnpm's layout.
|
|
69
|
-
*
|
|
70
|
-
* @example
|
|
71
|
-
* findPackage("react", "/app/build/server"); // => "/app/node_modules/.pnpm/react@19.3.1/node_modules/react"
|
|
72
|
-
*/
|
|
73
|
-
function findPackage(name, from) {
|
|
74
|
-
for (let directory = from;; directory = dirname(directory)) {
|
|
75
|
-
const candidate = join(directory, "node_modules", name);
|
|
76
|
-
if (basename(directory) !== "node_modules" && existsSync(join(candidate, "package.json"))) return realpathSync(candidate);
|
|
77
|
-
if (dirname(directory) === directory) return;
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* The directory of package `name` that holds `file`: the nearest directory
|
|
82
|
-
* above `file` at `node_modules/<name>`. Else `undefined`, such as for a file
|
|
83
|
-
* of a linked workspace package.
|
|
84
|
-
*
|
|
85
|
-
* @example
|
|
86
|
-
* packageDirectoryOf("/app/node_modules/react/cjs/react.js", "react"); // => "/app/node_modules/react"
|
|
87
|
-
*/
|
|
88
|
-
function packageDirectoryOf(file, name) {
|
|
89
|
-
for (let directory = dirname(file); directory !== dirname(directory); directory = dirname(directory)) if (directory.endsWith(`${sep}${join("node_modules", name)}`)) return realpathSync(directory);
|
|
90
|
-
}
|
|
91
|
-
/** Whether a `.node` file is in `directory`, outside its `node_modules`. */
|
|
92
|
-
function hasNodeFile(directory) {
|
|
93
|
-
return readdirSync(directory, { withFileTypes: true }).some((entry) => entry.isDirectory() ? entry.name !== "node_modules" && hasNodeFile(join(entry.parentPath, entry.name)) : entry.name.endsWith(".node"));
|
|
94
|
-
}
|
|
95
|
-
/**
|
|
96
|
-
* Whether the package in `directory` loads a native addon: a `.node` file is
|
|
97
|
-
* in the package, or in a package of its `dependencies` or
|
|
98
|
-
* `optionalDependencies`. The second case finds a package that gets its addon
|
|
99
|
-
* from a package for each platform, such as `oxc-parser` from
|
|
100
|
-
* `@oxc-parser/binding-darwin-arm64`. Only the installed platform package is
|
|
101
|
-
* there. `scans` keeps the result for each directory that the function
|
|
102
|
-
* searched, so a call with the same map does not search a directory again.
|
|
103
|
-
*
|
|
104
|
-
* @example
|
|
105
|
-
* isNativePackage("/app/node_modules/better-sqlite3"); // => true
|
|
106
|
-
*/
|
|
107
|
-
function isNativePackage(directory, scans = /* @__PURE__ */ new Map()) {
|
|
108
|
-
const scan = (path) => {
|
|
109
|
-
const found = scans.get(path) ?? hasNodeFile(path);
|
|
110
|
-
scans.set(path, found);
|
|
111
|
-
return found;
|
|
112
|
-
};
|
|
113
|
-
return scan(directory) || dependencyNames(directory, ["dependencies", "optionalDependencies"]).some((name) => {
|
|
114
|
-
const dependency = findPackage(name, directory);
|
|
115
|
-
return dependency != null && scan(dependency);
|
|
116
|
-
});
|
|
117
|
-
}
|
|
118
|
-
/**
|
|
119
|
-
* The `node_modules` directories where Node looks for a package that the
|
|
120
|
-
* package at `destination` imports, nearest first, down to `target`.
|
|
121
|
-
*/
|
|
122
|
-
function lookupDirectories(destination, target) {
|
|
123
|
-
const directories = [];
|
|
124
|
-
for (let directory = destination;; directory = dirname(directory)) {
|
|
125
|
-
if (basename(directory) !== "node_modules") directories.push(join(directory, "node_modules"));
|
|
126
|
-
if (directory === dirname(target)) return directories;
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
/**
|
|
130
|
-
* Copies each package, whole, with the installed packages of its
|
|
131
|
-
* `dependencies`, `optionalDependencies`, and `peerDependencies`, into the
|
|
132
|
-
* `node_modules` directory `target`, except the packages in `omit`. Node then
|
|
133
|
-
* finds each package from a file next to `target`, with no install. The copy
|
|
134
|
-
* follows symbolic links. A dependency goes to the top of `target`. If another
|
|
135
|
-
* copy of that package is nearer in the lookup path of the package that needs
|
|
136
|
-
* it, the dependency goes into that package's own `node_modules`.
|
|
137
|
-
*
|
|
138
|
-
* @example
|
|
139
|
-
* copyPackages(new Map([["oxc-parser", "/app/node_modules/oxc-parser"]]), "/app/build/server/node_modules");
|
|
140
|
-
*/
|
|
141
|
-
function copyPackages(packages, target, { omit = /* @__PURE__ */ new Set() } = {}) {
|
|
142
|
-
const copied = /* @__PURE__ */ new Map();
|
|
143
|
-
const queue = [];
|
|
144
|
-
const add = (destination, name, source) => {
|
|
145
|
-
const copy = {
|
|
146
|
-
name,
|
|
147
|
-
source,
|
|
148
|
-
dependencies: []
|
|
149
|
-
};
|
|
150
|
-
copied.set(destination, copy);
|
|
151
|
-
queue.push([destination, copy]);
|
|
152
|
-
};
|
|
153
|
-
for (const [name, source] of packages) if (!omit.has(name)) add(join(target, name), name, source);
|
|
154
|
-
for (const [destination, copy] of queue) {
|
|
155
|
-
const { source } = copy;
|
|
156
|
-
cpSync(source, destination, {
|
|
157
|
-
recursive: true,
|
|
158
|
-
dereference: true,
|
|
159
|
-
filter: (path) => path !== join(source, "node_modules")
|
|
160
|
-
});
|
|
161
|
-
for (const name of dependencyNames(source, [
|
|
162
|
-
"dependencies",
|
|
163
|
-
"optionalDependencies",
|
|
164
|
-
"peerDependencies"
|
|
165
|
-
])) {
|
|
166
|
-
const dependency = findPackage(name, source);
|
|
167
|
-
const found = lookupDirectories(destination, target).map((directory) => join(directory, name)).find((path) => copied.has(path));
|
|
168
|
-
if (dependency != null && !omit.has(name)) {
|
|
169
|
-
if (found == null || copied.get(found)?.source !== dependency) {
|
|
170
|
-
const placed = join(found == null ? target : join(destination, "node_modules"), name);
|
|
171
|
-
add(placed, name, dependency);
|
|
172
|
-
copy.dependencies.push(placed);
|
|
173
|
-
} else copy.dependencies.push(found);
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
return copied;
|
|
178
|
-
}
|
|
179
|
-
/** Each file under `directory`, except in a `node_modules` directory. */
|
|
180
|
-
function ownFiles(directory) {
|
|
181
|
-
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
|
|
182
|
-
const path = join(entry.parentPath, entry.name);
|
|
183
|
-
if (entry.isDirectory()) return entry.name === "node_modules" ? [] : ownFiles(path);
|
|
184
|
-
return [path];
|
|
185
|
-
});
|
|
186
|
-
}
|
|
187
|
-
/** Removes each empty directory in `directory`, and `directory` when it is then empty. */
|
|
188
|
-
function removeEmptyDirectories(directory) {
|
|
189
|
-
for (const entry of readdirSync(directory, { withFileTypes: true })) if (entry.isDirectory()) removeEmptyDirectories(join(directory, entry.name));
|
|
190
|
-
if (readdirSync(directory).length === 0) rmSync(directory, { recursive: true });
|
|
191
|
-
}
|
|
192
|
-
/**
|
|
193
|
-
* The export conditions of each runtime that the server runs on, besides
|
|
194
|
-
* `import`, `require`, and `default`. Why each: Bun and Deno take their own
|
|
195
|
-
* entry of a package before its `node` entry.
|
|
196
|
-
*/
|
|
197
|
-
const RUNTIME_CONDITIONS = [
|
|
198
|
-
["node"],
|
|
199
|
-
["bun", "node"],
|
|
200
|
-
["deno", "node"]
|
|
201
|
-
];
|
|
202
|
-
/**
|
|
203
|
-
* A `require.resolve()` or an `import.meta.resolve()` of a string literal.
|
|
204
|
-
* The `source` group is the string.
|
|
205
|
-
*/
|
|
206
|
-
const RESOLVE_CALL = /\b(?:require|import\.meta)\.resolve\(\s*(?<quote>["'`])(?<source>[^"'`$]+)\k<quote>/gu;
|
|
207
|
-
/** Code that finds a file next to its own module in a way that `@vercel/nft` does not follow. */
|
|
208
|
-
const UNTRACED_OWN_FILE = /import\.meta\.(?:dirname|filename)\b/u;
|
|
209
|
-
/** The warning of `@vercel/nft` for a module that it cannot parse, such as a TypeScript file, so it finds no import of it. */
|
|
210
|
-
const UNPARSED = /^Failed to parse (?<file>.+) as module:/u;
|
|
211
|
-
/**
|
|
212
|
-
* Removes each file of a package in `copied` that the server build in
|
|
213
|
-
* `serverDirectory` cannot load, as `@vercel/nft` traces it from each module
|
|
214
|
-
* of the build. A package that no traced file is in goes away whole. Each
|
|
215
|
-
* package for which `whole` is true, and each package that it depends on,
|
|
216
|
-
* keeps each file. Why: a native package can load a library through the
|
|
217
|
-
* system's loader, such as `sharp` loads libvips, and a trace cannot see it.
|
|
218
|
-
* The trace misses the files that a module loads through
|
|
219
|
-
* {@link UNTRACED_OWN_FILE}, the imports of a module that it cannot parse,
|
|
220
|
-
* and a file that {@link RESOLVE_CALL} finds through the `exports` of a
|
|
221
|
-
* package. So the package of such a module, or the package that it
|
|
222
|
-
* resolves, keeps each file, with each package that it depends on.
|
|
223
|
-
*
|
|
224
|
-
* @example
|
|
225
|
-
* await removeUntraced("/app/build/server", copied, (copy) => isNativePackage(copy.source));
|
|
226
|
-
*/
|
|
227
|
-
async function removeUntraced(serverDirectory, copied, whole) {
|
|
228
|
-
const kept = /* @__PURE__ */ new Set();
|
|
229
|
-
const keep = (destination) => {
|
|
230
|
-
if (!kept.has(destination)) {
|
|
231
|
-
kept.add(destination);
|
|
232
|
-
for (const dependency of copied.get(destination)?.dependencies ?? []) keep(dependency);
|
|
233
|
-
}
|
|
234
|
-
};
|
|
235
|
-
for (const [destination, copy] of copied) if (whole(copy)) keep(destination);
|
|
236
|
-
if (kept.size === copied.size) return;
|
|
237
|
-
const modules = ownFiles(serverDirectory).filter((file) => /\.[cm]?js$/u.test(file));
|
|
238
|
-
const cache = {};
|
|
239
|
-
const traces = await Promise.all(RUNTIME_CONDITIONS.map(async (conditions) => nodeFileTrace(modules, {
|
|
240
|
-
base: serverDirectory,
|
|
241
|
-
mixedModules: true,
|
|
242
|
-
conditions,
|
|
243
|
-
cache
|
|
244
|
-
})));
|
|
245
|
-
const traced = new Set(traces.flatMap(({ fileList }) => [...fileList].map((file) => join(serverDirectory, file))));
|
|
246
|
-
const real = realpathSync(serverDirectory);
|
|
247
|
-
const unparsed = new Set(traces.flatMap(({ warnings }) => [...warnings].flatMap(({ message }) => {
|
|
248
|
-
const file = UNPARSED.exec(message)?.groups?.file;
|
|
249
|
-
return file == null ? [] : [join(serverDirectory, relative(real, file))];
|
|
250
|
-
})));
|
|
251
|
-
const present = [...copied.keys()].filter((destination) => existsSync(destination));
|
|
252
|
-
for (const destination of present.filter((each) => !kept.has(each))) {
|
|
253
|
-
const loaded = ownFiles(destination).filter((file) => traced.has(file));
|
|
254
|
-
const code = loaded.filter((file) => /\.[cm]?js$/u.test(file)).map((file) => readFileSync(file, "utf8"));
|
|
255
|
-
if (loaded.some((file) => unparsed.has(file)) || code.some((each) => UNTRACED_OWN_FILE.test(each))) keep(destination);
|
|
256
|
-
const resolved = new Set(code.flatMap((each) => [...each.matchAll(RESOLVE_CALL)].map(({ groups }) => packageName(groups?.source ?? ""))));
|
|
257
|
-
for (const each of [destination, ...copied.get(destination)?.dependencies ?? []]) if (resolved.has(copied.get(each)?.name ?? "")) keep(each);
|
|
258
|
-
}
|
|
259
|
-
for (const destination of present.filter((each) => !kept.has(each))) {
|
|
260
|
-
const files = ownFiles(destination);
|
|
261
|
-
const used = files.some((file) => traced.has(file));
|
|
262
|
-
for (const file of files) if (!traced.has(file) && !(used && basename(file) === "package.json")) rmSync(file);
|
|
263
|
-
}
|
|
264
|
-
removeEmptyDirectories(join(serverDirectory, "node_modules"));
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
// src/vite/index.ts
|
|
268
|
-
/** The module ID of the server entry that {@link appServer} generates. */
|
|
269
|
-
const SERVER_ENTRY_ID = "virtual:@ngrok/app-server/entry";
|
|
270
|
-
const RESOLVED_SERVER_ENTRY_ID = `\0${SERVER_ENTRY_ID}`;
|
|
271
|
-
/** The Vite environment that builds the server. */
|
|
272
|
-
const SERVER_ENVIRONMENT = "ssr";
|
|
273
|
-
/** A bare import, such as `react` or `@scope/name/path`: not a path, a `\0` ID, or a `node:` or `virtual:` ID. */
|
|
274
|
-
const BARE_IMPORT = /^[\w@][^:]*$/u;
|
|
275
|
-
/** The file extensions of a module that Node imports as it is, with no transform by Vite. */
|
|
276
|
-
const JAVASCRIPT_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
277
|
-
"",
|
|
278
|
-
".js",
|
|
279
|
-
".mjs",
|
|
280
|
-
".cjs"
|
|
281
|
-
]);
|
|
282
|
-
/** The header that turns on Node's header store for a response, so `finish` can read every header. */
|
|
283
|
-
const CAPTURE_MARKER = "x-app-server-capture";
|
|
284
|
-
/**
|
|
285
|
-
* Headers that describe one transfer, not the resource. The server sets its
|
|
286
|
-
* own, and a cookie must never replay to every visitor. `Vary` is left out
|
|
287
|
-
* because the preview server adds `Vary: Origin` to every response.
|
|
288
|
-
*/
|
|
289
|
-
const UNCAPTURED_HEADERS = /* @__PURE__ */ new Set([
|
|
290
|
-
CAPTURE_MARKER,
|
|
291
|
-
"connection",
|
|
292
|
-
"content-encoding",
|
|
293
|
-
"content-length",
|
|
294
|
-
"date",
|
|
295
|
-
"etag",
|
|
296
|
-
"keep-alive",
|
|
297
|
-
"last-modified",
|
|
298
|
-
"set-cookie",
|
|
299
|
-
"transfer-encoding",
|
|
300
|
-
"vary"
|
|
301
|
-
]);
|
|
302
|
-
/** The built-in framework adapters, each with the name of the Vite plugin that marks its framework. */
|
|
303
|
-
const FRAMEWORKS = [{
|
|
304
|
-
plugin: "react-router:virtual-modules",
|
|
305
|
-
adapter: reactRouterAdapter
|
|
306
|
-
}, {
|
|
307
|
-
plugin: "tanstack-react-start:config",
|
|
308
|
-
adapter: tanstackStartAdapter
|
|
309
|
-
}];
|
|
310
|
-
/** The adapter of the one built-in framework whose plugin is in the Vite config. */
|
|
311
|
-
function detectFramework(plugins) {
|
|
312
|
-
const names = new Set(plugins.map((plugin) => plugin.name));
|
|
313
|
-
const [found, ...others] = FRAMEWORKS.filter(({ plugin }) => names.has(plugin));
|
|
314
|
-
if (found == null) throw new Error("@ngrok/app-server found no React Router or TanStack Start plugin in the Vite config. Add the framework's plugin, or pass `framework` to `appServer`.");
|
|
315
|
-
if (others.length > 0) throw new Error("@ngrok/app-server found the React Router and the TanStack Start plugins in the Vite config. Pass `framework` to `appServer`.");
|
|
316
|
-
return found.adapter();
|
|
317
|
-
}
|
|
318
|
-
/** The absolute path of `server.ts` or `server.js` in `root`, else `undefined` for the default app. */
|
|
319
|
-
function defaultApp(root) {
|
|
320
|
-
return ["server.ts", "server.js"].map((name) => join(root, name)).find((path) => existsSync(path));
|
|
321
|
-
}
|
|
322
|
-
/**
|
|
323
|
-
* The source of the server entry. When a runtime runs the file as its main
|
|
324
|
-
* module, such as `node build/server/app-server.js`, the entry starts the
|
|
325
|
-
* server. When the CLI imports it, the CLI starts the server.
|
|
326
|
-
*/
|
|
327
|
-
function serverEntrySource({ framework, host, appModule, clientDirectory }) {
|
|
328
|
-
const modules = [
|
|
329
|
-
framework.serverModule,
|
|
330
|
-
"@ngrok/app-server",
|
|
331
|
-
framework.runtimeModule,
|
|
332
|
-
host.runtimeModule,
|
|
333
|
-
...appModule == null ? [] : [appModule]
|
|
334
|
-
];
|
|
335
|
-
return [
|
|
336
|
-
"if (import.meta.main) {",
|
|
337
|
-
" process.env.NODE_ENV ??= \"production\";",
|
|
338
|
-
" if (typeof process.setSourceMapsEnabled === \"function\") {",
|
|
339
|
-
" process.setSourceMapsEnabled(true);",
|
|
340
|
-
" }",
|
|
341
|
-
"}",
|
|
342
|
-
`const [serverModule, { createEntry, createServer }, { runtime }, hostModule${appModule == null ? "" : ", { default: app }"}] = await Promise.all([`,
|
|
343
|
-
...modules.map((module) => `\timport(${JSON.stringify(module)}),`),
|
|
344
|
-
"]);",
|
|
345
|
-
...appModule == null ? [`const app = createServer({ trustForwardedProto: process.env.TRUST_FORWARDED_PROTO === "1", trustedProxyHops: Number(process.env.TRUSTED_PROXY_HOPS ?? 0) });`] : [],
|
|
346
|
-
`export const appServer = createEntry({`,
|
|
347
|
-
`\tapp,`,
|
|
348
|
-
`\thost: hostModule.host,`,
|
|
349
|
-
`\tclientDirectory: ${clientDirectory},`,
|
|
350
|
-
`\tframework: (mode) => runtime(serverModule, { ${framework.runtimeOptions == null ? "" : `...${framework.runtimeOptions}, `}mode }),`,
|
|
351
|
-
`});`,
|
|
352
|
-
"export { hostModule };",
|
|
353
|
-
"if (import.meta.main) {",
|
|
354
|
-
" await appServer.start();",
|
|
355
|
-
"}"
|
|
356
|
-
].join("\n");
|
|
357
|
-
}
|
|
358
|
-
/** The paths of the build that a host's `output` gets. */
|
|
359
|
-
function hostOutput(config, host) {
|
|
360
|
-
return {
|
|
361
|
-
root: config.root,
|
|
362
|
-
clientDirectory: outDir(config, "client"),
|
|
363
|
-
entryFile: join(outDir(config, SERVER_ENVIRONMENT), host.entryFileName),
|
|
364
|
-
assetsPath: urlPathOfAssetsDir(config.environments.client?.build.assetsDir ?? config.build.assetsDir)
|
|
365
|
-
};
|
|
366
|
-
}
|
|
367
|
-
/**
|
|
368
|
-
* The URL path of Vite's `build.assetsDir`. Why the default for the root: an
|
|
369
|
-
* immutable cache on each file of the client build would keep an old page.
|
|
370
|
-
*
|
|
371
|
-
* @example
|
|
372
|
-
* urlPathOfAssetsDir("blog-assets/build"); // => "/blog-assets/build/"
|
|
373
|
-
*/
|
|
374
|
-
function urlPathOfAssetsDir(assetsDir) {
|
|
375
|
-
const path = posix.normalize(`/${assetsDir.replaceAll("\\", "/")}/`);
|
|
376
|
-
return path === "/" ? DEFAULT_ASSETS_PATH : path;
|
|
377
|
-
}
|
|
378
|
-
/** The absolute path of an environment's build output. */
|
|
379
|
-
function outDir(config, environment) {
|
|
380
|
-
return resolve(config.root, config.environments[environment]?.build.outDir ?? config.build.outDir);
|
|
381
|
-
}
|
|
382
|
-
/**
|
|
383
|
-
* Whether `id` is a JavaScript file, which Node imports from `node_modules`
|
|
384
|
-
* as it is. Why: a plugin can resolve a bare import to a virtual module, and
|
|
385
|
-
* Vite transforms a JSON file or an asset, such as `?raw` on a file with no
|
|
386
|
-
* extension.
|
|
387
|
-
*/
|
|
388
|
-
function isJavaScriptFile(id) {
|
|
389
|
-
return isAbsolute(id) && !id.includes("?") && JAVASCRIPT_EXTENSIONS.has(extname(id));
|
|
390
|
-
}
|
|
391
|
-
/** The dependency fields of the app's `package.json` that can name a package the server imports. */
|
|
392
|
-
const APP_DEPENDENCY_FIELDS = [
|
|
393
|
-
"dependencies",
|
|
394
|
-
"optionalDependencies",
|
|
395
|
-
"devDependencies"
|
|
396
|
-
];
|
|
397
|
-
/** Whether `environment` builds the server. */
|
|
398
|
-
function isServerBuild(environment) {
|
|
399
|
-
return environment.name === SERVER_ENVIRONMENT && environment.mode === "build";
|
|
400
|
-
}
|
|
401
|
-
/**
|
|
402
|
-
* Makes the server build run with no install. The build bundles each
|
|
403
|
-
* dependency, except the packages that the app keeps external (`ssr.external`
|
|
404
|
-
* or the bundler's `external`), each native package (see `isNativePackage`),
|
|
405
|
-
* each package that reads a file next to its own module (see `readsOwnFiles`),
|
|
406
|
-
* and each package that the bundle shares with a package that the app keeps
|
|
407
|
-
* external: the whole package of an external subpath, and each peer, at each
|
|
408
|
-
* level. Those stay external, so the plugin copies each one, with its
|
|
409
|
-
* dependencies, into `node_modules` in the server build, and then removes each
|
|
410
|
-
* file that the build cannot load (see `removeUntraced`). A package in
|
|
411
|
-
* `ssr.external`, and a package that the app reads at run time, such as
|
|
412
|
-
* through `require.resolve`, keep each file. It also writes a `package.json` there, so Node, Bun, and
|
|
413
|
-
* Deno load the build as ES modules and find that `node_modules`.
|
|
414
|
-
*/
|
|
415
|
-
function standalone({ whole = [], omit = [] } = {}) {
|
|
416
|
-
const readByApp = /* @__PURE__ */ new Set();
|
|
417
|
-
const externals = /* @__PURE__ */ new Map();
|
|
418
|
-
const shared = /* @__PURE__ */ new Set();
|
|
419
|
-
const natives = /* @__PURE__ */ new Map();
|
|
420
|
-
const scans = /* @__PURE__ */ new Map();
|
|
421
|
-
const isNative = (directory) => {
|
|
422
|
-
const native = natives.get(directory) ?? isNativePackage(directory, scans);
|
|
423
|
-
natives.set(directory, native);
|
|
424
|
-
return native;
|
|
425
|
-
};
|
|
426
|
-
const ownFiles = /* @__PURE__ */ new Map();
|
|
427
|
-
const readsOwnFile = (file) => {
|
|
428
|
-
const reads = ownFiles.get(file) ?? (existsSync(file) && readsOwnFiles(file));
|
|
429
|
-
ownFiles.set(file, reads);
|
|
430
|
-
return reads;
|
|
431
|
-
};
|
|
432
|
-
const inBundle = /* @__PURE__ */ new Set();
|
|
433
|
-
/**
|
|
434
|
-
* Whether the bundled module `file` of package `name` must stay external:
|
|
435
|
-
* the package is native, or `file` reads a file next to it. Then the
|
|
436
|
-
* package and each of its peers stay external, so the bundle shares them.
|
|
437
|
-
*/
|
|
438
|
-
const staysExternal = ({ name, file, directory }, logger) => {
|
|
439
|
-
const native = directory != null && isNative(directory);
|
|
440
|
-
if (directory == null || !native && !readsOwnFile(file)) {
|
|
441
|
-
inBundle.add(name);
|
|
442
|
-
return false;
|
|
443
|
-
}
|
|
444
|
-
const group = withPeers([{
|
|
445
|
-
name,
|
|
446
|
-
from: directory
|
|
447
|
-
}]);
|
|
448
|
-
const held = [...group].find((peer) => inBundle.has(peer));
|
|
449
|
-
if (held != null && !native) {
|
|
450
|
-
logger.warn(`@ngrok/app-server bundles "${name}", but it reads a file next to its own module, so the server can fail when it reads that file. The bundle already holds "${held}", so "${name}" cannot stay external alone. Add "${name}" to \`ssr.external\`.`);
|
|
451
|
-
inBundle.add(name);
|
|
452
|
-
return false;
|
|
453
|
-
}
|
|
454
|
-
for (const peer of group) shared.add(peer);
|
|
455
|
-
return true;
|
|
456
|
-
};
|
|
457
|
-
return {
|
|
458
|
-
name: "@ngrok/app-server:standalone",
|
|
459
|
-
enforce: "pre",
|
|
460
|
-
config: (config, { command }) => {
|
|
461
|
-
const ssr = config.environments?.[SERVER_ENVIRONMENT]?.resolve;
|
|
462
|
-
return command === "build" && config.ssr?.noExternal == null && ssr?.noExternal == null && config.ssr?.external !== true && ssr?.external !== true ? { ssr: { noExternal: true } } : void 0;
|
|
463
|
-
},
|
|
464
|
-
buildStart() {
|
|
465
|
-
if (!isServerBuild(this.environment)) return;
|
|
466
|
-
externals.clear();
|
|
467
|
-
readByApp.clear();
|
|
468
|
-
shared.clear();
|
|
469
|
-
natives.clear();
|
|
470
|
-
scans.clear();
|
|
471
|
-
ownFiles.clear();
|
|
472
|
-
inBundle.clear();
|
|
473
|
-
const { resolve: resolveOptions, build, root } = this.environment.config;
|
|
474
|
-
const kept = [...resolveOptions.external === true ? [] : resolveOptions.external, ...[build.rolldownOptions.external].flat()];
|
|
475
|
-
const names = kept.flatMap((id) => typeof id === "string" && BARE_IMPORT.test(id) ? [packageName(id)] : []);
|
|
476
|
-
const patterns = kept.filter((id) => id != null && typeof id !== "string");
|
|
477
|
-
const matched = patterns.length === 0 || !existsSync(join(root, "package.json")) ? [] : dependencyNames(root, APP_DEPENDENCY_FIELDS).filter((name) => patterns.some((pattern) => matchesExternal(pattern, name)));
|
|
478
|
-
for (const name of names) {
|
|
479
|
-
const directory = findPackage(name, root);
|
|
480
|
-
if (directory != null) {
|
|
481
|
-
externals.set(name, directory);
|
|
482
|
-
readByApp.add(name);
|
|
483
|
-
}
|
|
484
|
-
}
|
|
485
|
-
for (const name of withPeers([...names, ...matched].map((dependency) => ({
|
|
486
|
-
name: dependency,
|
|
487
|
-
from: root
|
|
488
|
-
})))) shared.add(name);
|
|
489
|
-
},
|
|
490
|
-
resolveId: {
|
|
491
|
-
filter: { id: BARE_IMPORT },
|
|
492
|
-
async handler(source, importer, options) {
|
|
493
|
-
if (!isServerBuild(this.environment) || isBuiltin(source)) return null;
|
|
494
|
-
const resolved = await this.resolve(source, importer, {
|
|
495
|
-
...options,
|
|
496
|
-
skipSelf: true
|
|
497
|
-
});
|
|
498
|
-
const bundled = resolved?.external === false;
|
|
499
|
-
if (resolved == null || bundled && !isJavaScriptFile(resolved.id)) return resolved;
|
|
500
|
-
const name = packageName(source);
|
|
501
|
-
const directory = (bundled ? packageDirectoryOf(resolved.id, name) : void 0) ?? findPackage(name, importer != null && isAbsolute(importer) ? dirname(importer) : this.environment.config.root);
|
|
502
|
-
if (bundled && !shared.has(name) && !staysExternal({
|
|
503
|
-
name,
|
|
504
|
-
file: resolved.id,
|
|
505
|
-
directory
|
|
506
|
-
}, this.environment.logger)) return resolved;
|
|
507
|
-
const known = externals.get(name);
|
|
508
|
-
if (known != null && directory != null && known !== directory) throw new Error(`@ngrok/app-server found two copies of "${name}" that stay external, and the server build can hold one: ${known} and ${directory}. Install one version of "${name}".`);
|
|
509
|
-
externals.set(name, known ?? directory);
|
|
510
|
-
return bundled ? {
|
|
511
|
-
id: source,
|
|
512
|
-
external: true
|
|
513
|
-
} : resolved;
|
|
514
|
-
}
|
|
515
|
-
},
|
|
516
|
-
transform: {
|
|
517
|
-
filter: {
|
|
518
|
-
id: { exclude: /[\\/]node_modules[\\/]/u },
|
|
519
|
-
code: /\b(?:require|import\.meta)\.resolve\(/u
|
|
520
|
-
},
|
|
521
|
-
handler(code, id) {
|
|
522
|
-
if (!isServerBuild(this.environment)) return null;
|
|
523
|
-
for (const { groups } of code.matchAll(RESOLVE_CALL)) {
|
|
524
|
-
const source = groups?.source ?? "";
|
|
525
|
-
const name = packageName(source);
|
|
526
|
-
const directory = BARE_IMPORT.test(source) && !isBuiltin(source) && !externals.has(name) ? findPackage(name, isAbsolute(id) ? dirname(id) : this.environment.config.root) : void 0;
|
|
527
|
-
if (directory != null) externals.set(name, directory);
|
|
528
|
-
if (BARE_IMPORT.test(source) && !isBuiltin(source)) readByApp.add(name);
|
|
529
|
-
}
|
|
530
|
-
return null;
|
|
531
|
-
}
|
|
532
|
-
},
|
|
533
|
-
async writeBundle() {
|
|
534
|
-
if (!isServerBuild(this.environment)) return;
|
|
535
|
-
for (const importer of this.getModuleIds()) {
|
|
536
|
-
const info = this.getModuleInfo(importer);
|
|
537
|
-
for (const id of [...info?.importedIds ?? [], ...info?.dynamicallyImportedIds ?? []]) {
|
|
538
|
-
const name = packageName(id);
|
|
539
|
-
if (BARE_IMPORT.test(id) && !isBuiltin(id) && !externals.has(name)) externals.set(name, findPackage(name, isAbsolute(importer) ? dirname(importer) : this.environment.config.root));
|
|
540
|
-
}
|
|
541
|
-
}
|
|
542
|
-
const directory = outDir(this.environment.getTopLevelConfig(), SERVER_ENVIRONMENT);
|
|
543
|
-
const found = /* @__PURE__ */ new Map();
|
|
544
|
-
for (const [name, source] of externals) if (source == null) this.environment.logger.warn(`@ngrok/app-server cannot find "${name}", which stays external, so the server build does not hold it. The server fails if it imports "${name}".`);
|
|
545
|
-
else found.set(name, source);
|
|
546
|
-
const target = join(directory, "node_modules");
|
|
547
|
-
rmSync(target, {
|
|
548
|
-
recursive: true,
|
|
549
|
-
force: true
|
|
550
|
-
});
|
|
551
|
-
const copied = copyPackages(found, target, { omit: new Set(omit) });
|
|
552
|
-
const kept = /* @__PURE__ */ new Set([...whole, ...readByApp]);
|
|
553
|
-
await removeUntraced(directory, copied, ({ name, source }) => kept.has(name) || isNative(source));
|
|
554
|
-
writeFileSync(join(directory, "package.json"), `${JSON.stringify({ type: "module" })}\n`);
|
|
555
|
-
if (found.size > 0) this.environment.logger.info(`@ngrok/app-server copied the external packages ${[...found.keys()].join(", ")}, with the files of their dependencies that the server build loads, into ${target}.`);
|
|
556
|
-
}
|
|
557
|
-
};
|
|
558
|
-
}
|
|
559
|
-
/**
|
|
560
|
-
* Whether the app's `RegExp` or function external keeps the package `name`
|
|
561
|
-
* external. Why `false` when the function throws: the build calls it with no
|
|
562
|
-
* importer, and a function that reads the importer can throw.
|
|
563
|
-
*/
|
|
564
|
-
function matchesExternal(pattern, name) {
|
|
565
|
-
if (typeof pattern !== "function") return name.search(pattern) !== -1;
|
|
566
|
-
try {
|
|
567
|
-
return pattern(name, void 0, false) === true;
|
|
568
|
-
} catch {
|
|
569
|
-
return false;
|
|
570
|
-
}
|
|
571
|
-
}
|
|
572
|
-
/**
|
|
573
|
-
* Each package of `start` and each of its peers, at each level. Why each
|
|
574
|
-
* level: a peer can have peers, such as `react` for `react-router`.
|
|
575
|
-
*/
|
|
576
|
-
function withPeers(start) {
|
|
577
|
-
const names = /* @__PURE__ */ new Set();
|
|
578
|
-
const queue = [...start];
|
|
579
|
-
for (const { name, from } of queue) {
|
|
580
|
-
const directory = names.has(name) ? void 0 : findPackage(name, from);
|
|
581
|
-
names.add(name);
|
|
582
|
-
if (directory != null) for (const peer of dependencyNames(directory, ["peerDependencies"])) queue.push({
|
|
583
|
-
name: peer,
|
|
584
|
-
from: directory
|
|
585
|
-
});
|
|
586
|
-
}
|
|
587
|
-
return names;
|
|
588
|
-
}
|
|
589
|
-
/** Writes `.app-server.json` into the client build. */
|
|
590
|
-
function writeBuildManifest(clientDirectory, manifest) {
|
|
591
|
-
mkdirSync(clientDirectory, { recursive: true });
|
|
592
|
-
writeFileSync(join(clientDirectory, BUILD_MANIFEST_FILE), `${JSON.stringify(manifest, null, " ")}\n`);
|
|
593
|
-
}
|
|
594
|
-
/**
|
|
595
|
-
* Writes the build ID and the script hashes of the client build
|
|
596
|
-
* ({@link scriptHashesOf}) into `.app-server.json`, and keeps the rest of the
|
|
597
|
-
* file. Why after the build too: a build with no prerender pass can have HTML
|
|
598
|
-
* files, such as `public/offline.html`.
|
|
599
|
-
*/
|
|
600
|
-
function completeBuildManifest(clientDirectory, buildId) {
|
|
601
|
-
if (!existsSync(clientDirectory)) return;
|
|
602
|
-
const path = join(clientDirectory, BUILD_MANIFEST_FILE);
|
|
603
|
-
const recorded = existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : void 0;
|
|
604
|
-
writeBuildManifest(clientDirectory, {
|
|
605
|
-
prerendered: [],
|
|
606
|
-
headers: {},
|
|
607
|
-
...typeof recorded === "object" && recorded != null ? recorded : {},
|
|
608
|
-
...buildId == null ? {} : { buildId },
|
|
609
|
-
scriptHashes: scriptHashesOf(clientDirectory)
|
|
610
|
-
});
|
|
611
|
-
}
|
|
612
|
-
/**
|
|
613
|
-
* The ID of a client build: a hash of the name and the content of each file
|
|
614
|
-
* in its bundle. Why the bundle: it is the code that an open tab runs, so the
|
|
615
|
-
* ID changes when that code changes, and not for a change to the server, a
|
|
616
|
-
* `public/` file, or a prerendered page. Why the content, not the file
|
|
617
|
-
* names: a name has a content hash only when the output names ask for one.
|
|
618
|
-
*/
|
|
619
|
-
function bundleBuildId(bundle) {
|
|
620
|
-
const hash = createHash("sha256");
|
|
621
|
-
for (const file of Object.values(bundle).toSorted((first, second) => first.fileName < second.fileName ? -1 : 1)) {
|
|
622
|
-
hash.update(`${file.fileName}\0`);
|
|
623
|
-
hash.update(file.type === "chunk" ? file.code : file.source);
|
|
624
|
-
hash.update("\0");
|
|
625
|
-
}
|
|
626
|
-
return hash.digest("hex").slice(0, 16);
|
|
627
|
-
}
|
|
628
|
-
/** The path of each file under `directory` that is not a dotfile, in code unit order. */
|
|
629
|
-
function filesIn(directory) {
|
|
630
|
-
if (!existsSync(directory)) return [];
|
|
631
|
-
return readdirSync(directory, {
|
|
632
|
-
recursive: true,
|
|
633
|
-
withFileTypes: true
|
|
634
|
-
}).filter((entry) => entry.isFile() && !entry.name.startsWith(".")).map((entry) => relative(directory, join(entry.parentPath, entry.name)).split(sep).join("/")).toSorted();
|
|
635
|
-
}
|
|
636
|
-
/**
|
|
637
|
-
* The ID of the whole build: the {@link bundleBuildId} of the client bundle,
|
|
638
|
-
* with the name and the content of each file that a later build step added to
|
|
639
|
-
* the assets directory. Why: React Router writes its route manifest
|
|
640
|
-
* (`assets/manifest-*.js`) during the server build, and a route change, such
|
|
641
|
-
* as a new path for one module, can keep the client bundle the same.
|
|
642
|
-
*/
|
|
643
|
-
function appBuildId({ bundleId, assetsDirectory, assets }) {
|
|
644
|
-
const added = filesIn(assetsDirectory).filter((file) => !assets.has(file));
|
|
645
|
-
if (added.length === 0) return bundleId;
|
|
646
|
-
const hash = createHash("sha256").update(bundleId);
|
|
647
|
-
for (const file of added) {
|
|
648
|
-
hash.update(`\0${file}\0`);
|
|
649
|
-
hash.update(readFileSync(join(assetsDirectory, file)));
|
|
650
|
-
}
|
|
651
|
-
return hash.digest("hex").slice(0, 16);
|
|
652
|
-
}
|
|
653
|
-
/**
|
|
654
|
-
* The `buildId` and the `assetsPath` of the build manifest that the client
|
|
655
|
-
* build wrote. Why keep them: the prerender pass runs after the client build,
|
|
656
|
-
* which knows them.
|
|
657
|
-
*/
|
|
658
|
-
function clientBuildFields(clientDirectory) {
|
|
659
|
-
const path = join(clientDirectory, BUILD_MANIFEST_FILE);
|
|
660
|
-
const manifest = existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : void 0;
|
|
661
|
-
if (typeof manifest !== "object" || manifest == null) return {};
|
|
662
|
-
return {
|
|
663
|
-
..."buildId" in manifest && typeof manifest.buildId === "string" ? { buildId: manifest.buildId } : {},
|
|
664
|
-
..."assetsPath" in manifest && typeof manifest.assetsPath === "string" ? { assetsPath: manifest.assetsPath } : {}
|
|
665
|
-
};
|
|
666
|
-
}
|
|
667
|
-
/**
|
|
668
|
-
* Records each 2xx path and the headers of each non-document response while
|
|
669
|
-
* the framework's prerender pass runs. It writes them to `.app-server.json` in
|
|
670
|
-
* the client build when the preview server closes, with the script hashes of
|
|
671
|
-
* each HTML file.
|
|
672
|
-
*/
|
|
673
|
-
function capture(server, afterPass) {
|
|
674
|
-
const clientDirectory = outDir(server.config, "client");
|
|
675
|
-
const started = Date.now();
|
|
676
|
-
const paths = /* @__PURE__ */ new Set();
|
|
677
|
-
const headers = {};
|
|
678
|
-
server.middlewares.use((request, response, next) => {
|
|
679
|
-
const pathname = getPath(new Request(new URL(request.url ?? "/", "http://localhost")));
|
|
680
|
-
response.setHeader(CAPTURE_MARKER, "1");
|
|
681
|
-
response.once("finish", () => {
|
|
682
|
-
if (response.statusCode < 200 || response.statusCode >= 300) return;
|
|
683
|
-
const key = manifestKey(pathname);
|
|
684
|
-
paths.add(key);
|
|
685
|
-
if (String(response.getHeader("content-type") ?? "").startsWith("text/html")) return;
|
|
686
|
-
const recorded = {};
|
|
687
|
-
for (const [name, value] of Object.entries(response.getHeaders())) if (!UNCAPTURED_HEADERS.has(name) && !/^\d+$/u.test(name) && value != null) recorded[name] = Array.isArray(value) ? value.join(", ") : String(value);
|
|
688
|
-
headers[key] = recorded;
|
|
689
|
-
});
|
|
690
|
-
next();
|
|
691
|
-
});
|
|
692
|
-
server.httpServer.once("close", () => {
|
|
693
|
-
writeBuildManifest(clientDirectory, {
|
|
694
|
-
...clientBuildFields(clientDirectory),
|
|
695
|
-
prerendered: [...paths].toSorted(),
|
|
696
|
-
headers: Object.fromEntries(Object.entries(headers).toSorted(([first], [second]) => first.localeCompare(second))),
|
|
697
|
-
scriptHashes: scriptHashesOf(clientDirectory)
|
|
698
|
-
});
|
|
699
|
-
writeAllCopies(clientDirectory, { changedSince: started - 2e3 });
|
|
700
|
-
afterPass();
|
|
701
|
-
});
|
|
702
|
-
}
|
|
703
|
-
/**
|
|
704
|
-
* The brotli quality of the copies. Why 9, not the highest (11): on a docs
|
|
705
|
-
* build with 70 MB of text, 11 adds 46 s to the build and 9 adds 0.6 s. The
|
|
706
|
-
* copies of 9 are 9% larger, and still 25% smaller than the gzip copies.
|
|
707
|
-
*/
|
|
708
|
-
const BROTLI_QUALITY = 9;
|
|
709
|
-
/**
|
|
710
|
-
* Writes the compressed copies (`.<file>.gz` and `.<file>.br`) of the file at
|
|
711
|
-
* `path` when the server compresses the file: a compressible type of 1 KiB
|
|
712
|
-
* or more. It writes a copy only when it is smaller: the gzip copy than the
|
|
713
|
-
* file, and the brotli copy than the gzip copy. Else it removes an old copy,
|
|
714
|
-
* so a copy from an earlier build never replaces a changed file.
|
|
715
|
-
*/
|
|
716
|
-
function writeCopies(path) {
|
|
717
|
-
const bytes = isCompressible(contentType(path, {})) && statSync(path, { throwIfNoEntry: false })?.isFile() === true ? readFileSync(path) : void 0;
|
|
718
|
-
const gzip = bytes == null || bytes.byteLength < 1024 ? void 0 : gzipSync(bytes, { level: constants$1.Z_BEST_COMPRESSION });
|
|
719
|
-
const gzipCopy = gzip != null && bytes != null && gzip.byteLength < bytes.byteLength ? gzip : void 0;
|
|
720
|
-
const brotli = gzipCopy == null || bytes == null ? void 0 : brotliCompressSync(bytes, { params: {
|
|
721
|
-
[constants$1.BROTLI_PARAM_MODE]: constants$1.BROTLI_MODE_TEXT,
|
|
722
|
-
[constants$1.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY,
|
|
723
|
-
[constants$1.BROTLI_PARAM_SIZE_HINT]: bytes.byteLength
|
|
724
|
-
} });
|
|
725
|
-
const brotliCopy = brotli != null && gzipCopy != null && brotli.byteLength < gzipCopy.byteLength ? brotli : void 0;
|
|
726
|
-
const copies = [["gzip", gzipCopy], ["br", brotliCopy]];
|
|
727
|
-
for (const [encoding, copy] of copies) {
|
|
728
|
-
const copyPath = join(dirname(path), copyName(basename(path), encoding));
|
|
729
|
-
if (copy == null) rmSync(copyPath, { force: true });
|
|
730
|
-
else writeFileSync(copyPath, copy);
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
/**
|
|
734
|
-
* Runs {@link writeCopies} for each file in the client build, except dotfiles
|
|
735
|
-
* such as the copies, and except a link or a file in a linked directory. With `changedSince`, only for a file that changed at or
|
|
736
|
-
* after that time, in milliseconds since the epoch.
|
|
737
|
-
*/
|
|
738
|
-
function writeAllCopies(clientDirectory, { changedSince } = {}) {
|
|
739
|
-
if (!existsSync(clientDirectory)) return;
|
|
740
|
-
for (const path of filesInside(clientDirectory)) if (!basename(path).startsWith(".") && (changedSince == null || (statSync(path, { throwIfNoEntry: false })?.mtimeMs ?? 0) >= changedSince)) writeCopies(path);
|
|
741
|
-
}
|
|
742
|
-
/**
|
|
743
|
-
* The path of each file under `directory`. Why not through a link: a copy goes
|
|
744
|
-
* next to its file, so a file in a linked directory would get its copies in
|
|
745
|
-
* the link's target, outside the client build.
|
|
746
|
-
*/
|
|
747
|
-
function filesInside(directory) {
|
|
748
|
-
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
|
|
749
|
-
const path = join(directory, entry.name);
|
|
750
|
-
if (entry.isDirectory()) return filesInside(path);
|
|
751
|
-
return entry.isFile() ? [path] : [];
|
|
752
|
-
});
|
|
753
|
-
}
|
|
754
|
-
/**
|
|
755
|
-
* The Vite plugin for `@ngrok/app-server`. Put it next to the framework's
|
|
756
|
-
* plugin.
|
|
757
|
-
*
|
|
758
|
-
* - It adds the server entry to the server build, such as
|
|
759
|
-
* `build/server/app-server.js` on the node host. The entry bundles the app
|
|
760
|
-
* (the default export of `app`) with the framework's server module, so the
|
|
761
|
-
* server gets the app's path aliases and its one copy of the framework.
|
|
762
|
-
* The framework's own entry does not change. When a runtime runs the entry
|
|
763
|
-
* as its main module, the entry starts the server.
|
|
764
|
-
* - In a build, it bundles each dependency into the server build. It copies
|
|
765
|
-
* each package that stays external into `node_modules` in the server build.
|
|
766
|
-
* So the build directory runs with no install.
|
|
767
|
-
* - After the client build, it writes `.app-server.json` in the client
|
|
768
|
-
* build with the build ID: a hash of the client bundle. After the build,
|
|
769
|
-
* it adds the files that the server build wrote to the client's assets
|
|
770
|
-
* directory, such as React Router's route manifest. The `buildId` plugin
|
|
771
|
-
* sends the ID.
|
|
772
|
-
* - During the framework's prerender pass, it records each prerendered path
|
|
773
|
-
* and the headers of each prerendered file that is not an HTML document into
|
|
774
|
-
* `.app-server.json` in the client build. The `prerendered` plugin replays
|
|
775
|
-
* the headers. A document's headers depend on its request, so they are not
|
|
776
|
-
* recorded.
|
|
777
|
-
* - After the build and after the prerender pass, it records the hash of each
|
|
778
|
-
* inline script of each HTML file in `.app-server.json`, for the
|
|
779
|
-
* `contentSecurityPolicy` plugin. It also writes a gzip copy (`.<file>.gz`)
|
|
780
|
-
* and a brotli copy (`.<file>.br`) next to each text file of 1 KiB or more
|
|
781
|
-
* in the client build, HTML included. The static stages send a copy, so the
|
|
782
|
-
* server does not compress these files for each request.
|
|
783
|
-
*
|
|
784
|
-
* @example
|
|
785
|
-
* // vite.config.ts
|
|
786
|
-
* export default defineConfig({ plugins: [reactRouter(), appServer()] });
|
|
787
|
-
*/
|
|
788
|
-
function appServer(options = {}) {
|
|
789
|
-
const host = options.host ?? node();
|
|
790
|
-
let resolved;
|
|
791
|
-
let clientBuild;
|
|
792
|
-
return [
|
|
793
|
-
{
|
|
794
|
-
name: "@ngrok/app-server",
|
|
795
|
-
configResolved: (config) => {
|
|
796
|
-
const framework = options.framework ?? detectFramework(config.plugins);
|
|
797
|
-
framework.validate?.(config);
|
|
798
|
-
resolved = {
|
|
799
|
-
config,
|
|
800
|
-
framework,
|
|
801
|
-
appModule: options.app == null ? defaultApp(config.root) : resolve(config.root, options.app)
|
|
802
|
-
};
|
|
803
|
-
},
|
|
804
|
-
buildStart() {
|
|
805
|
-
if (isServerBuild(this.environment)) this.emitFile({
|
|
806
|
-
type: "chunk",
|
|
807
|
-
id: SERVER_ENTRY_ID,
|
|
808
|
-
fileName: host.entryFileName
|
|
809
|
-
});
|
|
810
|
-
},
|
|
811
|
-
writeBundle(output, bundle) {
|
|
812
|
-
if (this.environment.name === "client") {
|
|
813
|
-
const directory = output.dir ?? outDir(this.environment.config, "client");
|
|
814
|
-
const assetsDirectory = join(directory, this.environment.config.build.assetsDir);
|
|
815
|
-
clientBuild = {
|
|
816
|
-
bundleId: bundleBuildId(bundle),
|
|
817
|
-
assetsDirectory,
|
|
818
|
-
assets: new Set(filesIn(assetsDirectory))
|
|
819
|
-
};
|
|
820
|
-
writeBuildManifest(directory, {
|
|
821
|
-
buildId: clientBuild.bundleId,
|
|
822
|
-
assetsPath: urlPathOfAssetsDir(this.environment.config.build.assetsDir),
|
|
823
|
-
prerendered: [],
|
|
824
|
-
headers: {},
|
|
825
|
-
scriptHashes: {}
|
|
826
|
-
});
|
|
827
|
-
}
|
|
828
|
-
},
|
|
829
|
-
renderStart(output) {
|
|
830
|
-
if (this.environment.name === SERVER_ENVIRONMENT && output.format !== "es") throw new Error(`@ngrok/app-server needs an ES module server build, and this build has the format "${output.format}".`);
|
|
831
|
-
},
|
|
832
|
-
resolveId: (id) => id === "virtual:@ngrok/app-server/entry" ? RESOLVED_SERVER_ENTRY_ID : void 0,
|
|
833
|
-
load(id) {
|
|
834
|
-
if (id !== RESOLVED_SERVER_ENTRY_ID || resolved == null) return null;
|
|
835
|
-
const { config, framework, appModule } = resolved;
|
|
836
|
-
const clientDirectory = outDir(config, "client");
|
|
837
|
-
const serverDirectory = outDir(config, SERVER_ENVIRONMENT);
|
|
838
|
-
const fromClient = relative(clientDirectory, serverDirectory);
|
|
839
|
-
if (this.environment.mode === "build" && !fromClient.startsWith("..") && !isAbsolute(fromClient)) throw new Error(`@ngrok/app-server needs the server build outside the client build, and both are in ${clientDirectory}.`);
|
|
840
|
-
const fromEntry = relative(dirname(join(serverDirectory, host.entryFileName)), clientDirectory).replaceAll("\\", "/");
|
|
841
|
-
return serverEntrySource({
|
|
842
|
-
framework,
|
|
843
|
-
host,
|
|
844
|
-
appModule,
|
|
845
|
-
clientDirectory: this.environment.mode === "build" ? `new URL(${JSON.stringify(`${fromEntry}/`)}, import.meta.url).href` : JSON.stringify(clientDirectory)
|
|
846
|
-
});
|
|
847
|
-
},
|
|
848
|
-
configurePreviewServer: (server) => {
|
|
849
|
-
if (resolved?.framework.isPrerenderPass(server) === true) capture(server, () => host.output?.(hostOutput(server.config, host)));
|
|
850
|
-
}
|
|
851
|
-
},
|
|
852
|
-
{
|
|
853
|
-
name: "@ngrok/app-server:compressed-copies",
|
|
854
|
-
enforce: "post",
|
|
855
|
-
buildApp: {
|
|
856
|
-
order: "post",
|
|
857
|
-
handler: async (builder) => {
|
|
858
|
-
const clientDirectory = outDir(builder.config, "client");
|
|
859
|
-
completeBuildManifest(clientDirectory, clientBuild == null ? void 0 : appBuildId(clientBuild));
|
|
860
|
-
writeAllCopies(clientDirectory);
|
|
861
|
-
host.output?.(hostOutput(builder.config, host));
|
|
862
|
-
}
|
|
863
|
-
}
|
|
864
|
-
},
|
|
865
|
-
standalone(options.externals)
|
|
866
|
-
];
|
|
867
|
-
}
|
|
868
|
-
|
|
869
|
-
export { appServer as n, serverEntrySource as r, SERVER_ENTRY_ID as t };
|
|
870
|
-
//# sourceMappingURL=vite-DPiSKHDn.js.map
|