@ngrok/app-server 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +223 -64
  2. package/dist/brotli-only-BVAagKt3.js +63 -0
  3. package/dist/build-id-CwMbED1n.js +245 -0
  4. package/dist/{build-manifest-DBMWe3Lx.js → build-manifest-CoBztw_6.js} +13 -4
  5. package/dist/bun-BCz6K_Xv.js +1 -2
  6. package/dist/check-count-DQl5z_qe.js +17 -0
  7. package/dist/cli.js +9 -6
  8. package/dist/client-browser.d.ts +2 -3
  9. package/dist/client-browser.js +1 -1
  10. package/dist/client.d.ts +5 -4
  11. package/dist/client.js +9 -6
  12. package/dist/{compress-Cp5NfXCC.js → compress-2w3jqBh7.js} +2 -3
  13. package/dist/{compression-CT2mWlKM.js → compression-uJxu0JVb.js} +32 -5
  14. package/dist/content-types-Le-5BNEC.js +10 -0
  15. package/dist/{create-server-Bp1yILQk.js → create-server-DVTZun6D.js} +617 -306
  16. package/dist/create-server-PA0qniaK.js +3 -0
  17. package/dist/{create-server-X2GR-U6t.d.ts → create-server-UVsHFQyK.d.ts} +116 -54
  18. package/dist/deno-aqhikNMG.js +1 -2
  19. package/dist/{entry-BoxCqc6w.js → entry-CMhX3yf8.js} +85 -65
  20. package/dist/entry-CvZ4U0ia.js +3 -0
  21. package/dist/{entry-DZTCaL3d.d.ts → entry-DBq_3s8X.d.ts} +10 -36
  22. package/dist/entry-protocol-C30UPXzy.js +14 -0
  23. package/dist/entry-source-DSE5NAJu.js +70 -0
  24. package/dist/entry-source-SHoE-DUP.js +3 -0
  25. package/dist/exit-Hh-O3gp4.js +83 -0
  26. package/dist/{header-hook-Vzw9J9BY.js → header-hook-JfqaTt34.js} +69 -23
  27. package/dist/{index-B8LsM6Mh.d.ts → index-gzGs53Ue.d.ts} +43 -38
  28. package/dist/index.d.ts +88 -44
  29. package/dist/index.js +216 -84
  30. package/dist/listen-options-7TaXjyrk.js +1 -2
  31. package/dist/{load-entry-CCPWbsrj.js → load-entry-Bgq1_HDV.js} +11 -12
  32. package/dist/{log-DQAS5gGT.js → log-DfC9D5_T.js} +70 -49
  33. package/dist/{node-D6m6e6EI.js → node-DQPrMFyc.js} +20 -8
  34. package/dist/node-DyKDFII0.js +263 -0
  35. package/dist/node-vite.d.ts +2 -3
  36. package/dist/node-vite.js +1 -1
  37. package/dist/node.d.ts +41 -64
  38. package/dist/node.js +3 -3
  39. package/dist/react-router-vite.d.ts +2 -3
  40. package/dist/react-router-vite.js +1 -1
  41. package/dist/react-router.d.ts +6 -17
  42. package/dist/react-router.js +9 -14
  43. package/dist/request-context-Cslbrscf.js +163 -0
  44. package/dist/{response-edge-CU8ZvL_F.js → response-edge-Ow5Pi5qF.js} +13 -10
  45. package/dist/{response-writer-D7KHfr8n.js → response-writer-Dd4Ey99f.js} +57 -21
  46. package/dist/{script-hashes-CU7P9oZU.js → script-hashes-BdvJ0QI_.js} +2 -3
  47. package/dist/serve-AatMo9k6.js +26 -0
  48. package/dist/{stale-build-navigation-rg5xxmTr.js → stale-build-navigation-Qf_Lem39.js} +4 -5
  49. package/dist/{stale-build-navigation-ypV7Ow4o.d.ts → stale-build-navigation-WjhD8zHi.d.ts} +4 -4
  50. package/dist/start-DYFyGKsM.js +470 -0
  51. package/dist/static-files-BdTPam5b.js +438 -0
  52. package/dist/static-pages-6IBHdYQc.d.ts +30 -0
  53. package/dist/tanstack-start-vite.d.ts +2 -3
  54. package/dist/tanstack-start-vite.js +1 -1
  55. package/dist/tanstack-start.d.ts +3 -4
  56. package/dist/tanstack-start.js +2 -3
  57. package/dist/tcp-3v4pmnYU.js +58 -0
  58. package/dist/testing.d.ts +8 -6
  59. package/dist/testing.js +19 -17
  60. package/dist/{trailing-slash-D2QWKWEu.d.ts → trailing-slash-C-yBKCib.d.ts} +2 -3
  61. package/dist/{types-MgFtkNQW.d.ts → types-KsKRDwAv.d.ts} +97 -46
  62. package/dist/vercel-pages.d.ts +3 -16
  63. package/dist/vercel-pages.js +1 -2
  64. package/dist/vercel-vite.d.ts +4 -5
  65. package/dist/vercel-vite.js +48 -44
  66. package/dist/vercel.d.ts +13 -10
  67. package/dist/vercel.js +48 -35
  68. package/dist/{vite-D4hfj3ph.js → vite-Brb8YR9I.js} +2 -7
  69. package/dist/{vite-B-GfswoH.js → vite-CHppJWp_.js} +5 -7
  70. package/dist/{vite-DyrhyKEr.js → vite-DjlHdyTM.js} +2 -7
  71. package/dist/vite.d.ts +2 -2
  72. package/dist/vite.js +885 -2
  73. package/package.json +13 -12
  74. package/dist/brotli-only-DrA29Ecw.js +0 -97
  75. package/dist/brotli-only-DrA29Ecw.js.map +0 -1
  76. package/dist/build-id-B0448vZH.js +0 -151
  77. package/dist/build-id-B0448vZH.js.map +0 -1
  78. package/dist/build-manifest-DBMWe3Lx.js.map +0 -1
  79. package/dist/bun-BCz6K_Xv.js.map +0 -1
  80. package/dist/cli.js.map +0 -1
  81. package/dist/client.js.map +0 -1
  82. package/dist/compress-Cp5NfXCC.js.map +0 -1
  83. package/dist/compression-CT2mWlKM.js.map +0 -1
  84. package/dist/create-server-Bp1yILQk.js.map +0 -1
  85. package/dist/deno-aqhikNMG.js.map +0 -1
  86. package/dist/entry-BoxCqc6w.js.map +0 -1
  87. package/dist/header-hook-Vzw9J9BY.js.map +0 -1
  88. package/dist/index.js.map +0 -1
  89. package/dist/listen-options-7TaXjyrk.js.map +0 -1
  90. package/dist/load-entry-CCPWbsrj.js.map +0 -1
  91. package/dist/log-DQAS5gGT.js.map +0 -1
  92. package/dist/node-CVVdk2N6.js +0 -334
  93. package/dist/node-CVVdk2N6.js.map +0 -1
  94. package/dist/node-D6m6e6EI.js.map +0 -1
  95. package/dist/react-router.js.map +0 -1
  96. package/dist/request-context-Bxdbk5P1.js +0 -80
  97. package/dist/request-context-Bxdbk5P1.js.map +0 -1
  98. package/dist/response-edge-CU8ZvL_F.js.map +0 -1
  99. package/dist/response-writer-D7KHfr8n.js.map +0 -1
  100. package/dist/script-hashes-CU7P9oZU.js.map +0 -1
  101. package/dist/serve-W4WacdOw.js +0 -29
  102. package/dist/serve-W4WacdOw.js.map +0 -1
  103. package/dist/stale-build-navigation-rg5xxmTr.js.map +0 -1
  104. package/dist/start-j0VlxeiI.js +0 -324
  105. package/dist/start-j0VlxeiI.js.map +0 -1
  106. package/dist/static-files-C2ea8KQ6.js +0 -310
  107. package/dist/static-files-C2ea8KQ6.js.map +0 -1
  108. package/dist/tanstack-start.js.map +0 -1
  109. package/dist/tcp-BgDXbjOG.js +0 -42
  110. package/dist/tcp-BgDXbjOG.js.map +0 -1
  111. package/dist/testing.js.map +0 -1
  112. package/dist/vercel-pages.js.map +0 -1
  113. package/dist/vercel-vite.js.map +0 -1
  114. package/dist/vercel.js.map +0 -1
  115. package/dist/vite-B-GfswoH.js.map +0 -1
  116. package/dist/vite-D4hfj3ph.js.map +0 -1
  117. package/dist/vite-DPiSKHDn.js +0 -870
  118. package/dist/vite-DPiSKHDn.js.map +0 -1
  119. package/dist/vite-DyrhyKEr.js.map +0 -1
package/dist/node.d.ts CHANGED
@@ -1,86 +1,63 @@
1
- import { D as StaticFiles, c as HostRuntime, d as ListenerBindings, t as AppServerEnv, u as Listener } from "./types-MgFtkNQW.js";
2
- import { MiddlewareHandler } from "hono";
1
+ import { l as Listener, s as HostRuntime, u as ListenerBindings } from "./types-KsKRDwAv.js";
2
+ import "hono";
3
3
  import { IncomingMessage, ServerResponse } from "node:http";
4
- /** A Connect middleware, such as `vite.middlewares`. */
5
- type NodeMiddleware = (request: IncomingMessage, response: ServerResponse, next: (error?: unknown) => void) => void;
6
- /** What a `node:http` listener passes to the app with each request. */
7
- type NodeBindings = ListenerBindings & {
8
- /** Node's request. */
9
- incoming?: IncomingMessage;
10
- /** Node's response. */
11
- outgoing?: ServerResponse;
12
- };
13
- /** Options for {@link devServerStage}. */
14
- type DevServerStageOptions = {
15
- /**
16
- * The directory that the middleware serves as it is, and the URL base that
17
- * it serves the directory at, such as Vite's `publicDir` and `base`. An HTML
18
- * file from it gets the `contentSecurityPolicy` with the hashes of its
19
- * inline scripts, as it does in production. Why a function: a Vite restart
20
- * can change both.
21
- */
22
- publicFiles?: () => {
23
- directory: string;
24
- base: string;
25
- };
26
- };
27
- /**
28
- * Runs a Connect middleware, such as Vite's, inside the pipeline. The
29
- * middleware answers or calls `next`. A request with no Node request and
30
- * response goes on.
31
- *
32
- * @example
33
- * entry.fetchDev(request, bindings, devServerStage(viteServer.middlewares, {
34
- * publicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),
35
- * }));
36
- */
37
- export declare function devServerStage(middleware: NodeMiddleware, { publicFiles }?: DevServerStageOptions): MiddlewareHandler<AppServerEnv>;
38
- /**
39
- * The client build on the file system. A relative `clientDirectory` is
40
- * relative to the working directory.
41
- *
42
- * Its `snapshot` reads each file and directory once. It throws for an error
43
- * that does not mean a missing file, so the server does not start.
44
- *
45
- * @example
46
- * nodeFiles("build/client").stat("/llms.txt");
47
- */
48
- export declare function nodeFiles(clientDirectory: string): StaticFiles;
49
4
  /** Options for {@link tcp}. */
50
5
  type TcpOptions = {
51
- /** @default the `PORT` environment variable, else 3000 */
6
+ /**
7
+ * A port here wins over `PORT` and over the `--port` of `app-server serve`,
8
+ * with no message. Leave it out to let the operator choose.
9
+ * @default the `PORT` environment variable, else 3000
10
+ */
52
11
  port?: number;
53
- /** @default the `HOST` environment variable, else every interface */
12
+ /**
13
+ * A host here wins over `HOST`.
14
+ * @default the `HOST` environment variable, else every interface
15
+ */
54
16
  host?: string;
55
- /** @default 95000 */
17
+ /**
18
+ * How long an idle keep-alive connection stays open, in milliseconds. Set
19
+ * it above the idle time of the proxy in front of the server, so the proxy
20
+ * never sends a request on a connection that the server closes.
21
+ *
22
+ * - Node.js keeps an idle connection for this time.
23
+ * - Bun counts whole seconds, 255 at most. It also closes a response that
24
+ * sends no bytes for this time.
25
+ * - Deno has no idle timeout, so the option has no effect there.
26
+ *
27
+ * @default 95000, above the 90 s idle pool of the ngrok edge
28
+ */
56
29
  idleTimeoutMs?: number;
57
30
  };
58
- /**
59
- * Reads a port number. A value that is not an integer from 0 to 65535 throws,
60
- * so a bad `PORT` stops startup.
61
- *
62
- * @example
63
- * parsePort("8080"); // => 8080
64
- */
65
- export declare function parsePort(value: string): number;
66
31
  /**
67
32
  * The default listener: a TCP port, served by the runtime's own HTTP server
68
33
  * (`node:http` on Node, `Bun.serve` on Bun, `Deno.serve` on Deno). It reads
69
- * `PORT` and `HOST` when it starts.
34
+ * `PORT` and `HOST` when it starts, unless the options give a port or a host.
35
+ * When it cannot listen on the host from `HOST`, the error names `HOST` and
36
+ * has the error of the runtime as its `cause`. A port in use keeps the error of
37
+ * the runtime.
38
+ * An `idleTimeoutMs` that is not an integer from 0 to 2147482647 throws, so a
39
+ * bad value stops startup.
70
40
  *
71
41
  * @example
72
- * createServer({ listeners: [tcp({ port: 8080 })] });
42
+ * createServer({ listeners: [tcp({ idleTimeoutMs: 120_000 })] });
73
43
  */
74
44
  export declare function tcp({ port, host, idleTimeoutMs }?: TcpOptions): Listener;
45
+ /** What a `node:http` listener passes to the app with each request. */
46
+ type NodeBindings = ListenerBindings & {
47
+ /** Node's request. */
48
+ incoming?: IncomingMessage;
49
+ /** Node's response. */
50
+ outgoing?: ServerResponse;
51
+ };
75
52
  /**
76
53
  * The node host: one long-lived process on Node, Bun, or Deno, such as a
77
54
  * Docker image. It listens with `tcp()`, reads the client build from the file
78
55
  * system, and keeps `requestContext()` in `AsyncLocalStorage`. On `SIGTERM` or
79
- * `SIGINT`, it shuts down, then exits the process.
56
+ * `SIGINT`, it shuts down, then exits the process. After an uncaught error, it
57
+ * logs `uncaught exception`, shuts down, then exits with code 1.
80
58
  *
81
59
  * @example
82
60
  * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });
83
61
  */
84
- declare const host$1: HostRuntime;
85
- export { type DevServerStageOptions, type NodeBindings, type NodeMiddleware, type TcpOptions, host$1 as host };
86
- //# sourceMappingURL=node.d.ts.map
62
+ export declare const host: HostRuntime;
63
+ export type { NodeBindings, TcpOptions };
package/dist/node.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as tcp, t as parsePort } from "./tcp-BgDXbjOG.js";
2
- import { n as devServerStage, r as nodeFiles, t as host } from "./node-CVVdk2N6.js";
1
+ import { n as tcp } from "./tcp-3v4pmnYU.js";
2
+ import { t as host } from "./node-DyKDFII0.js";
3
3
 
4
- export { devServerStage, host, nodeFiles, parsePort, tcp };
4
+ export { host, tcp };
@@ -1,4 +1,4 @@
1
- import { n as FrameworkBuild } from "./index-B8LsM6Mh.js";
1
+ import { n as FrameworkBuild } from "./index-gzGs53Ue.js";
2
2
  /**
3
3
  * The build side of the React Router adapter. `appServer` uses it when the
4
4
  * Vite config has the React Router plugin, so pass it only to override that.
@@ -6,5 +6,4 @@ import { n as FrameworkBuild } from "./index-B8LsM6Mh.js";
6
6
  * @example
7
7
  * appServer({ framework: reactRouterAdapter() });
8
8
  */
9
- export declare function reactRouterAdapter(): FrameworkBuild;
10
- //# sourceMappingURL=react-router-vite.d.ts.map
9
+ export declare function reactRouterAdapter(): FrameworkBuild;
@@ -1,3 +1,3 @@
1
- import { t as reactRouterAdapter } from "./vite-B-GfswoH.js";
1
+ import { t as reactRouterAdapter } from "./vite-CHppJWp_.js";
2
2
 
3
3
  export { reactRouterAdapter };
@@ -1,12 +1,9 @@
1
- import { _ as Mode, a as FrameworkRuntime, y as RequestContext } from "./types-MgFtkNQW.js";
2
- import { ServerBuild } from "react-router";
3
- /** What the server puts in React Router's context for each request. */
4
- export type AppServerContext = RequestContext;
1
+ import { a as FrameworkRuntime, g as Mode, v as RequestContext } from "./types-KsKRDwAv.js";
5
2
  /**
6
- * The React Router context key for {@link AppServerContext}. Outside a server
7
- * request, such as in React Router's prerender pass, it holds no request ID
8
- * and the logger that `logger()` gives there. `requestContext()` from
9
- * `@ngrok/app-server` gives the same values.
3
+ * The React Router context key for the `RequestContext` that the server sets
4
+ * for each request. Outside a server request, such as in React Router's
5
+ * prerender pass, it holds no request ID and the logger that `logger()` gives
6
+ * there. `requestContext()` from `@ngrok/app-server` gives the same values.
10
7
  *
11
8
  * @example
12
9
  * export async function loader({ context }: Route.LoaderArgs) {
@@ -14,13 +11,6 @@ export type AppServerContext = RequestContext;
14
11
  * }
15
12
  */
16
13
  export declare const appServerContext: import("react-router").RouterContext<RequestContext>;
17
- /**
18
- * Whether a module is a React Router server build.
19
- *
20
- * @example
21
- * isServerBuild(await import("./build/server/index.js")); // => true
22
- */
23
- export declare function isServerBuild(value: unknown): value is ServerBuild;
24
14
  /**
25
15
  * The run side of the React Router adapter, for a server build. Each request
26
16
  * gets a `RouterContextProvider` that holds {@link appServerContext}. The
@@ -31,5 +21,4 @@ export declare function isServerBuild(value: unknown): value is ServerBuild;
31
21
  */
32
22
  export declare function runtime(build: unknown, { mode }: {
33
23
  mode: Mode;
34
- }): FrameworkRuntime;
35
- //# sourceMappingURL=react-router.d.ts.map
24
+ }): FrameworkRuntime;
@@ -1,12 +1,13 @@
1
- import { i as requestContextValues, n as outsideLogger } from "./request-context-Bxdbk5P1.js";
1
+ import { o as requestContextValues, r as outsideLogger } from "./request-context-Cslbrscf.js";
2
+ import { t as CONTENT_TYPES } from "./content-types-Le-5BNEC.js";
2
3
  import { RouterContextProvider, createContext, createRequestHandler } from "react-router";
3
4
 
4
5
  // src/react-router/index.ts
5
6
  /**
6
- * The React Router context key for {@link AppServerContext}. Outside a server
7
- * request, such as in React Router's prerender pass, it holds no request ID
8
- * and the logger that `logger()` gives there. `requestContext()` from
9
- * `@ngrok/app-server` gives the same values.
7
+ * The React Router context key for the `RequestContext` that the server sets
8
+ * for each request. Outside a server request, such as in React Router's
9
+ * prerender pass, it holds no request ID and the logger that `logger()` gives
10
+ * there. `requestContext()` from `@ngrok/app-server` gives the same values.
10
11
  *
11
12
  * @example
12
13
  * export async function loader({ context }: Route.LoaderArgs) {
@@ -46,12 +47,7 @@ function withRoutePattern(build) {
46
47
  routes
47
48
  };
48
49
  }
49
- /**
50
- * Whether a module is a React Router server build.
51
- *
52
- * @example
53
- * isServerBuild(await import("./build/server/index.js")); // => true
54
- */
50
+ /** Whether a module is a React Router server build. */
55
51
  function isServerBuild(value) {
56
52
  return typeof value === "object" && value != null && "routes" in value && "entry" in value && "assetsBuildDirectory" in value && typeof value.assetsBuildDirectory === "string";
57
53
  }
@@ -73,7 +69,7 @@ function runtime(build, { mode }) {
73
69
  clientDirectory: build.assetsBuildDirectory,
74
70
  prerenderedPaths: build.prerender,
75
71
  isDataRequest: (path) => path.endsWith(".data") || path === manifestPath,
76
- contentTypes: { ".data": "text/x-script" },
72
+ contentTypes: CONTENT_TYPES,
77
73
  fetch: async (request, context) => {
78
74
  const routerContext = new RouterContextProvider();
79
75
  routerContext.set(appServerContext, requestContextValues(context));
@@ -83,5 +79,4 @@ function runtime(build, { mode }) {
83
79
  };
84
80
  }
85
81
 
86
- export { appServerContext, isServerBuild, runtime };
87
- //# sourceMappingURL=react-router.js.map
82
+ export { appServerContext, runtime };
@@ -0,0 +1,163 @@
1
+ import { i as jsonSink, r as hookSink, s as sinkLogger } from "./log-DfC9D5_T.js";
2
+
3
+ // src/core/request-context.ts
4
+ /**
5
+ * Each store that a request ran in. Why a set: two entries in one process can
6
+ * have two hosts, and each request uses the store of its own app.
7
+ */
8
+ const stores = /* @__PURE__ */ new Set();
9
+ /** The {@link RequestContext} values of a request. */
10
+ function requestContextValues(context) {
11
+ return {
12
+ requestId: context.get("requestId"),
13
+ logger: context.get("logger"),
14
+ cspNonce: context.get("cspNonce"),
15
+ clientAddress: context.get("clientAddress")
16
+ };
17
+ }
18
+ /** Runs `work` in `store` with `scope` as the request that {@link requestContext} reads. */
19
+ function withRequestContext(store, scope, work) {
20
+ if (store == null) return work();
21
+ stores.add(store);
22
+ return store.run(scope, work);
23
+ }
24
+ /**
25
+ * The values of a request whose response is sent, with the fields of its log
26
+ * lines and without its Hono context. Why a logger that the first read makes:
27
+ * a timer that a request leaves keeps these values until it fires, and few of
28
+ * those requests log again.
29
+ */
30
+ var SentValues = class {
31
+ requestId;
32
+ cspNonce;
33
+ clientAddress;
34
+ /** The stop state of the app server of the request, for {@link currentShutdown}. */
35
+ shutdown;
36
+ #sink;
37
+ #method;
38
+ #path;
39
+ #logAttributes;
40
+ #logger;
41
+ /** `made` is the logger that the server made for the request, and `sink` is where it writes. */
42
+ constructor(context, sink, made) {
43
+ this.requestId = context.get("requestId");
44
+ this.cspNonce = context.get("cspNonce");
45
+ this.clientAddress = context.get("clientAddress");
46
+ this.shutdown = context.get("shutdown");
47
+ this.#sink = sink;
48
+ this.#method = context.req.method;
49
+ this.#path = context.req.path;
50
+ this.#logAttributes = context.get("logAttributes");
51
+ const current = context.get("logger");
52
+ this.#logger = current === made ? void 0 : current;
53
+ }
54
+ /** A logger whose lines carry the fields that the request's logger gave when the response ended. */
55
+ get logger() {
56
+ if (this.#logger == null) {
57
+ const fields = {
58
+ "http.request_id": this.requestId,
59
+ "http.method": this.#method,
60
+ "http.url_details.path": this.#path,
61
+ ...this.#logAttributes
62
+ };
63
+ this.#logger = sinkLogger(this.#sink, (attributes) => ({
64
+ ...fields,
65
+ ...attributes,
66
+ ...fields
67
+ }));
68
+ }
69
+ return this.#logger;
70
+ }
71
+ };
72
+ /**
73
+ * Puts the values of the request in `scope`, in place of its Hono context.
74
+ * `made` is the logger that the server made for the request, and `sink` is
75
+ * where it writes. Why: a timer that the request leaves keeps the scope until
76
+ * it fires. The context would keep the request, the response, and each hook
77
+ * with it.
78
+ */
79
+ function releaseContext(scope, sink, made) {
80
+ if (scope.context != null) {
81
+ scope.values = new SentValues(scope.context, sink, made);
82
+ scope.context = void 0;
83
+ }
84
+ }
85
+ /**
86
+ * The request ID, logger, CSP nonce, and client address of the request that
87
+ * runs. Work that the request started, such as a timer, gets the same values
88
+ * after the response is sent. It gives `undefined` outside a server request,
89
+ * such as in a prerender pass, or on a host with no request storage. To log
90
+ * there too, use {@link logger}.
91
+ *
92
+ * @example
93
+ * export async function loader() {
94
+ * const requestId = requestContext()?.requestId;
95
+ * }
96
+ */
97
+ function requestContext() {
98
+ const scope = currentScope();
99
+ if (scope?.context != null) return requestContextValues(scope.context);
100
+ const values = scope?.values;
101
+ return values == null ? void 0 : {
102
+ requestId: values.requestId,
103
+ logger: values.logger,
104
+ cspNonce: values.cspNonce,
105
+ clientAddress: values.clientAddress
106
+ };
107
+ }
108
+ /** The scope of the request that runs, else `undefined`. */
109
+ function currentScope() {
110
+ for (const store of stores) {
111
+ const scope = store.get();
112
+ if (scope != null) return scope;
113
+ }
114
+ }
115
+ /**
116
+ * The stop state of the app server of the request that runs, also in work
117
+ * that the request left after its response. It gives `undefined` outside a
118
+ * server request and on a host with no request storage.
119
+ */
120
+ function currentShutdown() {
121
+ const scope = currentScope();
122
+ const context = scope?.context;
123
+ if (context != null) return context.get("shutdown");
124
+ return scope?.values instanceof SentValues ? scope.values.shutdown : void 0;
125
+ }
126
+ /** The sink of the process. `createServer` sets it to its own sink, with its hooks. */
127
+ let processSink = hookSink(jsonSink());
128
+ /** Sets the sink of the logger that {@link logger} gives outside a request. The last call wins. */
129
+ function setProcessSink(sink) {
130
+ processSink = sink;
131
+ }
132
+ /**
133
+ * A logger that writes to the sink of the process at the time of each call.
134
+ * Why: a value made before `createServer`, such as a context default, then
135
+ * writes to the sink of the server.
136
+ */
137
+ const outsideLogger = sinkLogger({ log: ({ level, message, attributes }) => {
138
+ processSink.log({
139
+ level,
140
+ message,
141
+ attributes
142
+ });
143
+ } });
144
+ /**
145
+ * The logger of the request that runs. Work that the request started, such as
146
+ * a timer, gets a logger after the response is sent whose lines carry the
147
+ * fields that the request had then. Outside a request, such as at module
148
+ * load or in a prerender pass, it gives a logger that writes to the sink and
149
+ * the hooks of the last `createServer` call, else to `jsonSink()`.
150
+ *
151
+ * @example
152
+ * import { logger } from "@ngrok/app-server";
153
+ *
154
+ * export async function loader() {
155
+ * logger().info("loading the dashboard", { "usr.id": userId });
156
+ * }
157
+ */
158
+ function logger() {
159
+ const scope = currentScope();
160
+ return scope?.context?.get("logger") ?? scope?.values?.logger ?? outsideLogger;
161
+ }
162
+
163
+ export { requestContext as a, withRequestContext as c, releaseContext as i, logger as n, requestContextValues as o, outsideLogger as r, setProcessSink as s, currentShutdown as t };
@@ -1,5 +1,5 @@
1
- import { t as asError } from "./log-DQAS5gGT.js";
2
- import { a as replaceResponse, i as listView, n as headerList, t as headerIndex } from "./header-hook-Vzw9J9BY.js";
1
+ import { a as listView, n as headerIndex, o as replaceResponse, r as headerList } from "./header-hook-JfqaTt34.js";
2
+ import { t as asError } from "./log-DfC9D5_T.js";
3
3
 
4
4
  // src/core/response-edge.ts
5
5
  function ignore() {}
@@ -84,7 +84,7 @@ var ResponseEdge = class {
84
84
  * Keeps `headers`, the headers of the response after each header hook, and
85
85
  * `base`, its headers before the hooks. The server calls it.
86
86
  */
87
- useHeaders(base, headers) {
87
+ useHeaders({ base, headers }) {
88
88
  this.#base = base;
89
89
  this.#headers = headers;
90
90
  }
@@ -123,11 +123,12 @@ var ResponseEdge = class {
123
123
  console.error(error);
124
124
  }
125
125
  /**
126
- * Reports what went out, once: the status and the headers that the
127
- * listener sent, the bytes, and whether the body stopped before its end.
128
- * `head` is the flat list that the listener gave `writeHead`.
126
+ * Reports what went out, once: `status`, the headers that the listener
127
+ * sent, the bytes, and `aborted`, which says whether the body stopped
128
+ * before its end. `head` is the flat list that the listener gave
129
+ * `writeHead`.
129
130
  */
130
- close(status, aborted, head) {
131
+ close({ status, aborted, head }) {
131
132
  if (this.#sent != null) return;
132
133
  this.#sent = {
133
134
  status,
@@ -284,7 +285,10 @@ function finishFrom(context, finish, from) {
284
285
  });
285
286
  }
286
287
  if (edge != null) {
287
- edge.useHeaders(base, head);
288
+ edge.useHeaders({
289
+ base,
290
+ headers: head
291
+ });
288
292
  for (const report of reports) edge.onSent(report);
289
293
  return;
290
294
  }
@@ -323,5 +327,4 @@ function finishResponse(context, finish) {
323
327
  return finishFrom(context, finish, finish.hooks.length - 1);
324
328
  }
325
329
 
326
- export { finishResponse as n, onResponseSent as r, ResponseEdge as t };
327
- //# sourceMappingURL=response-edge-CU8ZvL_F.js.map
330
+ export { finishResponse as n, onResponseSent as r, ResponseEdge as t };
@@ -1,7 +1,7 @@
1
- import { n as headerList, t as headerIndex } from "./header-hook-Vzw9J9BY.js";
2
- import { t as ResponseEdge } from "./response-edge-CU8ZvL_F.js";
3
- import { s as readIfQueued } from "./compression-CT2mWlKM.js";
4
- import { r as waitsForZlib } from "./compress-Cp5NfXCC.js";
1
+ import { c as readIfQueued } from "./compression-uJxu0JVb.js";
2
+ import { n as headerIndex, r as headerList } from "./header-hook-JfqaTt34.js";
3
+ import { t as ResponseEdge } from "./response-edge-Ow5Pi5qF.js";
4
+ import { r as waitsForZlib } from "./compress-2w3jqBh7.js";
5
5
  import { IncomingMessage, ServerResponse } from "node:http";
6
6
  import { getRequestListener } from "@hono/node-server";
7
7
 
@@ -93,12 +93,22 @@ function sentHead(outgoing) {
93
93
  for (const [name, value] of Object.entries(outgoing.getHeaders())) for (const each of Array.isArray(value) ? value : [value]) if (each != null) head.push(name, String(each));
94
94
  return head;
95
95
  }
96
+ /**
97
+ * Writes a response with no body, with a `Content-Length` of 0. Why: with no
98
+ * length, Node sends `Transfer-Encoding: chunked` and an empty chunk. Why not
99
+ * for a 204, a 304, or a HEAD response: a 204 takes no length, and the others
100
+ * keep the length of the body that they do not send.
101
+ */
102
+ function writeEmpty(status, outgoing, head) {
103
+ if (status !== 204 && status !== 304 && outgoing.req.method !== "HEAD" && headerIndex(head, "content-length") === -1 && headerIndex(head, "transfer-encoding") === -1) head.push("content-length", "0");
104
+ outgoing.writeHead(status, head);
105
+ outgoing.end();
106
+ }
96
107
  /** Writes the head and the body of `response`, with `head` in place of its headers. */
97
108
  async function writeBody(response, reader, { outgoing, edge, head }) {
98
109
  const { body, status } = response;
99
110
  if (body == null || reader == null) {
100
- outgoing.writeHead(status, head);
101
- outgoing.end();
111
+ writeEmpty(status, outgoing, head);
102
112
  return;
103
113
  }
104
114
  if (headerIndex(head, "content-type") === -1) head.push("content-type", DEFAULT_CONTENT_TYPE);
@@ -108,17 +118,21 @@ async function writeBody(response, reader, { outgoing, edge, head }) {
108
118
  const index = headerIndex(head, "content-length");
109
119
  if (index === -1 && headerIndex(head, "transfer-encoding") === -1) head.push("content-length", String(ahead.size));
110
120
  else if (index !== -1 && Number(head[index + 1]) !== ahead.size) throw new Error("The body does not match its Content-Length.");
111
- outgoing.writeHead(status, head);
112
- outgoing.end(ahead.chunks.length === 1 ? ahead.chunks[0] : Buffer.concat(ahead.chunks));
113
- edge.bytes += ahead.size;
114
- return;
121
+ if (ahead.size < outgoing.writableHighWaterMark) {
122
+ outgoing.writeHead(status, head);
123
+ outgoing.end(ahead.chunks.length === 1 ? ahead.chunks[0] : Buffer.concat(ahead.chunks));
124
+ edge.bytes += ahead.size;
125
+ return;
126
+ }
115
127
  }
116
128
  outgoing.writeHead(status, head);
129
+ let flowing = true;
117
130
  for (const chunk of ahead.chunks) {
118
- outgoing.write(chunk);
131
+ flowing = outgoing.write(chunk);
119
132
  edge.bytes += chunk.byteLength;
120
133
  }
121
134
  if (ahead.chunks.length === 0) outgoing.flushHeaders();
135
+ if (!flowing) await drained(outgoing);
122
136
  await pump(reader, ahead.pending ?? reader.read(), {
123
137
  outgoing,
124
138
  edge
@@ -135,6 +149,9 @@ async function writeBody(response, reader, { outgoing, edge, head }) {
135
149
  * is the exception: zlib finishes it soon, so the head waits for it.
136
150
  * - It reads the next chunk only when Node takes the last one, and it cancels
137
151
  * the body when the socket closes.
152
+ * - It ends the response only after the socket takes each write that was at
153
+ * or over its high-water mark, so a server that stops does not cut a large
154
+ * body that still goes out.
138
155
  * - When a step fails before the head goes out, such as a body that fails or
139
156
  * a header that Node rejects, a 500 goes out. After the head, a failure or
140
157
  * a body that does not match its `Content-Length` destroys the socket, so
@@ -146,18 +163,30 @@ async function writeResponse(response, outgoing, edge) {
146
163
  const sendsBody = outgoing.req.method !== "HEAD";
147
164
  if (body == null && response.headers.has(ALREADY_SENT_HEADER)) {
148
165
  edge.bytes = sendsBody ? Number(response.headers.get("content-length") ?? 0) : 0;
149
- edge.close(status, false, sentHead(outgoing));
166
+ edge.close({
167
+ status,
168
+ aborted: false,
169
+ head: sentHead(outgoing)
170
+ });
150
171
  return;
151
172
  }
152
173
  let head = edge.headersFor(response) ?? headerList(response.headers);
153
174
  if (outgoing.destroyed) {
154
- edge.close(status, true, head);
175
+ edge.close({
176
+ status,
177
+ aborted: true,
178
+ head
179
+ });
155
180
  await body?.cancel().catch(() => {});
156
181
  return;
157
182
  }
158
183
  let reader;
159
184
  outgoing.on("close", () => {
160
- edge.close(status, !outgoing.writableFinished, head);
185
+ edge.close({
186
+ status,
187
+ aborted: !outgoing.writableFinished,
188
+ head
189
+ });
161
190
  reader?.cancel().catch(() => {});
162
191
  });
163
192
  try {
@@ -240,19 +269,22 @@ const writesResponses = !("Bun" in globalThis) && !("Deno" in globalThis);
240
269
  * the listener.
241
270
  * With `trustForwardedProto`, each request takes its scheme from
242
271
  * `X-Forwarded-Proto`, as the server option does.
272
+ * While `isDraining` gives `true`, each response that the listener writes
273
+ * says `Connection: close`, and Node closes its connection after it.
243
274
  *
244
275
  * @example
245
276
  * http.createServer(requestListener(async (request, bindings) => app.fetch(request, bindings)));
246
277
  */
247
- function requestListener(answer, { trustForwardedProto = false } = {}) {
248
- const listener = listenerOf(answer);
278
+ function requestListener(answer, { trustForwardedProto = false, isDraining } = {}) {
279
+ const listener = listenerOf(answer, isDraining);
249
280
  return trustForwardedProto ? async (incoming, outgoing) => {
250
281
  if (incoming instanceof IncomingMessage) useForwardedProto(incoming);
251
282
  return listener(incoming, outgoing);
252
283
  } : listener;
253
284
  }
254
285
  /** The listener of {@link requestListener}, with no scheme from `X-Forwarded-Proto`. */
255
- function listenerOf(answer) {
286
+ function listenerOf(answer, isDraining) {
287
+ const options = { hostname: "localhost" };
256
288
  return keepGlobalResponse(() => getRequestListener(async (request, { incoming, outgoing }) => {
257
289
  const { remoteAddress } = incoming.socket;
258
290
  if (!(incoming instanceof IncomingMessage) || !(outgoing instanceof ServerResponse)) return answer(request, { remoteAddress });
@@ -277,13 +309,17 @@ function listenerOf(answer) {
277
309
  edge
278
310
  });
279
311
  } catch (error) {
280
- edge.close(500, false, []);
312
+ edge.close({
313
+ status: 500,
314
+ aborted: false,
315
+ head: []
316
+ });
281
317
  throw error;
282
318
  }
319
+ if (isDraining?.() === true) outgoing.shouldKeepAlive = false;
283
320
  await writeResponse(response, outgoing, edge);
284
321
  return ALREADY_SENT;
285
- }));
322
+ }, options));
286
323
  }
287
324
 
288
- export { requestListener as t };
289
- //# sourceMappingURL=response-writer-D7KHfr8n.js.map
325
+ export { requestListener as t };
@@ -1,4 +1,4 @@
1
- import { t as contentType } from "./static-files-C2ea8KQ6.js";
1
+ import { t as contentType } from "./static-files-BdTPam5b.js";
2
2
  import { readFileSync, readdirSync, statSync } from "node:fs";
3
3
  import { join, relative, resolve, sep } from "node:path";
4
4
  import { createHash } from "node:crypto";
@@ -67,5 +67,4 @@ function scriptHashesOf(clientDirectory) {
67
67
  return Object.fromEntries(Object.entries(hashes).toSorted(([first], [second]) => first.localeCompare(second)));
68
68
  }
69
69
 
70
- export { scriptHashesOf as n, publicScriptHashes as t };
71
- //# sourceMappingURL=script-hashes-CU7P9oZU.js.map
70
+ export { scriptHashesOf as n, publicScriptHashes as t };
@@ -0,0 +1,26 @@
1
+ import { i as SERVER_ENTRY_FILE } from "./build-manifest-CoBztw_6.js";
2
+ import { t as loadEntry } from "./load-entry-Bgq1_HDV.js";
3
+ import { resolve } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+
6
+ // src/cli/serve.ts
7
+ /**
8
+ * Where `app-server serve` looks for the server build when no path is given:
9
+ * the server entry in the React Router and Vite output layouts, then a plain
10
+ * React Router build.
11
+ */
12
+ const DEFAULT_BUILD_PATHS = [
13
+ `build/server/${SERVER_ENTRY_FILE}`,
14
+ `dist/server/${SERVER_ENTRY_FILE}`,
15
+ "build/server/index.js"
16
+ ];
17
+ /**
18
+ * Loads the production server build at `buildPath`, a file that exists, and starts it. The copy of
19
+ * this package in the build runs the server when the build has one: see `loadEntry`.
20
+ */
21
+ async function serve({ buildPath }) {
22
+ const build = await import(pathToFileURL(resolve(buildPath)).href);
23
+ await (await loadEntry(build)).start();
24
+ }
25
+
26
+ export { DEFAULT_BUILD_PATHS, serve };