@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.
Files changed (119) hide show
  1. package/README.md +223 -64
  2. package/dist/brotli-only-BVAagKt3.js +63 -0
  3. package/dist/build-id-CwMbED1n.js +245 -0
  4. package/dist/{build-manifest-DBMWe3Lx.js → build-manifest-CoBztw_6.js} +13 -4
  5. package/dist/bun-BCz6K_Xv.js +1 -2
  6. package/dist/check-count-DQl5z_qe.js +17 -0
  7. package/dist/cli.js +9 -6
  8. package/dist/client-browser.d.ts +2 -3
  9. package/dist/client-browser.js +1 -1
  10. package/dist/client.d.ts +5 -4
  11. package/dist/client.js +9 -6
  12. package/dist/{compress-Cp5NfXCC.js → compress-2w3jqBh7.js} +2 -3
  13. package/dist/{compression-CT2mWlKM.js → compression-uJxu0JVb.js} +32 -5
  14. package/dist/content-types-Le-5BNEC.js +10 -0
  15. package/dist/{create-server-Bp1yILQk.js → create-server-DVTZun6D.js} +617 -306
  16. package/dist/create-server-PA0qniaK.js +3 -0
  17. package/dist/{create-server-X2GR-U6t.d.ts → create-server-UVsHFQyK.d.ts} +116 -54
  18. package/dist/deno-aqhikNMG.js +1 -2
  19. package/dist/{entry-BoxCqc6w.js → entry-CMhX3yf8.js} +85 -65
  20. package/dist/entry-CvZ4U0ia.js +3 -0
  21. package/dist/{entry-DZTCaL3d.d.ts → entry-DBq_3s8X.d.ts} +10 -36
  22. package/dist/entry-protocol-C30UPXzy.js +14 -0
  23. package/dist/entry-source-DSE5NAJu.js +70 -0
  24. package/dist/entry-source-SHoE-DUP.js +3 -0
  25. package/dist/exit-Hh-O3gp4.js +83 -0
  26. package/dist/{header-hook-Vzw9J9BY.js → header-hook-JfqaTt34.js} +69 -23
  27. package/dist/{index-B8LsM6Mh.d.ts → index-gzGs53Ue.d.ts} +43 -38
  28. package/dist/index.d.ts +88 -44
  29. package/dist/index.js +216 -84
  30. package/dist/listen-options-7TaXjyrk.js +1 -2
  31. package/dist/{load-entry-CCPWbsrj.js → load-entry-Bgq1_HDV.js} +11 -12
  32. package/dist/{log-DQAS5gGT.js → log-DfC9D5_T.js} +70 -49
  33. package/dist/{node-D6m6e6EI.js → node-DQPrMFyc.js} +20 -8
  34. package/dist/node-DyKDFII0.js +263 -0
  35. package/dist/node-vite.d.ts +2 -3
  36. package/dist/node-vite.js +1 -1
  37. package/dist/node.d.ts +41 -64
  38. package/dist/node.js +3 -3
  39. package/dist/react-router-vite.d.ts +2 -3
  40. package/dist/react-router-vite.js +1 -1
  41. package/dist/react-router.d.ts +6 -17
  42. package/dist/react-router.js +9 -14
  43. package/dist/request-context-Cslbrscf.js +163 -0
  44. package/dist/{response-edge-CU8ZvL_F.js → response-edge-Ow5Pi5qF.js} +13 -10
  45. package/dist/{response-writer-D7KHfr8n.js → response-writer-Dd4Ey99f.js} +57 -21
  46. package/dist/{script-hashes-CU7P9oZU.js → script-hashes-BdvJ0QI_.js} +2 -3
  47. package/dist/serve-AatMo9k6.js +26 -0
  48. package/dist/{stale-build-navigation-rg5xxmTr.js → stale-build-navigation-Qf_Lem39.js} +4 -5
  49. package/dist/{stale-build-navigation-ypV7Ow4o.d.ts → stale-build-navigation-WjhD8zHi.d.ts} +4 -4
  50. package/dist/start-DYFyGKsM.js +470 -0
  51. package/dist/static-files-BdTPam5b.js +438 -0
  52. package/dist/static-pages-6IBHdYQc.d.ts +30 -0
  53. package/dist/tanstack-start-vite.d.ts +2 -3
  54. package/dist/tanstack-start-vite.js +1 -1
  55. package/dist/tanstack-start.d.ts +3 -4
  56. package/dist/tanstack-start.js +2 -3
  57. package/dist/tcp-3v4pmnYU.js +58 -0
  58. package/dist/testing.d.ts +8 -6
  59. package/dist/testing.js +19 -17
  60. package/dist/{trailing-slash-D2QWKWEu.d.ts → trailing-slash-C-yBKCib.d.ts} +2 -3
  61. package/dist/{types-MgFtkNQW.d.ts → types-KsKRDwAv.d.ts} +97 -46
  62. package/dist/vercel-pages.d.ts +3 -16
  63. package/dist/vercel-pages.js +1 -2
  64. package/dist/vercel-vite.d.ts +4 -5
  65. package/dist/vercel-vite.js +48 -44
  66. package/dist/vercel.d.ts +13 -10
  67. package/dist/vercel.js +48 -35
  68. package/dist/{vite-D4hfj3ph.js → vite-Brb8YR9I.js} +2 -7
  69. package/dist/{vite-B-GfswoH.js → vite-CHppJWp_.js} +5 -7
  70. package/dist/{vite-DyrhyKEr.js → vite-DjlHdyTM.js} +2 -7
  71. package/dist/vite.d.ts +2 -2
  72. package/dist/vite.js +885 -2
  73. package/package.json +13 -12
  74. package/dist/brotli-only-DrA29Ecw.js +0 -97
  75. package/dist/brotli-only-DrA29Ecw.js.map +0 -1
  76. package/dist/build-id-B0448vZH.js +0 -151
  77. package/dist/build-id-B0448vZH.js.map +0 -1
  78. package/dist/build-manifest-DBMWe3Lx.js.map +0 -1
  79. package/dist/bun-BCz6K_Xv.js.map +0 -1
  80. package/dist/cli.js.map +0 -1
  81. package/dist/client.js.map +0 -1
  82. package/dist/compress-Cp5NfXCC.js.map +0 -1
  83. package/dist/compression-CT2mWlKM.js.map +0 -1
  84. package/dist/create-server-Bp1yILQk.js.map +0 -1
  85. package/dist/deno-aqhikNMG.js.map +0 -1
  86. package/dist/entry-BoxCqc6w.js.map +0 -1
  87. package/dist/header-hook-Vzw9J9BY.js.map +0 -1
  88. package/dist/index.js.map +0 -1
  89. package/dist/listen-options-7TaXjyrk.js.map +0 -1
  90. package/dist/load-entry-CCPWbsrj.js.map +0 -1
  91. package/dist/log-DQAS5gGT.js.map +0 -1
  92. package/dist/node-CVVdk2N6.js +0 -334
  93. package/dist/node-CVVdk2N6.js.map +0 -1
  94. package/dist/node-D6m6e6EI.js.map +0 -1
  95. package/dist/react-router.js.map +0 -1
  96. package/dist/request-context-Bxdbk5P1.js +0 -80
  97. package/dist/request-context-Bxdbk5P1.js.map +0 -1
  98. package/dist/response-edge-CU8ZvL_F.js.map +0 -1
  99. package/dist/response-writer-D7KHfr8n.js.map +0 -1
  100. package/dist/script-hashes-CU7P9oZU.js.map +0 -1
  101. package/dist/serve-W4WacdOw.js +0 -29
  102. package/dist/serve-W4WacdOw.js.map +0 -1
  103. package/dist/stale-build-navigation-rg5xxmTr.js.map +0 -1
  104. package/dist/start-j0VlxeiI.js +0 -324
  105. package/dist/start-j0VlxeiI.js.map +0 -1
  106. package/dist/static-files-C2ea8KQ6.js +0 -310
  107. package/dist/static-files-C2ea8KQ6.js.map +0 -1
  108. package/dist/tanstack-start.js.map +0 -1
  109. package/dist/tcp-BgDXbjOG.js +0 -42
  110. package/dist/tcp-BgDXbjOG.js.map +0 -1
  111. package/dist/testing.js.map +0 -1
  112. package/dist/vercel-pages.js.map +0 -1
  113. package/dist/vercel-vite.js.map +0 -1
  114. package/dist/vercel.js.map +0 -1
  115. package/dist/vite-B-GfswoH.js.map +0 -1
  116. package/dist/vite-D4hfj3ph.js.map +0 -1
  117. package/dist/vite-DPiSKHDn.js +0 -870
  118. package/dist/vite-DPiSKHDn.js.map +0 -1
  119. package/dist/vite-DyrhyKEr.js.map +0 -1
@@ -1,310 +0,0 @@
1
- import { r as hookedHeaders } from "./header-hook-Vzw9J9BY.js";
2
- import { i as forbidsTransform, o as preferredEncoding, r as copyName, t as COPY_ENCODINGS } from "./compression-CT2mWlKM.js";
3
- import { getMimeType } from "hono/utils/mime";
4
-
5
- // src/core/vary.ts
6
- /**
7
- * A `Vary` value with `name` added, or `undefined` when `vary` already covers
8
- * it. The existing values stay as they are.
9
- *
10
- * @example
11
- * withVary("Accept", "Accept-Encoding"); // => "Accept, Accept-Encoding"
12
- * withVary("accept-encoding", "Accept-Encoding"); // => undefined
13
- */
14
- function withVary(vary, name) {
15
- if (vary == null || vary.trim() === "") return name;
16
- const values = new Set(vary.split(",").map((value) => value.trim().toLowerCase()));
17
- return values.has(name.toLowerCase()) || values.has("*") ? void 0 : `${vary}, ${name}`;
18
- }
19
-
20
- // src/core/static-files.ts
21
- /** The content types that `mime` lacks and that no framework owns. */
22
- const CORE_CONTENT_TYPES = {
23
- ".atom": "application/atom+xml",
24
- ".md": "text/markdown; charset=utf-8",
25
- ".pem": "application/x-pem-file",
26
- ".rss": "application/rss+xml",
27
- ".sh": "application/x-sh",
28
- ".yaml": "text/yaml; charset=utf-8",
29
- ".yml": "text/yaml; charset=utf-8"
30
- };
31
- /**
32
- * Whether a URL path names a dotfile or goes through a dot directory.
33
- * `/.well-known/` stays reachable.
34
- *
35
- * @example
36
- * hasDotSegment("/assets/.private/key.json"); // => true
37
- * hasDotSegment("/.well-known/security.txt"); // => false
38
- */
39
- function hasDotSegment(path) {
40
- return path.split("/").some((segment, index) => segment.startsWith(".") && !(index === 1 && segment === ".well-known"));
41
- }
42
- /**
43
- * Whether a decoded URL path, such as Hono's `context.req.path`, can name a
44
- * file of the client build. Dotfiles, paths that leave the client build, and
45
- * a second URL for a file, such as `/a//b` or `/a/index.html`, cannot.
46
- */
47
- function isFilePath(path) {
48
- return path.startsWith("/") && !path.includes("\0") && !path.includes("\\") && !path.split("/").includes("..") && !path.includes("//") && !path.endsWith("/index.html") && !hasDotSegment(path);
49
- }
50
- /**
51
- * Finds the file in `files` that answers a decoded URL path, such as Hono's
52
- * `context.req.path`. A directory answers with its `index.html` and no
53
- * redirect, so a prerendered page keeps its URL. A path that fails
54
- * `isFilePath` finds nothing.
55
- *
56
- * Each file has one URL, because the headers for a file are keyed by that
57
- * URL. So `/a//b`, `/a/index.html`, and `/a%2Fb` find nothing. Hono decodes
58
- * the path but keeps an encoded `/` as `%2F`, so this function does not
59
- * decode it again.
60
- *
61
- * @example
62
- * await findStaticFile(files, "/components/button");
63
- * // => { path: "/components/button/index.html", size: 5120, mtimeMs: 1761652800000 }
64
- */
65
- async function findStaticFile(files, path) {
66
- if (!isFilePath(path)) return;
67
- const info = await files.stat(path);
68
- if (info?.kind === "file") return {
69
- path,
70
- size: info.size,
71
- mtimeMs: info.mtimeMs
72
- };
73
- if (info?.kind === "directory") {
74
- const index = `${path.replace(/\/$/u, "")}/index.html`;
75
- const indexInfo = await files.stat(index);
76
- if (indexInfo?.kind === "file") return {
77
- path: index,
78
- size: indexInfo.size,
79
- mtimeMs: indexInfo.mtimeMs
80
- };
81
- }
82
- }
83
- /** The content type of a file, by its extension. `contentTypes` win over `mime`. */
84
- function contentType(path, contentTypes) {
85
- const extension = /\.[^./]+$/u.exec(path)?.[0] ?? "";
86
- return contentTypes[extension] ?? CORE_CONTENT_TYPES[extension] ?? getMimeType(path) ?? "application/octet-stream";
87
- }
88
- /** An ETag without its weak prefix, for the weak comparison that `If-None-Match` uses. */
89
- function opaqueTag(etag) {
90
- return etag.trim().replace(/^W\//u, "");
91
- }
92
- /** Whether an `If-None-Match` header lists an ETag. */
93
- function matchesEtag(ifNoneMatch, etag) {
94
- return ifNoneMatch?.split(",").some((candidate) => {
95
- const trimmed = candidate.trim();
96
- return trimmed === "*" || opaqueTag(trimmed) === opaqueTag(etag);
97
- }) ?? false;
98
- }
99
- /**
100
- * The last `etagParts` and their hash. Why one entry: each request has the
101
- * same parts for the life of the process.
102
- */
103
- let lastParts;
104
- /** A short hash of the request's `etagParts`. */
105
- async function partsHash(parts) {
106
- const key = parts.join("\0");
107
- if (lastParts?.key === key) return lastParts.hash;
108
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(key));
109
- const hash = btoa(String.fromCodePoint(...new Uint8Array(digest))).replaceAll("+", "-").replaceAll("/", "_").slice(0, 16);
110
- lastParts = {
111
- key,
112
- hash
113
- };
114
- return hash;
115
- }
116
- /**
117
- * A weak ETag from a file's size, its modification time, the request's
118
- * `etagParts`, and the encoding of the body. Why the encoding: after a 304,
119
- * a cache that holds more than one encoding of the file picks the stored
120
- * response by its ETag (RFC 9111, section 4.3.4).
121
- */
122
- async function fileEtag(file, parts, encoding) {
123
- return `W/"${[
124
- file.size.toString(16),
125
- Math.trunc(file.mtimeMs).toString(16),
126
- ...parts.length === 0 ? [] : [await partsHash(parts)],
127
- ...encoding == null ? [] : [encoding]
128
- ].join("-")}"`;
129
- }
130
- /**
131
- * The byte range that a `Range` header asks for in a file of `size` bytes.
132
- * It gives `"unsatisfiable"` for a range that starts after the end of the
133
- * file, and `undefined` for a header to ignore: a header that is not valid,
134
- * or one with more than one range.
135
- *
136
- * @example
137
- * byteRange("bytes=-100", 1000); // => { start: 900, end: 999 }
138
- */
139
- function byteRange(header, size) {
140
- const groups = /^bytes=(?<first>\d*)-(?<last>\d*)$/u.exec(header.trim())?.groups;
141
- const first = groups?.first ?? "";
142
- const last = groups?.last ?? "";
143
- if (first === "" && last === "") return;
144
- if (first === "") {
145
- const suffix = Number(last);
146
- return suffix === 0 || size === 0 ? "unsatisfiable" : {
147
- start: Math.max(0, size - suffix),
148
- end: size - 1
149
- };
150
- }
151
- const start = Number(first);
152
- const end = last === "" ? Number.POSITIVE_INFINITY : Number(last);
153
- if (end < start) return;
154
- return start >= size ? "unsatisfiable" : {
155
- start,
156
- end: Math.min(end, size - 1)
157
- };
158
- }
159
- /** Why these caps: they hold the hashed chunks of a typical app, and they limit the memory of each process. */
160
- const KEPT_FILE_BYTES = 262144;
161
- const KEPT_TOTAL_BYTES = 33554432;
162
- /**
163
- * `files` that keep the bytes of each small file in memory after the first
164
- * read, up to {@link KEPT_TOTAL_BYTES} in all. Use it only for files that
165
- * do not change while the server runs, such as a `StaticFiles.snapshot()`.
166
- *
167
- * @example
168
- * const files = keptFiles(await nodeFiles("build/client").snapshot());
169
- */
170
- function keptFiles(files) {
171
- const kept = /* @__PURE__ */ new Map();
172
- let total = 0;
173
- return {
174
- stat: files.stat,
175
- open: async (path, range) => {
176
- let bytes = kept.get(path);
177
- const info = bytes == null ? await files.stat(path) : void 0;
178
- bytes ??= kept.get(path);
179
- if (bytes == null) {
180
- if (info?.kind !== "file" || info.size > KEPT_FILE_BYTES || total + info.size > KEPT_TOTAL_BYTES) return files.open(path, range);
181
- total += info.size;
182
- bytes = files.open(path, {
183
- start: 0,
184
- end: info.size - 1
185
- }).then(async (stream) => new Uint8Array(await new Response(stream).arrayBuffer()));
186
- kept.set(path, bytes);
187
- bytes.catch(() => {
188
- kept.delete(path);
189
- total -= info.size;
190
- });
191
- }
192
- const chunk = (await bytes).slice(range?.start ?? 0, range == null ? void 0 : range.end + 1);
193
- return new ReadableStream({ start(controller) {
194
- controller.enqueue(chunk);
195
- controller.close();
196
- } });
197
- }
198
- };
199
- }
200
- /**
201
- * The copy of the file at `path` that the request prefers, from the copies
202
- * that the build wrote. When a copy exists, it adds `Accept-Encoding` to the
203
- * `Vary` in `headers`, also for a request that gets no copy.
204
- */
205
- async function preferredCopy(context, { files, path, headers }) {
206
- if (headers.has("Content-Encoding") || context.get("rewritesHtml") === true && (headers.get("Content-Type")?.startsWith("text/html") ?? false)) return;
207
- const copies = [];
208
- for (const encoding of COPY_ENCODINGS) {
209
- const copyPath = path.replace(/[^/]*$/u, (name) => copyName(name, encoding));
210
- const info = await files.stat(copyPath);
211
- if (info?.kind === "file") copies.push({
212
- path: copyPath,
213
- size: info.size,
214
- mtimeMs: info.mtimeMs,
215
- encoding
216
- });
217
- }
218
- if (copies.length === 0) return;
219
- const vary = withVary(headers.get("Vary"), "Accept-Encoding");
220
- if (vary != null) headers.set("Vary", vary);
221
- if (forbidsTransform(hookedHeaders(context, headers).get("Cache-Control"))) return;
222
- const encoding = preferredEncoding(context.req.header("Accept-Encoding"), copies.map((copy) => copy.encoding));
223
- return copies.find((copy) => copy.encoding === encoding);
224
- }
225
- /**
226
- * All bytes of a file. Why the size as a range: the body then never has more
227
- * bytes than its `Content-Length`, even when the file grew after `stat`, and
228
- * a small file reads into a small buffer.
229
- */
230
- async function wholeFile(files, file) {
231
- return file.size === 0 ? null : files.open(file.path, {
232
- start: 0,
233
- end: file.size - 1
234
- });
235
- }
236
- /**
237
- * The response for a static file, with a weak ETag from its size,
238
- * modification time, the request's `etagParts`, and its encoding. A matching
239
- * `If-None-Match` gets a 304, and `HEAD` gets the headers only.
240
- *
241
- * A GET with one `bytes` range gets a 206 with those bytes, and a range
242
- * after the end of the file gets a 416. A request with `If-Range` gets the
243
- * full file. Why: the ETag is weak, and `If-Range` needs a strong match. An
244
- * HTML file gets no ranges.
245
- *
246
- * When the build wrote a compressed copy of the file (`.<file>.br` or
247
- * `.<file>.gz`), the response gets `Vary: Accept-Encoding`. A request gets
248
- * the copy that its `Accept-Encoding` prefers, brotli before gzip, with its
249
- * `Content-Encoding`, an ETag for that encoding, and no range. A response
250
- * marked `no-transform`, also by the header hook of an earlier stage, and a
251
- * response that `headers` encode, never get a copy. An HTML file gets no
252
- * copy when an earlier stage sets `rewritesHtml`.
253
- *
254
- * @example
255
- * const file = await findStaticFile(files, "/llms.txt");
256
- * if (file != null) {
257
- * return staticResponse(context, { files, file, headers: {}, contentTypes: {} });
258
- * }
259
- */
260
- async function staticResponse(context, { files, file, headers, contentTypes }) {
261
- const responseHeaders = new Headers({ "Content-Type": contentType(file.path, contentTypes) });
262
- for (const [name, value] of Object.entries(headers)) responseHeaders.set(name, value);
263
- const html = responseHeaders.get("Content-Type")?.startsWith("text/html") ?? false;
264
- if (html) context.set("staticDocument", file.path);
265
- const copy = await preferredCopy(context, {
266
- files,
267
- path: file.path,
268
- headers: responseHeaders
269
- });
270
- const etag = responseHeaders.get("ETag") ?? await fileEtag(file, context.get("etagParts") ?? [], copy?.encoding);
271
- responseHeaders.set("ETag", etag);
272
- if (matchesEtag(context.req.header("If-None-Match"), etag)) {
273
- responseHeaders.delete("Content-Type");
274
- return new Response(null, {
275
- status: 304,
276
- headers: responseHeaders
277
- });
278
- }
279
- if (copy != null) {
280
- responseHeaders.set("Content-Encoding", copy.encoding);
281
- responseHeaders.set("Content-Length", String(copy.size));
282
- const body = context.req.method === "HEAD" ? null : await wholeFile(files, copy);
283
- return new Response(body, { headers: responseHeaders });
284
- }
285
- if (!html) responseHeaders.set("Accept-Ranges", "bytes");
286
- responseHeaders.set("Content-Length", String(file.size));
287
- if (context.req.method === "HEAD") return new Response(null, { headers: responseHeaders });
288
- const rangeHeader = context.req.header("Range");
289
- const range = html || rangeHeader == null || context.req.header("If-Range") != null ? void 0 : byteRange(rangeHeader, file.size);
290
- if (range === "unsatisfiable") {
291
- responseHeaders.set("Content-Range", `bytes */${file.size}`);
292
- responseHeaders.delete("Content-Length");
293
- return new Response(null, {
294
- status: 416,
295
- headers: responseHeaders
296
- });
297
- }
298
- if (range != null) {
299
- responseHeaders.set("Content-Range", `bytes ${range.start}-${range.end}/${file.size}`);
300
- responseHeaders.set("Content-Length", String(range.end - range.start + 1));
301
- return new Response(await files.open(file.path, range), {
302
- status: 206,
303
- headers: responseHeaders
304
- });
305
- }
306
- return new Response(await wholeFile(files, file), { headers: responseHeaders });
307
- }
308
-
309
- export { keptFiles as a, isFilePath as i, findStaticFile as n, staticResponse as o, hasDotSegment as r, withVary as s, contentType as t };
310
- //# sourceMappingURL=static-files-C2ea8KQ6.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"static-files-C2ea8KQ6.js","names":[],"sources":["../src/core/vary.ts","../src/core/static-files.ts"],"sourcesContent":["/**\n * A `Vary` value with `name` added, or `undefined` when `vary` already covers\n * it. The existing values stay as they are.\n *\n * @example\n * withVary(\"Accept\", \"Accept-Encoding\"); // => \"Accept, Accept-Encoding\"\n * withVary(\"accept-encoding\", \"Accept-Encoding\"); // => undefined\n */\nexport function withVary(vary: string | null, name: string): string | undefined {\n\tif (vary == null || vary.trim() === \"\") {\n\t\treturn name;\n\t}\n\tconst values = new Set(vary.split(\",\").map((value) => value.trim().toLowerCase()));\n\treturn values.has(name.toLowerCase()) || values.has(\"*\") ? undefined : `${vary}, ${name}`;\n}\n","import type { Context } from \"hono\";\nimport { getMimeType } from \"hono/utils/mime\";\nimport { COPY_ENCODINGS, copyName, forbidsTransform, preferredEncoding } from \"./compression.js\";\nimport type { Encoding } from \"./compression.js\";\nimport { hookedHeaders } from \"./header-hook.js\";\nimport type { AppServerEnv, ByteRange, StaticFiles } from \"./types.js\";\nimport { withVary } from \"./vary.js\";\n\n/** A file under the client build that answers a request. */\nexport type StaticFile = {\n\t/** The URL path of the file, such as `/components/button/index.html`. */\n\tpath: string;\n\tsize: number;\n\tmtimeMs: number;\n};\n\n/** The content types that `mime` lacks and that no framework owns. */\nconst CORE_CONTENT_TYPES: Readonly<Record<string, string>> = {\n\t\".atom\": \"application/atom+xml\",\n\t\".md\": \"text/markdown; charset=utf-8\",\n\t\".pem\": \"application/x-pem-file\",\n\t\".rss\": \"application/rss+xml\",\n\t\".sh\": \"application/x-sh\",\n\t// Why `text/yaml`: a browser shows a text type, and `express.static` sends it.\n\t\".yaml\": \"text/yaml; charset=utf-8\",\n\t\".yml\": \"text/yaml; charset=utf-8\",\n};\n\n/**\n * Whether a URL path names a dotfile or goes through a dot directory.\n * `/.well-known/` stays reachable.\n *\n * @example\n * hasDotSegment(\"/assets/.private/key.json\"); // => true\n * hasDotSegment(\"/.well-known/security.txt\"); // => false\n */\nexport function hasDotSegment(path: string): boolean {\n\treturn path\n\t\t.split(\"/\")\n\t\t.some(\n\t\t\t(segment, index) => segment.startsWith(\".\") && !(index === 1 && segment === \".well-known\"),\n\t\t);\n}\n\n/**\n * Whether a decoded URL path, such as Hono's `context.req.path`, can name a\n * file of the client build. Dotfiles, paths that leave the client build, and\n * a second URL for a file, such as `/a//b` or `/a/index.html`, cannot.\n */\nexport function isFilePath(path: string): boolean {\n\treturn (\n\t\tpath.startsWith(\"/\") &&\n\t\t!path.includes(\"\\0\") &&\n\t\t!path.includes(\"\\\\\") &&\n\t\t!path.split(\"/\").includes(\"..\") &&\n\t\t!path.includes(\"//\") &&\n\t\t!path.endsWith(\"/index.html\") &&\n\t\t!hasDotSegment(path)\n\t);\n}\n\n/**\n * Finds the file in `files` that answers a decoded URL path, such as Hono's\n * `context.req.path`. A directory answers with its `index.html` and no\n * redirect, so a prerendered page keeps its URL. A path that fails\n * `isFilePath` finds nothing.\n *\n * Each file has one URL, because the headers for a file are keyed by that\n * URL. So `/a//b`, `/a/index.html`, and `/a%2Fb` find nothing. Hono decodes\n * the path but keeps an encoded `/` as `%2F`, so this function does not\n * decode it again.\n *\n * @example\n * await findStaticFile(files, \"/components/button\");\n * // => { path: \"/components/button/index.html\", size: 5120, mtimeMs: 1761652800000 }\n */\nexport async function findStaticFile(\n\tfiles: StaticFiles,\n\tpath: string,\n): Promise<StaticFile | undefined> {\n\tif (!isFilePath(path)) {\n\t\treturn undefined;\n\t}\n\tconst info = await files.stat(path);\n\tif (info?.kind === \"file\") {\n\t\treturn { path, size: info.size, mtimeMs: info.mtimeMs };\n\t}\n\tif (info?.kind === \"directory\") {\n\t\tconst index = `${path.replace(/\\/$/u, \"\")}/index.html`;\n\t\tconst indexInfo = await files.stat(index);\n\t\tif (indexInfo?.kind === \"file\") {\n\t\t\treturn { path: index, size: indexInfo.size, mtimeMs: indexInfo.mtimeMs };\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** The content type of a file, by its extension. `contentTypes` win over `mime`. */\nexport function contentType(path: string, contentTypes: Readonly<Record<string, string>>): string {\n\tconst extension = /\\.[^./]+$/u.exec(path)?.[0] ?? \"\";\n\treturn (\n\t\tcontentTypes[extension] ??\n\t\tCORE_CONTENT_TYPES[extension] ??\n\t\tgetMimeType(path) ??\n\t\t\"application/octet-stream\"\n\t);\n}\n\n/** An ETag without its weak prefix, for the weak comparison that `If-None-Match` uses. */\nfunction opaqueTag(etag: string): string {\n\treturn etag.trim().replace(/^W\\//u, \"\");\n}\n\n/** Whether an `If-None-Match` header lists an ETag. */\nfunction matchesEtag(ifNoneMatch: string | undefined, etag: string): boolean {\n\treturn (\n\t\tifNoneMatch?.split(\",\").some((candidate) => {\n\t\t\tconst trimmed = candidate.trim();\n\t\t\treturn trimmed === \"*\" || opaqueTag(trimmed) === opaqueTag(etag);\n\t\t}) ?? false\n\t);\n}\n\n/**\n * The last `etagParts` and their hash. Why one entry: each request has the\n * same parts for the life of the process.\n */\nlet lastParts: { key: string; hash: string } | undefined;\n\n/** A short hash of the request's `etagParts`. */\nasync function partsHash(parts: readonly string[]): Promise<string> {\n\tconst key = parts.join(\"\\0\");\n\tif (lastParts?.key === key) {\n\t\treturn lastParts.hash;\n\t}\n\t// Why Web Crypto: each host has it, and the core imports no Node module.\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(key));\n\tconst hash = btoa(String.fromCodePoint(...new Uint8Array(digest)))\n\t\t.replaceAll(\"+\", \"-\")\n\t\t.replaceAll(\"/\", \"_\")\n\t\t.slice(0, 16);\n\tlastParts = { key, hash };\n\treturn hash;\n}\n\n/**\n * A weak ETag from a file's size, its modification time, the request's\n * `etagParts`, and the encoding of the body. Why the encoding: after a 304,\n * a cache that holds more than one encoding of the file picks the stored\n * response by its ETag (RFC 9111, section 4.3.4).\n */\nasync function fileEtag(\n\tfile: StaticFile,\n\tparts: readonly string[],\n\tencoding: Encoding | undefined,\n): Promise<string> {\n\tconst tag = [\n\t\tfile.size.toString(16),\n\t\tMath.trunc(file.mtimeMs).toString(16),\n\t\t...(parts.length === 0 ? [] : [await partsHash(parts)]),\n\t\t...(encoding == null ? [] : [encoding]),\n\t];\n\treturn `W/\"${tag.join(\"-\")}\"`;\n}\n\n/**\n * The byte range that a `Range` header asks for in a file of `size` bytes.\n * It gives `\"unsatisfiable\"` for a range that starts after the end of the\n * file, and `undefined` for a header to ignore: a header that is not valid,\n * or one with more than one range.\n *\n * @example\n * byteRange(\"bytes=-100\", 1000); // => { start: 900, end: 999 }\n */\nexport function byteRange(header: string, size: number): ByteRange | \"unsatisfiable\" | undefined {\n\tconst groups = /^bytes=(?<first>\\d*)-(?<last>\\d*)$/u.exec(header.trim())?.groups;\n\tconst first = groups?.first ?? \"\";\n\tconst last = groups?.last ?? \"\";\n\tif (first === \"\" && last === \"\") {\n\t\treturn undefined;\n\t}\n\tif (first === \"\") {\n\t\tconst suffix = Number(last);\n\t\treturn suffix === 0 || size === 0\n\t\t\t? \"unsatisfiable\"\n\t\t\t: { start: Math.max(0, size - suffix), end: size - 1 };\n\t}\n\tconst start = Number(first);\n\tconst end = last === \"\" ? Number.POSITIVE_INFINITY : Number(last);\n\tif (end < start) {\n\t\treturn undefined;\n\t}\n\treturn start >= size ? \"unsatisfiable\" : { start, end: Math.min(end, size - 1) };\n}\n\n/** Why these caps: they hold the hashed chunks of a typical app, and they limit the memory of each process. */\nconst KEPT_FILE_BYTES = 256 * 1024;\nconst KEPT_TOTAL_BYTES = 32 * 1024 * 1024;\n\n/**\n * `files` that keep the bytes of each small file in memory after the first\n * read, up to {@link KEPT_TOTAL_BYTES} in all. Use it only for files that\n * do not change while the server runs, such as a `StaticFiles.snapshot()`.\n *\n * @example\n * const files = keptFiles(await nodeFiles(\"build/client\").snapshot());\n */\nexport function keptFiles(files: StaticFiles): StaticFiles {\n\tconst kept = new Map<string, Promise<Uint8Array>>();\n\tlet total = 0;\n\treturn {\n\t\tstat: files.stat,\n\t\topen: async (path, range) => {\n\t\t\tlet bytes = kept.get(path);\n\t\t\tconst info = bytes == null ? await files.stat(path) : undefined;\n\t\t\t// Why again: another request can start to read the file during the `stat`.\n\t\t\tbytes ??= kept.get(path);\n\t\t\tif (bytes == null) {\n\t\t\t\tif (\n\t\t\t\t\tinfo?.kind !== \"file\" ||\n\t\t\t\t\tinfo.size > KEPT_FILE_BYTES ||\n\t\t\t\t\ttotal + info.size > KEPT_TOTAL_BYTES\n\t\t\t\t) {\n\t\t\t\t\treturn files.open(path, range);\n\t\t\t\t}\n\t\t\t\ttotal += info.size;\n\t\t\t\t// Why the size as a range: the kept bytes then match the `Content-Length` from the lookup.\n\t\t\t\tbytes = files\n\t\t\t\t\t.open(path, { start: 0, end: info.size - 1 })\n\t\t\t\t\t.then(async (stream) => new Uint8Array(await new Response(stream).arrayBuffer()));\n\t\t\t\tkept.set(path, bytes);\n\t\t\t\tbytes.catch(() => {\n\t\t\t\t\tkept.delete(path);\n\t\t\t\t\ttotal -= info.size;\n\t\t\t\t});\n\t\t\t}\n\t\t\t// Why a copy: a later stage can change the bytes that it reads.\n\t\t\tconst chunk = (await bytes).slice(\n\t\t\t\trange?.start ?? 0,\n\t\t\t\trange == null ? undefined : range.end + 1,\n\t\t\t);\n\t\t\treturn new ReadableStream<Uint8Array>({\n\t\t\t\tstart(controller) {\n\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\tcontroller.close();\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t};\n}\n\n/** A compressed copy of a static file that the build wrote. */\ntype Copy = StaticFile & { encoding: Encoding };\n\n/**\n * The copy of the file at `path` that the request prefers, from the copies\n * that the build wrote. When a copy exists, it adds `Accept-Encoding` to the\n * `Vary` in `headers`, also for a request that gets no copy.\n */\nasync function preferredCopy(\n\tcontext: Context<AppServerEnv>,\n\t{ files, path, headers }: { files: StaticFiles; path: string; headers: Headers },\n): Promise<Copy | undefined> {\n\t// Why not for an encoded file: the copy would encode it again, under one `Content-Encoding`.\n\tif (\n\t\theaders.has(\"Content-Encoding\") ||\n\t\t(context.get(\"rewritesHtml\") === true &&\n\t\t\t(headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false))\n\t) {\n\t\treturn undefined;\n\t}\n\tconst copies: Copy[] = [];\n\tfor (const encoding of COPY_ENCODINGS) {\n\t\tconst copyPath = path.replace(/[^/]*$/u, (name) => copyName(name, encoding));\n\t\t// oxlint-disable-next-line no-await-in-loop -- two lookups, and a snapshot answers each at once.\n\t\tconst info = await files.stat(copyPath);\n\t\tif (info?.kind === \"file\") {\n\t\t\tcopies.push({ path: copyPath, size: info.size, mtimeMs: info.mtimeMs, encoding });\n\t\t}\n\t}\n\tif (copies.length === 0) {\n\t\treturn undefined;\n\t}\n\tconst vary = withVary(headers.get(\"Vary\"), \"Accept-Encoding\");\n\tif (vary != null) {\n\t\theaders.set(\"Vary\", vary);\n\t}\n\tif (forbidsTransform(hookedHeaders(context, headers).get(\"Cache-Control\"))) {\n\t\treturn undefined;\n\t}\n\tconst encoding = preferredEncoding(\n\t\tcontext.req.header(\"Accept-Encoding\"),\n\t\tcopies.map((copy) => copy.encoding),\n\t);\n\treturn copies.find((copy) => copy.encoding === encoding);\n}\n\n/**\n * All bytes of a file. Why the size as a range: the body then never has more\n * bytes than its `Content-Length`, even when the file grew after `stat`, and\n * a small file reads into a small buffer.\n */\nasync function wholeFile(\n\tfiles: StaticFiles,\n\tfile: StaticFile,\n): Promise<ReadableStream<Uint8Array> | null> {\n\treturn file.size === 0 ? null : files.open(file.path, { start: 0, end: file.size - 1 });\n}\n\n/** What {@link staticResponse} needs besides the request. */\nexport type StaticResponseOptions = {\n\tfiles: StaticFiles;\n\tfile: StaticFile;\n\t/** Headers that replace the defaults, so a captured `Content-Type` wins over the one from the file name. */\n\theaders: Readonly<Record<string, string>>;\n\tcontentTypes: Readonly<Record<string, string>>;\n};\n\n/**\n * The response for a static file, with a weak ETag from its size,\n * modification time, the request's `etagParts`, and its encoding. A matching\n * `If-None-Match` gets a 304, and `HEAD` gets the headers only.\n *\n * A GET with one `bytes` range gets a 206 with those bytes, and a range\n * after the end of the file gets a 416. A request with `If-Range` gets the\n * full file. Why: the ETag is weak, and `If-Range` needs a strong match. An\n * HTML file gets no ranges.\n *\n * When the build wrote a compressed copy of the file (`.<file>.br` or\n * `.<file>.gz`), the response gets `Vary: Accept-Encoding`. A request gets\n * the copy that its `Accept-Encoding` prefers, brotli before gzip, with its\n * `Content-Encoding`, an ETag for that encoding, and no range. A response\n * marked `no-transform`, also by the header hook of an earlier stage, and a\n * response that `headers` encode, never get a copy. An HTML file gets no\n * copy when an earlier stage sets `rewritesHtml`.\n *\n * @example\n * const file = await findStaticFile(files, \"/llms.txt\");\n * if (file != null) {\n * return staticResponse(context, { files, file, headers: {}, contentTypes: {} });\n * }\n */\nexport async function staticResponse(\n\tcontext: Context<AppServerEnv>,\n\t{ files, file, headers, contentTypes }: StaticResponseOptions,\n): Promise<Response> {\n\tconst responseHeaders = new Headers({ \"Content-Type\": contentType(file.path, contentTypes) });\n\tfor (const [name, value] of Object.entries(headers)) {\n\t\tresponseHeaders.set(name, value);\n\t}\n\t// Why no ranges for HTML: a stage such as `runtimeEnv` can change the bytes of a page.\n\tconst html = responseHeaders.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false;\n\tif (html) {\n\t\tcontext.set(\"staticDocument\", file.path);\n\t}\n\t// Why before the 304: a 304 sends the `Vary` and the ETag of its 200.\n\tconst copy = await preferredCopy(context, { files, path: file.path, headers: responseHeaders });\n\t// Why the header first: `headers` can replace the ETag.\n\tconst etag =\n\t\tresponseHeaders.get(\"ETag\") ??\n\t\t(await fileEtag(file, context.get(\"etagParts\") ?? [], copy?.encoding));\n\tresponseHeaders.set(\"ETag\", etag);\n\tif (matchesEtag(context.req.header(\"If-None-Match\"), etag)) {\n\t\tresponseHeaders.delete(\"Content-Type\");\n\t\treturn new Response(null, { status: 304, headers: responseHeaders });\n\t}\n\tif (copy != null) {\n\t\t// Why no ranges: a client asks for a range of the file, not of its compressed copy.\n\t\tresponseHeaders.set(\"Content-Encoding\", copy.encoding);\n\t\tresponseHeaders.set(\"Content-Length\", String(copy.size));\n\t\tconst body = context.req.method === \"HEAD\" ? null : await wholeFile(files, copy);\n\t\treturn new Response(body, { headers: responseHeaders });\n\t}\n\tif (!html) {\n\t\tresponseHeaders.set(\"Accept-Ranges\", \"bytes\");\n\t}\n\tresponseHeaders.set(\"Content-Length\", String(file.size));\n\tif (context.req.method === \"HEAD\") {\n\t\treturn new Response(null, { headers: responseHeaders });\n\t}\n\tconst rangeHeader = context.req.header(\"Range\");\n\tconst range =\n\t\thtml || rangeHeader == null || context.req.header(\"If-Range\") != null\n\t\t\t? undefined\n\t\t\t: byteRange(rangeHeader, file.size);\n\tif (range === \"unsatisfiable\") {\n\t\tresponseHeaders.set(\"Content-Range\", `bytes */${file.size}`);\n\t\tresponseHeaders.delete(\"Content-Length\");\n\t\treturn new Response(null, { status: 416, headers: responseHeaders });\n\t}\n\tif (range != null) {\n\t\tresponseHeaders.set(\"Content-Range\", `bytes ${range.start}-${range.end}/${file.size}`);\n\t\tresponseHeaders.set(\"Content-Length\", String(range.end - range.start + 1));\n\t\treturn new Response(await files.open(file.path, range), {\n\t\t\tstatus: 206,\n\t\t\theaders: responseHeaders,\n\t\t});\n\t}\n\treturn new Response(await wholeFile(files, file), { headers: responseHeaders });\n}\n"],"mappings":";;;;;;;;;;;;;AAQA,SAAgB,SAAS,MAAqB,MAAkC;CAC/E,IAAI,QAAQ,QAAQ,KAAK,KAAK,MAAM,IACnC,OAAO;CAER,MAAM,SAAS,IAAI,IAAI,KAAK,MAAM,GAAG,CAAC,CAAC,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,YAAY,CAAC,CAAC;CACjF,OAAO,OAAO,IAAI,KAAK,YAAY,CAAC,KAAK,OAAO,IAAI,GAAG,IAAI,SAAY,GAAG,KAAK,IAAI;AACpF;;;;ACGA,MAAM,qBAAuD;CAC5D,SAAS;CACT,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,OAAO;CAEP,SAAS;CACT,QAAQ;AACT;;;;;;;;;AAUA,SAAgB,cAAc,MAAuB;CACpD,OAAO,KACL,MAAM,GAAG,CAAC,CACV,MACC,SAAS,UAAU,QAAQ,WAAW,GAAG,KAAK,EAAE,UAAU,KAAK,YAAY,cAC7E;AACF;;;;;;AAOA,SAAgB,WAAW,MAAuB;CACjD,OACC,KAAK,WAAW,GAAG,KACnB,CAAC,KAAK,SAAS,IAAI,KACnB,CAAC,KAAK,SAAS,IAAI,KACnB,CAAC,KAAK,MAAM,GAAG,CAAC,CAAC,SAAS,IAAI,KAC9B,CAAC,KAAK,SAAS,IAAI,KACnB,CAAC,KAAK,SAAS,aAAa,KAC5B,CAAC,cAAc,IAAI;AAErB;;;;;;;;;;;;;;;;AAiBA,eAAsB,eACrB,OACA,MACkC;CAClC,IAAI,CAAC,WAAW,IAAI,GACnB;CAED,MAAM,OAAO,MAAM,MAAM,KAAK,IAAI;CAClC,IAAI,MAAM,SAAS,QAClB,OAAO;EAAE;EAAM,MAAM,KAAK;EAAM,SAAS,KAAK;CAAQ;CAEvD,IA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,SAAS,gBAAgB,CAAC;CACvD;CACA,IAAI,CAAC,MACJ,gBAAgB,IAAI,iBAAiB,OAAO;CAE7C,gBAAgB,IAAI,kBAAkB,OAAO,KAAK,IAAI,CAAC;CACvD,IAAI,QAAQ,IAAI,WAAW,QAC1B,OAAO,IAAI,SAAS,MAAM,EAAE,SAAS,gBAAgB,CAAC;CAEvD,MAAM,cAAc,QAAQ,IAAI,OAAO,OAAO;CAC9C,MAAM,QACL,QAAQ,eAAe,QAAQ,QAAQ,IAAI,OAAO,UAAU,KAAK,OAC9D,SACA,UAAU,aAAa,KAAK,IAAI;CACpC,IAAI,UAAU,iBAAiB;EAC9B,gBAAgB,IAAI,iBAAiB,WAAW,KAAK,MAAM;EAC3D,gBAAgB,OAAO,gBAAgB;EACvC,OAAO,IAAI,SAAS,MAAM;GAAE,QAAQ;GAAK,SAAS;EAAgB,CAAC;CACpE;CACA,IAAI,SAAS,MAAM;EAClB,gBAAgB,IAAI,iBAAiB,SAAS,MAAM,MAAM,GAAG,MAAM,IAAI,GAAG,KAAK,MAAM;EACrF,gBAAgB,IAAI,kBAAkB,OAAO,MAAM,MAAM,MAAM,QAAQ,CAAC,CAAC;EACzE,OAAO,IAAI,SAAS,MAAM,MAAM,KAAK,KAAK,MAAM,KAAK,GAAG;GACvD,QAAQ;GACR,SAAS;EACV,CAAC;CACF;CACA,OAAO,IAAI,SAAS,MAAM,UAAU,OAAO,IAAI,GAAG,EAAE,SAAS,gBAAgB,CAAC;AAC/E"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"tanstack-start.js","names":[],"sources":["../src/tanstack-start/index.ts"],"sourcesContent":["import type { AnyRouter, RegisteredRouter } from \"@tanstack/react-router\";\nimport type { TrailingSlash } from \"../core/plugins/trailing-slash.js\";\nimport { requestContextValues } from \"../core/request-context.js\";\nimport type { FrameworkRuntime, Mode } from \"../core/types.js\";\n\n/**\n * The `trailingSlash` mode of a TanStack router: the app's registered router\n * by default. A router with no `trailingSlash` has the mode `never`. With no\n * registered router, it is every mode.\n *\n * Use it with `satisfies` on the server's mode. TypeScript then fails when the\n * two modes differ, because different modes make the redirects loop.\n *\n * @example\n * createServer({ plugins: defaultPlugins({ trailingSlash: \"never\" satisfies RouterTrailingSlash }) });\n */\nexport type RouterTrailingSlash<TRouter extends AnyRouter = RegisteredRouter> = ModeOf<\n\tTRouter[\"options\"][\"trailingSlash\"]\n>;\n\n/** A router's `trailingSlash` type as a mode. Why the `any` test: `AnyRouter` has an `any` mode, and a conditional type makes `never` of it. */\ntype ModeOf<TOption> = 0 extends 1 & TOption\n\t? TrailingSlash\n\t: NonNullable<TOption> extends infer TMode extends TrailingSlash\n\t\t? TMode\n\t\t: TrailingSlash;\n\n/** The prefix of Start's server functions when the config sets none. */\nconst DEFAULT_SERVER_FN_BASE = \"/_serverFn/\";\n\n/** The part of a TanStack Start server entry that the adapter calls. */\ntype StartServerEntry = {\n\tfetch: (\n\t\trequest: Request,\n\t\toptions?: { context?: Record<string, unknown> },\n\t) => Response | Promise<Response>;\n};\n\n/** Whether a module's default export is a TanStack Start server entry. */\nfunction startServerEntry(module: unknown): StartServerEntry | undefined {\n\tif (typeof module !== \"object\" || module == null) {\n\t\treturn undefined;\n\t}\n\tconst entry: unknown = Reflect.get(module, \"default\");\n\tif (typeof entry !== \"object\" || entry == null || !(\"fetch\" in entry)) {\n\t\treturn undefined;\n\t}\n\tconst { fetch } = entry;\n\tif (typeof fetch !== \"function\") {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tfetch: async (request, options) => {\n\t\t\tconst response: unknown = await Reflect.apply(fetch, entry, [request, options]);\n\t\t\tif (!(response instanceof Response)) {\n\t\t\t\tthrow new TypeError(\"The TanStack Start server entry did not return a Response.\");\n\t\t\t}\n\t\t\treturn response;\n\t\t},\n\t};\n}\n\n/**\n * The run side of the TanStack Start adapter, for the module of Start's\n * server entry. Start gets the `requestContext()` values as `appServer` in its\n * request context. The server reads the prerendered paths that the Vite plugin\n * recorded.\n *\n * @param info.serverFnBase - The prefix of Start's server functions, `TSS_SERVER_FN_BASE`. The entry that the Vite plugin generates sets it.\n *\n * @example\n * const framework = runtime(await import(\"virtual:tanstack-start-server-entry\"), { mode: \"production\" });\n */\nexport function runtime(\n\tserverModule: unknown,\n\t{ serverFnBase = DEFAULT_SERVER_FN_BASE }: { mode: Mode; serverFnBase?: string },\n): FrameworkRuntime {\n\tconst entry = startServerEntry(serverModule);\n\tif (entry == null) {\n\t\tthrow new Error(\"The server module has no TanStack Start server entry as its default export.\");\n\t}\n\treturn {\n\t\tname: \"tanstack-start\",\n\t\tisDataRequest: (path) => path.startsWith(serverFnBase),\n\t\tfetch: async (request, context) =>\n\t\t\tentry.fetch(request, {\n\t\t\t\tcontext: {\n\t\t\t\t\tappServer: requestContextValues(context),\n\t\t\t\t},\n\t\t\t}),\n\t};\n}\n"],"mappings":";;;;AA4BA,MAAM,yBAAyB;;AAW/B,SAAS,iBAAiB,QAA+C;CACxE,IAAI,OAAO,WAAW,YAAY,UAAU,MAC3C;CAED,MAAM,QAAiB,QAAQ,IAAI,QAAQ,SAAS;CACpD,IAAI,OAAO,UAAU,YAAY,SAAS,QAAQ,EAAE,WAAW,QAC9D;CAED,MAAM,EAAE,UAAU;CAClB,IAAI,OAAO,UAAU,YACpB;CAED,OAAO,EACN,OAAO,OAAO,SAAS,YAAY;EAClC,MAAM,WAAoB,MAAM,QAAQ,MAAM,OAAO,OAAO,CAAC,SAAS,OAAO,CAAC;EAC9E,IAAI,EAAE,oBAAoB,WACzB,MAAM,IAAI,UAAU,4DAA4D;EAEjF,OAAO;CACR,EACD;AACD;;;;;;;;;;;;AAaA,SAAgB,QACf,cACA,EAAE,eAAe,0BACE;CACnB,MAAM,QAAQ,iBAAiB,YAAY;CAC3C,IAAI,SAAS,MACZ,MAAM,IAAI,MAAM,6EAA6E;CAE9F,OAAO;EACN,MAAM;EACN,gBAAgB,SAAS,KAAK,WAAW,YAAY;EACrD,OAAO,OAAO,SAAS,YACtB,MAAM,MAAM,SAAS,EACpB,SAAS,EACR,WAAW,qBAAqB,OAAO,EACxC,EACD,CAAC;CACH;AACD"}
@@ -1,42 +0,0 @@
1
- // src/node/tcp.ts
2
- /** Above the ngrok edge's 90 s idle pool, so the edge never reuses a socket that the server is closing. */
3
- const DEFAULT_IDLE_TIMEOUT_MS = 95e3;
4
- /**
5
- * Reads a port number. A value that is not an integer from 0 to 65535 throws,
6
- * so a bad `PORT` stops startup.
7
- *
8
- * @example
9
- * parsePort("8080"); // => 8080
10
- */
11
- function parsePort(value) {
12
- const port = Number(value);
13
- if (value.trim() === "" || !Number.isInteger(port) || port < 0 || port > 65535) throw new Error(`PORT must be an integer from 0 to 65535, not "${value}".`);
14
- return port;
15
- }
16
- /**
17
- * The default listener: a TCP port, served by the runtime's own HTTP server
18
- * (`node:http` on Node, `Bun.serve` on Bun, `Deno.serve` on Deno). It reads
19
- * `PORT` and `HOST` when it starts.
20
- *
21
- * @example
22
- * createServer({ listeners: [tcp({ port: 8080 })] });
23
- */
24
- function tcp({ port, host, idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS } = {}) {
25
- return {
26
- name: "tcp",
27
- start: async (fetch, { trustForwardedProto = false } = {}) => {
28
- const options = {
29
- port: port ?? (process.env.PORT == null ? 3e3 : parsePort(process.env.PORT)),
30
- hostname: host ?? (process.env.HOST || void 0),
31
- idleTimeoutMs,
32
- trustForwardedProto
33
- };
34
- if ("Bun" in globalThis) return (await import("./bun-BCz6K_Xv.js")).listen(fetch, options);
35
- if ("Deno" in globalThis) return (await import("./deno-aqhikNMG.js")).listen(fetch, options);
36
- return (await import("./node-D6m6e6EI.js")).listen(fetch, options);
37
- }
38
- };
39
- }
40
-
41
- export { tcp as n, parsePort as t };
42
- //# sourceMappingURL=tcp-BgDXbjOG.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"tcp-BgDXbjOG.js","names":[],"sources":["../src/node/tcp.ts"],"sourcesContent":["import type { Listener } from \"../core/types.js\";\n\n/** Above the ngrok edge's 90 s idle pool, so the edge never reuses a socket that the server is closing. */\nconst DEFAULT_IDLE_TIMEOUT_MS = 95_000;\n\n/** Options for {@link tcp}. */\nexport type TcpOptions = {\n\t/** @default the `PORT` environment variable, else 3000 */\n\tport?: number;\n\t/** @default the `HOST` environment variable, else every interface */\n\thost?: string;\n\t/** @default 95000 */\n\tidleTimeoutMs?: number;\n};\n\n/**\n * Reads a port number. A value that is not an integer from 0 to 65535 throws,\n * so a bad `PORT` stops startup.\n *\n * @example\n * parsePort(\"8080\"); // => 8080\n */\nexport function parsePort(value: string): number {\n\tconst port = Number(value);\n\tif (value.trim() === \"\" || !Number.isInteger(port) || port < 0 || port > 65_535) {\n\t\tthrow new Error(`PORT must be an integer from 0 to 65535, not \"${value}\".`);\n\t}\n\treturn port;\n}\n\n/**\n * The default listener: a TCP port, served by the runtime's own HTTP server\n * (`node:http` on Node, `Bun.serve` on Bun, `Deno.serve` on Deno). It reads\n * `PORT` and `HOST` when it starts.\n *\n * @example\n * createServer({ listeners: [tcp({ port: 8080 })] });\n */\nexport function tcp({\n\tport,\n\thost,\n\tidleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS,\n}: TcpOptions = {}): Listener {\n\treturn {\n\t\tname: \"tcp\",\n\t\tstart: async (fetch, { trustForwardedProto = false } = {}) => {\n\t\t\tconst options = {\n\t\t\t\tport: port ?? (process.env.PORT == null ? 3000 : parsePort(process.env.PORT)),\n\t\t\t\thostname: host ?? (process.env.HOST || undefined),\n\t\t\t\tidleTimeoutMs,\n\t\t\t\ttrustForwardedProto,\n\t\t\t};\n\t\t\tif (\"Bun\" in globalThis) {\n\t\t\t\treturn (await import(\"./runtimes/bun.js\")).listen(fetch, options);\n\t\t\t}\n\t\t\tif (\"Deno\" in globalThis) {\n\t\t\t\treturn (await import(\"./runtimes/deno.js\")).listen(fetch, options);\n\t\t\t}\n\t\t\treturn (await import(\"./runtimes/node.js\")).listen(fetch, options);\n\t\t},\n\t};\n}\n"],"mappings":";;AAGA,MAAM,0BAA0B;;;;;;;;AAmBhC,SAAgB,UAAU,OAAuB;CAChD,MAAM,OAAO,OAAO,KAAK;CACzB,IAAI,MAAM,KAAK,MAAM,MAAM,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,OAAO,OACxE,MAAM,IAAI,MAAM,iDAAiD,MAAM,GAAG;CAE3E,OAAO;AACR;;;;;;;;;AAUA,SAAgB,IAAI,EACnB,MACA,MACA,gBAAgB,4BACD,CAAC,GAAa;CAC7B,OAAO;EACN,MAAM;EACN,OAAO,OAAO,OAAO,EAAE,sBAAsB,UAAU,CAAC,MAAM;GAC7D,MAAM,UAAU;IACf,MAAM,SAAS,QAAQ,IAAI,QAAQ,OAAO,MAAO,UAAU,QAAQ,IAAI,IAAI;IAC3E,UAAU,SAAS,QAAQ,IAAI,QAAQ;IACvC;IACA;GACD;GACA,IAAI,SAAS,YACZ,QAAQ,MAAM,OAAO,qBAAoB,CAAE,OAAO,OAAO,OAAO;GAEjE,IAAI,UAAU,YACb,QAAQ,MAAM,OAAO,sBAAqB,CAAE,OAAO,OAAO,OAAO;GAElE,QAAQ,MAAM,OAAO,sBAAqB,CAAE,OAAO,OAAO,OAAO;EAClE;CACD;AACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"testing.js","names":["runInRequestContext"],"sources":["../src/testing/index.ts"],"sourcesContent":["import { mkdir, mkdtemp, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, isAbsolute, join, normalize, sep } from \"node:path\";\nimport { Context } from \"hono\";\nimport { BUILD_MANIFEST_FILE } from \"../core/build-manifest.js\";\nimport type { BuildManifest } from \"../core/build-manifest.js\";\nimport type { AppServer } from \"../core/create-server.js\";\nimport { createEntry } from \"../core/entry.js\";\nimport type { AppServerEntry } from \"../core/entry.js\";\nimport { requestLogger } from \"../core/log.js\";\nimport { withRequestContext as runInRequestContext } from \"../core/request-context.js\";\nimport type { AppServerEnv, FrameworkRuntime, RequestContext } from \"../core/types.js\";\nimport { host } from \"../node/index.js\";\nimport { scriptHashesOf } from \"../node/script-hashes.js\";\n\n/** Options for {@link createTestServer}. */\nexport type TestServerOptions = {\n\t/**\n\t * The app from `createServer`. Give each test server a new app, because an\n\t * app runs the `setup` of its plugins one time.\n\t */\n\tapp: AppServer;\n\t/**\n\t * The files of the client build, by their path in it, such as\n\t * `providers/index.html`.\n\t */\n\tfiles?: Readonly<Record<string, string | Uint8Array>>;\n\t/**\n\t * The framework's answer to a request that no stage answers.\n\t * @default a 404\n\t */\n\tframework?: FrameworkRuntime[\"fetch\"];\n};\n\n/** What {@link createTestServer} gives. */\nexport type TestServer = {\n\t/** Sends a request for `path`, such as `/providers?q=h100`, through the app. */\n\trequest: (path: string, init?: RequestInit) => Promise<Response>;\n\t/**\n\t * Cancels each body that the test did not read, runs each plugin's\n\t * `onShutdown`, and removes the client build.\n\t */\n\tclose: () => Promise<void>;\n};\n\n/** Why: an app runs the `setup` of its plugins one time, so a second test server would get the files of the first. */\nconst usedApps = new WeakSet<AppServer>();\n\nasync function notFound(): Promise<Response> {\n\treturn new Response(\"Not Found\", { status: 404 });\n}\n\n/** Writes `files` and the build manifest into `clientDirectory`, and gives the app's entry over them. */\nasync function startEntry(\n\tclientDirectory: string,\n\t{ app, files, framework }: Required<TestServerOptions>,\n): Promise<AppServerEntry> {\n\tfor (const [path, content] of Object.entries(files)) {\n\t\tconst file = join(clientDirectory, path);\n\t\tawait mkdir(dirname(file), { recursive: true });\n\t\tawait writeFile(file, content);\n\t}\n\tconst manifest: BuildManifest = {\n\t\tprerendered: [],\n\t\theaders: {},\n\t\tscriptHashes: scriptHashesOf(clientDirectory),\n\t};\n\tawait writeFile(join(clientDirectory, BUILD_MANIFEST_FILE), JSON.stringify(manifest));\n\treturn createEntry({\n\t\tapp,\n\t\thost,\n\t\tclientDirectory,\n\t\tframework: () => ({ name: \"test\", fetch: framework }),\n\t});\n}\n\n/**\n * Starts an app in production mode over a client build of `files`, with no\n * listener. It records the hashes of the inline scripts of each HTML file, as\n * the build does, so `contentSecurityPolicy()` gives a prerendered page its\n * CSP. `requestContext()` and `cspNonce()` work in the framework's answer.\n *\n * @example\n * const server = await createTestServer({\n * \tapp: createServer({ plugins: defaultPlugins() }),\n * \tfiles: { \"providers/index.html\": \"<!doctype html><script>go()</script>\" },\n * \tframework: async () => new Response(\"rendered\"),\n * });\n * const response = await server.request(\"/providers\");\n * await server.close();\n */\nexport async function createTestServer({\n\tapp,\n\tfiles = {},\n\tframework = notFound,\n}: TestServerOptions): Promise<TestServer> {\n\tif (usedApps.has(app)) {\n\t\tthrow new Error(\n\t\t\t\"This app runs in another test server. Give each test server a new app from `createServer()`.\",\n\t\t);\n\t}\n\tfor (const path of Object.keys(files)) {\n\t\tif (isAbsolute(path) || normalize(path).split(sep)[0] === \"..\") {\n\t\t\tthrow new Error(\n\t\t\t\t`The file \"${path}\" is outside the client build. Give a relative path in it.`,\n\t\t\t);\n\t\t}\n\t}\n\tusedApps.add(app);\n\tconst clientDirectory = await mkdtemp(join(tmpdir(), \"app-server-test-\"));\n\tlet entry: AppServerEntry;\n\ttry {\n\t\tentry = await startEntry(clientDirectory, { app, files, framework });\n\t} catch (error) {\n\t\tusedApps.delete(app);\n\t\tawait rm(clientDirectory, { recursive: true, force: true });\n\t\tthrow error;\n\t}\n\tconst responses: Response[] = [];\n\treturn {\n\t\trequest: async (path, init) => {\n\t\t\tconst response = await entry.fetch(new Request(new URL(path, \"http://localhost\"), init));\n\t\t\tresponses.push(response);\n\t\t\treturn response;\n\t\t},\n\t\tclose: async () => {\n\t\t\t// Why cancel an unread body: it can hold an open file, and Node.js 26 throws when garbage\n\t\t\t// collection closes a `FileHandle`. Why `allSettled`: the cancel of a body that failed\n\t\t\t// rejects, and the test sees that error when it reads the body.\n\t\t\tawait Promise.allSettled(\n\t\t\t\tresponses.map(async ({ body }) => (body?.locked === false ? body.cancel() : undefined)),\n\t\t\t);\n\t\t\ttry {\n\t\t\t\tawait entry.stopPlugins();\n\t\t\t} finally {\n\t\t\t\tawait rm(clientDirectory, { recursive: true, force: true });\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Runs `work` as if in a server request, so `requestContext()` and\n * `cspNonce()` give `values`. Use it to test a render. With no `logger`, the\n * log lines go nowhere.\n *\n * @example\n * const html = await withRequestContext({ cspNonce: \"test-nonce\" }, () => renderToString(<App />));\n */\nexport async function withRequestContext<Result>(\n\tvalues: Partial<RequestContext>,\n\twork: () => Result | Promise<Result>,\n): Promise<Result> {\n\tconst context = new Context<AppServerEnv>(new Request(\"http://localhost/\"));\n\tcontext.set(\"logger\", values.logger ?? requestLogger({ log: () => {} }, context));\n\tif (values.requestId != null) {\n\t\tcontext.set(\"requestId\", values.requestId);\n\t}\n\tif (values.cspNonce != null) {\n\t\tcontext.set(\"cspNonce\", values.cspNonce);\n\t}\n\tcontext.set(\"clientAddress\", values.clientAddress);\n\treturn runInRequestContext(host.storage, context, async () => work());\n}\n"],"mappings":";;;;;;;;;;;;;AA8CA,MAAM,2BAAW,IAAI,QAAmB;AAExC,eAAe,WAA8B;CAC5C,OAAO,IAAI,SAAS,aAAa,EAAE,QAAQ,IAAI,CAAC;AACjD;;AAGA,eAAe,WACd,iBACA,EAAE,KAAK,OAAO,aACY;CAC1B,KAAK,MAAM,CAAC,MAAM,YAAY,OAAO,QAAQ,KAAK,GAAG;EACpD,MAAM,OAAO,KAAK,iBAAiB,IAAI;EACvC,MAAM,MAAM,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;EAC9C,MAAM,UAAU,MAAM,OAAO;CAC9B;CACA,MAAM,WAA0B;EAC/B,aAAa,CAAC;EACd,SAAS,CAAC;EACV,cAAc,eAAe,eAAe;CAC7C;CACA,MAAM,UAAU,KAAK,iBAAiB,mBAAmB,GAAG,KAAK,UAAU,QAAQ,CAAC;CACpF,OAAO,YAAY;EAClB;EACA;EACA;EACA,kBAAkB;GAAE,MAAM;GAAQ,OAAO;EAAU;CACpD,CAAC;AACF;;;;;;;;;;;;;;;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;CAChF,IAAI,OAAO,aAAa,MACvB,QAAQ,IAAI,aAAa,OAAO,SAAS;CAE1C,IAAI,OAAO,YAAY,MACtB,QAAQ,IAAI,YAAY,OAAO,QAAQ;CAExC,QAAQ,IAAI,iBAAiB,OAAO,aAAa;CACjD,OAAOA,qBAAoB,KAAK,SAAS,SAAS,YAAY,KAAK,CAAC;AACrE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"vercel-pages.js","names":[],"sources":["../src/vercel/pages.ts"],"sourcesContent":["// The step of `vercel()` that finds the prerendered pages that Vercel's content delivery network\n// (CDN) can serve with no function. `vercel()` runs it in a child process after the build:\n//\n// node vercel-pages.js <server entry> <static directory> <report file>\n//\n// Why a child process: the step starts the built server, and the build output must stay sync. A\n// plugin's `setup` can also leave a socket or a timer, so the process exits when the step ends.\n// Why no relative import: the build runs this file from `src` in the tests of this package.\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\n/** A prerendered path that the CDN serves, as `vercel()` writes it. */\nexport type CdnPageReport = {\n\tpath: string;\n\t/**\n\t * The URL path of the page's body under the static directory, such as\n\t * `/0/index.html`. Why not the page's file: two paths can have one file,\n\t * such as with `prerendered({ rewrite })`, and different bodies.\n\t */\n\tfile: string;\n\tanswers: { present: readonly string[]; headers: Readonly<Record<string, string>> }[];\n\ttwin?: string;\n};\n\n/** What the step found: the paths that the CDN serves, and why the function serves each other path. */\nexport type PagesReport = {\n\tcdn: CdnPageReport[];\n\tserver: { path: string; reason: string }[];\n};\n\n/** The part of the server entry that this step calls. */\ntype Entry = {\n\tstaticPages: () => AsyncIterable<\n\t\t{ path: string } & (\n\t\t\t| {\n\t\t\t\t\tcdn: { file: string; body: Uint8Array; answers: CdnPageReport[\"answers\"]; twin?: string };\n\t\t\t }\n\t\t\t| { reason: string }\n\t\t)\n\t>;\n\tstopPlugins: () => Promise<void>;\n};\n\nfunction isEntry(value: unknown): value is Entry {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t\"staticPages\" in value &&\n\t\ttypeof value.staticPages === \"function\" &&\n\t\t\"stopPlugins\" in value &&\n\t\ttypeof value.stopPlugins === \"function\"\n\t);\n}\n\n/**\n * Writes the body of each page that the CDN can serve to `staticDirectory`,\n * at the path of its file, and the {@link PagesReport} to `reportFile`.\n *\n * @example\n * await writePages(\"build/server/app-server.js\", \".vercel/output/static/_app-server/pages\", \"pages.json\");\n */\nexport async function writePages(\n\tentryFile: string,\n\tstaticDirectory: string,\n\treportFile: string,\n): Promise<void> {\n\tconst module: unknown = await import(pathToFileURL(entryFile).href);\n\tconst entry =\n\t\ttypeof module === \"object\" && module != null && \"appServer\" in module\n\t\t\t? module.appServer\n\t\t\t: undefined;\n\tif (!isEntry(entry)) {\n\t\tthrow new Error(`${entryFile} exports no appServer of this version of @ngrok/app-server.`);\n\t}\n\tconst report: PagesReport = { cdn: [], server: [] };\n\ttry {\n\t\tfor await (const page of entry.staticPages()) {\n\t\t\tif (\"cdn\" in page) {\n\t\t\t\tconst { body, answers, twin } = page.cdn;\n\t\t\t\tconst file = `/${report.cdn.length}/${basename(page.cdn.file)}`;\n\t\t\t\tconst target = join(staticDirectory, file);\n\t\t\t\tmkdirSync(dirname(target), { recursive: true });\n\t\t\t\twriteFileSync(target, body);\n\t\t\t\treport.cdn.push({ path: page.path, file, answers, ...(twin == null ? {} : { twin }) });\n\t\t\t} else {\n\t\t\t\treport.server.push({ path: page.path, reason: page.reason });\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tawait entry.stopPlugins();\n\t}\n\tmkdirSync(dirname(reportFile), { recursive: true });\n\twriteFileSync(reportFile, JSON.stringify(report));\n}\n\nif (import.meta.main) {\n\tconst [entryFile = \"\", staticDirectory = \"\", reportFile = \"\"] = process.argv.slice(2);\n\tawait writePages(entryFile, staticDirectory, reportFile);\n\t// oxlint-disable-next-line unicorn/no-process-exit -- a plugin's `setup` can leave a socket or a timer that keeps the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,QAAQ,KAAK,MAAM,CAAC;CACpF,MAAM,WAAW,WAAW,iBAAiB,UAAU;CAEvD,QAAQ,KAAK,CAAC;AACf"}
@@ -1 +0,0 @@
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 { copyName } from \"../core/compression.js\";\nimport { hasDotSegment } from \"../core/static-files.js\";\nimport type { HostBuild, HostOutput } from \"../vite/index.js\";\nimport { BROTLI_ONLY_LIST } from \"./brotli-only.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\tconst clientFiles = filesUnder(clientDirectory);\n\tconst listed = new Set(clientFiles);\n\t/** The file of each brotli copy that the function keeps, with the size of the file. */\n\tconst brotliOnly: Record<string, number> = {};\n\t/**\n\t * Whether the function drops `file`, a file or a gzip copy, because the\n\t * brotli copy of its file takes its place. Why: the function then holds one\n\t * copy of each text file, not three. Each browser accepts brotli, and the\n\t * CDN compresses the decompressed file for a client that does not.\n\t */\n\tconst brotliCopyOnly = (file: string): boolean => {\n\t\tconst name = basename(file);\n\t\tconst original = name.startsWith(\".\") ? /^\\.(?<name>.+)\\.gz$/u.exec(name)?.groups?.name : name;\n\t\treturn (\n\t\t\toriginal != null &&\n\t\t\tlisted.has(join(dirname(file), original)) &&\n\t\t\tlisted.has(join(dirname(file), copyName(original, \"br\")))\n\t\t);\n\t};\n\tfor (const file of clientFiles) {\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\tif (!brotliCopyOnly(file)) {\n\t\t\t\tcopyFile(from, join(functionDirectory, fromRoot(from)));\n\t\t\t} else if (!basename(file).startsWith(\".\")) {\n\t\t\t\tbrotliOnly[`/${posix(file)}`] = statSync(from).size;\n\t\t\t}\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\tif (Object.keys(brotliOnly).length > 0) {\n\t\twriteFileSync(\n\t\t\tjoin(functionDirectory, fromRoot(clientDirectory), BROTLI_ONLY_LIST),\n\t\t\tJSON.stringify(brotliOnly),\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":";;;;;;;;;AA0DA,MAAM,YAAY;;AAGlB,MAAM,cAAc;;;;;;AAOpB,MAAM,QAAQ;;;;;;AAOd,MAAM,eAAe,cACpB,IAAI,IAAI,YAAY,IAAI,SAAS,KAAK,IAAI,eAAe,qBAAqB,YAAY,GAAG,CAC9F;;AAGA,MAAM,WAAW,gBAAgB,WAChC,YACC,WAAW,IAAI,SAAS,OAAO,YAAY,EAAE,EAC/C;;AAGA,MAAM,WAAW;;AAGjB,MAAM,gBAAgB;;AAGtB,SAASA,QAAM,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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,EAAE,EAC9H;AAGH;;;;;;;;;;;;;;;;AAiBA,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 +0,0 @@
1
- {"version":3,"file":"vercel.js","names":["nodeHost"],"sources":["../src/vercel/index.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { withForwardedProto } from \"../core/create-server.js\";\nimport type { AppServerEntry } from \"../core/entry.js\";\nimport { flushLogs } from \"../core/log.js\";\nimport type { FileInfo, HostRuntime, StaticFiles } from \"../core/types.js\";\nimport { host as nodeHost } from \"../node/index.js\";\nimport { requestListener } from \"../node/response-writer.js\";\nimport { brotliOnlyFiles } from \"./brotli-only.js\";\n\n/**\n * `files` that give each file and directory the modification time\n * `mtimeMs`. Why: the deploy gives each file of the function one fixed time,\n * so a file that changes and keeps its size would keep its ETag. `vercel()`\n * sets `APP_SERVER_BUILT_AT` to the time of the build.\n */\nfunction withModifiedTime(files: StaticFiles, mtimeMs: number): StaticFiles {\n\tconst { snapshot } = files;\n\treturn {\n\t\tstat: async (path) => {\n\t\t\tconst info: FileInfo | undefined = await files.stat(path);\n\t\t\treturn info == null ? undefined : { ...info, mtimeMs };\n\t\t},\n\t\topen: files.open,\n\t\t...(snapshot == null\n\t\t\t? {}\n\t\t\t: { snapshot: async () => withModifiedTime(await snapshot(), mtimeMs) }),\n\t};\n}\n\n/**\n * The vercel host: one Vercel Function on Node.js. It reads the client build\n * from the function's files and keeps `requestContext()` in\n * `AsyncLocalStorage`, as the node host does. It has no listeners and no\n * lifecycle: Vercel starts and stops the function, and {@link handler} calls\n * the entry's `fetch`. It reads a file that the function keeps only as a\n * brotli copy through that copy (see `vercel()`).\n *\n * Why no gzip: Vercel's CDN compresses each response, with Brotli when the\n * client accepts it.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport const host: HostRuntime = {\n\tname: \"vercel\",\n\tfiles: (clientDirectory) => {\n\t\tconst files = brotliOnlyFiles(nodeHost.files(clientDirectory));\n\t\tconst builtAt = Number(process.env.APP_SERVER_BUILT_AT);\n\t\treturn Number.isFinite(builtAt) ? withModifiedTime(files, builtAt) : files;\n\t},\n\t...(nodeHost.storage == null ? {} : { storage: nodeHost.storage }),\n};\n\n/**\n * The function handler for the entry of a server build. The function file\n * that `vercel()` writes exports it.\n *\n * - The scheme comes from `X-Forwarded-Proto`, and the client address from\n * `X-Real-IP`. Why trust them: Vercel sets both headers on each request,\n * and replaces a value that the client sends.\n * - The node response writer sends each response, as the node host's\n * listener does.\n * - The log lines of the request reach stdout before the handler returns.\n * Why: Vercel can freeze the function after the response, before the next\n * turn of the event loop writes them.\n *\n * @example\n * export default hostModule.handler(appServer);\n */\nexport function handler(\n\tentry: AppServerEntry,\n): (incoming: IncomingMessage, outgoing: ServerResponse) => Promise<void> {\n\tconst listener = requestListener(\n\t\tasync (request, bindings) => {\n\t\t\tconst realIp = bindings.incoming?.headers[\"x-real-ip\"];\n\t\t\treturn entry.fetch(withForwardedProto(request), {\n\t\t\t\t...bindings,\n\t\t\t\t...(typeof realIp === \"string\" ? { remoteAddress: realIp } : {}),\n\t\t\t});\n\t\t},\n\t\t{ trustForwardedProto: true },\n\t);\n\treturn async (incoming, outgoing) => {\n\t\ttry {\n\t\t\tawait listener(incoming, outgoing);\n\t\t\t// Why wait: the access log writes its line when the response closes, after the listener returns.\n\t\t\tif (!outgoing.closed) {\n\t\t\t\tawait new Promise((resolve) => {\n\t\t\t\t\toutgoing.once(\"close\", resolve);\n\t\t\t\t});\n\t\t\t}\n\t\t} finally {\n\t\t\tflushLogs();\n\t\t\t// Why wait: a full pipe keeps the rest of a write in a queue, and a frozen function does not send it.\n\t\t\tif (process.stdout.writableLength > 0) {\n\t\t\t\tawait new Promise((resolve) =>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AAI,QAAQ,OAAO,iBAAiB,GACnC,MAAM,IAAI,SAAS,YAAY;IAC9B,QAAQ,OAAO,MAAM,IAAI,OAAO;GACjC,CAAC;EAEH;CACD;AACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"vite-B-GfswoH.js","names":[],"sources":["../src/react-router/vite.ts"],"sourcesContent":["import type { FrameworkBuild } from \"../vite/index.js\";\n\n/**\n * The build side of the React Router adapter. `appServer` uses it when the\n * Vite config has the React Router plugin, so pass it only to override that.\n *\n * @example\n * appServer({ framework: reactRouterAdapter() });\n */\nexport function reactRouterAdapter(): FrameworkBuild {\n\treturn {\n\t\tname: \"react-router\",\n\t\tserverModule: \"virtual:react-router/server-build\",\n\t\truntimeModule: \"@ngrok/app-server/react-router\",\n\t\t// Why this flag: React Router sets it for the preview server of its prerender pass only.\n\t\tisPrerenderPass: () => process.env.IS_RR_BUILD_REQUEST === \"yes\",\n\t\tvalidate: (config) => {\n\t\t\tif (config.base !== \"/\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`@ngrok/app-server serves a build at \"/\" only, and this config has the base \"${config.base}\".`,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;AASA,SAAgB,qBAAqC;CACpD,OAAO;EACN,MAAM;EACN,cAAc;EACd,eAAe;EAEf,uBAAuB,QAAQ,IAAI,wBAAwB;EAC3D,WAAW,WAAW;GACrB,IAAI,OAAO,SAAS,KACnB,MAAM,IAAI,MACT,+EAA+E,OAAO,KAAK,GAC5F;EAEF;CACD;AACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"vite-D4hfj3ph.js","names":[],"sources":["../src/node/vite.ts"],"sourcesContent":["import type { HostBuild } from \"../vite/index.js\";\n\n/**\n * The build side of the node host, the default host of `appServer`. The\n * server build gets `server/app-server.js`. Run it with `node`, `bun`, or\n * `deno run`, or load it with `app-server serve`.\n *\n * @example\n * appServer({ host: node() });\n */\nexport function node(): HostBuild {\n\treturn {\n\t\tname: \"node\",\n\t\truntimeModule: \"@ngrok/app-server/node\",\n\t\tentryFileName: \"app-server.js\",\n\t};\n}\n"],"mappings":";;;;;;;;;AAUA,SAAgB,OAAkB;CACjC,OAAO;EACN,MAAM;EACN,eAAe;EACf,eAAe;CAChB;AACD"}