@ngrok/app-server 0.3.2 → 0.3.4
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 +63 -23
- package/dist/brotli-only-DrA29Ecw.js +97 -0
- package/dist/brotli-only-DrA29Ecw.js.map +1 -0
- 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 +3 -3
- package/dist/client-browser.js +1 -1
- package/dist/client.js +1 -1
- package/dist/compress-JuJf2HaO.js +377 -0
- package/dist/compress-JuJf2HaO.js.map +1 -0
- package/dist/{compression-7_gToa8R.js → compression-CT2mWlKM.js} +9 -2
- package/dist/compression-CT2mWlKM.js.map +1 -0
- package/dist/{create-server-D0De6R7Q.js → create-server-BX2rH6-E.js} +616 -547
- package/dist/create-server-BX2rH6-E.js.map +1 -0
- package/dist/{create-server-kzZWd_Lo.d.ts → create-server-kxyhCdhv.d.ts} +50 -13
- package/dist/{entry-DuGgSKeB.d.ts → entry-CNL4OsEn.d.ts} +39 -3
- package/dist/entry-ChHgs269.js +352 -0
- package/dist/entry-ChHgs269.js.map +1 -0
- package/dist/{index-Bo5G9LuQ.d.ts → index-B8LsM6Mh.d.ts} +26 -1
- package/dist/index.d.ts +14 -23
- package/dist/index.js +3 -3
- package/dist/{load-entry-Bodyd2Ok.js → load-entry-BOgJPt1I.js} +4 -4
- package/dist/{load-entry-Bodyd2Ok.js.map → load-entry-BOgJPt1I.js.map} +1 -1
- package/dist/{node-C1qudLs_.js → node-B0AYf_IA.js} +5 -4
- package/dist/{node-C1qudLs_.js.map → node-B0AYf_IA.js.map} +1 -1
- package/dist/{node-tBVQPjQv.js → node-C0Ad7CVL.js} +2 -2
- package/dist/{node-tBVQPjQv.js.map → node-C0Ad7CVL.js.map} +1 -1
- package/dist/node-vite.d.ts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +2 -2
- 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/{response-writer-B7FoJjEE.js → response-writer-DzvUAz9x.js} +3 -3
- package/dist/response-writer-DzvUAz9x.js.map +1 -0
- package/dist/{script-hashes-C6hQ5XnP.js → script-hashes-CU7P9oZU.js} +2 -2
- package/dist/{script-hashes-C6hQ5XnP.js.map → script-hashes-CU7P9oZU.js.map} +1 -1
- package/dist/{serve-caOkS3o5.js → serve-BUJ7ZonG.js} +2 -2
- package/dist/{serve-caOkS3o5.js.map → serve-BUJ7ZonG.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-DREqYrZh.js → start-DiQf9ttp.js} +36 -8
- package/dist/start-DiQf9ttp.js.map +1 -0
- package/dist/{static-files-Beju9riB.js → static-files-C2ea8KQ6.js} +11 -3
- package/dist/static-files-C2ea8KQ6.js.map +1 -0
- package/dist/tanstack-start-vite.d.ts +1 -1
- package/dist/tanstack-start.d.ts +2 -2
- package/dist/{tcp-Dd1Mt6sN.js → tcp-Bws6oEau.js} +2 -2
- package/dist/{tcp-Dd1Mt6sN.js.map → tcp-Bws6oEau.js.map} +1 -1
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +4 -4
- package/dist/{trailing-slash-BrymAEGv.d.ts → trailing-slash-DeOUxMYo.d.ts} +2 -2
- package/dist/{types-CEvzAmcn.d.ts → types-BKJxtIuj.d.ts} +24 -3
- 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 +183 -20
- package/dist/vercel-vite.js.map +1 -1
- package/dist/vercel.d.ts +4 -3
- package/dist/vercel.js +7 -5
- package/dist/vercel.js.map +1 -1
- package/dist/{vite-tTxVimP6.js → vite-DPiSKHDn.js} +182 -51
- package/dist/vite-DPiSKHDn.js.map +1 -0
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +1 -1
- package/package.json +2 -1
- package/dist/build-id-C6sYO9Yp.js.map +0 -1
- package/dist/build-manifest-UDNk81Ce.js.map +0 -1
- package/dist/compression-7_gToa8R.js.map +0 -1
- package/dist/create-server-D0De6R7Q.js.map +0 -1
- package/dist/entry-UDsxuqBC.js +0 -116
- package/dist/entry-UDsxuqBC.js.map +0 -1
- package/dist/gzip-Doi4wqjX.js +0 -294
- package/dist/gzip-Doi4wqjX.js.map +0 -1
- package/dist/response-writer-B7FoJjEE.js.map +0 -1
- package/dist/start-DREqYrZh.js.map +0 -1
- package/dist/static-files-Beju9riB.js.map +0 -1
- package/dist/vite-tTxVimP6.js.map +0 -1
package/dist/gzip-Doi4wqjX.js
DELETED
|
@@ -1,294 +0,0 @@
|
|
|
1
|
-
import { constants, crc32, createDeflateRaw, createGzip } from "node:zlib";
|
|
2
|
-
|
|
3
|
-
// src/node/gzip.ts
|
|
4
|
-
/**
|
|
5
|
-
* A stream from {@link gzipStream}. Why a class: the node response writer
|
|
6
|
-
* reads `busy` to hold the head for zlib's first chunk, and a field costs
|
|
7
|
-
* less than a `WeakMap` entry for each response.
|
|
8
|
-
*/
|
|
9
|
-
var GzipBody = class extends ReadableStream {
|
|
10
|
-
/** Whether the next chunk waits only on zlib, because the source gave the bytes already. */
|
|
11
|
-
busy = false;
|
|
12
|
-
};
|
|
13
|
-
/**
|
|
14
|
-
* Whether the next chunk of `stream` waits only on zlib, because its source
|
|
15
|
-
* gave the bytes already. It gives `undefined` for a stream that is not from
|
|
16
|
-
* {@link gzipStream}.
|
|
17
|
-
*
|
|
18
|
-
* @example
|
|
19
|
-
* waitsForZlib(gzipStream(source)); // => false, until the first read gives zlib a chunk
|
|
20
|
-
*/
|
|
21
|
-
function waitsForZlib(stream) {
|
|
22
|
-
return stream instanceof GzipBody ? stream.busy : void 0;
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* The gzip header (RFC 1952): the magic number, deflate, no flags, no time,
|
|
26
|
-
* and the Unix system code.
|
|
27
|
-
*/
|
|
28
|
-
const HEADER = Buffer.from([
|
|
29
|
-
31,
|
|
30
|
-
139,
|
|
31
|
-
8,
|
|
32
|
-
0,
|
|
33
|
-
0,
|
|
34
|
-
0,
|
|
35
|
-
0,
|
|
36
|
-
0,
|
|
37
|
-
0,
|
|
38
|
-
3
|
|
39
|
-
]);
|
|
40
|
-
/** The gzip member of an empty body: the header, a final empty block, a CRC-32 of 0, and a size of 0. */
|
|
41
|
-
const EMPTY_MEMBER = Buffer.concat([HEADER, Buffer.from([
|
|
42
|
-
3,
|
|
43
|
-
0,
|
|
44
|
-
0,
|
|
45
|
-
0,
|
|
46
|
-
0,
|
|
47
|
-
0,
|
|
48
|
-
0,
|
|
49
|
-
0,
|
|
50
|
-
0,
|
|
51
|
-
0
|
|
52
|
-
])]);
|
|
53
|
-
/**
|
|
54
|
-
* The largest body that a pooled deflate stream compresses. Why a limit: the
|
|
55
|
-
* CRC-32 of a pooled body runs on the main thread, and above about 64 KiB it
|
|
56
|
-
* costs more than a new zlib stream does.
|
|
57
|
-
*/
|
|
58
|
-
const POOLED_MAX_BYTES = 65536;
|
|
59
|
-
/** The most deflate streams that wait for a body. Why a limit: each one keeps about 276 KiB of zlib state. */
|
|
60
|
-
const MAX_IDLE = 16;
|
|
61
|
-
function ignore() {}
|
|
62
|
-
function newDeflater() {
|
|
63
|
-
const deflater = {
|
|
64
|
-
stream: createDeflateRaw({ flush: constants.Z_FINISH }),
|
|
65
|
-
output: ignore,
|
|
66
|
-
fail: ignore,
|
|
67
|
-
size: 0
|
|
68
|
-
};
|
|
69
|
-
deflater.stream.on("data", (chunk) => {
|
|
70
|
-
deflater.output(chunk);
|
|
71
|
-
});
|
|
72
|
-
deflater.stream.on("error", (error) => {
|
|
73
|
-
deflater.fail(error);
|
|
74
|
-
});
|
|
75
|
-
deflater.stream.on("close", () => {
|
|
76
|
-
if (deflater.fail !== ignore) deflater.fail(/* @__PURE__ */ new Error("The deflate stream closed."));
|
|
77
|
-
});
|
|
78
|
-
return deflater;
|
|
79
|
-
}
|
|
80
|
-
/** The deflate streams that wait for a body, the last one given back last. */
|
|
81
|
-
const idle = [];
|
|
82
|
-
/**
|
|
83
|
-
* An idle deflate stream for a body of `size` bytes, else a new one. It takes
|
|
84
|
-
* a stream whose bodies were each no longer than this one: the longest such,
|
|
85
|
-
* and of those the last one given back, whose memory is still in the cache.
|
|
86
|
-
*
|
|
87
|
-
* Why: a reset keeps the window of zlib, and zlib reads the bytes after the
|
|
88
|
-
* end of a body to hash and match its last bytes. After a longer body, these
|
|
89
|
-
* are bytes of that body, so they could change the output of this one. A
|
|
90
|
-
* stream whose bodies were no longer has only the zeros that zlib writes
|
|
91
|
-
* after each body there, as a new stream does.
|
|
92
|
-
*/
|
|
93
|
-
function takeDeflater(size) {
|
|
94
|
-
let best = -1;
|
|
95
|
-
let bestSize = -1;
|
|
96
|
-
for (let index = idle.length - 1; index >= 0; index -= 1) {
|
|
97
|
-
const each = idle[index]?.size ?? Infinity;
|
|
98
|
-
if (each <= size && each > bestSize) {
|
|
99
|
-
best = index;
|
|
100
|
-
bestSize = each;
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
if (best === -1) return newDeflater();
|
|
104
|
-
const taken = idle[best];
|
|
105
|
-
const last = idle.pop();
|
|
106
|
-
if (taken == null || last == null) return newDeflater();
|
|
107
|
-
if (last !== taken) idle[best] = last;
|
|
108
|
-
return taken;
|
|
109
|
-
}
|
|
110
|
-
/**
|
|
111
|
-
* Gives back a deflate stream after its body. Why reset: the next body must
|
|
112
|
-
* not use the bytes of this one as a dictionary. When the pool is full, it
|
|
113
|
-
* keeps the streams of the shortest bodies, which more bodies can take.
|
|
114
|
-
*/
|
|
115
|
-
function release(deflater) {
|
|
116
|
-
deflater.output = ignore;
|
|
117
|
-
deflater.fail = ignore;
|
|
118
|
-
const { stream } = deflater;
|
|
119
|
-
if (stream.destroyed || stream.readableLength !== 0 || stream.writableLength !== 0) {
|
|
120
|
-
stream.destroy();
|
|
121
|
-
return;
|
|
122
|
-
}
|
|
123
|
-
stream.reset();
|
|
124
|
-
if (stream.destroyed) return;
|
|
125
|
-
if (idle.length < MAX_IDLE) {
|
|
126
|
-
idle.push(deflater);
|
|
127
|
-
return;
|
|
128
|
-
}
|
|
129
|
-
let longest = 0;
|
|
130
|
-
for (let index = 1; index < idle.length; index += 1) if ((idle[index]?.size ?? 0) > (idle[longest]?.size ?? 0)) longest = index;
|
|
131
|
-
const evicted = idle[longest];
|
|
132
|
-
if (evicted != null && evicted.size > deflater.size) {
|
|
133
|
-
idle[longest] = deflater;
|
|
134
|
-
evicted.stream.destroy();
|
|
135
|
-
} else stream.destroy();
|
|
136
|
-
}
|
|
137
|
-
/** Writes `chunk` to `stream`. zlib gives all the output of the chunk before this resolves. */
|
|
138
|
-
async function write(stream, chunk) {
|
|
139
|
-
return new Promise((resolve, reject) => {
|
|
140
|
-
stream.write(chunk, (error) => {
|
|
141
|
-
if (error == null) resolve();
|
|
142
|
-
else reject(error);
|
|
143
|
-
});
|
|
144
|
-
});
|
|
145
|
-
}
|
|
146
|
-
/**
|
|
147
|
-
* The gzip member of a body of one chunk, from a pooled raw deflate stream,
|
|
148
|
-
* with the header and the trailer written here, so the body needs one zlib
|
|
149
|
-
* call. `use` gets the stream while zlib compresses, so a cancel can destroy
|
|
150
|
-
* it, and gets `undefined` before the stream goes back to the pool. Why only
|
|
151
|
-
* a body of one chunk: a reset keeps the old window, and a second write reads
|
|
152
|
-
* its bytes as history. The output of one write is the
|
|
153
|
-
* same as from a new stream, so it does not depend on an earlier body.
|
|
154
|
-
*/
|
|
155
|
-
async function gzipOnce(value, use) {
|
|
156
|
-
const deflater = takeDeflater(value.byteLength);
|
|
157
|
-
use(deflater);
|
|
158
|
-
const parts = [HEADER];
|
|
159
|
-
deflater.output = (chunk) => {
|
|
160
|
-
parts.push(chunk);
|
|
161
|
-
};
|
|
162
|
-
try {
|
|
163
|
-
await new Promise((resolve, reject) => {
|
|
164
|
-
deflater.fail = reject;
|
|
165
|
-
deflater.stream.write(value, (error) => {
|
|
166
|
-
if (error != null) reject(error);
|
|
167
|
-
else if (deflater.stream.destroyed) reject(/* @__PURE__ */ new Error("The deflate stream closed."));
|
|
168
|
-
else resolve();
|
|
169
|
-
});
|
|
170
|
-
});
|
|
171
|
-
} catch (error) {
|
|
172
|
-
deflater.output = ignore;
|
|
173
|
-
deflater.fail = ignore;
|
|
174
|
-
deflater.stream.destroy();
|
|
175
|
-
throw error;
|
|
176
|
-
}
|
|
177
|
-
deflater.size = Math.max(deflater.size, value.byteLength);
|
|
178
|
-
use(void 0);
|
|
179
|
-
release(deflater);
|
|
180
|
-
const trailer = Buffer.allocUnsafe(8);
|
|
181
|
-
trailer.writeUInt32LE(crc32(value), 0);
|
|
182
|
-
trailer.writeUInt32LE(value.byteLength, 4);
|
|
183
|
-
parts.push(trailer);
|
|
184
|
-
return Buffer.concat(parts);
|
|
185
|
-
}
|
|
186
|
-
/**
|
|
187
|
-
* Gzips a byte stream. `Z_SYNC_FLUSH` makes each written chunk readable at
|
|
188
|
-
* once. It reads the next source chunk only when the consumer pulls, so a slow
|
|
189
|
-
* client holds back the source. When the source ends by the time zlib
|
|
190
|
-
* finishes a chunk, that chunk and the gzip trailer go out as one. Why: the
|
|
191
|
-
* host writes each chunk to the socket on its own, and a write costs more
|
|
192
|
-
* than its few bytes.
|
|
193
|
-
*
|
|
194
|
-
* A body that ends with its first chunk, up to 64 KiB, takes a pooled raw
|
|
195
|
-
* deflate stream. Why: a new zlib stream costs more main-thread time than
|
|
196
|
-
* zlib takes for a small page.
|
|
197
|
-
*
|
|
198
|
-
* @example
|
|
199
|
-
* new Response(gzipStream(response.body), response);
|
|
200
|
-
*/
|
|
201
|
-
function gzipStream(source) {
|
|
202
|
-
const reader = source.getReader();
|
|
203
|
-
let ended = false;
|
|
204
|
-
const markEnded = () => {
|
|
205
|
-
ended = true;
|
|
206
|
-
};
|
|
207
|
-
reader.closed.then(markEnded, () => {});
|
|
208
|
-
/** The gzip stream of a body of more than one chunk. */
|
|
209
|
-
let gzip;
|
|
210
|
-
/** The pooled deflate stream while it compresses the one chunk of a body. */
|
|
211
|
-
let pooled;
|
|
212
|
-
let started = false;
|
|
213
|
-
/** The zlib output that waits for the next enqueue. */
|
|
214
|
-
let held = [];
|
|
215
|
-
let heldBytes = 0;
|
|
216
|
-
const enqueueHeld = (controller) => {
|
|
217
|
-
const [first] = held;
|
|
218
|
-
if (first == null) return;
|
|
219
|
-
controller.enqueue(held.length === 1 ? first : Buffer.concat(held));
|
|
220
|
-
held = [];
|
|
221
|
-
heldBytes = 0;
|
|
222
|
-
};
|
|
223
|
-
const startGzip = (body, controller) => {
|
|
224
|
-
const created = createGzip({ flush: constants.Z_SYNC_FLUSH });
|
|
225
|
-
created.on("data", (chunk) => {
|
|
226
|
-
held.push(chunk);
|
|
227
|
-
heldBytes += chunk.byteLength;
|
|
228
|
-
if (heldBytes >= constants.Z_DEFAULT_CHUNK) enqueueHeld(controller);
|
|
229
|
-
});
|
|
230
|
-
created.on("end", () => {
|
|
231
|
-
body.busy = false;
|
|
232
|
-
enqueueHeld(controller);
|
|
233
|
-
controller.close();
|
|
234
|
-
});
|
|
235
|
-
created.on("error", (error) => {
|
|
236
|
-
body.busy = false;
|
|
237
|
-
controller.error(error);
|
|
238
|
-
});
|
|
239
|
-
return created;
|
|
240
|
-
};
|
|
241
|
-
const stream = new GzipBody({
|
|
242
|
-
async pull(controller) {
|
|
243
|
-
try {
|
|
244
|
-
let chunk = await reader.read();
|
|
245
|
-
while (!chunk.done && chunk.value.byteLength === 0) chunk = await reader.read();
|
|
246
|
-
if (!started) {
|
|
247
|
-
started = true;
|
|
248
|
-
if (chunk.done) {
|
|
249
|
-
controller.enqueue(EMPTY_MEMBER);
|
|
250
|
-
controller.close();
|
|
251
|
-
return;
|
|
252
|
-
}
|
|
253
|
-
stream.busy = true;
|
|
254
|
-
await Promise.resolve();
|
|
255
|
-
if (ended && chunk.value.byteLength <= POOLED_MAX_BYTES) {
|
|
256
|
-
const member = await gzipOnce(chunk.value, (deflater) => {
|
|
257
|
-
pooled = deflater;
|
|
258
|
-
});
|
|
259
|
-
stream.busy = false;
|
|
260
|
-
controller.enqueue(member);
|
|
261
|
-
controller.close();
|
|
262
|
-
return;
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
gzip ??= startGzip(stream, controller);
|
|
266
|
-
stream.busy = true;
|
|
267
|
-
if (chunk.done) {
|
|
268
|
-
gzip.end();
|
|
269
|
-
return;
|
|
270
|
-
}
|
|
271
|
-
await write(gzip, chunk.value);
|
|
272
|
-
if (ended) {
|
|
273
|
-
gzip.end();
|
|
274
|
-
return;
|
|
275
|
-
}
|
|
276
|
-
stream.busy = false;
|
|
277
|
-
enqueueHeld(controller);
|
|
278
|
-
} catch (error) {
|
|
279
|
-
stream.busy = false;
|
|
280
|
-
gzip?.destroy();
|
|
281
|
-
throw error;
|
|
282
|
-
}
|
|
283
|
-
},
|
|
284
|
-
async cancel(reason) {
|
|
285
|
-
gzip?.destroy();
|
|
286
|
-
pooled?.stream.destroy();
|
|
287
|
-
return reader.cancel(reason);
|
|
288
|
-
}
|
|
289
|
-
}, { highWaterMark: 0 });
|
|
290
|
-
return stream;
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
export { waitsForZlib as n, gzipStream as t };
|
|
294
|
-
//# sourceMappingURL=gzip-Doi4wqjX.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"gzip-Doi4wqjX.js","names":[],"sources":["../src/node/gzip.ts"],"sourcesContent":["import { constants, crc32, createDeflateRaw, createGzip } from \"node:zlib\";\nimport type { DeflateRaw, Gzip } from \"node:zlib\";\n\n/**\n * A stream from {@link gzipStream}. Why a class: the node response writer\n * reads `busy` to hold the head for zlib's first chunk, and a field costs\n * less than a `WeakMap` entry for each response.\n */\nclass GzipBody extends ReadableStream<Uint8Array> {\n\t/** Whether the next chunk waits only on zlib, because the source gave the bytes already. */\n\tpublic busy = false;\n}\n\n/**\n * Whether the next chunk of `stream` waits only on zlib, because its source\n * gave the bytes already. It gives `undefined` for a stream that is not from\n * {@link gzipStream}.\n *\n * @example\n * waitsForZlib(gzipStream(source)); // => false, until the first read gives zlib a chunk\n */\nexport function waitsForZlib(stream: ReadableStream<Uint8Array>): boolean | undefined {\n\treturn stream instanceof GzipBody ? stream.busy : undefined;\n}\n\n/**\n * The gzip header (RFC 1952): the magic number, deflate, no flags, no time,\n * and the Unix system code.\n */\nconst HEADER = Buffer.from([31, 139, 8, 0, 0, 0, 0, 0, 0, 3]);\n\n/** The gzip member of an empty body: the header, a final empty block, a CRC-32 of 0, and a size of 0. */\nconst EMPTY_MEMBER = Buffer.concat([HEADER, Buffer.from([3, 0, 0, 0, 0, 0, 0, 0, 0, 0])]);\n\n/**\n * The largest body that a pooled deflate stream compresses. Why a limit: the\n * CRC-32 of a pooled body runs on the main thread, and above about 64 KiB it\n * costs more than a new zlib stream does.\n */\nconst POOLED_MAX_BYTES = 64 * 1024;\n\n/** The most deflate streams that wait for a body. Why a limit: each one keeps about 276 KiB of zlib state. */\nconst MAX_IDLE = 16;\n\nfunction ignore(): void {}\n\n/**\n * A raw deflate stream that compresses one body at a time, the target of its\n * output and of its failure, and the size of the longest body that it\n * compressed.\n */\ntype Deflater = {\n\tstream: DeflateRaw;\n\toutput: (chunk: Buffer) => void;\n\tfail: (error: Error) => void;\n\tsize: number;\n};\n\nfunction newDeflater(): Deflater {\n\tconst deflater: Deflater = {\n\t\t// Why `Z_FINISH`: when the output fills the buffer of the stream exactly, the stream calls zlib\n\t\t// again, and a sync flush then adds an empty block. So the output would depend on earlier bodies.\n\t\tstream: createDeflateRaw({ flush: constants.Z_FINISH }),\n\t\toutput: ignore,\n\t\tfail: ignore,\n\t\tsize: 0,\n\t};\n\tdeflater.stream.on(\"data\", (chunk: Buffer) => {\n\t\tdeflater.output(chunk);\n\t});\n\t// Why both: zlib destroys the stream at a failure, and then it never calls the write callback.\n\tdeflater.stream.on(\"error\", (error) => {\n\t\tdeflater.fail(error);\n\t});\n\tdeflater.stream.on(\"close\", () => {\n\t\t// Why the check: a stream that the pool destroys has no body, and an error costs its stack.\n\t\tif (deflater.fail !== ignore) {\n\t\t\tdeflater.fail(new Error(\"The deflate stream closed.\"));\n\t\t}\n\t});\n\treturn deflater;\n}\n\n/** The deflate streams that wait for a body, the last one given back last. */\nconst idle: Deflater[] = [];\n\n/**\n * An idle deflate stream for a body of `size` bytes, else a new one. It takes\n * a stream whose bodies were each no longer than this one: the longest such,\n * and of those the last one given back, whose memory is still in the cache.\n *\n * Why: a reset keeps the window of zlib, and zlib reads the bytes after the\n * end of a body to hash and match its last bytes. After a longer body, these\n * are bytes of that body, so they could change the output of this one. A\n * stream whose bodies were no longer has only the zeros that zlib writes\n * after each body there, as a new stream does.\n */\nfunction takeDeflater(size: number): Deflater {\n\tlet best = -1;\n\tlet bestSize = -1;\n\tfor (let index = idle.length - 1; index >= 0; index -= 1) {\n\t\tconst each = idle[index]?.size ?? Infinity;\n\t\tif (each <= size && each > bestSize) {\n\t\t\tbest = index;\n\t\t\tbestSize = each;\n\t\t}\n\t}\n\tif (best === -1) {\n\t\treturn newDeflater();\n\t}\n\tconst taken = idle[best];\n\tconst last = idle.pop();\n\tif (taken == null || last == null) {\n\t\treturn newDeflater();\n\t}\n\t// Why move the last one into the gap: the order of the others does not matter, and it costs no copy.\n\tif (last !== taken) {\n\t\tidle[best] = last;\n\t}\n\treturn taken;\n}\n\n/**\n * Gives back a deflate stream after its body. Why reset: the next body must\n * not use the bytes of this one as a dictionary. When the pool is full, it\n * keeps the streams of the shortest bodies, which more bodies can take.\n */\nfunction release(deflater: Deflater): void {\n\tdeflater.output = ignore;\n\tdeflater.fail = ignore;\n\tconst { stream } = deflater;\n\t// Why check the queues: a stream with output or input still queued would give it to the next body.\n\tif (stream.destroyed || stream.readableLength !== 0 || stream.writableLength !== 0) {\n\t\tstream.destroy();\n\t\treturn;\n\t}\n\tstream.reset();\n\t// Why the check: a reset that fails destroys the stream.\n\tif (stream.destroyed) {\n\t\treturn;\n\t}\n\tif (idle.length < MAX_IDLE) {\n\t\tidle.push(deflater);\n\t\treturn;\n\t}\n\tlet longest = 0;\n\tfor (let index = 1; index < idle.length; index += 1) {\n\t\tif ((idle[index]?.size ?? 0) > (idle[longest]?.size ?? 0)) {\n\t\t\tlongest = index;\n\t\t}\n\t}\n\tconst evicted = idle[longest];\n\tif (evicted != null && evicted.size > deflater.size) {\n\t\tidle[longest] = deflater;\n\t\tevicted.stream.destroy();\n\t} else {\n\t\tstream.destroy();\n\t}\n}\n\n/** Writes `chunk` to `stream`. zlib gives all the output of the chunk before this resolves. */\nasync function write(stream: Gzip, chunk: Uint8Array): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tstream.write(chunk, (error) => {\n\t\t\tif (error == null) {\n\t\t\t\tresolve();\n\t\t\t} else {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t});\n\t});\n}\n\n/**\n * The gzip member of a body of one chunk, from a pooled raw deflate stream,\n * with the header and the trailer written here, so the body needs one zlib\n * call. `use` gets the stream while zlib compresses, so a cancel can destroy\n * it, and gets `undefined` before the stream goes back to the pool. Why only\n * a body of one chunk: a reset keeps the old window, and a second write reads\n * its bytes as history. The output of one write is the\n * same as from a new stream, so it does not depend on an earlier body.\n */\nasync function gzipOnce(\n\tvalue: Uint8Array,\n\tuse: (deflater: Deflater | undefined) => void,\n): Promise<Buffer> {\n\tconst deflater = takeDeflater(value.byteLength);\n\tuse(deflater);\n\tconst parts: Buffer[] = [HEADER];\n\tdeflater.output = (chunk) => {\n\t\tparts.push(chunk);\n\t};\n\ttry {\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tdeflater.fail = reject;\n\t\t\tdeflater.stream.write(value, (error) => {\n\t\t\t\tif (error != null) {\n\t\t\t\t\treject(error);\n\t\t\t\t} else if (deflater.stream.destroyed) {\n\t\t\t\t\treject(new Error(\"The deflate stream closed.\"));\n\t\t\t\t} else {\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t} catch (error) {\n\t\tdeflater.output = ignore;\n\t\tdeflater.fail = ignore;\n\t\tdeflater.stream.destroy();\n\t\tthrow error;\n\t}\n\tdeflater.size = Math.max(deflater.size, value.byteLength);\n\t// Why first: a cancel after this must not destroy a stream that the pool gives to another body.\n\tuse(undefined);\n\trelease(deflater);\n\tconst trailer = Buffer.allocUnsafe(8);\n\ttrailer.writeUInt32LE(crc32(value), 0);\n\ttrailer.writeUInt32LE(value.byteLength, 4);\n\tparts.push(trailer);\n\treturn Buffer.concat(parts);\n}\n\n/**\n * Gzips a byte stream. `Z_SYNC_FLUSH` makes each written chunk readable at\n * once. It reads the next source chunk only when the consumer pulls, so a slow\n * client holds back the source. When the source ends by the time zlib\n * finishes a chunk, that chunk and the gzip trailer go out as one. Why: the\n * host writes each chunk to the socket on its own, and a write costs more\n * than its few bytes.\n *\n * A body that ends with its first chunk, up to 64 KiB, takes a pooled raw\n * deflate stream. Why: a new zlib stream costs more main-thread time than\n * zlib takes for a small page.\n *\n * @example\n * new Response(gzipStream(response.body), response);\n */\nexport function gzipStream(source: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {\n\tconst reader = source.getReader();\n\tlet ended = false;\n\tconst markEnded = () => {\n\t\tended = true;\n\t};\n\t// Why a flag: after each zlib write, it tells with no read whether the source ended meanwhile.\n\tvoid reader.closed.then(markEnded, () => {});\n\t/** The gzip stream of a body of more than one chunk. */\n\tlet gzip: Gzip | undefined;\n\t/** The pooled deflate stream while it compresses the one chunk of a body. */\n\tlet pooled: Deflater | undefined;\n\tlet started = false;\n\t/** The zlib output that waits for the next enqueue. */\n\tlet held: Buffer[] = [];\n\tlet heldBytes = 0;\n\tconst enqueueHeld = (controller: ReadableStreamDefaultController<Uint8Array>) => {\n\t\tconst [first] = held;\n\t\tif (first == null) {\n\t\t\treturn;\n\t\t}\n\t\t// Why no copy for one chunk: zlib gives each chunk its own bytes, and it never writes them again.\n\t\tcontroller.enqueue(held.length === 1 ? first : Buffer.concat(held));\n\t\theld = [];\n\t\theldBytes = 0;\n\t};\n\tconst startGzip = (\n\t\tbody: GzipBody,\n\t\tcontroller: ReadableStreamDefaultController<Uint8Array>,\n\t): Gzip => {\n\t\tconst created = createGzip({ flush: constants.Z_SYNC_FLUSH });\n\t\tcreated.on(\"data\", (chunk: Buffer) => {\n\t\t\theld.push(chunk);\n\t\t\theldBytes += chunk.byteLength;\n\t\t\t// Why: the output of a large source chunk goes out while zlib still compresses the rest.\n\t\t\tif (heldBytes >= constants.Z_DEFAULT_CHUNK) {\n\t\t\t\tenqueueHeld(controller);\n\t\t\t}\n\t\t});\n\t\tcreated.on(\"end\", () => {\n\t\t\tbody.busy = false;\n\t\t\tenqueueHeld(controller);\n\t\t\tcontroller.close();\n\t\t});\n\t\tcreated.on(\"error\", (error) => {\n\t\t\tbody.busy = false;\n\t\t\tcontroller.error(error);\n\t\t});\n\t\treturn created;\n\t};\n\tconst stream: GzipBody = new GzipBody(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\ttry {\n\t\t\t\t\tlet chunk = await reader.read();\n\t\t\t\t\t// Why skip empty chunks: zlib writes nothing for one, and a pull that enqueues nothing\n\t\t\t\t\t// is not called again.\n\t\t\t\t\twhile (!chunk.done && chunk.value.byteLength === 0) {\n\t\t\t\t\t\tchunk = await reader.read();\n\t\t\t\t\t}\n\t\t\t\t\tif (!started) {\n\t\t\t\t\t\tstarted = true;\n\t\t\t\t\t\tif (chunk.done) {\n\t\t\t\t\t\t\tcontroller.enqueue(EMPTY_MEMBER);\n\t\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstream.busy = true;\n\t\t\t\t\t\t// Why wait: a source that closes in the pull that gave this chunk ends one microtask later.\n\t\t\t\t\t\tawait Promise.resolve();\n\t\t\t\t\t\tif (ended && chunk.value.byteLength <= POOLED_MAX_BYTES) {\n\t\t\t\t\t\t\tconst member = await gzipOnce(chunk.value, (deflater) => {\n\t\t\t\t\t\t\t\tpooled = deflater;\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tstream.busy = false;\n\t\t\t\t\t\t\tcontroller.enqueue(member);\n\t\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tgzip ??= startGzip(stream, controller);\n\t\t\t\t\tstream.busy = true;\n\t\t\t\t\tif (chunk.done) {\n\t\t\t\t\t\tgzip.end();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tawait write(gzip, chunk.value);\n\t\t\t\t\tif (ended) {\n\t\t\t\t\t\tgzip.end();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tstream.busy = false;\n\t\t\t\t\t// Why the output is here: zlib emits the output of a chunk before it calls the write\n\t\t\t\t\t// callback, so this pull enqueues a chunk and the consumer's read does not wait.\n\t\t\t\t\tenqueueHeld(controller);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tstream.busy = false;\n\t\t\t\t\tgzip?.destroy();\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t},\n\t\t\t// Why cancel the source: a client disconnect must reach the handler, so it stops its work.\n\t\t\tasync cancel(reason) {\n\t\t\t\tgzip?.destroy();\n\t\t\t\t// Why destroy: a stream that a write still uses must never go back to the pool.\n\t\t\t\tpooled?.stream.destroy();\n\t\t\t\treturn reader.cancel(reason);\n\t\t\t},\n\t\t},\n\t\t// Why 0: the stream reads its source only when the consumer reads.\n\t\t{ highWaterMark: 0 },\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,CAAC;EACD,QAAQ,GAAG,UAAU,UAAU;GAC9B,KAAK,OAAO;GACZ,WAAW,MAAM,KAAK;EACvB,CAAC;EACD,OAAO;CACR;CACA,MAAM,SAAmB,IAAI,SAC5B;EACC,MAAM,KAAK,YAAY;GACtB,IAAI;IACH,IAAI,QAAQ,MAAM,OAAO,KAAK;IAG9B,OAAO,CAAC,MAAM,QAAQ,MAAM,MAAM,eAAe,GAChD,QAAQ,MAAM,OAAO,KAAK;IAE3B,IAAI,CAAC,SAAS;KACb,UAAU;KACV,IAAI,MAAM,MAAM;MACf,WAAW,QAAQ,YAAY;MAC/B,WAAW,MAAM;MACjB;KACD;KACA,OAAO,OAAO;KAEd,MAAM,QAAQ,QAAQ;KACtB,IAAI,SAAS,MAAM,MAAM,cAAc,kBAAkB;MACxD,MAAM,SAAS,MAAM,SAAS,MAAM,QAAQ,aAAa;OACxD,SAAS;MACV,CAAC;MACD,OAAO,OAAO;MACd,WAAW,QAAQ,MAAM;MACzB,WAAW,MAAM;MACjB;KACD;IACD;IACA,SAAS,UAAU,QAAQ,UAAU;IACrC,OAAO,OAAO;IACd,IAAI,MAAM,MAAM;KACf,KAAK,IAAI;KACT;IACD;IACA,MAAM,MAAM,MAAM,MAAM,KAAK;IAC7B,IAAI,OAAO;KACV,KAAK,IAAI;KACT;IACD;IACA,OAAO,OAAO;IAGd,YAAY,UAAU;GACvB,SAAS,OAAO;IACf,OAAO,OAAO;IACd,MAAM,QAAQ;IACd,MAAM;GACP;EACD;EAEA,MAAM,OAAO,QAAQ;GACpB,MAAM,QAAQ;GAEd,QAAQ,OAAO,QAAQ;GACvB,OAAO,OAAO,OAAO,MAAM;EAC5B;CACD,GAEA,EAAE,eAAe,EAAE,CACpB;CACA,OAAO;AACR"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"response-writer-B7FoJjEE.js","names":["targeted"],"sources":["../src/node/response-writer.ts"],"sourcesContent":["import { IncomingMessage, ServerResponse } from \"node:http\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport { readIfQueued } from \"../core/compression.js\";\nimport type { ReadResult } from \"../core/compression.js\";\nimport { headerIndex, headerList } from \"../core/header-hook.js\";\nimport { ResponseEdge } from \"../core/response-edge.js\";\nimport type { ListenerBindings } from \"../core/types.js\";\nimport type { NodeBindings } from \"./dev-server.js\";\nimport { waitsForZlib } from \"./gzip.js\";\n\n/** The header of a response that went out through Node's response already, as the dev server stage sends it. */\nconst ALREADY_SENT_HEADER = \"x-hono-already-sent\";\n/** Why one object for all requests: `@hono/node-server` only reads its headers. */\nconst ALREADY_SENT = new Response(null, { headers: { [ALREADY_SENT_HEADER]: \"true\" } });\n/** The type that `@hono/node-server` gives a body with none. */\nconst DEFAULT_CONTENT_TYPE = \"text/plain; charset=UTF-8\";\n/** The body of the 500 that goes out when the response cannot. */\nconst ERROR_BODY = Buffer.from(\"Internal Server Error\");\n\n/** Resolves after the microtasks that are queued now, and the ones that they queue. */\nasync function afterMicrotasks(): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tprocess.nextTick(resolve);\n\t});\n}\n\n/** Resolves on the next `drain` of `outgoing`, or when it closes. */\nasync function drained(outgoing: ServerResponse): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tconst done = () => {\n\t\t\toutgoing.off(\"drain\", done);\n\t\t\toutgoing.off(\"close\", done);\n\t\t\tresolve();\n\t\t};\n\t\toutgoing.on(\"drain\", done);\n\t\toutgoing.on(\"close\", done);\n\t});\n}\n\n/** `value` as a body chunk. Why throw: a string chunk has no `byteLength`, and the Fetch standard allows bytes only. */\nfunction bytesOf(value: unknown): Uint8Array {\n\tif (value instanceof Uint8Array) {\n\t\treturn value;\n\t}\n\tthrow new TypeError(\"A response body gave a chunk that is not a Uint8Array.\");\n}\n\n/** The chunks that a body had queued in at most two reads, and the read that is still open. */\ntype Ahead = {\n\tchunks: Uint8Array[];\n\tsize: number;\n\tdone: boolean;\n\tpending: Promise<ReadResult> | undefined;\n};\n\n/**\n * Reads the chunks that `body` has queued, in at most two reads, and never\n * waits for its source. The exception is a stream of the host's gzip whose\n * source gave bytes: it waits for zlib's first chunk, so the head goes out\n * with it.\n */\nasync function readAhead(\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tbody: ReadableStream<Uint8Array>,\n): Promise<Ahead> {\n\tconst ahead: Ahead = { chunks: [], size: 0, done: false, pending: undefined };\n\tfor (let reads = 0; reads < 2 && !ahead.done && ahead.pending == null; reads += 1) {\n\t\t// oxlint-disable-next-line no-await-in-loop -- each read takes only a chunk that is queued already.\n\t\tlet next = await readIfQueued(reader);\n\t\tif (\"pending\" in next && reads === 0 && waitsForZlib(body) != null) {\n\t\t\t// Why wait: the host's gzip stream gets its source chunk in a later microtask.\n\t\t\t// oxlint-disable-next-line no-await-in-loop -- this runs on the first read only.\n\t\t\tawait afterMicrotasks();\n\t\t\tif (waitsForZlib(body) === true) {\n\t\t\t\t// oxlint-disable-next-line no-await-in-loop -- this runs on the first read only.\n\t\t\t\tnext = { result: await next.pending };\n\t\t\t}\n\t\t}\n\t\tif (\"pending\" in next) {\n\t\t\tahead.pending = next.pending;\n\t\t} else if (next.result.done) {\n\t\t\tahead.done = true;\n\t\t} else {\n\t\t\tconst chunk = bytesOf(next.result.value);\n\t\t\tahead.chunks.push(chunk);\n\t\t\tahead.size += chunk.byteLength;\n\t\t}\n\t}\n\treturn ahead;\n}\n\n/**\n * Writes the rest of the body at the pace of the client, then ends the\n * response. Why no length check: `strictContentLength` makes Node throw for a\n * body that does not match its `Content-Length`.\n */\nasync function pump(\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tfirst: Promise<ReadResult>,\n\t{ outgoing, edge }: { outgoing: ServerResponse; edge: ResponseEdge },\n): Promise<void> {\n\tlet read = first;\n\tfor (;;) {\n\t\t// oxlint-disable-next-line no-await-in-loop -- the next read waits for the socket.\n\t\tconst result = await read;\n\t\tif (outgoing.destroyed) {\n\t\t\treturn;\n\t\t}\n\t\tif (result.done) {\n\t\t\toutgoing.end();\n\t\t\treturn;\n\t\t}\n\t\tconst chunk = bytesOf(result.value);\n\t\tconst flowing = outgoing.write(chunk);\n\t\tedge.bytes += chunk.byteLength;\n\t\tif (!flowing) {\n\t\t\t// oxlint-disable-next-line no-await-in-loop -- the client sets the pace.\n\t\t\tawait drained(outgoing);\n\t\t}\n\t\tread = reader.read();\n\t}\n}\n\n/** The headers that `outgoing` sent, as a flat list. Why: the dev server stage sends its own head. */\nfunction sentHead(outgoing: ServerResponse): string[] {\n\tconst head: string[] = [];\n\tfor (const [name, value] of Object.entries(outgoing.getHeaders())) {\n\t\tfor (const each of Array.isArray(value) ? value : [value]) {\n\t\t\tif (each != null) {\n\t\t\t\thead.push(name, String(each));\n\t\t\t}\n\t\t}\n\t}\n\treturn head;\n}\n\n/** Writes the head and the body of `response`, with `head` in place of its headers. */\nasync function writeBody(\n\tresponse: Response,\n\treader: ReadableStreamDefaultReader<Uint8Array> | undefined,\n\t{ outgoing, edge, head }: { outgoing: ServerResponse; edge: ResponseEdge; head: string[] },\n): Promise<void> {\n\tconst { body, status } = response;\n\tif (body == null || reader == null) {\n\t\toutgoing.writeHead(status, head);\n\t\toutgoing.end();\n\t\treturn;\n\t}\n\tif (headerIndex(head, \"content-type\") === -1) {\n\t\thead.push(\"content-type\", DEFAULT_CONTENT_TYPE);\n\t}\n\tconst ahead = await readAhead(reader, body);\n\tif (outgoing.destroyed) {\n\t\treturn;\n\t}\n\tif (ahead.done) {\n\t\tconst index = headerIndex(head, \"content-length\");\n\t\tif (index === -1 && headerIndex(head, \"transfer-encoding\") === -1) {\n\t\t\thead.push(\"content-length\", String(ahead.size));\n\t\t} else if (index !== -1 && Number(head[index + 1]) !== ahead.size) {\n\t\t\tthrow new Error(\"The body does not match its Content-Length.\");\n\t\t}\n\t\toutgoing.writeHead(status, head);\n\t\toutgoing.end(ahead.chunks.length === 1 ? ahead.chunks[0] : Buffer.concat(ahead.chunks));\n\t\tedge.bytes += ahead.size;\n\t\treturn;\n\t}\n\toutgoing.writeHead(status, head);\n\tfor (const chunk of ahead.chunks) {\n\t\toutgoing.write(chunk);\n\t\tedge.bytes += chunk.byteLength;\n\t}\n\tif (ahead.chunks.length === 0) {\n\t\t// Why: the client gets the head at once, such as the open of an event stream.\n\t\toutgoing.flushHeaders();\n\t}\n\tawait pump(reader, ahead.pending ?? reader.read(), { outgoing, edge });\n}\n\n/**\n * Writes `response` to `outgoing`, with the headers that the server gave\n * `edge` for it, and counts the body bytes in `edge`. It never rejects.\n *\n * - A body that ends within two reads of the chunks that it has queued goes\n * out with its `Content-Length`, in one socket write with the head.\n * - When the first chunk is not ready, the head goes out at once, so an event\n * stream opens at once. A stream of the host's gzip whose source gave bytes\n * is the exception: zlib finishes it soon, so the head waits for it.\n * - It reads the next chunk only when Node takes the last one, and it cancels\n * the body when the socket closes.\n * - When a step fails before the head goes out, such as a body that fails or\n * a header that Node rejects, a 500 goes out. After the head, a failure or\n * a body that does not match its `Content-Length` destroys the socket, so\n * no client and no cache keeps a cut response as complete.\n */\nasync function writeResponse(\n\tresponse: Response,\n\toutgoing: ServerResponse,\n\tedge: ResponseEdge,\n): Promise<void> {\n\tconst { body } = response;\n\tlet { status } = response;\n\tconst sendsBody = outgoing.req.method !== \"HEAD\";\n\tif (body == null && response.headers.has(ALREADY_SENT_HEADER)) {\n\t\t// Why: the dev server stage answered through Node's response, and gave its status and length.\n\t\t// Node sends no body for HEAD.\n\t\tedge.bytes = sendsBody ? Number(response.headers.get(\"content-length\") ?? 0) : 0;\n\t\tedge.close(status, false, sentHead(outgoing));\n\t\treturn;\n\t}\n\t// Why one list: `writeBody` adds the headers that it sets, so the report gets the head that went out.\n\tlet head = edge.headersFor(response) ?? headerList(response.headers);\n\tif (outgoing.destroyed) {\n\t\tedge.close(status, true, head);\n\t\tawait body?.cancel().catch(() => {});\n\t\treturn;\n\t}\n\tlet reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\t// Why one listener: it reports what went out and stops the body that the client no longer reads.\n\t// Why `on`: a response emits `close` once, and `once` adds a wrapper for each request.\n\toutgoing.on(\"close\", () => {\n\t\tedge.close(status, !outgoing.writableFinished, head);\n\t\treader?.cancel().catch(() => {});\n\t});\n\ttry {\n\t\treader = body?.getReader();\n\t\t// Why strict: Node then throws for a body that is longer or shorter than its `Content-Length`.\n\t\toutgoing.strictContentLength = true;\n\t\tawait writeBody(response, reader, { outgoing, edge, head });\n\t} catch (error) {\n\t\treader?.cancel(error).catch(() => {});\n\t\tedge.fail(error);\n\t\tif (outgoing.headersSent || outgoing.destroyed) {\n\t\t\toutgoing.destroy(error instanceof Error ? error : new Error(String(error)));\n\t\t\treturn;\n\t\t}\n\t\tstatus = 500;\n\t\thead = [\"content-type\", DEFAULT_CONTENT_TYPE, \"content-length\", String(ERROR_BODY.byteLength)];\n\t\toutgoing.writeHead(status, head);\n\t\toutgoing.end(ERROR_BODY);\n\t\tif (sendsBody) {\n\t\t\tedge.bytes += ERROR_BODY.byteLength;\n\t\t}\n\t}\n}\n\n/**\n * Runs `create`, which makes a listener of `@hono/node-server`, and keeps the\n * global `Response`. The listener makes its own `Request` class global.\n *\n * Why its `Request`: the listener gives each route a light request, and only\n * that class can copy it, such as `new Request(c.req.raw, init)` in Hono's\n * `methodOverride`. Why not its `Response`: a `fetch()` result must stay an\n * `instanceof Response`, as on Bun and Deno.\n *\n * @example\n * const listener = keepGlobalResponse(() => getRequestListener(app.fetch));\n */\nexport function keepGlobalResponse<T>(create: () => T): T {\n\t// Why the descriptor: on Deno, the listener leaves a `Response` that no one can assign.\n\tconst descriptor = Object.getOwnPropertyDescriptor(globalThis, \"Response\");\n\ttry {\n\t\treturn create();\n\t} finally {\n\t\tif (descriptor != null) {\n\t\t\tObject.defineProperty(globalThis, \"Response\", descriptor);\n\t\t}\n\t}\n}\n\n/** A `Host` header that a URL keeps as it is: a name or an address, and an optional port. */\nconst VALID_HOST = /^[a-z0-9.-]+(?::\\d{1,5})?$/iu;\n\n/** The request target that the client sent, on a request that {@link useForwardedProto} changed. */\nconst SENT_TARGET = Symbol(\"sentTarget\");\n\n/** A Node request whose target can carry the target that the client sent. */\ntype Targeted = IncomingMessage & { [SENT_TARGET]?: string };\n\n/**\n * Gives `incoming` an absolute target with the scheme of its\n * `X-Forwarded-Proto`. Why: `@hono/node-server` takes the scheme from the\n * socket, which is plain HTTP behind a proxy that ends TLS. A target with the\n * scheme gives the request its URL when it is made, so the server copies no\n * request to change it. {@link listenerOf} then puts the target that the\n * client sent back.\n */\nfunction useForwardedProto(incoming: Targeted): void {\n\tconst { host, \"x-forwarded-proto\": proto } = incoming.headers;\n\tconst target = incoming.url;\n\tif (\n\t\t(proto === \"https\" || proto === \"http\") &&\n\t\thost != null &&\n\t\tVALID_HOST.test(host) &&\n\t\ttarget?.startsWith(\"/\") === true\n\t) {\n\t\tincoming[SENT_TARGET] = target;\n\t\t// Why drop `:80` for https: a proxy can send the port of its own hop, and the server took the\n\t\t// scheme from the socket first, where 80 is the default port, so the URL never kept it.\n\t\tconst authority = proto === \"https\" && host.endsWith(\":80\") ? host.slice(0, -3) : host;\n\t\tincoming.url = `${proto}://${authority}${target}`;\n\t}\n}\n\n/**\n * Why not on Bun and Deno: their `node:http` does not always emit `close` or\n * set `destroyed`, so `@hono/node-server` writes the response there.\n */\nconst writesResponses = !(\"Bun\" in globalThis) && !(\"Deno\" in globalThis);\n\n/**\n * A `node:http` request listener. `@hono/node-server` builds each request,\n * `answer` makes the response, and the listener writes it. Each HTTP/1\n * request on Node.js gets an `edge` binding, so the server gives the listener\n * the headers after its header hooks, and the access log takes the bytes from\n * the listener.\n * With `trustForwardedProto`, each request takes its scheme from\n * `X-Forwarded-Proto`, as the server option does.\n *\n * @example\n * http.createServer(requestListener(async (request, bindings) => app.fetch(request, bindings)));\n */\nexport function requestListener(\n\tanswer: (request: Request, bindings: NodeBindings) => Response | Promise<Response>,\n\t{ trustForwardedProto = false }: { trustForwardedProto?: boolean } = {},\n): ReturnType<typeof getRequestListener> {\n\tconst listener = listenerOf(answer);\n\treturn trustForwardedProto\n\t\t? async (incoming, outgoing) => {\n\t\t\t\tif (incoming instanceof IncomingMessage) {\n\t\t\t\t\tuseForwardedProto(incoming);\n\t\t\t\t}\n\t\t\t\treturn listener(incoming, outgoing);\n\t\t\t}\n\t\t: listener;\n}\n\n/** The listener of {@link requestListener}, with no scheme from `X-Forwarded-Proto`. */\nfunction listenerOf(\n\tanswer: (request: Request, bindings: NodeBindings) => Response | Promise<Response>,\n): ReturnType<typeof getRequestListener> {\n\treturn keepGlobalResponse(() =>\n\t\tgetRequestListener(async (request, { incoming, outgoing }) => {\n\t\t\tconst { remoteAddress } = incoming.socket;\n\t\t\t// Why: an HTTP/2 response is not a `ServerResponse`, so `@hono/node-server` writes it.\n\t\t\tif (!(incoming instanceof IncomingMessage) || !(outgoing instanceof ServerResponse)) {\n\t\t\t\treturn answer(request, { remoteAddress } satisfies ListenerBindings);\n\t\t\t}\n\t\t\tconst targeted: Targeted = incoming;\n\t\t\tconst target = targeted[SENT_TARGET];\n\t\t\t// Why: the request has its URL now, and the app gets the target that the client sent.\n\t\t\tif (target != null) {\n\t\t\t\tincoming.url = target;\n\t\t\t}\n\t\t\tif (!writesResponses) {\n\t\t\t\tconst response = await answer(request, { remoteAddress, incoming, outgoing });\n\t\t\t\t// Why: `@hono/node-server` drops the body of a response whose socket closed, with no cancel.\n\t\t\t\tif (outgoing.destroyed) {\n\t\t\t\t\tawait response.body?.cancel();\n\t\t\t\t}\n\t\t\t\treturn response;\n\t\t\t}\n\t\t\tconst edge = new ResponseEdge();\n\t\t\tlet response: Response;\n\t\t\ttry {\n\t\t\t\tresponse = await answer(request, { remoteAddress, incoming, outgoing, edge });\n\t\t\t} catch (error) {\n\t\t\t\t// Why 500 with no headers: `@hono/node-server` answers a failed request with one.\n\t\t\t\tedge.close(500, false, []);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tawait writeResponse(response, outgoing, edge);\n\t\t\treturn ALREADY_SENT;\n\t\t}),\n\t);\n}\n"],"mappings":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C;AACJ;;AAGA,SAAS,WACR,QACwC;CACxC,OAAO,yBACN,mBAAmB,OAAO,SAAS,EAAE,UAAU,eAAe;EAC7D,MAAM,EAAE,kBAAkB,SAAS;EAEnC,IAAI,EAAE,oBAAoB,oBAAoB,EAAE,oBAAoB,iBACnE,OAAO,OAAO,SAAS,EAAE,cAAc,CAA4B;EAGpE,MAAM,SAASA,SAAS;EAExB,IAAI,UAAU,MACb,SAAS,MAAM;EAEhB,IAAI,CAAC,iBAAiB;GACrB,MAAM,WAAW,MAAM,OAAO,SAAS;IAAE;IAAe;IAAU;GAAS,CAAC;GAE5E,IAAI,SAAS,WACZ,MAAM,SAAS,MAAM,OAAO;GAE7B,OAAO;EACR;EACA,MAAM,OAAO,IAAI,aAAa;EAC9B,IAAI;EACJ,IAAI;GACH,WAAW,MAAM,OAAO,SAAS;IAAE;IAAe;IAAU;IAAU;GAAK,CAAC;EAC7E,SAAS,OAAO;GAEf,KAAK,MAAM,KAAK,OAAO,CAAC,CAAC;GACzB,MAAM;EACP;EACA,MAAM,cAAc,UAAU,UAAU,IAAI;EAC5C,OAAO;CACR,CAAC,CACF;AACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"start-DREqYrZh.js","names":["createServer","createHttpServer"],"sources":["../src/cli/served-apps.ts","../src/cli/start-port.ts","../src/cli/start.ts"],"sourcesContent":["import type { AppServerEntry } from \"../core/entry.js\";\n\ntype ServedApp = { entry: AppServerEntry; pending: number; replaced: boolean };\n\n/** What {@link servedApps} returns. */\ntype ServedApps = {\n\t/** Runs `handle` for a request that `entry` serves. */\n\tserve: <Result>(\n\t\tentry: AppServerEntry,\n\t\thandle: (entry: AppServerEntry) => Promise<Result>,\n\t) => Promise<Result>;\n\t/**\n\t * At exit: aborts `shutdownSignal()` and runs the `onShutdown` hooks of each\n\t * app still held. Resolves when the hooks finish or pass the deadline.\n\t */\n\tstopAll: () => Promise<void>;\n};\n\n/**\n * Tracks the apps that `app-server start` serves. An edit to `server.ts` makes a\n * new app, and the old app's plugins still hold what their `setup` opened.\n * When the last request that the old app took returns, its `onShutdown` hooks\n * run, and the tracker lets go of it. A route edit makes a new entry with the\n * same app, which keeps its plugins.\n */\nexport function servedApps(): ServedApps {\n\tlet current: ServedApp | undefined;\n\tconst served = new Set<ServedApp>();\n\t// Why keep the app until its hooks settle: `stopAll` must wait for hooks that already run.\n\t// `stopPlugins` runs the hooks once, so a second call only waits.\n\tconst retire = async (app: ServedApp) => {\n\t\ttry {\n\t\t\tawait app.entry.stopPlugins();\n\t\t} finally {\n\t\t\tserved.delete(app);\n\t\t}\n\t};\n\treturn {\n\t\tserve: async (entry, handle) => {\n\t\t\tif (current?.entry.app === entry.app) {\n\t\t\t\tcurrent.entry = entry;\n\t\t\t} else {\n\t\t\t\tif (current != null) {\n\t\t\t\t\tcurrent.replaced = true;\n\t\t\t\t\tif (current.pending === 0) {\n\t\t\t\t\t\tvoid retire(current);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent = { entry, pending: 0, replaced: false };\n\t\t\t\tserved.add(current);\n\t\t\t}\n\t\t\tconst app = current;\n\t\t\tapp.pending += 1;\n\t\t\ttry {\n\t\t\t\treturn await handle(entry);\n\t\t\t} finally {\n\t\t\t\tapp.pending -= 1;\n\t\t\t\tif (app.replaced && app.pending === 0) {\n\t\t\t\t\tvoid retire(app);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tstopAll: async () => {\n\t\t\tawait Promise.all(\n\t\t\t\tArray.from(served, async (app) => {\n\t\t\t\t\tapp.entry.abortShutdownSignal();\n\t\t\t\t\tawait retire(app);\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t};\n}\n","import { createServer } from \"node:net\";\nimport type { Server } from \"node:net\";\n\nconst MAX_PORT = 65_535;\n\n/** Options for {@link listenFromPort}. */\nexport type ListenFromPortOptions = {\n\t/** The first port to try. 0 lets the OS pick one. */\n\tport: number;\n\t/** @default every interface */\n\thostname?: string | undefined;\n\t/** When true, a port in use throws and no other port is tried. */\n\tstrictPort: boolean;\n\t/** Runs for each port in use before the next port is tried. */\n\tonPortInUse?: (port: number) => void;\n\t/**\n\t * Runs when `strictPort` is true and the server listens on `hostname`, but\n\t * another server holds the port on a wildcard address.\n\t */\n\tonWildcardInUse?: (port: number) => void;\n};\n\n/**\n * Starts `server` on `port`. When the port is in use, it tries each next port\n * up to 65535, like Vite and `react-router-serve` do in development.\n *\n * @returns the port that the server listens on\n */\nexport async function listenFromPort(\n\tserver: Server,\n\t{ port, hostname, strictPort, onPortInUse, onWildcardInUse }: ListenFromPortOptions,\n): Promise<number> {\n\tif (port === 0) {\n\t\tawait bind(server, port, hostname);\n\t\treturn boundPort(server, port);\n\t}\n\tif (strictPort) {\n\t\t// Why a warning and not an error: a server on one other address also fails the wildcard\n\t\t// check, and that server does not share `hostname`. Vite warns for the same reason.\n\t\tconst freeOnWildcard = hostname == null || (await isFreeOnWildcard(port));\n\t\tawait bind(server, port, hostname);\n\t\tif (!freeOnWildcard) {\n\t\t\tonWildcardInUse?.(port);\n\t\t}\n\t\treturn port;\n\t}\n\tfor (let candidate = port; candidate <= MAX_PORT; candidate++) {\n\t\t// Why the wildcard check: a server on `::` and a server on `localhost` can share a port, and\n\t\t// then the browser can reach the other server.\n\t\tif (hostname == null || (await isFreeOnWildcard(candidate))) {\n\t\t\ttry {\n\t\t\t\tawait bind(server, candidate, hostname);\n\t\t\t\treturn candidate;\n\t\t\t} catch (error) {\n\t\t\t\tif (!isAddressInUse(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tonPortInUse?.(candidate);\n\t}\n\tthrow new Error(`No open port from ${port} to ${MAX_PORT}.`);\n}\n\nasync function bind(server: Server, port: number, hostname: string | undefined): Promise<void> {\n\treturn new Promise<void>((resolve, reject) => {\n\t\tfunction onError(error: Error) {\n\t\t\tserver.off(\"listening\", onListening);\n\t\t\treject(error);\n\t\t}\n\t\tfunction onListening() {\n\t\t\tserver.off(\"error\", onError);\n\t\t\tresolve();\n\t\t}\n\t\tserver.once(\"error\", onError);\n\t\tserver.once(\"listening\", onListening);\n\t\tserver.listen(port, hostname);\n\t});\n}\n\nasync function isFreeOnWildcard(port: number): Promise<boolean> {\n\tconst probe = createServer();\n\ttry {\n\t\tawait bind(probe, port, undefined);\n\t} catch (error) {\n\t\tif (isAddressInUse(error)) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow error;\n\t}\n\tawait new Promise<void>((resolve) => {\n\t\tprobe.close(() => {\n\t\t\tresolve();\n\t\t});\n\t});\n\treturn true;\n}\n\nfunction boundPort(server: Server, fallback: number): number {\n\tconst address = server.address();\n\treturn typeof address === \"object\" && address != null ? address.port : fallback;\n}\n\nfunction isAddressInUse(error: unknown): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === \"EADDRINUSE\";\n}\n","import { createServer as createHttpServer } from \"node:http\";\nimport { errorAttributes, jsonSink } from \"../core/log.js\";\nimport { devServerStage } from \"../node/dev-server.js\";\nimport { exitAfterFlush } from \"../node/exit.js\";\nimport { listenerUrl } from \"../node/runtimes/listen-options.js\";\nimport { requestListener } from \"../node/response-writer.js\";\nimport { parsePort } from \"../node/tcp.js\";\nimport { SERVER_ENTRY_ID } from \"../vite/index.js\";\nimport { loadEntry } from \"./load-entry.js\";\nimport { servedApps } from \"./served-apps.js\";\nimport { listenFromPort } from \"./start-port.js\";\n\n/**\n * Runs the app in development: the same pipeline as production, with Vite in\n * middleware mode inside it. Each request loads the server entry through\n * Vite's SSR runner, so an edit to a route or to the app's `server.ts` applies\n * at once. HMR shares the port.\n *\n * The port is `--port`, else `PORT`, else Vite's `server.port`. When that port is in use, the\n * server tries each next port, unless Vite's `server.strictPort` is true. The\n * host is `HOST`, else Vite's `server.host`.\n */\nexport async function start(): Promise<void> {\n\tconst vite = await import(\"vite\");\n\tconst httpServer = createHttpServer();\n\tconst viteServer = await vite.createServer({\n\t\tserver: { middlewareMode: true, ws: { server: httpServer } },\n\t\tappType: \"custom\",\n\t});\n\t// Why read it for each request: a Vite restart, such as after a config edit, replaces the environments.\n\tconst ssrRunner = () => {\n\t\tconst { ssr } = viteServer.environments;\n\t\tif (ssr == null || !vite.isRunnableDevEnvironment(ssr)) {\n\t\t\tthrow new Error(\"Vite's SSR environment cannot run modules.\");\n\t\t}\n\t\treturn ssr.runner;\n\t};\n\tssrRunner();\n\tif (!viteServer.config.plugins.some((plugin) => plugin.name === \"@ngrok/app-server\")) {\n\t\tawait viteServer.close();\n\t\tthrow new Error(\n\t\t\t\"`app-server start` needs the `appServer` plugin from @ngrok/app-server/vite in the Vite config.\",\n\t\t);\n\t}\n\tconst devServer = devServerStage(viteServer.middlewares, {\n\t\tpublicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),\n\t});\n\tconst sink = jsonSink();\n\tconst apps = servedApps();\n\n\tconst listener = requestListener(async (request, bindings) => {\n\t\ttry {\n\t\t\treturn await apps.serve(\n\t\t\t\tawait loadEntry(await ssrRunner().import(SERVER_ENTRY_ID)),\n\t\t\t\tasync (entry) => entry.fetchDev(request, bindings, devServer),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tviteServer.ssrFixStacktrace(error);\n\t\t\t}\n\t\t\tsink.log(\"error\", \"dev request failed\", errorAttributes(error));\n\t\t\treturn new Response(error instanceof Error ? (error.stack ?? error.message) : String(error), {\n\t\t\t\tstatus: 500,\n\t\t\t\theaders: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n\t\t\t});\n\t\t}\n\t});\n\thttpServer.on(\"request\", (request, response) => {\n\t\tvoid listener(request, response);\n\t});\n\n\tconst port =\n\t\tprocess.env.PORT == null ? viteServer.config.server.port : parsePort(process.env.PORT);\n\tconst hostname = process.env.HOST || viteHostname(viteServer.config.server.host);\n\tconst boundPort = await listenFromPort(httpServer, {\n\t\tport,\n\t\thostname,\n\t\tstrictPort: viteServer.config.server.strictPort,\n\t\tonPortInUse: (inUse) => {\n\t\t\tsink.log(\"info\", \"port in use, trying the next port\", { \"server.port\": inUse });\n\t\t},\n\t\tonWildcardInUse: (inUse) => {\n\t\t\tsink.log(\"warn\", \"port in use on a wildcard address\", {\n\t\t\t\t\"server.port\": inUse,\n\t\t\t\t\"server.address\": hostname,\n\t\t\t});\n\t\t},\n\t});\n\tsink.log(\"info\", \"listening\", { \"app_server.urls\": [listenerUrl(hostname, boundPort)] });\n\n\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\tprocess.once(signal, () => {\n\t\t\tconst pluginsStopped = apps.stopAll();\n\t\t\thttpServer.closeAllConnections();\n\t\t\tconst httpClosed = new Promise<void>((resolve) => {\n\t\t\t\thttpServer.close(() => {\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t});\n\t\t\tconst viteClosed = viteServer.close().catch((error: unknown) => {\n\t\t\t\tsink.log(\"error\", \"Vite close failed\", errorAttributes(error));\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t});\n\t\t\tvoid Promise.all([pluginsStopped, httpClosed, viteClosed]).finally(exitAfterFlush);\n\t\t});\n\t}\n}\n\n/** The hostname for Vite's `server.host`: `true` is every interface, and no value is `localhost`. */\nfunction viteHostname(host: string | boolean | undefined): string | undefined {\n\tif (host === true) {\n\t\treturn undefined;\n\t}\n\treturn typeof host === \"string\" && host !== \"\" ? host : \"localhost\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyBA,SAAgB,aAAyB;CACxC,IAAI;CACJ,MAAM,yBAAS,IAAI,IAAe;CAGlC,MAAM,SAAS,OAAO,QAAmB;EACxC,IAAI;GACH,MAAM,IAAI,MAAM,YAAY;EAC7B,UAAU;GACT,OAAO,OAAO,GAAG;EAClB;CACD;CACA,OAAO;EACN,OAAO,OAAO,OAAO,WAAW;GAC/B,IAAI,SAAS,MAAM,QAAQ,MAAM,KAChC,QAAQ,QAAQ;QACV;IACN,IAAI,WAAW,MAAM;KACpB,QAAQ,WAAW;KACnB,IAAI,QAAQ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AAC,WAAW,QAAQ,GACxC,QAAQ,KAAK,cAAc;EAC1B,MAAM,iBAAiB,KAAK,QAAQ;EACpC,WAAW,oBAAoB;EAC/B,MAAM,aAAa,IAAI,SAAe,YAAY;GACjD,WAAW,YAAY;IACtB,QAAQ;GACT,CAAC;EACF,CAAC;EACD,MAAM,aAAa,WAAW,MAAM,CAAC,CAAC,OAAO,UAAmB;GAC/D,KAAK,IAAI,SAAS,qBAAqB,gBAAgB,KAAK,CAAC;GAC7D,QAAQ,WAAW;EACpB,CAAC;EACD,AAAK,QAAQ,IAAI;GAAC;GAAgB;GAAY;EAAU,CAAC,CAAC,CAAC,QAAQ,cAAc;CAClF,CAAC;AAEH;;AAGA,SAAS,aAAa,MAAwD;CAC7E,IAAI,SAAS,MACZ;CAED,OAAO,OAAO,SAAS,YAAY,SAAS,KAAK,OAAO;AACzD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"static-files-Beju9riB.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\".md\": \"text/markdown; 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,M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O,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":"vite-tTxVimP6.js","names":["constants"],"sources":["../src/vite/standalone.ts","../src/vite/index.ts"],"sourcesContent":["import { cpSync, existsSync, readdirSync, readFileSync, realpathSync } from \"node:fs\";\nimport { basename, dirname, join, sep } from \"node:path\";\n\n/**\n * A package name: an optional scope and a name, each with no `/` or `\\` and\n * no `.` at the start. Why: a name such as `..` or `../x` in a manifest must\n * not move a copy out of `node_modules`.\n */\nconst PACKAGE_NAME = /^(?:@[^./\\\\][^/\\\\]*\\/)?[^./\\\\][^/\\\\]*$/u;\n\n/**\n * The package names in the dependency `fields` of the `package.json` in\n * `directory`. It skips a key that is not a package name.\n *\n * @example\n * dependencyNames(\"/app/node_modules/react-dom\", [\"peerDependencies\"]); // => [\"react\"]\n */\nexport function dependencyNames(directory: string, fields: readonly string[]): string[] {\n\tconst manifest: unknown = JSON.parse(readFileSync(join(directory, \"package.json\"), \"utf8\"));\n\tconst names = fields.flatMap((field) => {\n\t\tconst value: unknown =\n\t\t\ttypeof manifest === \"object\" && manifest != null ? Reflect.get(manifest, field) : undefined;\n\t\treturn typeof value === \"object\" && value != null\n\t\t\t? Object.keys(value).filter((name) => PACKAGE_NAME.test(name))\n\t\t\t: [];\n\t});\n\treturn [...new Set(names)];\n}\n\n/**\n * The package name of a bare import.\n *\n * @example\n * packageName(\"@scope/name/sub/path\"); // => \"@scope/name\"\n */\nexport function packageName(specifier: string): string {\n\tconst parts = specifier.split(\"/\");\n\treturn parts.slice(0, specifier.startsWith(\"@\") ? 2 : 1).join(\"/\");\n}\n\n/**\n * Code that finds a file next to its own module: a relative `new URL()` on\n * `import.meta.url`, `fileURLToPath(import.meta.url)`, or\n * `import.meta.dirname`.\n */\nconst OWN_FILE =\n\t/new\\s+URL\\(\\s*(?<quote>[\"'`])\\.{1,2}\\/[^\"'`]*\\k<quote>\\s*,\\s*import\\.meta\\.url\\s*\\)|fileURLToPath\\(\\s*import\\.meta\\.url\\s*\\)|import\\.meta\\.(?:dirname|filename)\\b/u;\n\n/**\n * Whether the module `file` finds a file next to itself, such as\n * `@vercel/og`, which reads `resvg.wasm` through\n * `new URL(\"./resvg.wasm\", import.meta.url)`. Why: in the bundle,\n * `import.meta.url` is the URL of the bundle, so the file is not there.\n *\n * @example\n * readsOwnFiles(\"/app/node_modules/@vercel/og/dist/index.node.js\"); // => true\n */\nexport function readsOwnFiles(file: string): boolean {\n\treturn OWN_FILE.test(readFileSync(file, \"utf8\"));\n}\n\n/**\n * The real path of the directory of package `name`, as Node finds it from the\n * directory `from`: in each `node_modules` directory above `from`. Else\n * `undefined`. The real path follows the symbolic links of pnpm's layout.\n *\n * @example\n * findPackage(\"react\", \"/app/build/server\"); // => \"/app/node_modules/.pnpm/react@19.3.1/node_modules/react\"\n */\nexport function findPackage(name: string, from: string): string | undefined {\n\tfor (let directory = from; ; directory = dirname(directory)) {\n\t\tconst candidate = join(directory, \"node_modules\", name);\n\t\tif (basename(directory) !== \"node_modules\" && existsSync(join(candidate, \"package.json\"))) {\n\t\t\treturn realpathSync(candidate);\n\t\t}\n\t\tif (dirname(directory) === directory) {\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n\n/**\n * The directory of package `name` that holds `file`: the nearest directory\n * above `file` at `node_modules/<name>`. Else `undefined`, such as for a file\n * of a linked workspace package.\n *\n * @example\n * packageDirectoryOf(\"/app/node_modules/react/cjs/react.js\", \"react\"); // => \"/app/node_modules/react\"\n */\nexport function packageDirectoryOf(file: string, name: string): string | undefined {\n\tfor (\n\t\tlet directory = dirname(file);\n\t\tdirectory !== dirname(directory);\n\t\tdirectory = dirname(directory)\n\t) {\n\t\tif (directory.endsWith(`${sep}${join(\"node_modules\", name)}`)) {\n\t\t\t// Why the real path: `findPackage` gives real paths, and the two must compare equal.\n\t\t\treturn realpathSync(directory);\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** Whether a `.node` file is in `directory`, outside its `node_modules`. */\nfunction hasNodeFile(directory: string): boolean {\n\treturn readdirSync(directory, { withFileTypes: true }).some((entry) =>\n\t\tentry.isDirectory()\n\t\t\t? entry.name !== \"node_modules\" && hasNodeFile(join(entry.parentPath, entry.name))\n\t\t\t: entry.name.endsWith(\".node\"),\n\t);\n}\n\n/**\n * Whether the package in `directory` loads a native addon: a `.node` file is\n * in the package, or in a package of its `dependencies` or\n * `optionalDependencies`. The second case finds a package that gets its addon\n * from a package for each platform, such as `oxc-parser` from\n * `@oxc-parser/binding-darwin-arm64`. Only the installed platform package is\n * there. `scans` keeps the result for each directory that the function\n * searched, so a call with the same map does not search a directory again.\n *\n * @example\n * isNativePackage(\"/app/node_modules/better-sqlite3\"); // => true\n */\nexport function isNativePackage(directory: string, scans = new Map<string, boolean>()): boolean {\n\tconst scan = (path: string): boolean => {\n\t\tconst found = scans.get(path) ?? hasNodeFile(path);\n\t\tscans.set(path, found);\n\t\treturn found;\n\t};\n\treturn (\n\t\tscan(directory) ||\n\t\tdependencyNames(directory, [\"dependencies\", \"optionalDependencies\"]).some((name) => {\n\t\t\tconst dependency = findPackage(name, directory);\n\t\t\treturn dependency != null && scan(dependency);\n\t\t})\n\t);\n}\n\n/**\n * The `node_modules` directories where Node looks for a package that the\n * package at `destination` imports, nearest first, down to `target`.\n */\nfunction lookupDirectories(destination: string, target: string): string[] {\n\tconst directories: string[] = [];\n\tfor (let directory = destination; ; directory = dirname(directory)) {\n\t\tif (basename(directory) !== \"node_modules\") {\n\t\t\tdirectories.push(join(directory, \"node_modules\"));\n\t\t}\n\t\tif (directory === dirname(target)) {\n\t\t\treturn directories;\n\t\t}\n\t}\n}\n\n/**\n * Copies each package, whole, with the installed packages of its\n * `dependencies`, `optionalDependencies`, and `peerDependencies`, into the\n * `node_modules` directory `target`. Node then finds each package from a file\n * next to `target`, with no install. The copy follows symbolic links. A\n * dependency goes to the top of `target`. If another copy of that package is\n * nearer in the lookup path of the package that needs it, the dependency goes\n * into that package's own `node_modules`.\n *\n * @example\n * copyPackages(new Map([[\"oxc-parser\", \"/app/node_modules/oxc-parser\"]]), \"/app/build/server/node_modules\");\n */\nexport function copyPackages(packages: ReadonlyMap<string, string>, target: string): void {\n\t// Why a map of destinations: a later lookup must know which copy is at each path.\n\tconst sources = new Map<string, string>();\n\tconst queue: string[] = [];\n\tconst add = (destination: string, source: string) => {\n\t\tsources.set(destination, source);\n\t\tqueue.push(destination);\n\t};\n\tfor (const [name, source] of packages) {\n\t\tadd(join(target, name), source);\n\t}\n\t// Why breadth first: a package places all its own dependencies before a dependency looks up\n\t// its own, so a later copy never hides an earlier lookup.\n\tfor (const destination of queue) {\n\t\tconst source = sources.get(destination) ?? \"\";\n\t\tcpSync(source, destination, {\n\t\t\trecursive: true,\n\t\t\tdereference: true,\n\t\t\tfilter: (path) => path !== join(source, \"node_modules\"),\n\t\t});\n\t\tfor (const name of dependencyNames(source, [\n\t\t\t\"dependencies\",\n\t\t\t\"optionalDependencies\",\n\t\t\t\"peerDependencies\",\n\t\t])) {\n\t\t\tconst dependency = findPackage(name, source);\n\t\t\tconst found = lookupDirectories(destination, target)\n\t\t\t\t.map((directory) => join(directory, name))\n\t\t\t\t.find((path) => sources.has(path));\n\t\t\tif (dependency != null && (found == null || sources.get(found) !== dependency)) {\n\t\t\t\tadd(join(found == null ? target : join(destination, \"node_modules\"), name), dependency);\n\t\t\t}\n\t\t}\n\t}\n}\n","import { createHash } from \"node:crypto\";\nimport {\n\texistsSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trmSync,\n\tstatSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { isBuiltin } from \"node:module\";\nimport { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { brotliCompressSync, constants, gzipSync } from \"node:zlib\";\nimport { getPath } from \"hono/utils/url\";\nimport type { Environment, Plugin, PreviewServer, ResolvedConfig, Rolldown } from \"vite\";\nimport { BUILD_MANIFEST_FILE, manifestKey } from \"../core/build-manifest.js\";\nimport type { BuildManifest } from \"../core/build-manifest.js\";\nimport { copyName, isCompressible, MIN_COMPRESS_BYTES } from \"../core/compression.js\";\nimport type { Encoding } from \"../core/compression.js\";\nimport { contentType } from \"../core/static-files.js\";\nimport { scriptHashesOf } from \"../node/script-hashes.js\";\nimport { node } from \"../node/vite.js\";\nimport { reactRouterAdapter } from \"../react-router/vite.js\";\nimport { tanstackStartAdapter } from \"../tanstack-start/vite.js\";\nimport {\n\tcopyPackages,\n\tdependencyNames,\n\tfindPackage,\n\tisNativePackage,\n\tpackageDirectoryOf,\n\tpackageName,\n\treadsOwnFiles,\n} from \"./standalone.js\";\n\n/** The module ID of the server entry that {@link appServer} generates. */\nexport const SERVER_ENTRY_ID = \"virtual:@ngrok/app-server/entry\";\nconst RESOLVED_SERVER_ENTRY_ID = `\\0${SERVER_ENTRY_ID}`;\n\n/** The Vite environment that builds the server. */\nconst SERVER_ENVIRONMENT = \"ssr\";\n\n/** A bare import, such as `react` or `@scope/name/path`: not a path, a `\\0` ID, or a `node:` or `virtual:` ID. */\nconst BARE_IMPORT = /^[\\w@][^:]*$/u;\n\n/** The file extensions of a module that Node imports as it is, with no transform by Vite. */\nconst JAVASCRIPT_EXTENSIONS = new Set([\"\", \".js\", \".mjs\", \".cjs\"]);\n\n/** The header that turns on Node's header store for a response, so `finish` can read every header. */\nconst CAPTURE_MARKER = \"x-app-server-capture\";\n\n/**\n * Headers that describe one transfer, not the resource. The server sets its\n * own, and a cookie must never replay to every visitor. `Vary` is left out\n * because the preview server adds `Vary: Origin` to every response.\n */\nconst UNCAPTURED_HEADERS = new Set([\n\tCAPTURE_MARKER,\n\t\"connection\",\n\t\"content-encoding\",\n\t\"content-length\",\n\t\"date\",\n\t\"etag\",\n\t\"keep-alive\",\n\t\"last-modified\",\n\t\"set-cookie\",\n\t\"transfer-encoding\",\n\t\"vary\",\n]);\n\n/**\n * The build side of a framework adapter. The Vite config imports it, such as\n * `reactRouterAdapter()` from `@ngrok/app-server/react-router/vite`.\n */\nexport type FrameworkBuild = {\n\t/** A name for logs and errors. */\n\tname: string;\n\t/** The Vite ID of the framework's server module, such as `virtual:react-router/server-build`. */\n\tserverModule: string;\n\t/**\n\t * The module whose `runtime` export makes the run side from the server\n\t * module. It has the type `FrameworkRuntimeFactory`.\n\t */\n\truntimeModule: string;\n\t/**\n\t * The source of an object literal with more options for `runtime`, such as\n\t * a build constant of the framework. The bundler replaces the constants in\n\t * it, because the source is part of the server entry.\n\t */\n\truntimeOptions?: string;\n\t/** Whether a preview server runs the framework's prerender pass. */\n\tisPrerenderPass: (server: PreviewServer) => boolean;\n\t/** Throws for a config that the adapter does not support, so the build fails, not the first request. */\n\tvalidate?: (config: ResolvedConfig) => void;\n};\n\n/**\n * The build side of a host adapter. The Vite config imports it, such as\n * `node()` from `@ngrok/app-server/node/vite`.\n */\nexport type HostBuild = {\n\t/** A name for logs and errors. */\n\tname: string;\n\t/** The module whose `host` export is the run side, a `HostRuntime`. */\n\truntimeModule: string;\n\t/** The file name of the server entry in the server build, such as `app-server.js`. */\n\tentryFileName: string;\n\t/**\n\t * Writes the host's deploy output, such as Vercel's `.vercel/output`. It\n\t * runs after each prerender pass and after the build, so it can run two\n\t * times. Why after the pass too: when `appServer` comes before the\n\t * framework's plugin, the pass runs after the build. Why sync: Vite does\n\t * not wait for the end of that pass.\n\t */\n\toutput?: (build: HostOutput) => void;\n};\n\n/** What a host's `output` gets: the absolute paths of the build. */\nexport type HostOutput = {\n\t/** The Vite root. */\n\troot: string;\n\t/** The client build, such as `build/client`. */\n\tclientDirectory: string;\n\t/** The server entry, such as `build/server/app-server.js`. */\n\tentryFile: string;\n};\n\n/** Options for {@link appServer}. */\nexport type AppServerOptions = {\n\t/**\n\t * The framework adapter. When omitted, the plugin finds the React Router or\n\t * TanStack Start plugin in the Vite config. It throws when it finds neither\n\t * or both.\n\t */\n\tframework?: FrameworkBuild;\n\t/** The host adapter. Default `node()`. */\n\thost?: HostBuild;\n\t/**\n\t * The module whose default export is the app from `createServer`, relative\n\t * to the Vite root. When omitted, the plugin uses `server.ts`, else\n\t * `server.js`, in the Vite root. When neither exists, the server uses its\n\t * default plugins.\n\t */\n\tapp?: string;\n};\n\n/** The built-in framework adapters, each with the name of the Vite plugin that marks its framework. */\nconst FRAMEWORKS = [\n\t// Why not the `react-router` plugin: React Router's child compiler drops that plugin and keeps\n\t// this one, which serves the server module.\n\t{ plugin: \"react-router:virtual-modules\", adapter: reactRouterAdapter },\n\t{ plugin: \"tanstack-react-start:config\", adapter: tanstackStartAdapter },\n];\n\n/** The adapter of the one built-in framework whose plugin is in the Vite config. */\nfunction detectFramework(plugins: readonly Plugin[]): FrameworkBuild {\n\tconst names = new Set(plugins.map((plugin) => plugin.name));\n\tconst [found, ...others] = FRAMEWORKS.filter(({ plugin }) => names.has(plugin));\n\tif (found == null) {\n\t\tthrow new Error(\n\t\t\t\"@ngrok/app-server found no React Router or TanStack Start plugin in the Vite config. Add the framework's plugin, or pass `framework` to `appServer`.\",\n\t\t);\n\t}\n\tif (others.length > 0) {\n\t\tthrow new Error(\n\t\t\t\"@ngrok/app-server found the React Router and the TanStack Start plugins in the Vite config. Pass `framework` to `appServer`.\",\n\t\t);\n\t}\n\treturn found.adapter();\n}\n\n/** The absolute path of `server.ts` or `server.js` in `root`, else `undefined` for the default app. */\nfunction defaultApp(root: string): string | undefined {\n\treturn [\"server.ts\", \"server.js\"]\n\t\t.map((name) => join(root, name))\n\t\t.find((path) => existsSync(path));\n}\n\n/** What {@link serverEntrySource} needs. */\ntype EntrySource = {\n\tframework: Pick<FrameworkBuild, \"serverModule\" | \"runtimeModule\" | \"runtimeOptions\">;\n\thost: Pick<HostBuild, \"runtimeModule\">;\n\t/** The absolute path of the app module, else `undefined` for the default app. */\n\tappModule: string | undefined;\n\t/** The source of an expression that gives the client build: a path or a `file:` URL. */\n\tclientDirectory: string;\n};\n\n/**\n * The source of the server entry. When a runtime runs the file as its main\n * module, such as `node build/server/app-server.js`, the entry starts the\n * server. When the CLI imports it, the CLI starts the server.\n */\nexport function serverEntrySource({\n\tframework,\n\thost,\n\tappModule,\n\tclientDirectory,\n}: EntrySource): string {\n\tconst modules = [\n\t\tframework.serverModule,\n\t\t// Why from the bundle: the CLI calls this export, so the server runs on the bundle's copy of\n\t\t// this package and of the framework, the same copies as the app and the routes.\n\t\t\"@ngrok/app-server\",\n\t\tframework.runtimeModule,\n\t\thost.runtimeModule,\n\t\t...(appModule == null ? [] : [appModule]),\n\t];\n\treturn [\n\t\t// Why before the imports: React reads `NODE_ENV` when it loads. Why dynamic imports: a static\n\t\t// import loads before this line.\n\t\t\"if (import.meta.main) {\",\n\t\t'\\tprocess.env.NODE_ENV ??= \"production\";',\n\t\t'\\tif (typeof process.setSourceMapsEnabled === \"function\") {',\n\t\t\"\\t\\tprocess.setSourceMapsEnabled(true);\",\n\t\t\"\\t}\",\n\t\t\"}\",\n\t\t`const [serverModule, { createEntry, createServer }, { runtime }, hostModule${appModule == null ? \"\" : \", { default: app }\"}] = await Promise.all([`,\n\t\t...modules.map((module) => `\\timport(${JSON.stringify(module)}),`),\n\t\t\"]);\",\n\t\t...(appModule == null\n\t\t\t? [\n\t\t\t\t\t`const app = createServer({ trustForwardedProto: process.env.TRUST_FORWARDED_PROTO === \"1\", trustedProxyHops: Number(process.env.TRUSTED_PROXY_HOPS ?? 0) });`,\n\t\t\t\t]\n\t\t\t: []),\n\t\t`export const appServer = createEntry({`,\n\t\t`\\tapp,`,\n\t\t`\\thost: hostModule.host,`,\n\t\t`\\tclientDirectory: ${clientDirectory},`,\n\t\t`\\tframework: (mode) => runtime(serverModule, { ${framework.runtimeOptions == null ? \"\" : `...${framework.runtimeOptions}, `}mode }),`,\n\t\t`});`,\n\t\t// Why: a serverless host's function file calls the run side through the bundle's copy.\n\t\t\"export { hostModule };\",\n\t\t\"if (import.meta.main) {\",\n\t\t\"\\tawait appServer.start();\",\n\t\t\"}\",\n\t].join(\"\\n\");\n}\n\n/** The paths of the build that a host's `output` gets. */\nfunction hostOutput(config: ResolvedConfig, host: HostBuild): HostOutput {\n\treturn {\n\t\troot: config.root,\n\t\tclientDirectory: outDir(config, \"client\"),\n\t\tentryFile: join(outDir(config, SERVER_ENVIRONMENT), host.entryFileName),\n\t};\n}\n\n/** The absolute path of an environment's build output. */\nfunction outDir(config: ResolvedConfig, environment: string): string {\n\treturn resolve(\n\t\tconfig.root,\n\t\tconfig.environments[environment]?.build.outDir ?? config.build.outDir,\n\t);\n}\n\n/**\n * Whether `id` is a JavaScript file, which Node imports from `node_modules`\n * as it is. Why: a plugin can resolve a bare import to a virtual module, and\n * Vite transforms a JSON file or an asset, such as `?raw` on a file with no\n * extension.\n */\nfunction isJavaScriptFile(id: string): boolean {\n\treturn isAbsolute(id) && !id.includes(\"?\") && JAVASCRIPT_EXTENSIONS.has(extname(id));\n}\n\n/**\n * A `require.resolve()` or an `import.meta.resolve()` of a string literal.\n * The `source` group is the string.\n */\nconst RESOLVE_CALL =\n\t/\\b(?:require|import\\.meta)\\.resolve\\(\\s*(?<quote>[\"'`])(?<source>[^\"'`$]+)\\k<quote>/gu;\n\n/** The dependency fields of the app's `package.json` that can name a package the server imports. */\nconst APP_DEPENDENCY_FIELDS = [\"dependencies\", \"optionalDependencies\", \"devDependencies\"];\n\n/** Whether `environment` builds the server. */\nfunction isServerBuild(environment: Pick<Environment, \"name\" | \"mode\">): boolean {\n\treturn environment.name === SERVER_ENVIRONMENT && environment.mode === \"build\";\n}\n\n/**\n * Makes the server build run with no install. The build bundles each\n * dependency, except the packages that the app keeps external (`ssr.external`\n * or the bundler's `external`), each native package (see `isNativePackage`),\n * each package that reads a file next to its own module (see `readsOwnFiles`),\n * and each package that the bundle shares with a package that the app keeps\n * external: the whole package of an external subpath, and each peer, at each\n * level. Those stay external, so the plugin copies each one, whole, with its\n * dependencies, into `node_modules` in the server build. It also writes a `package.json` there, so\n * Node, Bun, and Deno load the build as ES modules and find that `node_modules`.\n */\nfunction standalone(): Plugin {\n\t// Why a value for each name: two copies of one external package cannot share one `node_modules`.\n\tconst externals = new Map<string, string | undefined>();\n\t// Why: the bundle and an external package must share one copy of a package, such as `react`.\n\tconst shared = new Set<string>();\n\tconst natives = new Map<string, boolean>();\n\t// Why: many packages share one dependency, and each search reads its whole directory.\n\tconst scans = new Map<string, boolean>();\n\tconst isNative = (directory: string): boolean => {\n\t\tconst native = natives.get(directory) ?? isNativePackage(directory, scans);\n\t\tnatives.set(directory, native);\n\t\treturn native;\n\t};\n\t// Why: many modules import one package, and each check reads the file.\n\tconst ownFiles = new Map<string, boolean>();\n\t// Why `existsSync`: another plugin can give a module that is not on disk.\n\tconst readsOwnFile = (file: string): boolean => {\n\t\tconst reads = ownFiles.get(file) ?? (existsSync(file) && readsOwnFiles(file));\n\t\townFiles.set(file, reads);\n\t\treturn reads;\n\t};\n\t// Why: a package that stays external after the bundle holds one of its peers gets a second copy.\n\tconst inBundle = new Set<string>();\n\t/**\n\t * Whether the bundled module `file` of package `name` must stay external:\n\t * the package is native, or `file` reads a file next to it. Then the\n\t * package and each of its peers stay external, so the bundle shares them.\n\t */\n\tconst staysExternal = (\n\t\t{ name, file, directory }: { name: string; file: string; directory: string | undefined },\n\t\tlogger: Environment[\"logger\"],\n\t): boolean => {\n\t\tconst native = directory != null && isNative(directory);\n\t\tif (directory == null || (!native && !readsOwnFile(file))) {\n\t\t\tinBundle.add(name);\n\t\t\treturn false;\n\t\t}\n\t\tconst group = withPeers([{ name, from: directory }]);\n\t\tconst held = [...group].find((peer) => inBundle.has(peer));\n\t\t// Why bundle it: a second copy of a peer, such as `react`, breaks more than a lost file.\n\t\tif (held != null && !native) {\n\t\t\tlogger.warn(\n\t\t\t\t`@ngrok/app-server bundles \"${name}\", but it reads a file next to its own module, so the server can fail when it reads that file. The bundle already holds \"${held}\", so \"${name}\" cannot stay external alone. Add \"${name}\" to \\`ssr.external\\`.`,\n\t\t\t);\n\t\t\tinBundle.add(name);\n\t\t\treturn false;\n\t\t}\n\t\tfor (const peer of group) {\n\t\t\tshared.add(peer);\n\t\t}\n\t\treturn true;\n\t};\n\treturn {\n\t\tname: \"@ngrok/app-server:standalone\",\n\t\t// Why `pre`: Vite's resolver runs before a plugin with no `enforce`, so that plugin cannot keep\n\t\t// a native package out of the bundle.\n\t\tenforce: \"pre\",\n\t\tconfig: (config, { command }) => {\n\t\t\tconst ssr = config.environments?.[SERVER_ENVIRONMENT]?.resolve;\n\t\t\t// Why a build only: in development, Vite loads each dependency from `node_modules`. Why not\n\t\t\t// with the app's value: Vite merges `true` over a list, and `noExternal: true` wins over\n\t\t\t// `external: true`, so the app's value then has no effect.\n\t\t\treturn command === \"build\" &&\n\t\t\t\tconfig.ssr?.noExternal == null &&\n\t\t\t\tssr?.noExternal == null &&\n\t\t\t\tconfig.ssr?.external !== true &&\n\t\t\t\tssr?.external !== true\n\t\t\t\t? { ssr: { noExternal: true } }\n\t\t\t\t: undefined;\n\t\t},\n\t\tbuildStart() {\n\t\t\tif (!isServerBuild(this.environment)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\texternals.clear();\n\t\t\tshared.clear();\n\t\t\tnatives.clear();\n\t\t\tscans.clear();\n\t\t\townFiles.clear();\n\t\t\tinBundle.clear();\n\t\t\tconst { resolve: resolveOptions, build, root } = this.environment.config;\n\t\t\tconst kept = [\n\t\t\t\t...(resolveOptions.external === true ? [] : resolveOptions.external),\n\t\t\t\t...[build.rolldownOptions.external].flat(),\n\t\t\t];\n\t\t\tconst names = kept.flatMap((id) =>\n\t\t\t\ttypeof id === \"string\" && BARE_IMPORT.test(id) ? [packageName(id)] : [],\n\t\t\t);\n\t\t\tconst patterns = kept.filter(\n\t\t\t\t(id): id is Exclude<typeof id, string | undefined> => id != null && typeof id !== \"string\",\n\t\t\t);\n\t\t\t// Why the app's dependencies: the bundler never shows the plugin an import that a `RegExp` or\n\t\t\t// a function keeps external, so the build must find their peers before it bundles.\n\t\t\tconst matched =\n\t\t\t\tpatterns.length === 0 || !existsSync(join(root, \"package.json\"))\n\t\t\t\t\t? []\n\t\t\t\t\t: dependencyNames(root, APP_DEPENDENCY_FIELDS).filter((name) =>\n\t\t\t\t\t\t\tpatterns.some((pattern) => matchesExternal(pattern, name)),\n\t\t\t\t\t\t);\n\t\t\t// Why with no import: the app can read a file of a package at run time, such as through\n\t\t\t// `require.resolve`.\n\t\t\tfor (const name of names) {\n\t\t\t\tconst directory = findPackage(name, root);\n\t\t\t\tif (directory != null) {\n\t\t\t\t\texternals.set(name, directory);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const name of withPeers(\n\t\t\t\t[...names, ...matched].map((dependency) => ({ name: dependency, from: root })),\n\t\t\t)) {\n\t\t\t\tshared.add(name);\n\t\t\t}\n\t\t},\n\t\tresolveId: {\n\t\t\tfilter: { id: BARE_IMPORT },\n\t\t\tasync handler(source, importer, options) {\n\t\t\t\tif (!isServerBuild(this.environment) || isBuiltin(source)) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tconst resolved = await this.resolve(source, importer, { ...options, skipSelf: true });\n\t\t\t\tconst bundled = resolved?.external === false;\n\t\t\t\tif (resolved == null || (bundled && !isJavaScriptFile(resolved.id))) {\n\t\t\t\t\treturn resolved;\n\t\t\t\t}\n\t\t\t\tconst name = packageName(source);\n\t\t\t\t// Why the resolved file first: Vite can pick another copy than Node, such as for\n\t\t\t\t// `resolve.dedupe`.\n\t\t\t\tconst directory =\n\t\t\t\t\t(bundled ? packageDirectoryOf(resolved.id, name) : undefined) ??\n\t\t\t\t\tfindPackage(\n\t\t\t\t\t\tname,\n\t\t\t\t\t\timporter != null && isAbsolute(importer)\n\t\t\t\t\t\t\t? dirname(importer)\n\t\t\t\t\t\t\t: this.environment.config.root,\n\t\t\t\t\t);\n\t\t\t\tif (\n\t\t\t\t\tbundled &&\n\t\t\t\t\t!shared.has(name) &&\n\t\t\t\t\t!staysExternal({ name, file: resolved.id, directory }, this.environment.logger)\n\t\t\t\t) {\n\t\t\t\t\treturn resolved;\n\t\t\t\t}\n\t\t\t\tconst known = externals.get(name);\n\t\t\t\tif (known != null && directory != null && known !== directory) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`@ngrok/app-server found two copies of \"${name}\" that stay external, and the server build can hold one: ${known} and ${directory}. Install one version of \"${name}\".`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\texternals.set(name, known ?? directory);\n\t\t\t\treturn bundled ? { id: source, external: true } : resolved;\n\t\t\t},\n\t\t},\n\t\ttransform: {\n\t\t\t// Why only the app's code: a package that resolves a file of another package at run time,\n\t\t\t// such as an optional binary, would copy a large package that the server never reads.\n\t\t\tfilter: {\n\t\t\t\tid: { exclude: /[\\\\/]node_modules[\\\\/]/u },\n\t\t\t\tcode: /\\b(?:require|import\\.meta)\\.resolve\\(/u,\n\t\t\t},\n\t\t\thandler(code, id) {\n\t\t\t\tif (!isServerBuild(this.environment)) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\t// Why: the server reads a file of the package at run time, so the build must hold the package.\n\t\t\t\tfor (const { groups } of code.matchAll(RESOLVE_CALL)) {\n\t\t\t\t\tconst source = groups?.source ?? \"\";\n\t\t\t\t\tconst name = packageName(source);\n\t\t\t\t\tconst directory =\n\t\t\t\t\t\tBARE_IMPORT.test(source) && !isBuiltin(source) && !externals.has(name)\n\t\t\t\t\t\t\t? findPackage(name, isAbsolute(id) ? dirname(id) : this.environment.config.root)\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t// Why only a package it finds: the module-graph pass in `writeBundle` can find it from another importer.\n\t\t\t\t\tif (directory != null) {\n\t\t\t\t\t\texternals.set(name, directory);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t},\n\t\t},\n\t\twriteBundle() {\n\t\t\tif (!isServerBuild(this.environment)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Why: the bundler does not call `resolveId` for a package in its own `external` option. Why\n\t\t\t// from the importer: with pnpm, only the importer's `node_modules` holds its dependencies.\n\t\t\tfor (const importer of this.getModuleIds()) {\n\t\t\t\tconst info = this.getModuleInfo(importer);\n\t\t\t\tfor (const id of [...(info?.importedIds ?? []), ...(info?.dynamicallyImportedIds ?? [])]) {\n\t\t\t\t\tconst name = packageName(id);\n\t\t\t\t\tif (BARE_IMPORT.test(id) && !isBuiltin(id) && !externals.has(name)) {\n\t\t\t\t\t\texternals.set(\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tfindPackage(\n\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\tisAbsolute(importer) ? dirname(importer) : this.environment.config.root,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst directory = outDir(this.environment.getTopLevelConfig(), SERVER_ENVIRONMENT);\n\t\t\tconst found = new Map<string, string>();\n\t\t\tfor (const [name, source] of externals) {\n\t\t\t\tif (source == null) {\n\t\t\t\t\tthis.environment.logger.warn(\n\t\t\t\t\t\t`@ngrok/app-server cannot find \"${name}\", which stays external, so the server build does not hold it. The server fails if it imports \"${name}\".`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tfound.set(name, source);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst target = join(directory, \"node_modules\");\n\t\t\trmSync(target, { recursive: true, force: true });\n\t\t\tcopyPackages(found, target);\n\t\t\twriteFileSync(join(directory, \"package.json\"), `${JSON.stringify({ type: \"module\" })}\\n`);\n\t\t\tif (found.size > 0) {\n\t\t\t\tthis.environment.logger.info(\n\t\t\t\t\t`@ngrok/app-server copied the external packages ${[...found.keys()].join(\", \")}, with their dependencies, into ${target}.`,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Whether the app's `RegExp` or function external keeps the package `name`\n * external. Why `false` when the function throws: the build calls it with no\n * importer, and a function that reads the importer can throw.\n */\nfunction matchesExternal(\n\tpattern: RegExp | ((id: string, importer: string | undefined, isResolved: boolean) => unknown),\n\tname: string,\n): boolean {\n\tif (typeof pattern !== \"function\") {\n\t\treturn name.search(pattern) !== -1;\n\t}\n\ttry {\n\t\treturn pattern(name, undefined, false) === true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Each package of `start` and each of its peers, at each level. Why each\n * level: a peer can have peers, such as `react` for `react-router`.\n */\nfunction withPeers(start: { name: string; from: string }[]): Set<string> {\n\tconst names = new Set<string>();\n\tconst queue = [...start];\n\tfor (const { name, from } of queue) {\n\t\tconst directory = names.has(name) ? undefined : findPackage(name, from);\n\t\tnames.add(name);\n\t\tif (directory != null) {\n\t\t\tfor (const peer of dependencyNames(directory, [\"peerDependencies\"])) {\n\t\t\t\tqueue.push({ name: peer, from: directory });\n\t\t\t}\n\t\t}\n\t}\n\treturn names;\n}\n\n/** Writes `.app-server.json` into the client build. */\nfunction writeBuildManifest(clientDirectory: string, manifest: BuildManifest): void {\n\tmkdirSync(clientDirectory, { recursive: true });\n\twriteFileSync(\n\t\tjoin(clientDirectory, BUILD_MANIFEST_FILE),\n\t\t`${JSON.stringify(manifest, null, \"\\t\")}\\n`,\n\t);\n}\n\n/**\n * Writes the build ID and the script hashes of the client build\n * ({@link scriptHashesOf}) into `.app-server.json`, and keeps the rest of the\n * file. Why after the build too: a build with no prerender pass can have HTML\n * files, such as `public/offline.html`.\n */\nfunction completeBuildManifest(clientDirectory: string, buildId: string | undefined): void {\n\tif (!existsSync(clientDirectory)) {\n\t\treturn;\n\t}\n\tconst path = join(clientDirectory, BUILD_MANIFEST_FILE);\n\tconst recorded: unknown = existsSync(path) ? JSON.parse(readFileSync(path, \"utf8\")) : undefined;\n\twriteBuildManifest(clientDirectory, {\n\t\tprerendered: [],\n\t\theaders: {},\n\t\t...(typeof recorded === \"object\" && recorded != null ? recorded : {}),\n\t\t...(buildId == null ? {} : { buildId }),\n\t\tscriptHashes: scriptHashesOf(clientDirectory),\n\t});\n}\n\n/**\n * The ID of a client build: a hash of the name and the content of each file\n * in its bundle. Why the bundle: it is the code that an open tab runs, so the\n * ID changes when that code changes, and not for a change to the server, a\n * `public/` file, or a prerendered page. Why the content, not the file\n * names: a name has a content hash only when the output names ask for one.\n */\nfunction bundleBuildId(bundle: Rolldown.OutputBundle): string {\n\tconst hash = createHash(\"sha256\");\n\t// Why `<`, not `localeCompare`: the order of `localeCompare` changes with the locale of the\n\t// machine, so two machines would give one bundle two IDs.\n\tfor (const file of Object.values(bundle).toSorted((first, second) =>\n\t\tfirst.fileName < second.fileName ? -1 : 1,\n\t)) {\n\t\thash.update(`${file.fileName}\\0`);\n\t\thash.update(file.type === \"chunk\" ? file.code : file.source);\n\t\thash.update(\"\\0\");\n\t}\n\t// Why 16 hex digits: 64 bits keep two builds apart, and the ID goes in each document's headers.\n\treturn hash.digest(\"hex\").slice(0, 16);\n}\n\n/** The path of each file under `directory` that is not a dotfile, in code unit order. */\nfunction filesIn(directory: string): string[] {\n\tif (!existsSync(directory)) {\n\t\treturn [];\n\t}\n\treturn readdirSync(directory, { recursive: true, withFileTypes: true })\n\t\t.filter((entry) => entry.isFile() && !entry.name.startsWith(\".\"))\n\t\t.map((entry) => relative(directory, join(entry.parentPath, entry.name)).split(sep).join(\"/\"))\n\t\t.toSorted();\n}\n\n/** The client build, as its `writeBundle` hook saw it. */\ntype ClientBuild = {\n\t/** The {@link bundleBuildId} of the client bundle. */\n\tbundleId: string;\n\t/** The assets directory of the client build, such as `build/client/assets`. */\n\tassetsDirectory: string;\n\t/** The files in the assets directory ({@link filesIn}) after the client build wrote its bundle. */\n\tassets: ReadonlySet<string>;\n};\n\n/**\n * The ID of the whole build: the {@link bundleBuildId} of the client bundle,\n * with the name and the content of each file that a later build step added to\n * the assets directory. Why: React Router writes its route manifest\n * (`assets/manifest-*.js`) during the server build, and a route change, such\n * as a new path for one module, can keep the client bundle the same.\n */\nfunction appBuildId({ bundleId, assetsDirectory, assets }: ClientBuild): string {\n\tconst added = filesIn(assetsDirectory).filter((file) => !assets.has(file));\n\tif (added.length === 0) {\n\t\treturn bundleId;\n\t}\n\tconst hash = createHash(\"sha256\").update(bundleId);\n\tfor (const file of added) {\n\t\thash.update(`\\0${file}\\0`);\n\t\thash.update(readFileSync(join(assetsDirectory, file)));\n\t}\n\treturn hash.digest(\"hex\").slice(0, 16);\n}\n\n/** The `buildId` of the build manifest that the client build wrote, if any. */\nfunction writtenBuildId(clientDirectory: string): string | undefined {\n\tconst path = join(clientDirectory, BUILD_MANIFEST_FILE);\n\tif (!existsSync(path)) {\n\t\treturn undefined;\n\t}\n\tconst manifest: unknown = JSON.parse(readFileSync(path, \"utf8\"));\n\treturn typeof manifest === \"object\" &&\n\t\tmanifest != null &&\n\t\t\"buildId\" in manifest &&\n\t\ttypeof manifest.buildId === \"string\"\n\t\t? manifest.buildId\n\t\t: undefined;\n}\n\n/**\n * Records each 2xx path and the headers of each non-document response while\n * the framework's prerender pass runs. It writes them to `.app-server.json` in\n * the client build when the preview server closes, with the script hashes of\n * each HTML file.\n */\nfunction capture(server: PreviewServer, afterPass: () => void): void {\n\tconst clientDirectory = outDir(server.config, \"client\");\n\tconst started = Date.now();\n\tconst paths = new Set<string>();\n\tconst headers: BuildManifest[\"headers\"] = {};\n\tserver.middlewares.use((request, response, next) => {\n\t\t// Why `getPath`: the static stages look a file up by Hono's decoded path, such as `/café.json`.\n\t\tconst pathname = getPath(new Request(new URL(request.url ?? \"/\", \"http://localhost\")));\n\t\t// Why: Node keeps the headers that `writeHead` gets readable only when a header was set first.\n\t\tresponse.setHeader(CAPTURE_MARKER, \"1\");\n\t\tresponse.once(\"finish\", () => {\n\t\t\tif (response.statusCode < 200 || response.statusCode >= 300) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst key = manifestKey(pathname);\n\t\t\tpaths.add(key);\n\t\t\t// Why skip documents: the framework sets their headers for each request (a nonce, the\n\t\t\t// host), so the headers of the build's request are wrong for every other one.\n\t\t\tif (String(response.getHeader(\"content-type\") ?? \"\").startsWith(\"text/html\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst recorded: Record<string, string> = {};\n\t\t\tfor (const [name, value] of Object.entries(response.getHeaders())) {\n\t\t\t\t// Why skip index names: after a `setHeader`, Node stores a flat header array from\n\t\t\t\t// `writeHead`, as TanStack Start's preview server sends, under its indexes too.\n\t\t\t\tif (!UNCAPTURED_HEADERS.has(name) && !/^\\d+$/u.test(name) && value != null) {\n\t\t\t\t\trecorded[name] = Array.isArray(value) ? value.join(\", \") : String(value);\n\t\t\t\t}\n\t\t\t}\n\t\t\theaders[key] = recorded;\n\t\t});\n\t\tnext();\n\t});\n\tserver.httpServer.once(\"close\", () => {\n\t\tconst buildId = writtenBuildId(clientDirectory);\n\t\twriteBuildManifest(clientDirectory, {\n\t\t\t// Why keep it: the prerender pass runs after the client build, which derived it.\n\t\t\t...(buildId == null ? {} : { buildId }),\n\t\t\tprerendered: [...paths].toSorted(),\n\t\t\theaders: Object.fromEntries(\n\t\t\t\tObject.entries(headers).toSorted(([first], [second]) => first.localeCompare(second)),\n\t\t\t),\n\t\t\tscriptHashes: scriptHashesOf(clientDirectory),\n\t\t});\n\t\t// Why here too: the copy step of `buildApp` runs before this pass when `appServer` comes\n\t\t// before the framework's plugin. Why sync: Vite does not wait for this listener.\n\t\t// Why each file that the pass changed, not each path: a path does not name its file, as\n\t\t// TanStack Start can write `/page` to `page.html`. Why 2 s early: a file system can keep the\n\t\t// modification time in steps of 1 or 2 s.\n\t\twriteAllCopies(clientDirectory, { changedSince: started - 2000 });\n\t\tafterPass();\n\t});\n}\n\n/**\n * The brotli quality of the copies. Why 9, not the highest (11): on a docs\n * build with 70 MB of text, 11 adds 46 s to the build and 9 adds 0.6 s. The\n * copies of 9 are 9% larger, and still 25% smaller than the gzip copies.\n */\nconst BROTLI_QUALITY = 9;\n\n/**\n * Writes the compressed copies (`.<file>.gz` and `.<file>.br`) of the file at\n * `path` when the server compresses the file: a compressible type of 1 KiB\n * or more. It writes a copy only when it is smaller: the gzip copy than the\n * file, and the brotli copy than the gzip copy. Else it removes an old copy,\n * so a copy from an earlier build never replaces a changed file.\n */\nfunction writeCopies(path: string): void {\n\tconst bytes =\n\t\tisCompressible(contentType(path, {})) &&\n\t\tstatSync(path, { throwIfNoEntry: false })?.isFile() === true\n\t\t\t? readFileSync(path)\n\t\t\t: undefined;\n\t// Why the highest gzip level: the build compresses each file once, and each response sends fewer bytes.\n\tconst gzip =\n\t\tbytes == null || bytes.byteLength < MIN_COMPRESS_BYTES\n\t\t\t? undefined\n\t\t\t: gzipSync(bytes, { level: constants.Z_BEST_COMPRESSION });\n\tconst gzipCopy =\n\t\tgzip != null && bytes != null && gzip.byteLength < bytes.byteLength ? gzip : undefined;\n\tconst brotli =\n\t\tgzipCopy == null || bytes == null\n\t\t\t? undefined\n\t\t\t: brotliCompressSync(bytes, {\n\t\t\t\t\tparams: {\n\t\t\t\t\t\t[constants.BROTLI_PARAM_MODE]: constants.BROTLI_MODE_TEXT,\n\t\t\t\t\t\t[constants.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY,\n\t\t\t\t\t\t[constants.BROTLI_PARAM_SIZE_HINT]: bytes.byteLength,\n\t\t\t\t\t},\n\t\t\t\t});\n\tconst brotliCopy =\n\t\tbrotli != null && gzipCopy != null && brotli.byteLength < gzipCopy.byteLength\n\t\t\t? brotli\n\t\t\t: undefined;\n\tconst copies: readonly (readonly [Encoding, Uint8Array | undefined])[] = [\n\t\t[\"gzip\", gzipCopy],\n\t\t[\"br\", brotliCopy],\n\t];\n\tfor (const [encoding, copy] of copies) {\n\t\tconst copyPath = join(dirname(path), copyName(basename(path), encoding));\n\t\tif (copy == null) {\n\t\t\trmSync(copyPath, { force: true });\n\t\t} else {\n\t\t\twriteFileSync(copyPath, copy);\n\t\t}\n\t}\n}\n\n/**\n * Runs {@link writeCopies} for each file in the client build, except dotfiles\n * such as the copies. With `changedSince`, only for a file that changed at or\n * after that time, in milliseconds since the epoch.\n */\nfunction writeAllCopies(\n\tclientDirectory: string,\n\t{ changedSince }: { changedSince?: number } = {},\n): void {\n\tif (!existsSync(clientDirectory)) {\n\t\treturn;\n\t}\n\tfor (const entry of readdirSync(clientDirectory, { recursive: true, withFileTypes: true })) {\n\t\tconst path = join(entry.parentPath, entry.name);\n\t\t// Why skip dotfiles: the server never sends one, such as `.app-server.json`.\n\t\tif (\n\t\t\tentry.isFile() &&\n\t\t\t!entry.name.startsWith(\".\") &&\n\t\t\t(changedSince == null ||\n\t\t\t\t(statSync(path, { throwIfNoEntry: false })?.mtimeMs ?? 0) >= changedSince)\n\t\t) {\n\t\t\twriteCopies(path);\n\t\t}\n\t}\n}\n\n/**\n * The Vite plugin for `@ngrok/app-server`. Put it next to the framework's\n * plugin.\n *\n * - It adds the server entry to the server build, such as\n * `build/server/app-server.js` on the node host. The entry bundles the app\n * (the default export of `app`) with the framework's server module, so the\n * server gets the app's path aliases and its one copy of the framework.\n * The framework's own entry does not change. When a runtime runs the entry\n * as its main module, the entry starts the server.\n * - In a build, it bundles each dependency into the server build. It copies\n * each package that stays external into `node_modules` in the server build.\n * So the build directory runs with no install.\n * - After the client build, it writes `.app-server.json` in the client\n * build with the build ID: a hash of the client bundle. After the build,\n * it adds the files that the server build wrote to the client's assets\n * directory, such as React Router's route manifest. The `buildId` plugin\n * sends the ID.\n * - During the framework's prerender pass, it records each prerendered path\n * and the headers of each prerendered file that is not an HTML document into\n * `.app-server.json` in the client build. The `prerendered` plugin replays\n * the headers. A document's headers depend on its request, so they are not\n * recorded.\n * - After the build and after the prerender pass, it records the hash of each\n * inline script of each HTML file in `.app-server.json`, for the\n * `contentSecurityPolicy` plugin. It also writes a gzip copy (`.<file>.gz`)\n * and a brotli copy (`.<file>.br`) next to each text file of 1 KiB or more\n * in the client build, HTML included. The static stages send a copy, so the\n * server does not compress these files for each request.\n *\n * @example\n * // vite.config.ts\n * export default defineConfig({ plugins: [reactRouter(), appServer()] });\n */\nexport function appServer(options: AppServerOptions = {}): Plugin[] {\n\tconst host = options.host ?? node();\n\t// Why one value: `configResolved` sets all three, so no hook sees a config with no framework.\n\tlet resolved:\n\t\t| { config: ResolvedConfig; framework: FrameworkBuild; appModule: string | undefined }\n\t\t| undefined;\n\tlet clientBuild: ClientBuild | undefined;\n\tconst copies: Plugin = {\n\t\tname: \"@ngrok/app-server:compressed-copies\",\n\t\t// Why last: the framework prerenders in a `buildApp` hook of an `enforce: \"post\"` plugin.\n\t\tenforce: \"post\",\n\t\tbuildApp: {\n\t\t\torder: \"post\",\n\t\t\thandler: async (builder) => {\n\t\t\t\tconst clientDirectory = outDir(builder.config, \"client\");\n\t\t\t\tcompleteBuildManifest(\n\t\t\t\t\tclientDirectory,\n\t\t\t\t\tclientBuild == null ? undefined : appBuildId(clientBuild),\n\t\t\t\t);\n\t\t\t\twriteAllCopies(clientDirectory);\n\t\t\t\thost.output?.(hostOutput(builder.config, host));\n\t\t\t},\n\t\t},\n\t};\n\tconst main: Plugin = {\n\t\tname: \"@ngrok/app-server\",\n\t\tconfigResolved: (config) => {\n\t\t\tconst framework = options.framework ?? detectFramework(config.plugins);\n\t\t\tframework.validate?.(config);\n\t\t\tresolved = {\n\t\t\t\tconfig,\n\t\t\t\tframework,\n\t\t\t\tappModule:\n\t\t\t\t\toptions.app == null ? defaultApp(config.root) : resolve(config.root, options.app),\n\t\t\t};\n\t\t},\n\t\tbuildStart() {\n\t\t\t// Why a chunk and not an input: the framework's own entry stays the same, and its prerender\n\t\t\t// preview reads that entry.\n\t\t\tif (isServerBuild(this.environment)) {\n\t\t\t\tthis.emitFile({ type: \"chunk\", id: SERVER_ENTRY_ID, fileName: host.entryFileName });\n\t\t\t}\n\t\t},\n\t\twriteBundle(output, bundle) {\n\t\t\tif (this.environment.name === \"client\") {\n\t\t\t\tconst directory = output.dir ?? outDir(this.environment.config, \"client\");\n\t\t\t\tconst assetsDirectory = join(directory, this.environment.config.build.assetsDir);\n\t\t\t\tclientBuild = {\n\t\t\t\t\tbundleId: bundleBuildId(bundle),\n\t\t\t\t\tassetsDirectory,\n\t\t\t\t\tassets: new Set(filesIn(assetsDirectory)),\n\t\t\t\t};\n\t\t\t\twriteBuildManifest(directory, {\n\t\t\t\t\tbuildId: clientBuild.bundleId,\n\t\t\t\t\tprerendered: [],\n\t\t\t\t\theaders: {},\n\t\t\t\t\tscriptHashes: {},\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\trenderStart(output) {\n\t\t\t// Why: the server entry uses `import.meta.url`, and the CLI loads it as an ES module.\n\t\t\tif (this.environment.name === SERVER_ENVIRONMENT && output.format !== \"es\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`@ngrok/app-server needs an ES module server build, and this build has the format \"${output.format}\".`,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t\tresolveId: (id) => (id === SERVER_ENTRY_ID ? RESOLVED_SERVER_ENTRY_ID : undefined),\n\t\tload(id) {\n\t\t\tif (id !== RESOLVED_SERVER_ENTRY_ID || resolved == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst { config, framework, appModule } = resolved;\n\t\t\tconst clientDirectory = outDir(config, \"client\");\n\t\t\tconst serverDirectory = outDir(config, SERVER_ENVIRONMENT);\n\t\t\tconst fromClient = relative(clientDirectory, serverDirectory);\n\t\t\t// Why: the static stages serve each file in the client build, so they would serve the server's\n\t\t\t// code. Why a build only: development serves no build directory.\n\t\t\tif (\n\t\t\t\tthis.environment.mode === \"build\" &&\n\t\t\t\t!fromClient.startsWith(\"..\") &&\n\t\t\t\t!isAbsolute(fromClient)\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`@ngrok/app-server needs the server build outside the client build, and both are in ${clientDirectory}.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Why a URL in a build: the build can move, and the client build stays next to it.\n\t\t\tconst fromEntry = relative(\n\t\t\t\tdirname(join(serverDirectory, host.entryFileName)),\n\t\t\t\tclientDirectory,\n\t\t\t).replaceAll(\"\\\\\", \"/\");\n\t\t\treturn serverEntrySource({\n\t\t\t\tframework,\n\t\t\t\thost,\n\t\t\t\tappModule,\n\t\t\t\tclientDirectory:\n\t\t\t\t\tthis.environment.mode === \"build\"\n\t\t\t\t\t\t? `new URL(${JSON.stringify(`${fromEntry}/`)}, import.meta.url).href`\n\t\t\t\t\t\t: JSON.stringify(clientDirectory),\n\t\t\t});\n\t\t},\n\t\tconfigurePreviewServer: (server) => {\n\t\t\tif (resolved?.framework.isPrerenderPass(server) === true) {\n\t\t\t\t// Why the preview's config: the framework starts the preview with a new instance of this plugin.\n\t\t\t\tcapture(server, () => host.output?.(hostOutput(server.config, host)));\n\t\t\t}\n\t\t},\n\t};\n\treturn [main, copies, standalone()];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAQA,MAAM,eAAe;;;;;;;;AASrB,SAAgB,gBAAgB,WAAmB,QAAqC;CACvF,MAAM,WAAoB,KAAK,MAAM,aAAa,KAAK,WAAW,cAAc,GAAG,MAAM,CAAC;CAC1F,MAAM,QAAQ,OAAO,SAAS,UAAU;EACvC,MAAM,QACL,OAAO,aA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