@ngrok/app-server 0.3.1 → 0.3.3
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 +83 -27
- package/dist/{build-id-C6sYO9Yp.js → build-id-B0448vZH.js} +27 -2
- package/dist/build-id-B0448vZH.js.map +1 -0
- package/dist/{build-manifest-UDNk81Ce.js → build-manifest-DBMWe3Lx.js} +12 -2
- package/dist/build-manifest-DBMWe3Lx.js.map +1 -0
- package/dist/cli.js +2 -2
- package/dist/client-browser.js +1 -1
- package/dist/client.js +1 -1
- package/dist/{entry-CM6Ma-Tv.d.ts → create-server-D4-nVOVJ.d.ts} +56 -70
- package/dist/{create-server-DkTeIJ8L.js → create-server-jMl2ltHD.js} +454 -394
- package/dist/create-server-jMl2ltHD.js.map +1 -0
- package/dist/entry-BPrgE_6K.d.ts +94 -0
- package/dist/entry-D9H4LA9c.js +351 -0
- package/dist/entry-D9H4LA9c.js.map +1 -0
- package/dist/{index-Bo5G9LuQ.d.ts → index-Db7dspq6.d.ts} +6 -1
- package/dist/index.d.ts +5 -14
- package/dist/index.js +3 -3
- package/dist/{load-entry-CmkdlmDX.js → load-entry-D7r0mjEp.js} +4 -4
- package/dist/{load-entry-CmkdlmDX.js.map → load-entry-D7r0mjEp.js.map} +1 -1
- package/dist/{node-BFH82eeL.js → node-C1qudLs_.js} +2 -2
- package/dist/{node-BFH82eeL.js.map → node-C1qudLs_.js.map} +1 -1
- package/dist/node-vite.d.ts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +1 -1
- package/dist/react-router-vite.d.ts +1 -1
- package/dist/react-router.d.ts +3 -2
- package/dist/react-router.js +31 -2
- package/dist/react-router.js.map +1 -1
- package/dist/request-context-BtQ87VYb.js.map +1 -1
- package/dist/{script-hashes-hqUk6kG7.js → script-hashes-C6hQ5XnP.js} +22 -4
- package/dist/script-hashes-C6hQ5XnP.js.map +1 -0
- package/dist/{serve-Cc-ADdhZ.js → serve-E0hSGe6_.js} +2 -2
- package/dist/{serve-Cc-ADdhZ.js.map → serve-E0hSGe6_.js.map} +1 -1
- package/dist/{stale-build-navigation-PnMLtTF8.js → stale-build-navigation-rg5xxmTr.js} +2 -2
- package/dist/{stale-build-navigation-PnMLtTF8.js.map → stale-build-navigation-rg5xxmTr.js.map} +1 -1
- package/dist/{start-Cb3kknlF.js → start-CifYPRq1.js} +34 -6
- package/dist/start-CifYPRq1.js.map +1 -0
- package/dist/tanstack-start-vite.d.ts +1 -1
- package/dist/tanstack-start.d.ts +2 -2
- package/dist/testing.d.ts +56 -0
- package/dist/testing.js +114 -0
- package/dist/testing.js.map +1 -0
- package/dist/{trailing-slash-DX7NB88H.d.ts → trailing-slash-CFSv_Gzx.d.ts} +2 -2
- package/dist/{types-DLYxYS6M.d.ts → types-j29vspx_.d.ts} +16 -2
- package/dist/vercel-pages.d.ts +32 -0
- package/dist/vercel-pages.js +54 -0
- package/dist/vercel-pages.js.map +1 -0
- package/dist/vercel-vite.d.ts +30 -9
- package/dist/vercel-vite.js +160 -17
- package/dist/vercel-vite.js.map +1 -1
- package/dist/vercel.d.ts +2 -2
- package/dist/vercel.js +2 -2
- package/dist/{vite-iioAoxSt.js → vite-BDREIgiH.js} +45 -33
- package/dist/vite-BDREIgiH.js.map +1 -0
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +1 -1
- package/package.json +5 -1
- package/dist/build-id-C6sYO9Yp.js.map +0 -1
- package/dist/build-manifest-UDNk81Ce.js.map +0 -1
- package/dist/create-server-DkTeIJ8L.js.map +0 -1
- package/dist/entry-CenmvESk.js +0 -116
- package/dist/entry-CenmvESk.js.map +0 -1
- package/dist/script-hashes-hqUk6kG7.js.map +0 -1
- package/dist/start-Cb3kknlF.js.map +0 -1
- package/dist/vite-iioAoxSt.js.map +0 -1
package/dist/vercel-vite.js
CHANGED
|
@@ -1,17 +1,33 @@
|
|
|
1
1
|
import { r as hasDotSegment } from "./static-files-Beju9riB.js";
|
|
2
|
-
import { copyFileSync, cpSync, mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { copyFileSync, cpSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { execFileSync } from "node:child_process";
|
|
4
6
|
|
|
5
7
|
// src/vercel/vite.ts
|
|
6
|
-
/** The hashed files of the client build. Their names change with their content. */
|
|
7
|
-
const ASSETS = "/assets/";
|
|
8
8
|
const IMMUTABLE = "public, max-age=31536000, immutable";
|
|
9
|
+
/** The most routes of a deployment. See https://vercel.com/docs/limits. */
|
|
10
|
+
const ROUTE_LIMIT = 2048;
|
|
11
|
+
/**
|
|
12
|
+
* The URL path under `static/` of the bodies of the pages that the CDN
|
|
13
|
+
* serves. A route sends a request for it to the function, so a page has one
|
|
14
|
+
* URL.
|
|
15
|
+
*/
|
|
16
|
+
const PAGES = "/_app-server/pages";
|
|
17
|
+
/**
|
|
18
|
+
* The script that finds the pages that the CDN serves. Why the source in a
|
|
19
|
+
* `.ts` module: the tests of this package run the source, and Node.js runs a
|
|
20
|
+
* `.ts` file with no import of its own.
|
|
21
|
+
*/
|
|
22
|
+
const PAGES_SCRIPT = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./pages.ts" : "./vercel-pages.js", import.meta.url));
|
|
23
|
+
/** A case-insensitive pattern for `text/markdown`, in the regular expression syntax of any engine. */
|
|
24
|
+
const MARKDOWN = "text/markdown".replaceAll(/[a-z]/gu, (letter) => `[${letter}${letter.toUpperCase()}]`);
|
|
9
25
|
/** The variable that gives the function the time of the build, in milliseconds. */
|
|
10
26
|
const BUILT_AT = "APP_SERVER_BUILT_AT";
|
|
11
27
|
/** The function's file, next to the server entry. */
|
|
12
28
|
const FUNCTION_FILE = "vercel-function.js";
|
|
13
29
|
/** A path with `/` separators, as Vercel's config reads it. */
|
|
14
|
-
function posix(path) {
|
|
30
|
+
function posix$1(path) {
|
|
15
31
|
return path.split(sep).join("/");
|
|
16
32
|
}
|
|
17
33
|
/** A regular expression source that matches `text` as it is. */
|
|
@@ -40,11 +56,17 @@ function filesUnder(directory, under = "", parents = /* @__PURE__ */ new Set())
|
|
|
40
56
|
}
|
|
41
57
|
/**
|
|
42
58
|
* The `.vercel/output` routes: a CDN file gets its headers, and each other
|
|
43
|
-
* request goes to the function.
|
|
44
|
-
*
|
|
59
|
+
* request goes to the function. A file under `assetsPath` also gets the
|
|
60
|
+
* immutable cache. Why the `hit` phase: a CDN path with no file goes to the
|
|
61
|
+
* function, whose `no-store` 404 must not get the immutable cache.
|
|
45
62
|
*/
|
|
46
|
-
function routes(prefixes, cdnHeaders) {
|
|
63
|
+
function routes(prefixes, { assetsPath, cdnHeaders, pages }) {
|
|
47
64
|
return [
|
|
65
|
+
...pages.length === 0 ? [] : [{
|
|
66
|
+
src: `^${escaped(PAGES)}(?:/.*)?$`,
|
|
67
|
+
dest: "/index"
|
|
68
|
+
}],
|
|
69
|
+
...pages.flatMap((page) => pageRoutes(page)),
|
|
48
70
|
{ handle: "filesystem" },
|
|
49
71
|
{
|
|
50
72
|
src: "^/(.*)$",
|
|
@@ -53,7 +75,7 @@ function routes(prefixes, cdnHeaders) {
|
|
|
53
75
|
{ handle: "hit" },
|
|
54
76
|
...prefixes.map((prefix) => ({
|
|
55
77
|
src: `^${escaped(prefix)}.*$`,
|
|
56
|
-
headers: prefix ===
|
|
78
|
+
headers: prefix === assetsPath ? {
|
|
57
79
|
...cdnHeaders,
|
|
58
80
|
"Cache-Control": IMMUTABLE
|
|
59
81
|
} : cdnHeaders,
|
|
@@ -61,25 +83,141 @@ function routes(prefixes, cdnHeaders) {
|
|
|
61
83
|
}))
|
|
62
84
|
];
|
|
63
85
|
}
|
|
86
|
+
/**
|
|
87
|
+
* The routes of one page that the CDN serves: one for each case of the
|
|
88
|
+
* presence headers, with the headers of that case. Why only GET and HEAD: the
|
|
89
|
+
* function answers the other methods, such as a form's POST. Why the
|
|
90
|
+
* function for a request that names `text/markdown`: it negotiates the twin.
|
|
91
|
+
*/
|
|
92
|
+
function pageRoutes({ path, file, answers, twin }) {
|
|
93
|
+
const src = `^${escaped(path)}$`;
|
|
94
|
+
const names = [...new Set(answers.flatMap(({ present }) => present))];
|
|
95
|
+
return [...twin == null ? [] : [{
|
|
96
|
+
src,
|
|
97
|
+
has: [{
|
|
98
|
+
type: "header",
|
|
99
|
+
key: "accept",
|
|
100
|
+
value: { re: MARKDOWN }
|
|
101
|
+
}],
|
|
102
|
+
dest: "/index"
|
|
103
|
+
}], ...answers.map(({ present, headers }) => {
|
|
104
|
+
const missing = names.filter((name) => !present.includes(name));
|
|
105
|
+
return {
|
|
106
|
+
src,
|
|
107
|
+
caseSensitive: true,
|
|
108
|
+
methods: ["GET", "HEAD"],
|
|
109
|
+
...present.length === 0 ? {} : { has: present.map((key) => ({
|
|
110
|
+
type: "header",
|
|
111
|
+
key
|
|
112
|
+
})) },
|
|
113
|
+
...missing.length === 0 ? {} : { missing: missing.map((key) => ({
|
|
114
|
+
type: "header",
|
|
115
|
+
key
|
|
116
|
+
})) },
|
|
117
|
+
headers,
|
|
118
|
+
dest: `${PAGES}${file}`
|
|
119
|
+
};
|
|
120
|
+
})];
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Whether `cdnPages` accepts `path`. Why both trailing-slash forms: with
|
|
124
|
+
* `trailingSlash: "always"`, the CDN serves `/blog/` for the prerendered
|
|
125
|
+
* path `/blog`.
|
|
126
|
+
*/
|
|
127
|
+
function accepts(cdnPages, path) {
|
|
128
|
+
return cdnPages(path) && (path === "/" || !path.endsWith("/") || cdnPages(path.slice(0, -1)));
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Finds the pages that the CDN serves ({@link VercelOptions.cdnPages}), and
|
|
132
|
+
* writes their bodies under `static/`.
|
|
133
|
+
*/
|
|
134
|
+
function findCdnPages(entryFile, output, { cdnPages, routeBudget }) {
|
|
135
|
+
if (cdnPages === false) return {
|
|
136
|
+
cdn: [],
|
|
137
|
+
server: []
|
|
138
|
+
};
|
|
139
|
+
const pagesDirectory = join(output, "static", PAGES);
|
|
140
|
+
const reportFile = join(output, "pages.json");
|
|
141
|
+
try {
|
|
142
|
+
execFileSync(process.execPath, [
|
|
143
|
+
PAGES_SCRIPT,
|
|
144
|
+
entryFile,
|
|
145
|
+
pagesDirectory,
|
|
146
|
+
reportFile
|
|
147
|
+
], {
|
|
148
|
+
stdio: "inherit",
|
|
149
|
+
env: {
|
|
150
|
+
...process.env,
|
|
151
|
+
NODE_ENV: "production"
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
} catch (error) {
|
|
155
|
+
throw new Error("@ngrok/app-server/vercel could not start the server build to find the prerendered pages that the CDN can serve. Give the build the environment of the app, or remove `cdnPages`.", { cause: error });
|
|
156
|
+
}
|
|
157
|
+
const report = JSON.parse(readFileSync(reportFile, "utf8"));
|
|
158
|
+
rmSync(reportFile);
|
|
159
|
+
const pages = {
|
|
160
|
+
cdn: [],
|
|
161
|
+
server: [...report.server]
|
|
162
|
+
};
|
|
163
|
+
let routeCount = 0;
|
|
164
|
+
for (const page of report.cdn) {
|
|
165
|
+
const count = pageRoutes(page).length;
|
|
166
|
+
let reason;
|
|
167
|
+
if (cdnPages !== true && !accepts(cdnPages, page.path)) reason = "`cdnPages` keeps it in the function";
|
|
168
|
+
else if (page.answers.some(({ headers }) => Object.values(headers).some((value) => value.includes("$")))) reason = "a header has a `$`, which a Vercel route reads as a capture";
|
|
169
|
+
else if (routeCount + count > routeBudget) reason = `the CDN routes of the pages reach Vercel's limit of ${ROUTE_LIMIT} routes`;
|
|
170
|
+
if (reason == null) {
|
|
171
|
+
pages.cdn.push(page);
|
|
172
|
+
routeCount += count;
|
|
173
|
+
} else {
|
|
174
|
+
rmSync(join(pagesDirectory, page.file));
|
|
175
|
+
pages.server.push({
|
|
176
|
+
path: page.path,
|
|
177
|
+
reason
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return pages;
|
|
182
|
+
}
|
|
183
|
+
/** Writes the paths that the function serves, and why, so the build log shows them. */
|
|
184
|
+
function reportPages({ cdn, server }) {
|
|
185
|
+
const shown = server.slice(0, 20);
|
|
186
|
+
process.stdout.write([
|
|
187
|
+
`@ngrok/app-server/vercel: the CDN serves ${cdn.length} prerendered paths, and the function serves ${server.length}.`,
|
|
188
|
+
...shown.map(({ path, reason }) => ` ${path}: ${reason}`),
|
|
189
|
+
...server.length > shown.length ? [` and ${server.length - shown.length} more`] : [],
|
|
190
|
+
""
|
|
191
|
+
].join("\n"));
|
|
192
|
+
}
|
|
64
193
|
/** Writes `.vercel/output` (the Build Output API, version 3) for one build. */
|
|
65
|
-
function writeOutput({ root, clientDirectory, entryFile }, { cdnPaths = [], cdnHeaders = {}, regions, memory, maxDuration }) {
|
|
66
|
-
const prefixes = [
|
|
194
|
+
function writeOutput({ root, clientDirectory, entryFile, assetsPath }, { cdnPaths = [], cdnHeaders = {}, cdnPages = false, regions, memory, maxDuration }) {
|
|
195
|
+
const prefixes = [...cdnPaths.filter((path) => path !== assetsPath), assetsPath];
|
|
67
196
|
const output = join(root, ".vercel/output");
|
|
68
197
|
rmSync(output, {
|
|
69
198
|
recursive: true,
|
|
70
199
|
force: true
|
|
71
200
|
});
|
|
201
|
+
const pages = findCdnPages(entryFile, output, {
|
|
202
|
+
cdnPages,
|
|
203
|
+
routeBudget: ROUTE_LIMIT - routes(prefixes, {
|
|
204
|
+
assetsPath,
|
|
205
|
+
cdnHeaders,
|
|
206
|
+
pages: []
|
|
207
|
+
}).length - 1
|
|
208
|
+
});
|
|
209
|
+
if (cdnPages !== false) reportPages(pages);
|
|
72
210
|
const fromRoot = (path) => {
|
|
73
211
|
const inside = relative(root, path);
|
|
74
212
|
if (inside.startsWith("..") || isAbsolute(inside)) throw new Error(`@ngrok/app-server/vercel needs ${path} inside the Vite root ${root}.`);
|
|
75
213
|
return inside;
|
|
76
214
|
};
|
|
77
215
|
const functionDirectory = join(output, "functions/index.func");
|
|
78
|
-
const isCdnFile = (file) => prefixes.some((prefix) => `/${posix(file)}`.startsWith(prefix));
|
|
216
|
+
const isCdnFile = (file) => prefixes.some((prefix) => `/${posix$1(file)}`.startsWith(prefix));
|
|
79
217
|
for (const file of filesUnder(clientDirectory)) {
|
|
80
218
|
const from = join(clientDirectory, file);
|
|
81
219
|
if (!isCdnFile(file)) copyFile(from, join(functionDirectory, fromRoot(from)));
|
|
82
|
-
else if (!hasDotSegment(`/${posix(file)}`)) copyFile(from, join(output, "static", file));
|
|
220
|
+
else if (!hasDotSegment(`/${posix$1(file)}`)) copyFile(from, join(output, "static", file));
|
|
83
221
|
}
|
|
84
222
|
const serverDirectory = dirname(entryFile);
|
|
85
223
|
const functionFile = join(serverDirectory, FUNCTION_FILE);
|
|
@@ -95,7 +233,7 @@ function writeOutput({ root, clientDirectory, entryFile }, { cdnPaths = [], cdnH
|
|
|
95
233
|
].join("\n"));
|
|
96
234
|
writeFileSync(join(functionDirectory, ".vc-config.json"), `${JSON.stringify({
|
|
97
235
|
runtime: `nodejs${process.versions.node.split(".")[0]}.x`,
|
|
98
|
-
handler: posix(fromRoot(functionFile)),
|
|
236
|
+
handler: posix$1(fromRoot(functionFile)),
|
|
99
237
|
launcherType: "Nodejs",
|
|
100
238
|
supportsResponseStreaming: true,
|
|
101
239
|
environment: { [BUILT_AT]: String(Date.now()) },
|
|
@@ -105,7 +243,11 @@ function writeOutput({ root, clientDirectory, entryFile }, { cdnPaths = [], cdnH
|
|
|
105
243
|
}, null, " ")}\n`);
|
|
106
244
|
writeFileSync(join(output, "config.json"), `${JSON.stringify({
|
|
107
245
|
version: 3,
|
|
108
|
-
routes: routes(prefixes,
|
|
246
|
+
routes: routes(prefixes, {
|
|
247
|
+
assetsPath,
|
|
248
|
+
cdnHeaders,
|
|
249
|
+
pages: pages.cdn
|
|
250
|
+
})
|
|
109
251
|
}, null, " ")}\n`);
|
|
110
252
|
}
|
|
111
253
|
/** Throws for a CDN path that is not a URL path prefix, so the config fails, not the deploy. */
|
|
@@ -116,9 +258,10 @@ function checkCdnPaths(paths) {
|
|
|
116
258
|
* The build side of the vercel host. After the build, it writes
|
|
117
259
|
* `.vercel/output` in the Vite root, for `vercel deploy --prebuilt`:
|
|
118
260
|
*
|
|
119
|
-
* - `static/`: the files
|
|
120
|
-
* serves them, and each file
|
|
121
|
-
* cache.
|
|
261
|
+
* - `static/`: the files of Vite's `build.assetsDir` (`/assets/` by default)
|
|
262
|
+
* and the other `cdnPaths`. The CDN serves them, and each file of
|
|
263
|
+
* `build.assetsDir` gets a one-year immutable cache. It also holds the
|
|
264
|
+
* prerendered pages that the CDN serves, with `cdnPages`.
|
|
122
265
|
* - `functions/index.func/`: one Node.js function that runs the pipeline for
|
|
123
266
|
* each other request, with the whole server build and the rest of the
|
|
124
267
|
* client build.
|
package/dist/vercel-vite.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vercel-vite.js","names":[],"sources":["../src/vercel/vite.ts"],"sourcesContent":["import {\n\tcopyFileSync,\n\tcpSync,\n\tmkdirSync,\n\treaddirSync,\n\trmSync,\n\tstatSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { basename, dirname, isAbsolute, join, relative, sep } from \"node:path\";\nimport { hasDotSegment } from \"../core/static-files.js\";\nimport type { HostBuild, HostOutput } from \"../vite/index.js\";\n\n/** Options for {@link vercel}. */\nexport type VercelOptions = {\n\t/**\n\t * More URL path prefixes of the client build that Vercel's CDN serves,\n\t * such as `[\"/blog-assets/\"]`. Each starts and ends with `/`. `/assets/`\n\t * is always one. Their files skip the pipeline, and the function does not\n\t * carry them.\n\t */\n\tcdnPaths?: readonly string[];\n\t/** Headers for each file that the CDN serves, such as CORS headers. */\n\tcdnHeaders?: Readonly<Record<string, string>>;\n\t/** The Vercel regions of the function, such as `[\"iad1\"]`. @default the project's */\n\tregions?: readonly string[];\n\t/** The memory of the function, in MB. @default the project's */\n\tmemory?: number;\n\t/** The longest time that a request runs, in seconds. @default the project's */\n\tmaxDuration?: number;\n};\n\n/** The hashed files of the client build. Their names change with their content. */\nconst ASSETS = \"/assets/\";\n\nconst IMMUTABLE = \"public, max-age=31536000, immutable\";\n\n/** The variable that gives the function the time of the build, in milliseconds. */\nconst BUILT_AT = \"APP_SERVER_BUILT_AT\";\n\n/** The function's file, next to the server entry. */\nconst FUNCTION_FILE = \"vercel-function.js\";\n\n/** A path with `/` separators, as Vercel's config reads it. */\nfunction posix(path: string): string {\n\treturn path.split(sep).join(\"/\");\n}\n\n/** A regular expression source that matches `text` as it is. */\nfunction escaped(text: string): string {\n\treturn text.replaceAll(/[$()*+.?[\\\\\\]^{|}]/gu, String.raw`\\$&`);\n}\n\n/** Copies the file at `from` to `to`, and makes the directories of `to`. */\nfunction copyFile(from: string, to: string): void {\n\tmkdirSync(dirname(to), { recursive: true });\n\tcopyFileSync(from, to);\n}\n\n/**\n * The path of each file under `directory`, relative to it. Why follow links:\n * the CDN and the function each get a copy of the linked file, not a link\n * whose target can be in the other part. Why the inodes of the parents: a\n * link to a parent directory must not make the walk endless.\n */\nfunction filesUnder(\n\tdirectory: string,\n\tunder = \"\",\n\tparents: ReadonlySet<string> = new Set(),\n): string[] {\n\tconst stats = statSync(join(directory, under), { throwIfNoEntry: false });\n\tif (stats == null) {\n\t\treturn [];\n\t}\n\tif (!stats.isDirectory()) {\n\t\treturn [under];\n\t}\n\tconst inode = `${stats.dev}:${stats.ino}`;\n\tif (parents.has(inode)) {\n\t\treturn [];\n\t}\n\tconst inside = new Set(parents).add(inode);\n\treturn readdirSync(join(directory, under)).flatMap((name) =>\n\t\tfilesUnder(directory, join(under, name), inside),\n\t);\n}\n\n/**\n * The `.vercel/output` routes: a CDN file gets its headers, and each other\n * request goes to the function. Why the `hit` phase: a CDN path with no file\n * goes to the function, whose `no-store` 404 must not get the immutable cache.\n */\nfunction routes(prefixes: readonly string[], cdnHeaders: Readonly<Record<string, string>>) {\n\treturn [\n\t\t{ handle: \"filesystem\" },\n\t\t{ src: \"^/(.*)$\", dest: \"/index\" },\n\t\t{ handle: \"hit\" },\n\t\t...prefixes.map((prefix) => ({\n\t\t\t// Why `.*$`: Vercel adds `$` to a pattern that has none.\n\t\t\tsrc: `^${escaped(prefix)}.*$`,\n\t\t\theaders: prefix === ASSETS ? { ...cdnHeaders, \"Cache-Control\": IMMUTABLE } : cdnHeaders,\n\t\t\tcontinue: true,\n\t\t})),\n\t];\n}\n\n/** Writes `.vercel/output` (the Build Output API, version 3) for one build. */\nfunction writeOutput(\n\t{ root, clientDirectory, entryFile }: HostOutput,\n\t{ cdnPaths = [], cdnHeaders = {}, regions, memory, maxDuration }: VercelOptions,\n): void {\n\tconst prefixes = [ASSETS, ...cdnPaths.filter((path) => path !== ASSETS)];\n\tconst output = join(root, \".vercel/output\");\n\trmSync(output, { recursive: true, force: true });\n\tconst fromRoot = (path: string): string => {\n\t\tconst inside = relative(root, path);\n\t\tif (inside.startsWith(\"..\") || isAbsolute(inside)) {\n\t\t\tthrow new Error(`@ngrok/app-server/vercel needs ${path} inside the Vite root ${root}.`);\n\t\t}\n\t\treturn inside;\n\t};\n\tconst functionDirectory = join(output, \"functions/index.func\");\n\tconst isCdnFile = (file: string): boolean =>\n\t\tprefixes.some((prefix) => `/${posix(file)}`.startsWith(prefix));\n\n\tfor (const file of filesUnder(clientDirectory)) {\n\t\tconst from = join(clientDirectory, file);\n\t\tif (!isCdnFile(file)) {\n\t\t\tcopyFile(from, join(functionDirectory, fromRoot(from)));\n\t\t} else if (!hasDotSegment(`/${posix(file)}`)) {\n\t\t\t// Why the static stages' check: the CDN sends each file that it has, and the static stages\n\t\t\t// send no dotfile, such as a compressed copy, and no file in a dot directory.\n\t\t\tcopyFile(from, join(output, \"static\", file));\n\t\t}\n\t}\n\n\t// Why the whole server build: it runs with no install, and it keeps the client build's path.\n\tconst serverDirectory = dirname(entryFile);\n\tconst functionFile = join(serverDirectory, FUNCTION_FILE);\n\tcpSync(serverDirectory, join(functionDirectory, fromRoot(serverDirectory)), {\n\t\trecursive: true,\n\t\t// Why: a link that keeps its target can point at the build machine.\n\t\tdereference: true,\n\t\t// Why: the client build can be inside the server build, and the loop above copied its part.\n\t\tfilter: (path) => path !== clientDirectory,\n\t});\n\twriteFileSync(\n\t\tjoin(functionDirectory, fromRoot(functionFile)),\n\t\t[\n\t\t\t`import { appServer, hostModule } from ${JSON.stringify(`./${basename(entryFile)}`)};`,\n\t\t\t`export default hostModule.handler(appServer);`,\n\t\t\t\"\",\n\t\t].join(\"\\n\"),\n\t);\n\twriteFileSync(\n\t\tjoin(functionDirectory, \".vc-config.json\"),\n\t\t`${JSON.stringify(\n\t\t\t{\n\t\t\t\t// Why the build's Node.js: the server build targets the Node.js that built it.\n\t\t\t\truntime: `nodejs${process.versions.node.split(\".\")[0]}.x`,\n\t\t\t\thandler: posix(fromRoot(functionFile)),\n\t\t\t\tlauncherType: \"Nodejs\",\n\t\t\t\tsupportsResponseStreaming: true,\n\t\t\t\t// Why: the deploy gives each file of the function one fixed time, and the ETag of a file\n\t\t\t\t// reads its time. See `host` in `@ngrok/app-server/vercel`.\n\t\t\t\tenvironment: { [BUILT_AT]: String(Date.now()) },\n\t\t\t\t...(regions == null ? {} : { regions }),\n\t\t\t\t...(memory == null ? {} : { memory }),\n\t\t\t\t...(maxDuration == null ? {} : { maxDuration }),\n\t\t\t},\n\t\t\tnull,\n\t\t\t\"\\t\",\n\t\t)}\\n`,\n\t);\n\twriteFileSync(\n\t\tjoin(output, \"config.json\"),\n\t\t`${JSON.stringify({ version: 3, routes: routes(prefixes, cdnHeaders) }, null, \"\\t\")}\\n`,\n\t);\n}\n\n/** Throws for a CDN path that is not a URL path prefix, so the config fails, not the deploy. */\nfunction checkCdnPaths(paths: readonly string[]): void {\n\tfor (const path of paths) {\n\t\tif (!path.startsWith(\"/\") || !path.endsWith(\"/\") || path === \"/\" || path.includes(\"..\")) {\n\t\t\tthrow new Error(\n\t\t\t\t`Each cdnPaths entry is a URL path prefix that starts and ends with \"/\", such as \"/blog-assets/\", not ${JSON.stringify(path)}.`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * The build side of the vercel host. After the build, it writes\n * `.vercel/output` in the Vite root, for `vercel deploy --prebuilt`:\n *\n * - `static/`: the files under `/assets/` and the other `cdnPaths`. The CDN\n * serves them, and each file under `/assets/` gets a one-year immutable\n * cache.\n * - `functions/index.func/`: one Node.js function that runs the pipeline for\n * each other request, with the whole server build and the rest of the\n * client build.\n *\n * @example\n * appServer({ host: vercel() });\n */\nexport function vercel(options: VercelOptions = {}): HostBuild {\n\tcheckCdnPaths(options.cdnPaths ?? []);\n\treturn {\n\t\tname: \"vercel\",\n\t\truntimeModule: \"@ngrok/app-server/vercel\",\n\t\tentryFileName: \"app-server.js\",\n\t\toutput: (build) => {\n\t\t\twriteOutput(build, options);\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;AAiCA,MAAM,SAAS;AAEf,MAAM,YAAY;;AAGlB,MAAM,WAAW;;AAGjB,MAAM,gBAAgB;;AAGtB,SAAS,MAAM,MAAsB;CACpC,OAAO,KAAK,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG;AAChC;;AAGA,SAAS,QAAQ,MAAsB;CACtC,OAAO,KAAK,WAAW,wBAAwB,OAAO,GAAG,KAAK;AAC/D;;AAGA,SAAS,SAAS,MAAc,IAAkB;CACjD,UAAU,QAAQ,EAAE,GAAG,EAAE,WAAW,KAAK,CAAC;CAC1C,aAAa,MAAM,EAAE;AACtB;;;;;;;AAQA,SAAS,WACR,WACA,QAAQ,IACR,0BAA+B,IAAI,IAAI,GAC5B;CACX,MAAM,QAAQ,SAAS,KAAK,WAAW,KAAK,GAAG,EAAE,gBAAgB,MAAM,CAAC;CACxE,IAAI,SAAS,MACZ,OAAO,CAAC;CAET,IAAI,CAAC,MAAM,YAAY,GACtB,OAAO,CAAC,KAAK;CAEd,MAAM,QAAQ,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,KAAK,SAAS,IAAI,GACrF,MAAM,IAAI,MACT,wGAAwG,KAAK,UAAU,IAAI,EAAE,EAC9H;AAGH;;;;;;;;;;;;;;;AAgBA,SAAgB,OAAO,UAAyB,CAAC,GAAc;CAC9D,cAAc,QAAQ,YAAY,CAAC,CAAC;CACpC,OAAO;EACN,MAAM;EACN,eAAe;EACf,eAAe;EACf,SAAS,UAAU;GAClB,YAAY,OAAO,OAAO;EAC3B;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"vercel-vite.js","names":["posix"],"sources":["../src/vercel/vite.ts"],"sourcesContent":["import { execFileSync } from \"node:child_process\";\nimport {\n\tcopyFileSync,\n\tcpSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trmSync,\n\tstatSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { basename, dirname, isAbsolute, join, relative, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { hasDotSegment } from \"../core/static-files.js\";\nimport type { HostBuild, HostOutput } from \"../vite/index.js\";\nimport type { CdnPageReport, PagesReport } from \"./pages.js\";\n\n/** Options for {@link vercel}. */\nexport type VercelOptions = {\n\t/**\n\t * More URL path prefixes of the client build that Vercel's CDN serves,\n\t * such as `[\"/blog-assets/\"]`. Each starts and ends with `/`. The URL path\n\t * of Vite's `build.assetsDir`, `/assets/` by default, is always one. Their\n\t * files skip the pipeline, and the function does not carry them.\n\t */\n\tcdnPaths?: readonly string[];\n\t/** Headers for each file under `cdnPaths` and Vite's `build.assetsDir`, such as CORS headers. */\n\tcdnHeaders?: Readonly<Record<string, string>>;\n\t/**\n\t * Which prerendered pages the CDN serves, with no function. With `true`,\n\t * `vercel()` starts the server build once after the build and sends each\n\t * prerendered path through the pipeline as an anonymous client. The CDN\n\t * serves a page when its answer is a public 200 from its file, and the\n\t * same for a second client with another host, address, query, cookie,\n\t * `Authorization`, language, and country. The CDN then sends the\n\t * pipeline's body and headers. The function serves each other page, and\n\t * the CDN never keeps its answer. A function keeps each path that it\n\t * refuses in either trailing-slash form in the function, such as a page\n\t * whose answer depends on one query key. Why off by default: the build\n\t * runs each plugin's `setup`, and a check that the build cannot see can\n\t * then reach the CDN.\n\t * @default false\n\t */\n\tcdnPages?: boolean | ((path: string) => boolean);\n\t/** The Vercel regions of the function, such as `[\"iad1\"]`. @default the project's */\n\tregions?: readonly string[];\n\t/** The memory of the function, in MB. @default the project's */\n\tmemory?: number;\n\t/**\n\t * The longest time that a request runs, in seconds. It applies to each\n\t * request, because one function serves each route. A route module's\n\t * `config` export does nothing. @default the project's\n\t */\n\tmaxDuration?: number;\n};\n\nconst IMMUTABLE = \"public, max-age=31536000, immutable\";\n\n/** The most routes of a deployment. See https://vercel.com/docs/limits. */\nconst ROUTE_LIMIT = 2048;\n\n/**\n * The URL path under `static/` of the bodies of the pages that the CDN\n * serves. A route sends a request for it to the function, so a page has one\n * URL.\n */\nconst PAGES = \"/_app-server/pages\";\n\n/**\n * The script that finds the pages that the CDN serves. Why the source in a\n * `.ts` module: the tests of this package run the source, and Node.js runs a\n * `.ts` file with no import of its own.\n */\nconst PAGES_SCRIPT = fileURLToPath(\n\tnew URL(import.meta.url.endsWith(\".ts\") ? \"./pages.ts\" : \"./vercel-pages.js\", import.meta.url),\n);\n\n/** A case-insensitive pattern for `text/markdown`, in the regular expression syntax of any engine. */\nconst MARKDOWN = \"text/markdown\".replaceAll(\n\t/[a-z]/gu,\n\t(letter) => `[${letter}${letter.toUpperCase()}]`,\n);\n\n/** The variable that gives the function the time of the build, in milliseconds. */\nconst BUILT_AT = \"APP_SERVER_BUILT_AT\";\n\n/** The function's file, next to the server entry. */\nconst FUNCTION_FILE = \"vercel-function.js\";\n\n/** A path with `/` separators, as Vercel's config reads it. */\nfunction posix(path: string): string {\n\treturn path.split(sep).join(\"/\");\n}\n\n/** A regular expression source that matches `text` as it is. */\nfunction escaped(text: string): string {\n\treturn text.replaceAll(/[$()*+.?[\\\\\\]^{|}]/gu, String.raw`\\$&`);\n}\n\n/** Copies the file at `from` to `to`, and makes the directories of `to`. */\nfunction copyFile(from: string, to: string): void {\n\tmkdirSync(dirname(to), { recursive: true });\n\tcopyFileSync(from, to);\n}\n\n/**\n * The path of each file under `directory`, relative to it. Why follow links:\n * the CDN and the function each get a copy of the linked file, not a link\n * whose target can be in the other part. Why the inodes of the parents: a\n * link to a parent directory must not make the walk endless.\n */\nfunction filesUnder(\n\tdirectory: string,\n\tunder = \"\",\n\tparents: ReadonlySet<string> = new Set(),\n): string[] {\n\tconst stats = statSync(join(directory, under), { throwIfNoEntry: false });\n\tif (stats == null) {\n\t\treturn [];\n\t}\n\tif (!stats.isDirectory()) {\n\t\treturn [under];\n\t}\n\tconst inode = `${stats.dev}:${stats.ino}`;\n\tif (parents.has(inode)) {\n\t\treturn [];\n\t}\n\tconst inside = new Set(parents).add(inode);\n\treturn readdirSync(join(directory, under)).flatMap((name) =>\n\t\tfilesUnder(directory, join(under, name), inside),\n\t);\n}\n\n/**\n * The `.vercel/output` routes: a CDN file gets its headers, and each other\n * request goes to the function. A file under `assetsPath` also gets the\n * immutable cache. Why the `hit` phase: a CDN path with no file goes to the\n * function, whose `no-store` 404 must not get the immutable cache.\n */\nfunction routes(\n\tprefixes: readonly string[],\n\t{\n\t\tassetsPath,\n\t\tcdnHeaders,\n\t\tpages,\n\t}: {\n\t\tassetsPath: string;\n\t\tcdnHeaders: Readonly<Record<string, string>>;\n\t\tpages: readonly CdnPageReport[];\n\t},\n) {\n\treturn [\n\t\t...(pages.length === 0 ? [] : [{ src: `^${escaped(PAGES)}(?:/.*)?$`, dest: \"/index\" }]),\n\t\t...pages.flatMap((page) => pageRoutes(page)),\n\t\t{ handle: \"filesystem\" },\n\t\t{ src: \"^/(.*)$\", dest: \"/index\" },\n\t\t{ handle: \"hit\" },\n\t\t...prefixes.map((prefix) => ({\n\t\t\t// Why `.*$`: Vercel adds `$` to a pattern that has none.\n\t\t\tsrc: `^${escaped(prefix)}.*$`,\n\t\t\theaders: prefix === assetsPath ? { ...cdnHeaders, \"Cache-Control\": IMMUTABLE } : cdnHeaders,\n\t\t\tcontinue: true,\n\t\t})),\n\t];\n}\n\n/**\n * The routes of one page that the CDN serves: one for each case of the\n * presence headers, with the headers of that case. Why only GET and HEAD: the\n * function answers the other methods, such as a form's POST. Why the\n * function for a request that names `text/markdown`: it negotiates the twin.\n */\nfunction pageRoutes({ path, file, answers, twin }: CdnPageReport) {\n\tconst src = `^${escaped(path)}$`;\n\tconst names = [...new Set(answers.flatMap(({ present }) => present))];\n\treturn [\n\t\t...(twin == null\n\t\t\t? []\n\t\t\t: [\n\t\t\t\t\t{\n\t\t\t\t\t\tsrc,\n\t\t\t\t\t\thas: [{ type: \"header\", key: \"accept\", value: { re: MARKDOWN } }],\n\t\t\t\t\t\tdest: \"/index\",\n\t\t\t\t\t},\n\t\t\t\t]),\n\t\t...answers.map(({ present, headers }) => {\n\t\t\tconst missing = names.filter((name) => !present.includes(name));\n\t\t\treturn {\n\t\t\t\tsrc,\n\t\t\t\tcaseSensitive: true,\n\t\t\t\tmethods: [\"GET\", \"HEAD\"],\n\t\t\t\t...(present.length === 0 ? {} : { has: present.map((key) => ({ type: \"header\", key })) }),\n\t\t\t\t...(missing.length === 0\n\t\t\t\t\t? {}\n\t\t\t\t\t: { missing: missing.map((key) => ({ type: \"header\", key })) }),\n\t\t\t\theaders,\n\t\t\t\tdest: `${PAGES}${file}`,\n\t\t\t};\n\t\t}),\n\t];\n}\n\n/**\n * Whether `cdnPages` accepts `path`. Why both trailing-slash forms: with\n * `trailingSlash: \"always\"`, the CDN serves `/blog/` for the prerendered\n * path `/blog`.\n */\nfunction accepts(cdnPages: (path: string) => boolean, path: string): boolean {\n\treturn cdnPages(path) && (path === \"/\" || !path.endsWith(\"/\") || cdnPages(path.slice(0, -1)));\n}\n\n/**\n * Finds the pages that the CDN serves ({@link VercelOptions.cdnPages}), and\n * writes their bodies under `static/`.\n */\nfunction findCdnPages(\n\tentryFile: string,\n\toutput: string,\n\t{\n\t\tcdnPages,\n\t\trouteBudget,\n\t}: { cdnPages: NonNullable<VercelOptions[\"cdnPages\"]>; routeBudget: number },\n): PagesReport {\n\tif (cdnPages === false) {\n\t\treturn { cdn: [], server: [] };\n\t}\n\tconst pagesDirectory = join(output, \"static\", PAGES);\n\tconst reportFile = join(output, \"pages.json\");\n\ttry {\n\t\texecFileSync(process.execPath, [PAGES_SCRIPT, entryFile, pagesDirectory, reportFile], {\n\t\t\tstdio: \"inherit\",\n\t\t\tenv: { ...process.env, NODE_ENV: \"production\" },\n\t\t});\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t\"@ngrok/app-server/vercel could not start the server build to find the prerendered pages that the CDN can serve. Give the build the environment of the app, or remove `cdnPages`.\",\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the step of this package wrote the file.\n\tconst report = JSON.parse(readFileSync(reportFile, \"utf8\")) as PagesReport;\n\trmSync(reportFile);\n\tconst pages: PagesReport = { cdn: [], server: [...report.server] };\n\tlet routeCount = 0;\n\tfor (const page of report.cdn) {\n\t\tconst count = pageRoutes(page).length;\n\t\tlet reason: string | undefined;\n\t\tif (cdnPages !== true && !accepts(cdnPages, page.path)) {\n\t\t\treason = \"`cdnPages` keeps it in the function\";\n\t\t} else if (\n\t\t\tpage.answers.some(({ headers }) =>\n\t\t\t\tObject.values(headers).some((value) => value.includes(\"$\")),\n\t\t\t)\n\t\t) {\n\t\t\t// Why: Vercel reads `$1` or `$name` in a route's header as a capture of its `src`.\n\t\t\treason = \"a header has a `$`, which a Vercel route reads as a capture\";\n\t\t} else if (routeCount + count > routeBudget) {\n\t\t\treason = `the CDN routes of the pages reach Vercel's limit of ${ROUTE_LIMIT} routes`;\n\t\t}\n\t\tif (reason == null) {\n\t\t\tpages.cdn.push(page);\n\t\t\trouteCount += count;\n\t\t} else {\n\t\t\trmSync(join(pagesDirectory, page.file));\n\t\t\tpages.server.push({ path: page.path, reason });\n\t\t}\n\t}\n\treturn pages;\n}\n\n/** Writes the paths that the function serves, and why, so the build log shows them. */\nfunction reportPages({ cdn, server }: PagesReport): void {\n\tconst shown = server.slice(0, 20);\n\tprocess.stdout.write(\n\t\t[\n\t\t\t`@ngrok/app-server/vercel: the CDN serves ${cdn.length} prerendered paths, and the function serves ${server.length}.`,\n\t\t\t...shown.map(({ path, reason }) => ` ${path}: ${reason}`),\n\t\t\t...(server.length > shown.length ? [` and ${server.length - shown.length} more`] : []),\n\t\t\t\"\",\n\t\t].join(\"\\n\"),\n\t);\n}\n\n/** Writes `.vercel/output` (the Build Output API, version 3) for one build. */\nfunction writeOutput(\n\t{ root, clientDirectory, entryFile, assetsPath }: HostOutput,\n\t{ cdnPaths = [], cdnHeaders = {}, cdnPages = false, regions, memory, maxDuration }: VercelOptions,\n): void {\n\t// Why `assetsPath` last: Vercel applies each matched rule in order, so its immutable cache wins\n\t// over a `cdnHeaders` value for a `cdnPaths` entry that holds it.\n\tconst prefixes = [...cdnPaths.filter((path) => path !== assetsPath), assetsPath];\n\tconst output = join(root, \".vercel/output\");\n\trmSync(output, { recursive: true, force: true });\n\tconst pages = findCdnPages(entryFile, output, {\n\t\tcdnPages,\n\t\t// Why one less: the route that sends a request for a page's body to the function.\n\t\trouteBudget: ROUTE_LIMIT - routes(prefixes, { assetsPath, cdnHeaders, pages: [] }).length - 1,\n\t});\n\tif (cdnPages !== false) {\n\t\treportPages(pages);\n\t}\n\tconst fromRoot = (path: string): string => {\n\t\tconst inside = relative(root, path);\n\t\tif (inside.startsWith(\"..\") || isAbsolute(inside)) {\n\t\t\tthrow new Error(`@ngrok/app-server/vercel needs ${path} inside the Vite root ${root}.`);\n\t\t}\n\t\treturn inside;\n\t};\n\tconst functionDirectory = join(output, \"functions/index.func\");\n\tconst isCdnFile = (file: string): boolean =>\n\t\tprefixes.some((prefix) => `/${posix(file)}`.startsWith(prefix));\n\n\tfor (const file of filesUnder(clientDirectory)) {\n\t\tconst from = join(clientDirectory, file);\n\t\t// Why the function keeps the file of a page that the CDN serves: a request that no page route\n\t\t// matches, such as the other trailing slash form, or a markdown request, reaches the function.\n\t\tif (!isCdnFile(file)) {\n\t\t\tcopyFile(from, join(functionDirectory, fromRoot(from)));\n\t\t} else if (!hasDotSegment(`/${posix(file)}`)) {\n\t\t\t// Why the static stages' check: the CDN sends each file that it has, and the static stages\n\t\t\t// send no dotfile, such as a compressed copy, and no file in a dot directory.\n\t\t\tcopyFile(from, join(output, \"static\", file));\n\t\t}\n\t}\n\n\t// Why the whole server build: it runs with no install, and it keeps the client build's path.\n\tconst serverDirectory = dirname(entryFile);\n\tconst functionFile = join(serverDirectory, FUNCTION_FILE);\n\tcpSync(serverDirectory, join(functionDirectory, fromRoot(serverDirectory)), {\n\t\trecursive: true,\n\t\t// Why: a link that keeps its target can point at the build machine.\n\t\tdereference: true,\n\t\t// Why: the client build can be inside the server build, and the loop above copied its part.\n\t\tfilter: (path) => path !== clientDirectory,\n\t});\n\twriteFileSync(\n\t\tjoin(functionDirectory, fromRoot(functionFile)),\n\t\t[\n\t\t\t`import { appServer, hostModule } from ${JSON.stringify(`./${basename(entryFile)}`)};`,\n\t\t\t`export default hostModule.handler(appServer);`,\n\t\t\t\"\",\n\t\t].join(\"\\n\"),\n\t);\n\twriteFileSync(\n\t\tjoin(functionDirectory, \".vc-config.json\"),\n\t\t`${JSON.stringify(\n\t\t\t{\n\t\t\t\t// Why the build's Node.js: the server build targets the Node.js that built it.\n\t\t\t\truntime: `nodejs${process.versions.node.split(\".\")[0]}.x`,\n\t\t\t\thandler: posix(fromRoot(functionFile)),\n\t\t\t\tlauncherType: \"Nodejs\",\n\t\t\t\tsupportsResponseStreaming: true,\n\t\t\t\t// Why: the deploy gives each file of the function one fixed time, and the ETag of a file\n\t\t\t\t// reads its time. See `host` in `@ngrok/app-server/vercel`.\n\t\t\t\tenvironment: { [BUILT_AT]: String(Date.now()) },\n\t\t\t\t...(regions == null ? {} : { regions }),\n\t\t\t\t...(memory == null ? {} : { memory }),\n\t\t\t\t...(maxDuration == null ? {} : { maxDuration }),\n\t\t\t},\n\t\t\tnull,\n\t\t\t\"\\t\",\n\t\t)}\\n`,\n\t);\n\twriteFileSync(\n\t\tjoin(output, \"config.json\"),\n\t\t`${JSON.stringify({ version: 3, routes: routes(prefixes, { assetsPath, cdnHeaders, pages: pages.cdn }) }, null, \"\\t\")}\\n`,\n\t);\n}\n\n/** Throws for a CDN path that is not a URL path prefix, so the config fails, not the deploy. */\nfunction checkCdnPaths(paths: readonly string[]): void {\n\tfor (const path of paths) {\n\t\tif (!path.startsWith(\"/\") || !path.endsWith(\"/\") || path === \"/\" || path.includes(\"..\")) {\n\t\t\tthrow new Error(\n\t\t\t\t`Each cdnPaths entry is a URL path prefix that starts and ends with \"/\", such as \"/blog-assets/\", not ${JSON.stringify(path)}.`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * The build side of the vercel host. After the build, it writes\n * `.vercel/output` in the Vite root, for `vercel deploy --prebuilt`:\n *\n * - `static/`: the files of Vite's `build.assetsDir` (`/assets/` by default)\n * and the other `cdnPaths`. The CDN serves them, and each file of\n * `build.assetsDir` gets a one-year immutable cache. It also holds the\n * prerendered pages that the CDN serves, with `cdnPages`.\n * - `functions/index.func/`: one Node.js function that runs the pipeline for\n * each other request, with the whole server build and the rest of the\n * client build.\n *\n * @example\n * appServer({ host: vercel() });\n */\nexport function vercel(options: VercelOptions = {}): HostBuild {\n\tcheckCdnPaths(options.cdnPaths ?? []);\n\treturn {\n\t\tname: \"vercel\",\n\t\truntimeModule: \"@ngrok/app-server/vercel\",\n\t\tentryFileName: \"app-server.js\",\n\t\toutput: (build) => {\n\t\t\twriteOutput(build, options);\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;AAwDA,MAAM,YAAY;;AAGlB,MAAM,cAAc;;;;;;AAOpB,MAAM,QAAQ;;;;;;AAOd,MAAM,eAAe,cACpB,IAAI,IAAI,YAAY,IAAI,SAAS,KAAK,IAAI,eAAe,qBAAqB,YAAY,GAAG,C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AAQ,YAAY,CAAC,CAAC;CACpC,OAAO;EACN,MAAM;EACN,eAAe;EACf,eAAe;EACf,SAAS,UAAU;GAClB,YAAY,OAAO,OAAO;EAC3B;CACD;AACD"}
|
package/dist/vercel.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { c as HostRuntime } from "./types-
|
|
2
|
-
import { t as AppServerEntry } from "./entry-
|
|
1
|
+
import { c as HostRuntime } from "./types-j29vspx_.js";
|
|
2
|
+
import { t as AppServerEntry } from "./entry-BPrgE_6K.js";
|
|
3
3
|
import { IncomingMessage, ServerResponse } from "node:http";
|
|
4
4
|
/**
|
|
5
5
|
* The vercel host: one Vercel Function on Node.js. It reads the client build
|
package/dist/vercel.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { n as flushLogs } from "./log-BP6xXXZl.js";
|
|
2
|
-
import { i as withForwardedProto } from "./create-server-
|
|
3
|
-
import { t as host$1 } from "./node-
|
|
2
|
+
import { i as withForwardedProto } from "./create-server-jMl2ltHD.js";
|
|
3
|
+
import { t as host$1 } from "./node-C1qudLs_.js";
|
|
4
4
|
import { t as requestListener } from "./response-writer-B7FoJjEE.js";
|
|
5
5
|
|
|
6
6
|
// src/vercel/index.ts
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
+
import { n as DEFAULT_ASSETS_PATH, r as manifestKey, t as BUILD_MANIFEST_FILE } from "./build-manifest-DBMWe3Lx.js";
|
|
1
2
|
import { a as isCompressible, n as MIN_COMPRESS_BYTES, r as copyName } from "./compression-7_gToa8R.js";
|
|
2
3
|
import { t as contentType } from "./static-files-Beju9riB.js";
|
|
3
|
-
import { n as
|
|
4
|
-
import { t as inlineScriptHashes } from "./script-hashes-hqUk6kG7.js";
|
|
4
|
+
import { n as scriptHashesOf } from "./script-hashes-C6hQ5XnP.js";
|
|
5
5
|
import { t as node } from "./vite-D4hfj3ph.js";
|
|
6
6
|
import { t as reactRouterAdapter } from "./vite-B-GfswoH.js";
|
|
7
7
|
import { t as tanstackStartAdapter } from "./vite-DyrhyKEr.js";
|
|
8
8
|
import { isBuiltin } from "node:module";
|
|
9
9
|
import { getPath } from "hono/utils/url";
|
|
10
10
|
import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
11
|
-
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
11
|
+
import { basename, dirname, extname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
|
|
12
12
|
import { brotliCompressSync, constants as constants$1, gzipSync } from "node:zlib";
|
|
13
13
|
import { createHash } from "node:crypto";
|
|
14
14
|
|
|
@@ -260,9 +260,21 @@ function hostOutput(config, host) {
|
|
|
260
260
|
return {
|
|
261
261
|
root: config.root,
|
|
262
262
|
clientDirectory: outDir(config, "client"),
|
|
263
|
-
entryFile: join(outDir(config, SERVER_ENVIRONMENT), host.entryFileName)
|
|
263
|
+
entryFile: join(outDir(config, SERVER_ENVIRONMENT), host.entryFileName),
|
|
264
|
+
assetsPath: urlPathOfAssetsDir(config.environments.client?.build.assetsDir ?? config.build.assetsDir)
|
|
264
265
|
};
|
|
265
266
|
}
|
|
267
|
+
/**
|
|
268
|
+
* The URL path of Vite's `build.assetsDir`. Why the default for the root: an
|
|
269
|
+
* immutable cache on each file of the client build would keep an old page.
|
|
270
|
+
*
|
|
271
|
+
* @example
|
|
272
|
+
* urlPathOfAssetsDir("blog-assets/build"); // => "/blog-assets/build/"
|
|
273
|
+
*/
|
|
274
|
+
function urlPathOfAssetsDir(assetsDir) {
|
|
275
|
+
const path = posix.normalize(`/${assetsDir.replaceAll("\\", "/")}/`);
|
|
276
|
+
return path === "/" ? DEFAULT_ASSETS_PATH : path;
|
|
277
|
+
}
|
|
266
278
|
/** The absolute path of an environment's build output. */
|
|
267
279
|
function outDir(config, environment) {
|
|
268
280
|
return resolve(config.root, config.environments[environment]?.build.outDir ?? config.build.outDir);
|
|
@@ -468,19 +480,6 @@ function withPeers(start) {
|
|
|
468
480
|
}
|
|
469
481
|
return names;
|
|
470
482
|
}
|
|
471
|
-
/** The {@link inlineScriptHashes} of each HTML file in the client build, by its URL path. */
|
|
472
|
-
function scriptHashesOf(clientDirectory) {
|
|
473
|
-
const hashes = {};
|
|
474
|
-
for (const entry of readdirSync(clientDirectory, {
|
|
475
|
-
recursive: true,
|
|
476
|
-
withFileTypes: true
|
|
477
|
-
})) if (entry.isFile() && contentType(entry.name, {}).startsWith("text/html")) {
|
|
478
|
-
const path = join(entry.parentPath, entry.name);
|
|
479
|
-
const urlPath = `/${relative(clientDirectory, path).split(sep).join("/")}`;
|
|
480
|
-
hashes[urlPath] = inlineScriptHashes(readFileSync(path, "utf8"));
|
|
481
|
-
}
|
|
482
|
-
return Object.fromEntries(Object.entries(hashes).toSorted(([first], [second]) => first.localeCompare(second)));
|
|
483
|
-
}
|
|
484
483
|
/** Writes `.app-server.json` into the client build. */
|
|
485
484
|
function writeBuildManifest(clientDirectory, manifest) {
|
|
486
485
|
mkdirSync(clientDirectory, { recursive: true });
|
|
@@ -545,12 +544,19 @@ function appBuildId({ bundleId, assetsDirectory, assets }) {
|
|
|
545
544
|
}
|
|
546
545
|
return hash.digest("hex").slice(0, 16);
|
|
547
546
|
}
|
|
548
|
-
/**
|
|
549
|
-
|
|
547
|
+
/**
|
|
548
|
+
* The `buildId` and the `assetsPath` of the build manifest that the client
|
|
549
|
+
* build wrote. Why keep them: the prerender pass runs after the client build,
|
|
550
|
+
* which knows them.
|
|
551
|
+
*/
|
|
552
|
+
function clientBuildFields(clientDirectory) {
|
|
550
553
|
const path = join(clientDirectory, BUILD_MANIFEST_FILE);
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
return
|
|
554
|
+
const manifest = existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : void 0;
|
|
555
|
+
if (typeof manifest !== "object" || manifest == null) return {};
|
|
556
|
+
return {
|
|
557
|
+
..."buildId" in manifest && typeof manifest.buildId === "string" ? { buildId: manifest.buildId } : {},
|
|
558
|
+
..."assetsPath" in manifest && typeof manifest.assetsPath === "string" ? { assetsPath: manifest.assetsPath } : {}
|
|
559
|
+
};
|
|
554
560
|
}
|
|
555
561
|
/**
|
|
556
562
|
* Records each 2xx path and the headers of each non-document response while
|
|
@@ -578,9 +584,8 @@ function capture(server, afterPass) {
|
|
|
578
584
|
next();
|
|
579
585
|
});
|
|
580
586
|
server.httpServer.once("close", () => {
|
|
581
|
-
const buildId = writtenBuildId(clientDirectory);
|
|
582
587
|
writeBuildManifest(clientDirectory, {
|
|
583
|
-
...
|
|
588
|
+
...clientBuildFields(clientDirectory),
|
|
584
589
|
prerendered: [...paths].toSorted(),
|
|
585
590
|
headers: Object.fromEntries(Object.entries(headers).toSorted(([first], [second]) => first.localeCompare(second))),
|
|
586
591
|
scriptHashes: scriptHashesOf(clientDirectory)
|
|
@@ -621,18 +626,24 @@ function writeCopies(path) {
|
|
|
621
626
|
}
|
|
622
627
|
/**
|
|
623
628
|
* Runs {@link writeCopies} for each file in the client build, except dotfiles
|
|
624
|
-
* such as the copies. With `changedSince`, only for a file that changed at or
|
|
629
|
+
* 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
|
|
625
630
|
* after that time, in milliseconds since the epoch.
|
|
626
631
|
*/
|
|
627
632
|
function writeAllCopies(clientDirectory, { changedSince } = {}) {
|
|
628
633
|
if (!existsSync(clientDirectory)) return;
|
|
629
|
-
for (const
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
634
|
+
for (const path of filesInside(clientDirectory)) if (!basename(path).startsWith(".") && (changedSince == null || (statSync(path, { throwIfNoEntry: false })?.mtimeMs ?? 0) >= changedSince)) writeCopies(path);
|
|
635
|
+
}
|
|
636
|
+
/**
|
|
637
|
+
* The path of each file under `directory`. Why not through a link: a copy goes
|
|
638
|
+
* next to its file, so a file in a linked directory would get its copies in
|
|
639
|
+
* the link's target, outside the client build.
|
|
640
|
+
*/
|
|
641
|
+
function filesInside(directory) {
|
|
642
|
+
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
|
|
643
|
+
const path = join(directory, entry.name);
|
|
644
|
+
if (entry.isDirectory()) return filesInside(path);
|
|
645
|
+
return entry.isFile() ? [path] : [];
|
|
646
|
+
});
|
|
636
647
|
}
|
|
637
648
|
/**
|
|
638
649
|
* The Vite plugin for `@ngrok/app-server`. Put it next to the framework's
|
|
@@ -702,6 +713,7 @@ function appServer(options = {}) {
|
|
|
702
713
|
};
|
|
703
714
|
writeBuildManifest(directory, {
|
|
704
715
|
buildId: clientBuild.bundleId,
|
|
716
|
+
assetsPath: urlPathOfAssetsDir(this.environment.config.build.assetsDir),
|
|
705
717
|
prerendered: [],
|
|
706
718
|
headers: {},
|
|
707
719
|
scriptHashes: {}
|
|
@@ -749,4 +761,4 @@ function appServer(options = {}) {
|
|
|
749
761
|
}
|
|
750
762
|
|
|
751
763
|
export { appServer as n, serverEntrySource as r, SERVER_ENTRY_ID as t };
|
|
752
|
-
//# sourceMappingURL=vite-
|
|
764
|
+
//# sourceMappingURL=vite-BDREIgiH.js.map
|