@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/index.d.ts CHANGED
@@ -1,8 +1,24 @@
1
- import { C as SentResponse, D as StaticFiles, E as StartedListener, O as ResponseEdge, S as ResponseHeaders, T as SetupInfo, _ as Mode, a as FrameworkRuntime, b as RequestLogger, c as HostRuntime, d as ListenerBindings, f as ListenerStartOptions, g as LogSink, h as LogOptions, i as FileInfo, l as Lifecycle, m as LogLine, n as ByteRange, o as FrameworkRuntimeFactory, p as LogLevel, r as FetchHandler, s as HeaderHook, t as AppServerEnv, u as Listener, v as Plugin, w as ServerBindings, x as RequestStore, y as RequestContext } from "./types-MgFtkNQW.js";
2
- import { A as buildId, C as RedirectRule, D as HealthOptions, E as noindex, M as accessLog, O as health, S as securityHeaders, T as NoindexOptions, _ as requestId, a as createServer, b as SecurityHeadersOptions, c as assets, d as PUBLIC_ENV_SCRIPT_ID, f as RuntimeEnv, g as RequestIdOptions, h as runtimeEnv, i as RunningServer, j as AccessLogOptions, k as BuildIdOptions, l as prerendered, m as StandardSchemaV1, n as CreateServerOptions, o as defaultPlugins, p as RuntimeEnvOptions, r as DefaultPluginsOptions, s as PrerenderedOptions, t as AppServer, u as InferOutput, v as ContentSecurityPolicyOptions, w as redirects, x as contentSecurityPolicy, y as SecurityHeaderValues } from "./create-server-X2GR-U6t.js";
3
- import { n as TrailingSlashOptions, r as trailingSlash, t as TrailingSlash } from "./trailing-slash-D2QWKWEu.js";
4
- import { n as CreateEntryOptions, r as createEntry, t as AppServerEntry } from "./entry-DZTCaL3d.js";
1
+ import { A as AccessLogOptions, C as redirects, D as health, E as HealthOptions, O as BuildIdOptions, S as RedirectsOptions, T as noindex, _ as SecurityHeaderValues, a as defaultPlugins, b as securityHeaders, c as prerendered, d as RuntimeEnvOptions, f as StandardSchemaV1, g as ContentSecurityPolicyOptions, h as requestId, i as createServer, j as accessLog, k as buildId, l as InferOutput, m as RequestIdOptions, n as CreateServerOptions, o as PrerenderedOptions, p as runtimeEnv, r as DefaultPluginsOptions, s as assets, t as AppServer, u as RuntimeEnv, v as SecurityHeadersOptions, w as NoindexOptions, x as RedirectRule, y as contentSecurityPolicy } from "./create-server-UVsHFQyK.js";
2
+ import { n as CreateEntryOptions, r as createEntry, t as AppServerEntry } from "./entry-DBq_3s8X.js";
3
+ import { C as SentResponse, D as StaticFiles, E as StartedListener, O as ResponseEdge, S as ResponseHeaders, T as SetupInfo, _ as Plugin, a as FrameworkRuntime, b as RequestScope, c as Lifecycle, d as ListenerStartOptions, f as LogLevel, g as Mode, h as LogSink, i as FileInfo, l as Listener, m as LogOptions, n as ByteRange, o as HeaderHook, p as LogLine, r as FetchHandler, s as HostRuntime, t as AppServerEnv, u as ListenerBindings, v as RequestContext, w as ServerBindings, x as RequestStore, y as RequestLogger } from "./types-KsKRDwAv.js";
4
+ import { n as TrailingSlashOptions, r as trailingSlash, t as TrailingSlash } from "./trailing-slash-C-yBKCib.js";
5
+ import { n as StaticPage, t as CdnPage } from "./static-pages-6IBHdYQc.js";
5
6
  import { Context, Next } from "hono";
7
+ /**
8
+ * A signal that aborts when the server starts to shut down. A handler that
9
+ * holds a response open, such as an event stream, stops on it so that the
10
+ * drain does not wait for the deadline.
11
+ *
12
+ * In a request, and in work that the request started, it is the signal of the
13
+ * app server that serves the request. Outside a request, and on a host with
14
+ * no request storage, it is the signal of the last `createServer` call, as
15
+ * the sink of `logger()` is.
16
+ *
17
+ * @example
18
+ * const timer = setInterval(sendUpdate, 1_000);
19
+ * shutdownSignal().addEventListener("abort", () => clearInterval(timer), { once: true });
20
+ */
21
+ export declare function shutdownSignal(): AbortSignal;
6
22
  /** One server-sent event. */
7
23
  type ServerSentEvent = {
8
24
  data: string;
@@ -11,8 +27,15 @@ type ServerSentEvent = {
11
27
  };
12
28
  /** What {@link eventStream} passes to its producer. */
13
29
  type EventStreamSink = {
14
- send: (event: ServerSentEvent) => void;
15
- /** Aborts when the client disconnects or the server shuts down. Stop the work on it. */
30
+ /**
31
+ * Sends `event` at once. The promise resolves when the client has read
32
+ * the earlier events, down to 64 KiB of unread bytes, or when the stream
33
+ * ends. It never rejects. Await it, so that a slow client slows the
34
+ * producer. A stream with more than 1 MiB of unread bytes stops. An
35
+ * event with a bad field throws a `TypeError` at once.
36
+ */
37
+ send: (event: ServerSentEvent) => Promise<void>;
38
+ /** Aborts while the stream is open: when the client disconnects or the server shuts down. Stop the work on it. */
16
39
  signal: AbortSignal;
17
40
  };
18
41
  /** Options for {@link eventStream}. */
@@ -20,11 +43,16 @@ type EventStreamOptions = {
20
43
  /** The request's signal, so a client disconnect stops the stream. */
21
44
  signal?: AbortSignal;
22
45
  /**
23
- * How often a `: ping` comment goes out, so that a proxy keeps a quiet stream open.
46
+ * How often a `: ping` comment goes out, in milliseconds, so that a proxy keeps a quiet stream
47
+ * open. It must be from 1 to 2,147,483,647, or `eventStream` throws a `RangeError`.
24
48
  * @default 15000
25
49
  */
26
50
  heartbeatMs?: number;
27
- /** Extra response headers. */
51
+ /**
52
+ * Extra response headers. A `Cache-Control` here takes the place of the default `no-cache`, so
53
+ * keep `no-cache` in it. `no-cache, no-transform` sends the stream with no compression: then
54
+ * `streamingCompress()` holds no encoder for the life of the stream, and the events take more bytes.
55
+ */
28
56
  headers?: HeadersInit;
29
57
  };
30
58
  /**
@@ -33,41 +61,64 @@ type EventStreamOptions = {
33
61
  * closes at server shutdown so the drain does not wait for the deadline. The
34
62
  * stream closes when `produce` resolves.
35
63
  *
64
+ * Await `send`: it waits while the client has 64 KiB or more of events that
65
+ * it has not read. When the unread events pass 1 MiB, the stream stops: the
66
+ * response fails, and `signal` aborts.
67
+ *
36
68
  * @example
37
69
  * export async function loader({ request }: Route.LoaderArgs) {
38
- * return eventStream({ signal: request.signal }, async ({ send, signal }) => {
39
- * for await (const update of watchUpdates({ signal })) {
40
- * send({ event: "update", data: JSON.stringify(update) });
41
- * }
42
- * });
70
+ * return eventStream(
71
+ * async ({ send, signal }) => {
72
+ * for await (const update of watchUpdates({ signal })) {
73
+ * await send({ event: "update", data: JSON.stringify(update) });
74
+ * }
75
+ * },
76
+ * { signal: request.signal },
77
+ * );
43
78
  * }
44
79
  */
45
- export declare function eventStream({ signal, heartbeatMs, headers }: EventStreamOptions, produce: (sink: EventStreamSink) => void | Promise<void>): Response;
80
+ export declare function eventStream(produce: (sink: EventStreamSink) => void | Promise<void>, { signal, heartbeatMs, headers }?: EventStreamOptions): Response;
81
+ /** Options for {@link withHeaderHook}. */
82
+ type HeaderHookOptions = {
83
+ /** The context of the stage. */
84
+ context: Context<AppServerEnv>;
85
+ /** The `next` of the stage. */
86
+ next: Next;
87
+ /** Changes the response headers where the response leaves. */
88
+ hook: HeaderHook;
89
+ };
46
90
  /**
47
91
  * Runs `hook` on the response headers after the later stages. In an app
48
92
  * server, the hook changes the head once, where the response leaves, so the
49
93
  * response needs no copy. That run comes after the code that each stage runs
50
94
  * after its `next()`, so a stage can decide there what its hook does. A hook
51
- * that throws gives a 500. See {@link HeaderHook} for the order of the hooks
52
- * and the views that also run them.
95
+ * that throws gets the answer of the app's `onError`, as a stage that throws
96
+ * does. See {@link HeaderHook} for the order of the hooks and the views that
97
+ * also run them.
53
98
  *
54
99
  * @example
55
100
  * const frameOptions: Plugin = {
56
101
  * name: "frame-options",
57
- * middleware: async (c, next) =>
58
- * withHeaderHook(c, next, (response) => {
59
- * response.set("X-Frame-Options", "DENY");
102
+ * middleware: async (context, next) =>
103
+ * withHeaderHook({
104
+ * context,
105
+ * next,
106
+ * hook: (response) => {
107
+ * response.set("X-Frame-Options", "DENY");
108
+ * },
60
109
  * }),
61
110
  * };
62
111
  */
63
- export declare function withHeaderHook(context: Context<AppServerEnv>, next: Next, hook: HeaderHook): Promise<void>;
112
+ export declare function withHeaderHook({ context, next, hook }: HeaderHookOptions): Promise<void>;
64
113
  /**
65
114
  * A log sink that writes one JSON object per line. Each line has `time`,
66
115
  * `level`, `message`, and the flat attributes, which Datadog reads as its
67
- * standard attributes. The default writes the lines of one event-loop turn
68
- * to stdout at the end of the turn.
116
+ * standard attributes.
69
117
  *
70
- * @param write - Where each line goes. Defaults to stdout.
118
+ * @param write - Where each line goes. Defaults to the log writer of the
119
+ * host. The node host and the vercel host write the lines of one event-loop
120
+ * turn to standard output (stdout) at the end of the turn. On a host with no
121
+ * log writer, and before `createEntry` runs, `console.log` writes each line.
71
122
  *
72
123
  * @example
73
124
  * createServer({ logger: jsonSink() });
@@ -92,7 +143,7 @@ type BodyLimitOptions = {
92
143
  * next stage runs, so an upload cannot stream.
93
144
  *
94
145
  * @example
95
- * createServer({ plugins: [requestId(), accessLog(), bodyLimit({ maxBytes: 1_048_576 })] });
146
+ * createServer({ plugins: [requestId(), accessLog(), bodyLimit({ maxBytes: 1_048_576 }), assets()] });
96
147
  */
97
148
  export declare function bodyLimit({ maxBytes }: BodyLimitOptions): Plugin;
98
149
  /**
@@ -122,7 +173,7 @@ export declare function privateDocuments(): Plugin;
122
173
  * host gives the streams. On a host with none, the plugin does nothing.
123
174
  *
124
175
  * @example
125
- * createServer({ plugins: [requestId(), accessLog(), streamingCompress()] });
176
+ * createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets()] });
126
177
  */
127
178
  export declare function streamingCompress(): Plugin;
128
179
  /**
@@ -142,7 +193,8 @@ export declare function streamingCompress(): Plugin;
142
193
  * the client named it.
143
194
  * - Both answers are UTF-8. A range with `charset=utf-8` is more specific
144
195
  * than a range with no charset, and a range with another charset does not
145
- * match. Other parameters, such as `variant`, do not change the match.
196
+ * match. A `charset` with no value counts as no charset. Other parameters,
197
+ * such as `variant`, do not change the match.
146
198
  * - Media types and parameter names are not case-sensitive. A quoted
147
199
  * parameter value can hold a `,` or a `;`.
148
200
  *
@@ -158,18 +210,22 @@ export declare function streamingCompress(): Plugin;
158
210
  */
159
211
  export declare function prefersMarkdown(request: Request): boolean;
160
212
  /**
161
- * The request ID, logger, and CSP nonce of the request that runs. It gives `undefined`
162
- * outside a server request, such as in a prerender pass, or on a host with no
163
- * request storage.
213
+ * The request ID, logger, CSP nonce, and client address of the request that
214
+ * runs. Work that the request started, such as a timer, gets the same values
215
+ * after the response is sent. It gives `undefined` outside a server request,
216
+ * such as in a prerender pass, or on a host with no request storage. To log
217
+ * there too, use {@link logger}.
164
218
  *
165
219
  * @example
166
220
  * export async function loader() {
167
- * requestContext()?.logger.info("loading the dashboard");
221
+ * const requestId = requestContext()?.requestId;
168
222
  * }
169
223
  */
170
224
  export declare function requestContext(): RequestContext | undefined;
171
225
  /**
172
- * The logger of the request that runs. Outside a request, such as at module
226
+ * The logger of the request that runs. Work that the request started, such as
227
+ * a timer, gets a logger after the response is sent whose lines carry the
228
+ * fields that the request had then. Outside a request, such as at module
173
229
  * load or in a prerender pass, it gives a logger that writes to the sink and
174
230
  * the hooks of the last `createServer` call, else to `jsonSink()`.
175
231
  *
@@ -181,16 +237,4 @@ export declare function requestContext(): RequestContext | undefined;
181
237
  * }
182
238
  */
183
239
  export declare function logger(): RequestLogger;
184
- /**
185
- * A signal that aborts when the server starts to shut down. Read it for each
186
- * request: each start of a server makes a new one. A handler that
187
- * holds a response open, such as an event stream, stops on it so that the
188
- * drain does not wait for the deadline.
189
- *
190
- * @example
191
- * const timer = setInterval(sendUpdate, 1_000);
192
- * shutdownSignal().addEventListener("abort", () => clearInterval(timer), { once: true });
193
- */
194
- export declare function shutdownSignal(): AbortSignal;
195
- export { type AccessLogOptions, type AppServer, type AppServerEntry, type AppServerEnv, type BodyLimitOptions, type BuildIdOptions, type ByteRange, type ContentSecurityPolicyOptions, type CreateEntryOptions, type CreateServerOptions, type DefaultPluginsOptions, type EventStreamOptions, type EventStreamSink, type FetchHandler, type FileInfo, type FrameworkRuntime, type FrameworkRuntimeFactory, type HeaderHook, type HealthOptions, type HostRuntime, type InferOutput, type Lifecycle, type Listener, type ListenerBindings, type ListenerStartOptions, type LogLevel, type LogLine, type LogOptions, type LogSink, type Mode, type NoindexOptions, PUBLIC_ENV_SCRIPT_ID, type Plugin, type PrerenderedOptions, type RedirectRule, type RequestContext, type RequestIdOptions, type RequestLogger, type RequestStore, ResponseEdge, type ResponseHeaders, type RunningServer, type RuntimeEnv, type RuntimeEnvOptions, type SecurityHeaderValues, type SecurityHeadersOptions, type SentResponse, type ServerBindings, type ServerSentEvent, type SetupInfo, type StandardSchemaV1, type StartedListener, type StaticFiles, type TrailingSlash, type TrailingSlashOptions, accessLog, assets, buildId, contentSecurityPolicy, createEntry, createServer, defaultPlugins, health, noindex, prerendered, redirects, requestId, runtimeEnv, securityHeaders, trailingSlash };
196
- //# sourceMappingURL=index.d.ts.map
240
+ export { type AccessLogOptions, type AppServer, type AppServerEntry, type AppServerEnv, type BodyLimitOptions, type BuildIdOptions, type ByteRange, type CdnPage, type ContentSecurityPolicyOptions, type CreateEntryOptions, type CreateServerOptions, type DefaultPluginsOptions, type EventStreamOptions, type EventStreamSink, type FetchHandler, type FileInfo, type FrameworkRuntime, type HeaderHook, type HeaderHookOptions, type HealthOptions, type HostRuntime, type InferOutput, type Lifecycle, type Listener, type ListenerBindings, type ListenerStartOptions, type LogLevel, type LogLine, type LogOptions, type LogSink, type Mode, type NoindexOptions, type Plugin, type PrerenderedOptions, type RedirectRule, type RedirectsOptions, type RequestContext, type RequestIdOptions, type RequestLogger, type RequestScope, type RequestStore, ResponseEdge, type ResponseHeaders, type RuntimeEnv, type RuntimeEnvOptions, type SecurityHeaderValues, type SecurityHeadersOptions, type SentResponse, type ServerBindings, type ServerSentEvent, type SetupInfo, type StandardSchemaV1, type StartedListener, type StaticFiles, type StaticPage, type TrailingSlash, type TrailingSlashOptions, accessLog, assets, buildId, contentSecurityPolicy, createEntry, createServer, defaultPlugins, health, noindex, prerendered, redirects, requestId, runtimeEnv, securityHeaders, trailingSlash };
package/dist/index.js CHANGED
@@ -1,19 +1,35 @@
1
- import { i as jsonSink } from "./log-DQAS5gGT.js";
2
- import { r as requestContext, t as logger } from "./request-context-Bxdbk5P1.js";
3
- import { a as replaceResponse, o as withHeaderHook, s as writableHeaders } from "./header-hook-Vzw9J9BY.js";
4
- import { r as buildId, s as optionPlugin } from "./build-id-B0448vZH.js";
5
- import { t as ResponseEdge } from "./response-edge-CU8ZvL_F.js";
6
- import { _ as assets, a as streamingCompress, b as prefersMarkdown, c as securityHeaders, d as noindex, f as health, g as accessLog, h as bodyLimit, l as redirects, m as shutdownSignal, n as defaultPlugins, o as requestId, s as contentSecurityPolicy, t as createServer, u as privateDocuments, v as prerendered, y as trailingSlash } from "./create-server-Bp1yILQk.js";
7
- import { t as createEntry } from "./entry-BoxCqc6w.js";
1
+ import { _ as assets, b as prefersMarkdown, c as requestId, d as redirects, f as privateDocuments, g as accessLog, h as bodyLimit, l as contentSecurityPolicy, m as health, n as defaultPlugins, o as shutdownSignal, p as noindex, s as streamingCompress, t as createServer, u as securityHeaders, v as prerendered, y as trailingSlash } from "./create-server-DVTZun6D.js";
2
+ import { t as createEntry } from "./entry-CMhX3yf8.js";
3
+ import { c as withHeaderHook, l as writableHeaders, o as replaceResponse } from "./header-hook-JfqaTt34.js";
4
+ import { i as jsonSink } from "./log-DfC9D5_T.js";
5
+ import { l as optionPlugin, r as buildId } from "./build-id-CwMbED1n.js";
6
+ import { o as rewritesHtmlWithEtagPart } from "./static-files-BdTPam5b.js";
7
+ import { a as requestContext, n as logger } from "./request-context-Cslbrscf.js";
8
+ import { t as ResponseEdge } from "./response-edge-Ow5Pi5qF.js";
8
9
 
9
10
  // src/core/event-stream.ts
11
+ /** Why: `setInterval` turns a longer delay, and a delay under 1, into 1 ms. */
12
+ const MAX_TIMER_MS = 2147483647;
13
+ /** The unread bytes at which `send` makes the producer wait. */
14
+ const HIGH_WATER_BYTES = 65536;
15
+ /**
16
+ * The unread bytes at which the stream stops. Why a limit: a producer that
17
+ * does not await `send` would keep each event for a client that does not
18
+ * read in memory. A producer that awaits `send` never gets near it.
19
+ */
20
+ const MAX_UNREAD_BYTES = 1048576;
21
+ /** What `send` gives when the stream has room. Why one promise: a send with room allocates nothing. */
22
+ const ROOM = Promise.resolve();
23
+ /** The line of the field `name` of an event, or no text when the event does not have the field. */
24
+ function fieldLine(name, value) {
25
+ if (value == null) return "";
26
+ if (/[\r\n]/u.test(value)) throw new TypeError("An event's `event` and `id` cannot contain a line break.");
27
+ return `${name}: ${value}\n`;
28
+ }
10
29
  function formatEvent({ data, event, id }) {
11
- if (/[\r\n]/u.test(`${event ?? ""}${id ?? ""}`)) throw new TypeError("An event's `event` and `id` cannot contain a line break.");
12
- return `${[
13
- ...event == null ? [] : [`event: ${event}`],
14
- ...id == null ? [] : [`id: ${id}`],
15
- ...data.split(/\r\n|\r|\n/u).map((line) => `data: ${line}`)
16
- ].join("\n")}\n\n`;
30
+ if (typeof data !== "string") throw new TypeError(`An event's \`data\` must be a string, not ${typeof data}.`);
31
+ const lines = data.includes("\n") || data.includes("\r") ? data.replaceAll(/\r\n|\r|\n/gu, "\ndata: ") : data;
32
+ return `${fieldLine("event", event)}${fieldLine("id", id)}data: ${lines}\n\n`;
17
33
  }
18
34
  /**
19
35
  * A `text/event-stream` response that stays correct for its whole life: it
@@ -21,74 +37,109 @@ function formatEvent({ data, event, id }) {
21
37
  * closes at server shutdown so the drain does not wait for the deadline. The
22
38
  * stream closes when `produce` resolves.
23
39
  *
40
+ * Await `send`: it waits while the client has 64 KiB or more of events that
41
+ * it has not read. When the unread events pass 1 MiB, the stream stops: the
42
+ * response fails, and `signal` aborts.
43
+ *
24
44
  * @example
25
45
  * export async function loader({ request }: Route.LoaderArgs) {
26
- * return eventStream({ signal: request.signal }, async ({ send, signal }) => {
27
- * for await (const update of watchUpdates({ signal })) {
28
- * send({ event: "update", data: JSON.stringify(update) });
29
- * }
30
- * });
46
+ * return eventStream(
47
+ * async ({ send, signal }) => {
48
+ * for await (const update of watchUpdates({ signal })) {
49
+ * await send({ event: "update", data: JSON.stringify(update) });
50
+ * }
51
+ * },
52
+ * { signal: request.signal },
53
+ * );
31
54
  * }
32
55
  */
33
- function eventStream({ signal, heartbeatMs = 15e3, headers }, produce) {
56
+ function eventStream(produce, { signal, heartbeatMs = 15e3, headers } = {}) {
57
+ if (!(heartbeatMs >= 1 && heartbeatMs <= MAX_TIMER_MS)) throw new RangeError(`eventStream needs a heartbeatMs from 1 to ${MAX_TIMER_MS}, not ${heartbeatMs}.`);
34
58
  const encoder = new TextEncoder();
59
+ const upstream = AbortSignal.any(signal == null ? [shutdownSignal()] : [shutdownSignal(), signal]);
35
60
  const stopped = new AbortController();
36
- const stopSignal = AbortSignal.any([
37
- stopped.signal,
38
- shutdownSignal(),
39
- ...signal == null ? [] : [signal]
40
- ]);
41
61
  let heartbeat;
42
- let closed = false;
62
+ /** The controller of the body, until the stream ends. */
63
+ let open;
64
+ /** What each `send` that waits gives, and the function that resolves it. */
65
+ let room;
66
+ /** Ends the stream. It gives the controller to the first call only, to close or fail the body. */
67
+ function end() {
68
+ const controller = open;
69
+ open = void 0;
70
+ clearInterval(heartbeat);
71
+ upstream.removeEventListener("abort", stop);
72
+ release();
73
+ return controller;
74
+ }
75
+ function release() {
76
+ room?.resolve();
77
+ room = void 0;
78
+ }
79
+ function close() {
80
+ end()?.close();
81
+ }
82
+ function stop() {
83
+ close();
84
+ stopped.abort(upstream.reason);
85
+ }
86
+ function send(event) {
87
+ const controller = open;
88
+ if (controller == null) return ROOM;
89
+ controller.enqueue(encoder.encode(formatEvent(event)));
90
+ const unread = HIGH_WATER_BYTES - (controller.desiredSize ?? 0);
91
+ if (unread < HIGH_WATER_BYTES) return ROOM;
92
+ if (unread > MAX_UNREAD_BYTES) {
93
+ const error = /* @__PURE__ */ new Error(`eventStream stopped: the client did not read ${unread} bytes of events. Await send().`);
94
+ end()?.error(error);
95
+ stopped.abort(error);
96
+ return ROOM;
97
+ }
98
+ room ??= Promise.withResolvers();
99
+ return room.promise;
100
+ }
43
101
  const body = new ReadableStream({
44
102
  start(controller) {
45
- const close = () => {
46
- if (closed) return;
47
- closed = true;
48
- clearInterval(heartbeat);
49
- stopSignal.removeEventListener("abort", close);
50
- controller.close();
51
- };
52
- const write = (text) => {
53
- if (!closed) controller.enqueue(encoder.encode(text));
54
- };
55
- heartbeat = setInterval(() => {
56
- write(": ping\n\n");
57
- }, heartbeatMs);
58
- stopSignal.addEventListener("abort", close, { once: true });
59
- if (stopSignal.aborted) {
60
- close();
61
- return;
62
- }
63
- Promise.resolve().then(async () => produce({
64
- send: (event) => {
65
- write(formatEvent(event));
66
- },
67
- signal: stopSignal
68
- })).then(close, (error) => {
69
- closed = true;
70
- clearInterval(heartbeat);
71
- stopSignal.removeEventListener("abort", close);
72
- controller.error(error);
73
- });
103
+ open = controller;
74
104
  },
105
+ pull: release,
75
106
  cancel() {
76
- closed = true;
77
- clearInterval(heartbeat);
107
+ end();
78
108
  stopped.abort();
79
109
  }
110
+ }, {
111
+ highWaterMark: HIGH_WATER_BYTES,
112
+ size: (chunk) => chunk.byteLength
80
113
  });
114
+ if (upstream.aborted) close();
115
+ else {
116
+ heartbeat = setInterval(() => {
117
+ if ((open?.desiredSize ?? 0) > 0) open?.enqueue(encoder.encode(": ping\n\n"));
118
+ }, heartbeatMs);
119
+ upstream.addEventListener("abort", stop);
120
+ Promise.resolve().then(async () => produce({
121
+ send,
122
+ signal: stopped.signal
123
+ })).then(close, (error) => {
124
+ end()?.error(error);
125
+ });
126
+ }
81
127
  const responseHeaders = new Headers(headers);
82
128
  responseHeaders.set("Content-Type", "text/event-stream; charset=utf-8");
83
- responseHeaders.set("Cache-Control", "no-cache");
129
+ if (!responseHeaders.has("Cache-Control")) responseHeaders.set("Cache-Control", "no-cache");
84
130
  return new Response(body, { headers: responseHeaders });
85
131
  }
86
132
 
87
133
  // src/core/plugins/runtime-env.ts
88
134
  /** The `id` of the JSON `<script>` that carries the public values into each HTML document. */
89
135
  const PUBLIC_ENV_SCRIPT_ID = "app-server-public-env";
90
- /** Stops the search for `</head>` after this many characters, so a page with none still streams. */
136
+ /** The search for `</head>` stops after this many bytes, so the rest of a long body costs no search. */
91
137
  const HEAD_SEARCH_LIMIT = 1048576;
138
+ const encoder = new TextEncoder();
139
+ /** `</head>` in lowercase and in uppercase. Why both: HTML reads a tag name in each letter case. */
140
+ const HEAD_END = encoder.encode("</head>");
141
+ const HEAD_END_UPPER = encoder.encode("</HEAD>");
142
+ const NO_BYTES = /* @__PURE__ */ new Uint8Array(0);
92
143
  function formatIssue(issue) {
93
144
  const path = (issue.path ?? []).map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".");
94
145
  return ` ${path === "" ? "(root)" : path}: ${issue.message}`;
@@ -98,35 +149,111 @@ function publicEnvScript(values) {
98
149
  const json = JSON.stringify(values).replaceAll("<", String.raw`\u003c`);
99
150
  return `<script id="${PUBLIC_ENV_SCRIPT_ID}" type="application/json">${json}<\/script>`;
100
151
  }
101
- /** Inserts `html` before the first `</head>` of a streamed document. The rest streams as is. */
152
+ /** A 32-bit word with 1 in each of its four bytes. */
153
+ const EACH_BYTE = 16843009;
154
+ /**
155
+ * Whether one of the four bytes of `word` is `<`, which is byte 60. Why bit
156
+ * operations: with two of these tests for each 8 bytes, the search of a head
157
+ * with 30 KB of inline CSS takes 5.5 µs. A loop that tests each byte takes
158
+ * 26 µs (Node.js 26, Apple M3 Max).
159
+ */
160
+ function hasLessThan(word) {
161
+ const zeroed = word ^ 60 * EACH_BYTE;
162
+ return (zeroed - EACH_BYTE & ~zeroed & 128 * EACH_BYTE) !== 0;
163
+ }
164
+ /**
165
+ * Whether `</head>` starts at `start` in `bytes`. It is also `true` when
166
+ * `bytes` ends inside the tag, because the next chunk can have the rest.
167
+ */
168
+ function startsHeadEnd(bytes, start) {
169
+ const length = Math.min(HEAD_END.length, bytes.length - start);
170
+ for (let offset = 0; offset < length; offset += 1) {
171
+ const byte = bytes[start + offset];
172
+ if (byte !== HEAD_END[offset] && byte !== HEAD_END_UPPER[offset]) return false;
173
+ }
174
+ return true;
175
+ }
176
+ /**
177
+ * The index of the first `</head>` in `bytes`. With none, it gives the index
178
+ * of a `</head>` that the end of `bytes` cuts, else `bytes.length`.
179
+ */
180
+ function headEndIndex(bytes) {
181
+ const { length } = bytes;
182
+ const words = new DataView(bytes.buffer, bytes.byteOffset, length);
183
+ const lastStep = length - 8;
184
+ let index = 0;
185
+ while (index < length) {
186
+ while (index <= lastStep && !hasLessThan(words.getUint32(index)) && !hasLessThan(words.getUint32(index + 4))) index += 8;
187
+ for (const end = Math.min(index + 8, length); index < end; index += 1) if (startsHeadEnd(bytes, index)) return index;
188
+ }
189
+ return length;
190
+ }
191
+ /** The bytes of `parts` in one new array. */
192
+ function joined(...parts) {
193
+ let size = 0;
194
+ for (const part of parts) size += part.length;
195
+ const bytes = new Uint8Array(size);
196
+ let offset = 0;
197
+ for (const part of parts) {
198
+ bytes.set(part, offset);
199
+ offset += part.length;
200
+ }
201
+ return bytes;
202
+ }
203
+ /**
204
+ * `chunk` as a `Uint8Array` of the same bytes. Why: Bun also takes a body
205
+ * chunk that is an `ArrayBuffer` or another view of one, and the search
206
+ * reads the bytes of a `Uint8Array`.
207
+ */
208
+ function asBytes(chunk) {
209
+ if (chunk instanceof Uint8Array) return chunk;
210
+ if (ArrayBuffer.isView(chunk)) return new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
211
+ if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk);
212
+ throw new TypeError("A response body gave a chunk that is not bytes.");
213
+ }
214
+ /**
215
+ * `body` with `html` before its first `</head>`, in any letter case. It
216
+ * changes no other byte, so a document that is not UTF-8 stays whole. It
217
+ * holds only the end of a chunk that can start `</head>`, 6 bytes at most,
218
+ * so each chunk goes out when it comes.
219
+ */
102
220
  function injectBeforeHeadEnd(body, html) {
103
- const decoder = new TextDecoder();
104
- const encoder = new TextEncoder();
105
221
  const reader = body.getReader();
106
- let pending = "";
107
- /** The text to send for `text`, or `undefined` while the search for `</head>` goes on. */
108
- const transform = (text) => {
109
- if (pending == null) return text;
110
- pending += text;
111
- const index = pending.search(/<\/head>/iu);
112
- if (index === -1 && pending.length <= HEAD_SEARCH_LIMIT) return;
113
- const out = index === -1 ? pending : `${pending.slice(0, index)}${html}${pending.slice(index)}`;
114
- pending = void 0;
115
- return out;
222
+ let searching = true;
223
+ let searched = 0;
224
+ /** The end of the chunks so far, when the next chunk can complete a `</head>` that starts there. */
225
+ let held = NO_BYTES;
226
+ /** The bytes to send for `chunk` while the search goes on. */
227
+ const search = (chunk) => {
228
+ const bytes = held.length === 0 ? chunk : joined(held, chunk);
229
+ const index = headEndIndex(bytes);
230
+ searched += chunk.length;
231
+ if (index + HEAD_END.length <= bytes.length) {
232
+ searching = false;
233
+ held = NO_BYTES;
234
+ return joined(bytes.subarray(0, index), html, bytes.subarray(index));
235
+ }
236
+ searching = searched <= HEAD_SEARCH_LIMIT;
237
+ held = searching ? joined(bytes.subarray(index)) : NO_BYTES;
238
+ return bytes.subarray(0, bytes.length - held.length);
116
239
  };
117
240
  return new ReadableStream({
118
241
  async pull(controller) {
119
242
  for (;;) {
120
243
  const { done, value } = await reader.read();
121
244
  if (done) {
122
- const rest = `${pending ?? ""}${decoder.decode()}`;
123
- if (rest !== "") controller.enqueue(encoder.encode(rest));
245
+ if (held.length > 0) controller.enqueue(held);
124
246
  controller.close();
125
247
  return;
126
248
  }
127
- const out = transform(decoder.decode(value, { stream: true }));
128
- if (out != null) {
129
- controller.enqueue(encoder.encode(out));
249
+ const chunk = asBytes(value);
250
+ if (!searching) {
251
+ controller.enqueue(chunk);
252
+ return;
253
+ }
254
+ const bytes = search(chunk);
255
+ if (bytes.length > 0) {
256
+ controller.enqueue(bytes);
130
257
  return;
131
258
  }
132
259
  }
@@ -156,6 +283,7 @@ function injectBeforeHeadEnd(body, html) {
156
283
  * const publicEnv = JSON.parse(document.getElementById("app-server-public-env")?.textContent ?? "{}");
157
284
  */
158
285
  function runtimeEnv(schema, { source = process.env, publicPrefix = "PUBLIC_" } = {}) {
286
+ if (publicPrefix === "") throw new RangeError("runtimeEnv needs a publicPrefix of one character or more, not \"\". With \"\", each value, such as a secret, goes into each HTML document.");
159
287
  let parsed;
160
288
  const parse = () => {
161
289
  if (parsed != null) return parsed;
@@ -164,10 +292,14 @@ function runtimeEnv(schema, { source = process.env, publicPrefix = "PUBLIC_" } =
164
292
  if (result.issues != null) throw new Error(`The environment is not valid:\n${result.issues.map(formatIssue).join("\n")}`);
165
293
  const values = result.value;
166
294
  const publicValues = typeof values === "object" && values != null ? Object.fromEntries(Object.entries(values).filter(([name]) => name.startsWith(publicPrefix))) : {};
295
+ const html = Object.keys(publicValues).length > 0 ? publicEnvScript(publicValues) : void 0;
167
296
  parsed = {
168
297
  values,
169
298
  publicValues,
170
- script: Object.keys(publicValues).length > 0 ? publicEnvScript(publicValues) : void 0
299
+ script: html == null ? void 0 : {
300
+ html,
301
+ bytes: encoder.encode(html)
302
+ }
171
303
  };
172
304
  return parsed;
173
305
  };
@@ -182,20 +314,20 @@ function runtimeEnv(schema, { source = process.env, publicPrefix = "PUBLIC_" } =
182
314
  setup: () => {
183
315
  parse();
184
316
  },
185
- etagPart: () => parse().script,
317
+ etagPart: () => parse().script?.html,
186
318
  middleware: async (context, next) => {
187
319
  const { script } = parse();
188
- if (script != null) context.set("rewritesHtml", true);
320
+ if (script != null) rewritesHtmlWithEtagPart(context);
189
321
  await next();
322
+ if (script == null) return;
190
323
  const response = context.res;
191
- if (script == null || response.headers.has("Content-Encoding") || response.headers.has("Content-Range") || !(response.headers.get("Content-Type")?.startsWith("text/html") ?? false)) return;
192
- if (response.body != null) replaceResponse(context, new Response(injectBeforeHeadEnd(response.body, script), response));
324
+ if (!(response.headers.get("Content-Type")?.startsWith("text/html") ?? false) || response.headers.has("Content-Encoding") || response.headers.has("Content-Range")) return;
325
+ if (response.body != null) replaceResponse(context, new Response(injectBeforeHeadEnd(response.body, script.bytes), response));
193
326
  const headers = writableHeaders(context);
194
327
  headers.delete("Content-Length");
195
- headers.delete("ETag");
328
+ if (context.get("staticDocument") == null) headers.delete("ETag");
196
329
  }
197
330
  });
198
331
  }
199
332
 
200
- export { PUBLIC_ENV_SCRIPT_ID, ResponseEdge, accessLog, assets, bodyLimit, buildId, contentSecurityPolicy, createEntry, createServer, defaultPlugins, eventStream, health, jsonSink, logger, noindex, prefersMarkdown, prerendered, privateDocuments, redirects, requestContext, requestId, runtimeEnv, securityHeaders, shutdownSignal, streamingCompress, trailingSlash, withHeaderHook };
201
- //# sourceMappingURL=index.js.map
333
+ export { ResponseEdge, accessLog, assets, bodyLimit, buildId, contentSecurityPolicy, createEntry, createServer, defaultPlugins, eventStream, health, jsonSink, logger, noindex, prefersMarkdown, prerendered, privateDocuments, redirects, requestContext, requestId, runtimeEnv, securityHeaders, shutdownSignal, streamingCompress, trailingSlash, withHeaderHook };
@@ -11,5 +11,4 @@ function listenerUrl(hostname, port) {
11
11
  return hostname.includes(":") ? `http://[${hostname}]:${port}/` : `http://${hostname}:${port}/`;
12
12
  }
13
13
 
14
- export { listenerUrl as t };
15
- //# sourceMappingURL=listen-options-7TaXjyrk.js.map
14
+ export { listenerUrl as t };