@ngrok/app-server 0.0.0-stage → 0.0.0

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.
@@ -0,0 +1,793 @@
1
+ import { n as capturedHeadersKey, r as readCapturedHeaders } from "./captured-headers-ewL_t3MQ.js";
2
+ import { Hono } from "hono";
3
+ import { requestId } from "hono/request-id";
4
+ import { RESPONSE_ALREADY_SENT } from "@hono/node-server/utils/response";
5
+ import { open, stat } from "node:fs/promises";
6
+ import { join, sep } from "node:path";
7
+ import { createHash } from "node:crypto";
8
+ import { getMimeType } from "hono/utils/mime";
9
+ import { accepts } from "hono/accepts";
10
+ import { constants, createGzip } from "node:zlib";
11
+
12
+ // src/log.ts
13
+ /**
14
+ * A log sink that writes one JSON object per line. Each line has `time`,
15
+ * `level`, `message`, and the flat attributes, which Datadog reads as its
16
+ * standard attributes.
17
+ *
18
+ * @param write - Where each line goes. Defaults to stdout.
19
+ *
20
+ * @example
21
+ * createServer({ logger: jsonSink() });
22
+ * // {"time":"2026-10-28T12:00:00.000Z","level":"info","message":"request","http.status_code":200}
23
+ */
24
+ function jsonSink(write = (line) => {
25
+ process.stdout.write(line);
26
+ }) {
27
+ return { log: (level, message, attributes) => {
28
+ write(`${JSON.stringify({
29
+ time: (/* @__PURE__ */ new Date()).toISOString(),
30
+ level,
31
+ message,
32
+ ...attributes
33
+ })}\n`);
34
+ } };
35
+ }
36
+ /** Flat `error.*` attributes for a thrown value. */
37
+ function errorAttributes(error) {
38
+ if (error instanceof Error) return {
39
+ "error.kind": error.name,
40
+ "error.message": error.message,
41
+ "error.stack": error.stack
42
+ };
43
+ return { "error.message": String(error) };
44
+ }
45
+ /** A logger that writes to `sink`, with the attributes from `base` first on each line. */
46
+ function sinkLogger(sink, base = () => ({})) {
47
+ const line = (level) => (message, attributes = {}) => {
48
+ sink.log(level, message, {
49
+ ...base(),
50
+ ...attributes
51
+ });
52
+ };
53
+ return {
54
+ debug: line("debug"),
55
+ info: line("info"),
56
+ warn: line("warn"),
57
+ error: line("error")
58
+ };
59
+ }
60
+ /** A logger whose lines carry the request's ID, method, and path. */
61
+ function requestLogger(sink, context) {
62
+ return sinkLogger(sink, () => ({
63
+ "http.request_id": context.get("requestId"),
64
+ "http.method": context.req.method,
65
+ "http.url_details.path": context.req.path
66
+ }));
67
+ }
68
+
69
+ // src/plugins/access-log.ts
70
+ /**
71
+ * A URL's path and query, with each query value replaced when `redact` is set.
72
+ *
73
+ * @example
74
+ * loggedUrl(new URL("https://example.com/verify?code=123"), { redact: true }); // => "/verify?code=REDACTED"
75
+ */
76
+ function loggedUrl(url, { redact }) {
77
+ if (!redact || url.search === "") return `${url.pathname}${url.search}`;
78
+ const query = Array.from(url.searchParams.keys()).map((key) => `${encodeURIComponent(key)}=REDACTED`).join("&");
79
+ return `${url.pathname}?${query}`;
80
+ }
81
+ /** A `Referer` with its query redacted like {@link loggedUrl}. A value that is not a URL is dropped. */
82
+ function loggedReferer(referer, { redact }) {
83
+ if (referer == null || !redact) return referer;
84
+ const url = URL.parse(referer);
85
+ return url == null ? void 0 : `${url.origin}${loggedUrl(url, { redact })}`;
86
+ }
87
+ /**
88
+ * One log line per request, static hits included, with Datadog standard
89
+ * attribute names. The line goes out when the body ends or the client
90
+ * disconnects, so a streamed response logs its full duration and size.
91
+ *
92
+ * @example
93
+ * createServer({ plugins: [requestId(), accessLog({ redactQuery: false })] });
94
+ * // {"level":"info","message":"request","http.status_code":200,"network.bytes_written":5120,"duration":1830000,...}
95
+ */
96
+ function accessLog({ redactQuery = true } = {}) {
97
+ return {
98
+ name: "access-log",
99
+ middleware: async (context, next) => {
100
+ const started = performance.now();
101
+ await next();
102
+ const write = ({ bytes, aborted }) => {
103
+ context.var.logger.info("request", lineAttributes(context, {
104
+ bytes,
105
+ aborted,
106
+ started
107
+ }));
108
+ };
109
+ const response = context.res;
110
+ if (context.req.method === "HEAD") {
111
+ write({
112
+ bytes: 0,
113
+ aborted: false
114
+ });
115
+ return;
116
+ }
117
+ if (response.body == null) {
118
+ write({
119
+ bytes: Number(response.headers.get("Content-Length") ?? 0),
120
+ aborted: false
121
+ });
122
+ return;
123
+ }
124
+ const reader = response.body.getReader();
125
+ let bytes = 0;
126
+ const counted = new ReadableStream({
127
+ async pull(controller) {
128
+ let result;
129
+ try {
130
+ result = await reader.read();
131
+ } catch (error) {
132
+ write({
133
+ bytes,
134
+ aborted: true
135
+ });
136
+ throw error;
137
+ }
138
+ const { done, value } = result;
139
+ if (done) {
140
+ controller.close();
141
+ write({
142
+ bytes,
143
+ aborted: false
144
+ });
145
+ return;
146
+ }
147
+ bytes += value.byteLength;
148
+ controller.enqueue(value);
149
+ },
150
+ async cancel(reason) {
151
+ write({
152
+ bytes,
153
+ aborted: true
154
+ });
155
+ await reader.cancel(reason);
156
+ }
157
+ });
158
+ context.res = new Response(counted, response);
159
+ }
160
+ };
161
+ function lineAttributes(context, { bytes, aborted, started }) {
162
+ return {
163
+ "http.url": loggedUrl(new URL(context.req.url), { redact: redactQuery }),
164
+ "http.status_code": context.res.status,
165
+ "http.useragent": context.req.header("User-Agent"),
166
+ "http.referer": loggedReferer(context.req.header("Referer"), { redact: redactQuery }),
167
+ "network.client.ip": context.env.remoteAddress,
168
+ "network.bytes_written": bytes,
169
+ duration: Math.round((performance.now() - started) * 1e6),
170
+ ...aborted ? { "http.client_aborted": true } : {}
171
+ };
172
+ }
173
+ }
174
+
175
+ // src/plugins/request-id.ts
176
+ /**
177
+ * Gives each request an ID: a valid incoming header (up to 255 word
178
+ * characters, `-`, and `=`), else a new UUID. The ID goes on the response, on
179
+ * every log line, and into the framework's context.
180
+ *
181
+ * @example
182
+ * const app = createServer({ plugins: [requestId()] });
183
+ * const response = await app.request("/", { headers: { "X-Request-Id": "abc-123" } });
184
+ * response.headers.get("X-Request-Id"); // => "abc-123"
185
+ */
186
+ function requestId$1({ headerName = "X-Request-Id" } = {}) {
187
+ const assign = requestId({ headerName });
188
+ return {
189
+ name: "request-id",
190
+ middleware: async (context, next) => {
191
+ await assign(context, next);
192
+ const id = context.get("requestId");
193
+ if (id != null) context.header(headerName, id);
194
+ }
195
+ };
196
+ }
197
+
198
+ // src/static-files.ts
199
+ /**
200
+ * Whether a URL path names a dotfile or goes through a dot directory.
201
+ * `/.well-known/` stays reachable.
202
+ */
203
+ function hasDotSegment(path) {
204
+ return path.split("/").some((segment, index) => segment.startsWith(".") && !(index === 1 && segment === ".well-known"));
205
+ }
206
+ async function fileStats(path) {
207
+ try {
208
+ return await stat(path);
209
+ } catch {
210
+ return;
211
+ }
212
+ }
213
+ /**
214
+ * Finds the file under `root` that answers a decoded URL path, such as
215
+ * Hono's `context.req.path`. A directory answers with its `index.html` and no
216
+ * redirect, so a prerendered page keeps its URL. Dotfiles and paths outside
217
+ * `root` find nothing.
218
+ *
219
+ * Each file has one URL, because the headers for a file are keyed by that
220
+ * URL. So `/a//b`, `/a/index.html`, and `/a%2Fb` find nothing. Hono decodes
221
+ * the path but keeps an encoded `/` as `%2F`, so this function does not
222
+ * decode it again.
223
+ *
224
+ * @example
225
+ * await findStaticFile("/app/build/client", "/components/button");
226
+ * // => { path: "/app/build/client/components/button/index.html", size: 5120, mtimeMs: 1761652800000 }
227
+ */
228
+ async function findStaticFile(root, path) {
229
+ if (path.includes("\0") || path.includes("\\") || path.split("/").includes("..") || path.includes("//") || path.endsWith("/index.html") || hasDotSegment(path)) return;
230
+ const candidate = join(root, path);
231
+ if (candidate !== root && !candidate.startsWith(`${root}${sep}`)) return;
232
+ const stats = await fileStats(candidate);
233
+ if (stats?.isFile()) return {
234
+ path: candidate,
235
+ size: stats.size,
236
+ mtimeMs: stats.mtimeMs
237
+ };
238
+ if (stats?.isDirectory()) {
239
+ const index = join(candidate, "index.html");
240
+ const indexStats = await fileStats(index);
241
+ if (indexStats?.isFile()) return {
242
+ path: index,
243
+ size: indexStats.size,
244
+ mtimeMs: indexStats.mtimeMs
245
+ };
246
+ }
247
+ }
248
+ /**
249
+ * A file's bytes, one chunk for each pull, so a slow client holds one chunk,
250
+ * not the whole file. The handle closes at the end, on an error, or on cancel.
251
+ */
252
+ function fileStream(handle) {
253
+ return new ReadableStream({
254
+ async pull(controller) {
255
+ try {
256
+ const { bytesRead, buffer } = await handle.read({ buffer: /* @__PURE__ */ new Uint8Array(65536) });
257
+ if (bytesRead === 0) {
258
+ await handle.close();
259
+ controller.close();
260
+ } else controller.enqueue(buffer.subarray(0, bytesRead));
261
+ } catch (error) {
262
+ await handle.close();
263
+ throw error;
264
+ }
265
+ },
266
+ cancel: () => handle.close()
267
+ });
268
+ }
269
+ /** The content type of a file, with the React Router and markdown types that `mime` lacks. */
270
+ function contentType(path) {
271
+ if (path.endsWith(".md")) return "text/markdown; charset=utf-8";
272
+ if (path.endsWith(".data")) return "text/x-script";
273
+ return getMimeType(path) ?? "application/octet-stream";
274
+ }
275
+ /** An ETag without its weak prefix, for the weak comparison that `If-None-Match` uses. */
276
+ function opaqueTag(etag) {
277
+ return etag.trim().replace(/^W\//, "");
278
+ }
279
+ /** Whether an `If-None-Match` header lists an ETag. */
280
+ function matchesEtag(ifNoneMatch, etag) {
281
+ return ifNoneMatch?.split(",").some((candidate) => {
282
+ const trimmed = candidate.trim();
283
+ return trimmed === "*" || opaqueTag(trimmed) === opaqueTag(etag);
284
+ }) ?? false;
285
+ }
286
+ /** A weak ETag from a file's size, its modification time, and the request's `etagParts`. */
287
+ function fileEtag(file, parts) {
288
+ const base = `${file.size.toString(16)}-${Math.trunc(file.mtimeMs).toString(16)}`;
289
+ if (parts.length === 0) return `W/"${base}"`;
290
+ return `W/"${base}-${createHash("sha256").update(parts.join("\0")).digest("base64url").slice(0, 16)}"`;
291
+ }
292
+ /**
293
+ * The response for a static file, with a weak ETag from its size,
294
+ * modification time, and the request's `etagParts`. A matching
295
+ * `If-None-Match` gets a 304, and `HEAD` gets the headers only. `headers`
296
+ * replace the defaults, so a captured `Content-Type` wins over the one from
297
+ * the file name.
298
+ */
299
+ async function staticResponse(context, file, headers) {
300
+ const etag = fileEtag(file, context.get("etagParts") ?? []);
301
+ const responseHeaders = new Headers({
302
+ "Content-Type": contentType(file.path),
303
+ ETag: etag
304
+ });
305
+ for (const [name, value] of Object.entries(headers)) responseHeaders.set(name, value);
306
+ if (matchesEtag(context.req.header("If-None-Match"), responseHeaders.get("ETag") ?? etag)) {
307
+ responseHeaders.delete("Content-Type");
308
+ return new Response(null, {
309
+ status: 304,
310
+ headers: responseHeaders
311
+ });
312
+ }
313
+ if (context.req.method === "HEAD") {
314
+ responseHeaders.set("Content-Length", String(file.size));
315
+ return new Response(null, { headers: responseHeaders });
316
+ }
317
+ responseHeaders.set("Content-Length", String(file.size));
318
+ return new Response(fileStream(await open(file.path)), { headers: responseHeaders });
319
+ }
320
+
321
+ // src/plugins/static.ts
322
+ const IMMUTABLE = "public, max-age=31536000, immutable";
323
+ /** Runs Vite's middleware inside the pipeline. Vite answers or calls `next`. */
324
+ function viteStage(viteMiddleware) {
325
+ return async (context, next) => {
326
+ const { incoming, outgoing } = context.env;
327
+ if (incoming == null || outgoing == null) return next();
328
+ for (const [name, value] of context.res.headers) outgoing.appendHeader(name, value);
329
+ if (await new Promise((resolve, reject) => {
330
+ const onFinish = () => {
331
+ resolve(true);
332
+ };
333
+ outgoing.once("finish", onFinish);
334
+ viteMiddleware(incoming, outgoing, (error) => {
335
+ outgoing.off("finish", onFinish);
336
+ if (error == null) resolve(false);
337
+ else reject(new Error("Vite middleware failed", { cause: error }));
338
+ });
339
+ })) {
340
+ const headers = new Headers(RESPONSE_ALREADY_SENT.headers);
341
+ const length = outgoing.getHeader("Content-Length");
342
+ if (length != null) headers.set("Content-Length", String(length));
343
+ return new Response(null, {
344
+ status: outgoing.statusCode,
345
+ headers
346
+ });
347
+ }
348
+ return next();
349
+ };
350
+ }
351
+ /**
352
+ * Serves the hashed files under `/assets/` with a one-year immutable cache.
353
+ * A missing asset gets a plain 404, not a rendered page. In development,
354
+ * Vite serves the source modules, the HMR client, and the CSS here instead.
355
+ *
356
+ * @example
357
+ * createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });
358
+ */
359
+ function assets() {
360
+ let stage;
361
+ return {
362
+ name: "assets",
363
+ setup: (info) => {
364
+ if (info.mode === "development") {
365
+ stage = viteStage(info.viteMiddleware);
366
+ return;
367
+ }
368
+ const root = info.clientDirectory;
369
+ stage = async (context, next) => {
370
+ const { method, path } = context.req;
371
+ if (!path.startsWith("/assets/") || method !== "GET" && method !== "HEAD") return next();
372
+ const file = await findStaticFile(root, path);
373
+ if (file == null) return context.text("Not Found", 404);
374
+ return staticResponse(context, file, { "Cache-Control": IMMUTABLE });
375
+ };
376
+ },
377
+ middleware: (context, next) => stage == null ? next() : stage(context, next)
378
+ };
379
+ }
380
+ /**
381
+ * Serves the client build: prerendered pages at their own URL with a 200 and
382
+ * no trailing-slash redirect, plus every other file in it. Each response gets
383
+ * the headers its loader sent at build time (the `serverEntry` Vite plugin
384
+ * captures them), an ETag, and a 304 for a matching `If-None-Match`. A path
385
+ * with no file goes on to the framework. Off in development.
386
+ *
387
+ * At startup, it warns about each prerendered path that has no file.
388
+ *
389
+ * @example
390
+ * prerendered({
391
+ * headers: (path) => (path.startsWith("/api/") ? { "Access-Control-Allow-Origin": "*" } : undefined),
392
+ * });
393
+ */
394
+ function prerendered(options = {}) {
395
+ let stage;
396
+ return {
397
+ name: "prerendered",
398
+ setup: async (info) => {
399
+ if (info.mode === "development") return;
400
+ const root = info.clientDirectory;
401
+ const captured = await readCapturedHeaders(root);
402
+ const missing = [];
403
+ for (const path of info.prerenderedPaths) if (await findStaticFile(root, path) == null) missing.push(path);
404
+ if (missing.length > 0) info.logger.log("warn", "prerendered paths with no file", { "app_server.missing_paths": missing });
405
+ stage = async (context, next) => {
406
+ const { method } = context.req;
407
+ if (method !== "GET" && method !== "HEAD") return next();
408
+ const path = options.rewrite?.(context.req.path, context) ?? context.req.path;
409
+ const file = await findStaticFile(root, path);
410
+ if (file == null) return next();
411
+ return staticResponse(context, file, {
412
+ ...captured.get(capturedHeadersKey(path)),
413
+ ...options.headers?.(path, context)
414
+ });
415
+ };
416
+ },
417
+ middleware: (context, next) => stage == null ? next() : stage(context, next)
418
+ };
419
+ }
420
+
421
+ // src/plugins/streaming-compress.ts
422
+ const COMPRESSIBLE = /^(text\/|application\/(json|javascript|xml|schema\+json|manifest\+json|x-ndjson|connect\+json)|image\/svg\+xml)/;
423
+ /**
424
+ * Gzips a byte stream. `Z_SYNC_FLUSH` makes each written chunk readable at
425
+ * once. It reads the next source chunk only when the consumer pulls, so a slow
426
+ * client holds back the source.
427
+ */
428
+ function gzipStream(source) {
429
+ const gzip = createGzip({ flush: constants.Z_SYNC_FLUSH });
430
+ const reader = source.getReader();
431
+ return new ReadableStream({
432
+ start(controller) {
433
+ gzip.on("data", (chunk) => {
434
+ controller.enqueue(new Uint8Array(chunk));
435
+ });
436
+ gzip.on("end", () => {
437
+ controller.close();
438
+ });
439
+ gzip.on("error", (error) => {
440
+ controller.error(error);
441
+ });
442
+ },
443
+ async pull() {
444
+ try {
445
+ let chunk = await reader.read();
446
+ while (!chunk.done && chunk.value.byteLength === 0) chunk = await reader.read();
447
+ if (chunk.done) {
448
+ gzip.end();
449
+ return;
450
+ }
451
+ const { value } = chunk;
452
+ await new Promise((resolve, reject) => {
453
+ gzip.write(value, (error) => {
454
+ if (error == null) resolve();
455
+ else reject(error);
456
+ });
457
+ });
458
+ } catch (error) {
459
+ gzip.destroy();
460
+ throw error;
461
+ }
462
+ },
463
+ cancel(reason) {
464
+ gzip.destroy();
465
+ return reader.cancel(reason);
466
+ }
467
+ });
468
+ }
469
+ /**
470
+ * Gzips text responses and flushes after each chunk, so a streamed page shell
471
+ * or a server-sent event reaches the client at once. `hono/compress` holds a
472
+ * stream until it ends. Skips a response that is already encoded, a partial
473
+ * response, and one marked `no-transform`. Always sets `Vary: Accept-Encoding`.
474
+ *
475
+ * @example
476
+ * createServer({ plugins: [requestId(), accessLog(), streamingCompress()] });
477
+ */
478
+ function streamingCompress() {
479
+ return {
480
+ name: "streaming-compress",
481
+ middleware: async (context, next) => {
482
+ await next();
483
+ context.header("Vary", "Accept-Encoding", { append: true });
484
+ const response = context.res;
485
+ if (response.body == null || context.req.method === "HEAD" || accepts(context, {
486
+ header: "Accept-Encoding",
487
+ supports: ["gzip"],
488
+ default: "identity"
489
+ }) !== "gzip" || response.headers.has("Content-Encoding") || response.headers.has("Content-Range") || /\bno-transform\b/.test(response.headers.get("Cache-Control") ?? "") || !COMPRESSIBLE.test(response.headers.get("Content-Type") ?? "")) return;
490
+ context.res = new Response(gzipStream(response.body), response);
491
+ context.res.headers.set("Content-Encoding", "gzip");
492
+ context.res.headers.delete("Content-Length");
493
+ }
494
+ };
495
+ }
496
+
497
+ // src/shutdown.ts
498
+ let controller = new AbortController();
499
+ /**
500
+ * A signal that aborts when the server starts to shut down. Read it for each
501
+ * request: each start of a server makes a new one. A handler that
502
+ * holds a response open, such as an event stream, stops on it so that the
503
+ * drain does not wait for the deadline.
504
+ *
505
+ * @example
506
+ * const timer = setInterval(sendUpdate, 1_000);
507
+ * shutdownSignal().addEventListener("abort", () => clearInterval(timer), { once: true });
508
+ */
509
+ function shutdownSignal() {
510
+ return controller.signal;
511
+ }
512
+ /** Replaces {@link shutdownSignal} with a new one that has not aborted. */
513
+ function renewShutdownSignal() {
514
+ controller = new AbortController();
515
+ }
516
+ /** Aborts {@link shutdownSignal}. */
517
+ function abortShutdownSignal() {
518
+ controller.abort();
519
+ }
520
+
521
+ // src/tcp.ts
522
+ /** Above the ngrok edge's 90 s idle pool, so the edge never reuses a socket that the server is closing. */
523
+ const DEFAULT_IDLE_TIMEOUT_MS = 95e3;
524
+ /**
525
+ * Reads a port number. A value that is not an integer from 0 to 65535 throws,
526
+ * so a bad `PORT` stops startup.
527
+ *
528
+ * @example
529
+ * parsePort("8080"); // => 8080
530
+ */
531
+ function parsePort(value) {
532
+ const port = Number(value);
533
+ if (value.trim() === "" || !Number.isInteger(port) || port < 0 || port > 65535) throw new Error(`PORT must be an integer from 0 to 65535, not "${value}".`);
534
+ return port;
535
+ }
536
+ /**
537
+ * The default listener: a TCP port, served by the runtime's own HTTP server
538
+ * (`node:http` on Node, `Bun.serve` on Bun, `Deno.serve` on Deno). It reads
539
+ * `PORT` and `HOST` when it starts.
540
+ *
541
+ * @example
542
+ * createServer({ listeners: [tcp({ port: 8080 })] });
543
+ */
544
+ function tcp({ port, host, idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS } = {}) {
545
+ return {
546
+ name: "tcp",
547
+ start: async (fetch) => {
548
+ const options = {
549
+ port: port ?? (process.env.PORT == null ? 3e3 : parsePort(process.env.PORT)),
550
+ hostname: host ?? (process.env.HOST || void 0),
551
+ idleTimeoutMs
552
+ };
553
+ if ("Bun" in globalThis) return (await import("./bun-DCGnDEPn.js")).listen(fetch, options);
554
+ if ("Deno" in globalThis) return (await import("./deno-BnMfk2n1.js")).listen(fetch, options);
555
+ return (await import("./node-2wWBMFeO.js")).listen(fetch, options);
556
+ }
557
+ };
558
+ }
559
+
560
+ // src/create-server.ts
561
+ const appInternals = /* @__PURE__ */ new WeakMap();
562
+ /**
563
+ * The default pipeline, in order: `requestId`, `accessLog`,
564
+ * `streamingCompress`, the `beforeStatic` plugins, `assets`, and
565
+ * `prerendered`. It is a plain array, so an app can filter it or splice into it.
566
+ *
567
+ * @example
568
+ * createServer({ plugins: defaultPlugins({ accessLog: { redactQuery: false }, beforeStatic: [env] }) });
569
+ */
570
+ function defaultPlugins(options = {}) {
571
+ return [
572
+ requestId$1(options.requestId),
573
+ accessLog(options.accessLog),
574
+ streamingCompress(),
575
+ ...options.beforeStatic ?? [],
576
+ assets(),
577
+ prerendered(options.prerendered)
578
+ ];
579
+ }
580
+ /** The request with the scheme from `X-Forwarded-Proto`, when that header holds one. */
581
+ function withForwardedProto(request) {
582
+ const proto = request.headers.get("X-Forwarded-Proto");
583
+ if (proto !== "http" && proto !== "https") return request;
584
+ const url = new URL(request.url);
585
+ url.protocol = `${proto}:`;
586
+ return new Request(url, request);
587
+ }
588
+ /**
589
+ * Runs `step`, and rethrows a thrown value that is not an `Error` as one.
590
+ * Hono sends only an `Error` to `onError`, and rethrows any other value.
591
+ */
592
+ async function asError(step) {
593
+ try {
594
+ return await step();
595
+ } catch (error) {
596
+ throw error instanceof Error ? error : new Error(`A non-Error value was thrown: ${String(error)}`, { cause: error });
597
+ }
598
+ }
599
+ /** Whether `work` settles before `ms` pass. */
600
+ async function settlesWithin(work, ms) {
601
+ let timer;
602
+ const settled = await Promise.race([work.then(() => true), new Promise((resolve) => {
603
+ timer = setTimeout(resolve, ms, false);
604
+ })]);
605
+ clearTimeout(timer);
606
+ return settled;
607
+ }
608
+ /**
609
+ * Builds an app server: a Hono app that runs the plugins in list order, then
610
+ * the app's own routes, then the framework. It does not listen; the
611
+ * `app-server` CLI starts it.
612
+ *
613
+ * @example
614
+ * // server.ts
615
+ * const app = createServer({ logger: slogSink, plugins: defaultPlugins({ beforeStatic: [env] }) });
616
+ * app.get("/livez", (c) => c.text("ok"));
617
+ * export default app;
618
+ */
619
+ function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listeners = [tcp()], trustForwardedProto = false, shutdownDeadlineMs = 1e4 } = {}) {
620
+ const app = new Hono();
621
+ if (trustForwardedProto) {
622
+ const dispatch = app.fetch;
623
+ app.fetch = (request, ...rest) => dispatch(withForwardedProto(request), ...rest);
624
+ }
625
+ app.use(async (context, next) => {
626
+ context.set("logger", requestLogger(logger, context));
627
+ await next();
628
+ if (context.req.method === "HEAD") await context.res.body?.cancel();
629
+ });
630
+ for (const { middleware, etagPart } of plugins) app.use((context, next) => {
631
+ const part = etagPart?.();
632
+ if (part != null) context.set("etagParts", [...context.get("etagParts") ?? [], part]);
633
+ return asError(async () => middleware == null ? next() : middleware(context, next));
634
+ });
635
+ app.use((_, next) => asError(next));
636
+ app.onError((error, context) => {
637
+ if ("getResponse" in error && typeof error.getResponse === "function") {
638
+ const response = error.getResponse();
639
+ if (response instanceof Response) return response;
640
+ }
641
+ context.var.logger.error("unhandled error", errorAttributes(error));
642
+ return context.text("Internal Server Error", 500);
643
+ });
644
+ let prepared;
645
+ let running;
646
+ let stoppingPlugins;
647
+ const internals = {
648
+ logger,
649
+ prepare: (info) => {
650
+ prepared ??= (async () => {
651
+ for (const plugin of plugins) await plugin.setup?.(info);
652
+ app.all("*", (context) => context.env.framework.fetch(context.req.raw, context));
653
+ })();
654
+ return prepared;
655
+ },
656
+ listen: async (framework) => {
657
+ if (running != null) throw new Error("This app server is already listening.");
658
+ renewShutdownSignal();
659
+ let deadlinePassed = false;
660
+ const fetch = async (request, bindings) => {
661
+ const response = await app.fetch(request, {
662
+ ...bindings,
663
+ framework
664
+ });
665
+ if (deadlinePassed) await response.body?.cancel();
666
+ return response;
667
+ };
668
+ const starts = await Promise.allSettled(listeners.map((listener) => listener.start(fetch)));
669
+ const started = starts.flatMap((start) => start.status === "fulfilled" ? [start.value] : []);
670
+ const failed = starts.find((start) => start.status === "rejected");
671
+ if (failed != null) {
672
+ await Promise.all(started.map((listener) => listener.stop({ deadlineMs: 0 })));
673
+ throw failed.reason;
674
+ }
675
+ const urls = started.map((listener) => listener.url);
676
+ logger.log("info", "listening", { "app_server.urls": urls });
677
+ let stopping;
678
+ running = {
679
+ urls,
680
+ shutdown: () => {
681
+ stopping ??= (async () => {
682
+ logger.log("info", "draining", { "app_server.deadline_ms": shutdownDeadlineMs });
683
+ abortShutdownSignal();
684
+ const deadline = setTimeout(() => {
685
+ deadlinePassed = true;
686
+ }, shutdownDeadlineMs);
687
+ await Promise.all([internals.stopPlugins(), ...started.map((listener) => listener.stop({ deadlineMs: shutdownDeadlineMs }))]);
688
+ clearTimeout(deadline);
689
+ logger.log("info", "stopped", {});
690
+ })();
691
+ return stopping;
692
+ }
693
+ };
694
+ return running;
695
+ },
696
+ stopPlugins: () => {
697
+ stoppingPlugins ??= (async () => {
698
+ if (!await settlesWithin((async () => {
699
+ const results = await Promise.allSettled(plugins.map(async (plugin) => plugin.onShutdown?.()));
700
+ for (const result of results) if (result.status === "rejected") logger.log("error", "plugin shutdown failed", errorAttributes(result.reason));
701
+ })(), shutdownDeadlineMs)) logger.log("warn", "plugin shutdown passed the deadline", { "app_server.deadline_ms": shutdownDeadlineMs });
702
+ })();
703
+ return stoppingPlugins;
704
+ }
705
+ };
706
+ appInternals.set(app, internals);
707
+ return app;
708
+ }
709
+ /** The internals of an app from {@link createServer} of this copy of the package, else `undefined`. */
710
+ function serverInternals(app) {
711
+ return appInternals.get(app);
712
+ }
713
+
714
+ // src/entry.ts
715
+ /** The version of the contract between the CLI and the `appServer` export of a build. */
716
+ const ENTRY_PROTOCOL = 1;
717
+ /**
718
+ * The `appServer` export of a server build: an app from `createServer` and
719
+ * the framework adapter for each mode. The `serverEntry` Vite plugin makes
720
+ * this export for a React Router build. Call this for another framework.
721
+ *
722
+ * @example
723
+ * export const appServer = createEntry({ app, framework: (mode) => myAdapter(build, mode) });
724
+ */
725
+ function createEntry({ app, framework }) {
726
+ const internals = serverInternals(app);
727
+ if (internals == null) throw new Error("The app is not from `createServer()` of the copy of @ngrok/app-server in this build.");
728
+ let development;
729
+ return {
730
+ protocol: 1,
731
+ app,
732
+ start: async () => {
733
+ const adapter = framework("production");
734
+ await internals.prepare({
735
+ mode: "production",
736
+ clientDirectory: adapter.clientDirectory,
737
+ prerenderedPaths: adapter.prerenderedPaths,
738
+ logger: internals.logger
739
+ });
740
+ const server = await internals.listen(adapter);
741
+ for (const signal of ["SIGTERM", "SIGINT"]) process.once(signal, () => {
742
+ server.shutdown().catch((error) => {
743
+ internals.logger.log("error", "shutdown failed", errorAttributes(error));
744
+ process.exitCode = 1;
745
+ });
746
+ });
747
+ },
748
+ fetchDev: async (request, bindings, viteMiddleware) => {
749
+ development ??= framework("development");
750
+ await internals.prepare({
751
+ mode: "development",
752
+ viteMiddleware,
753
+ clientDirectory: development.clientDirectory,
754
+ prerenderedPaths: development.prerenderedPaths,
755
+ logger: internals.logger
756
+ });
757
+ return app.fetch(request, {
758
+ ...bindings,
759
+ framework: development
760
+ });
761
+ },
762
+ stopPlugins: internals.stopPlugins,
763
+ abortShutdownSignal
764
+ };
765
+ }
766
+ function isAppServerEntry(value) {
767
+ return typeof value === "object" && value != null && "protocol" in value && value.protocol === 1;
768
+ }
769
+ /** Entries that this copy made for plain React Router builds, by build module. */
770
+ const plainEntries = /* @__PURE__ */ new WeakMap();
771
+ /**
772
+ * The entry that runs a server build: its `appServer` export when the
773
+ * `serverEntry` Vite plugin made it, else this copy of the package over a
774
+ * plain React Router build with the default plugins.
775
+ */
776
+ async function loadEntry(build) {
777
+ if (typeof build !== "object" || build == null) throw new Error("The server build entry is not a module.");
778
+ const exported = Reflect.get(build, "appServer");
779
+ if (exported != null) {
780
+ if (!isAppServerEntry(exported)) throw new Error(`The build's @ngrok/app-server does not use entry protocol ${1}. Install the same version of @ngrok/app-server that the build uses.`);
781
+ return exported;
782
+ }
783
+ const known = plainEntries.get(build);
784
+ if (known != null) return known;
785
+ const { appServerEntry, isServerBuild } = await import("./react-router.js");
786
+ if (!isServerBuild(build)) throw new Error("The server build entry is not a React Router server build.");
787
+ const entry = appServerEntry(build);
788
+ plainEntries.set(build, entry);
789
+ return entry;
790
+ }
791
+
792
+ export { parsePort as a, streamingCompress as c, requestId$1 as d, accessLog as f, sinkLogger as h, defaultPlugins as i, assets as l, jsonSink as m, loadEntry as n, tcp as o, errorAttributes as p, createServer as r, shutdownSignal as s, createEntry as t, prerendered as u };
793
+ //# sourceMappingURL=entry-2XXp2Ukh.js.map