@ngrok/app-server 0.2.0 → 0.3.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.
Files changed (103) hide show
  1. package/README.md +610 -76
  2. package/dist/build-id-C6sYO9Yp.js +126 -0
  3. package/dist/build-id-C6sYO9Yp.js.map +1 -0
  4. package/dist/{build-manifest-8NfD1wnO.js → build-manifest-UDNk81Ce.js} +24 -6
  5. package/dist/build-manifest-UDNk81Ce.js.map +1 -0
  6. package/dist/cli.js +45 -25
  7. package/dist/cli.js.map +1 -1
  8. package/dist/client.d.ts +141 -0
  9. package/dist/client.js +326 -0
  10. package/dist/client.js.map +1 -0
  11. package/dist/compression-7_gToa8R.js +97 -0
  12. package/dist/compression-7_gToa8R.js.map +1 -0
  13. package/dist/create-server-iE1-s6Bi.js +1409 -0
  14. package/dist/create-server-iE1-s6Bi.js.map +1 -0
  15. package/dist/{deno-DNRgzHrk.js → deno-aqhikNMG.js} +2 -2
  16. package/dist/deno-aqhikNMG.js.map +1 -0
  17. package/dist/entry-DZ3qo7qF.js +116 -0
  18. package/dist/entry-DZ3qo7qF.js.map +1 -0
  19. package/dist/entry-DmJEqVfd.d.ts +622 -0
  20. package/dist/gzip-Doi4wqjX.js +294 -0
  21. package/dist/gzip-Doi4wqjX.js.map +1 -0
  22. package/dist/header-hook-Vzw9J9BY.js +159 -0
  23. package/dist/header-hook-Vzw9J9BY.js.map +1 -0
  24. package/dist/{index-oSE-tYRW.d.ts → index-Bo5G9LuQ.d.ts} +53 -14
  25. package/dist/index.d.ts +99 -269
  26. package/dist/index.js +47 -59
  27. package/dist/index.js.map +1 -1
  28. package/dist/listen-options-7TaXjyrk.js.map +1 -1
  29. package/dist/{load-entry-C03qqmhr.js → load-entry-AfYS_zS9.js} +8 -4
  30. package/dist/{load-entry-C03qqmhr.js.map → load-entry-AfYS_zS9.js.map} +1 -1
  31. package/dist/log-BP6xXXZl.js +122 -0
  32. package/dist/log-BP6xXXZl.js.map +1 -0
  33. package/dist/node-BFH82eeL.js +333 -0
  34. package/dist/node-BFH82eeL.js.map +1 -0
  35. package/dist/node-tBVQPjQv.js +41 -0
  36. package/dist/node-tBVQPjQv.js.map +1 -0
  37. package/dist/node-vite.d.ts +5 -4
  38. package/dist/node-vite.js +2 -17
  39. package/dist/node.d.ts +23 -4
  40. package/dist/node.js +2 -2
  41. package/dist/react-router-vite.d.ts +4 -3
  42. package/dist/react-router-vite.js +2 -20
  43. package/dist/react-router.d.ts +1 -1
  44. package/dist/react-router.js +8 -7
  45. package/dist/react-router.js.map +1 -1
  46. package/dist/request-context-BtQ87VYb.js +40 -0
  47. package/dist/request-context-BtQ87VYb.js.map +1 -0
  48. package/dist/response-edge-Bc1-C_Cx.js +327 -0
  49. package/dist/response-edge-Bc1-C_Cx.js.map +1 -0
  50. package/dist/response-writer-B7FoJjEE.js +289 -0
  51. package/dist/response-writer-B7FoJjEE.js.map +1 -0
  52. package/dist/script-hashes-hqUk6kG7.js +53 -0
  53. package/dist/script-hashes-hqUk6kG7.js.map +1 -0
  54. package/dist/{serve-Cleo8RMO.js → serve-CDNgThjk.js} +3 -3
  55. package/dist/{serve-Cleo8RMO.js.map → serve-CDNgThjk.js.map} +1 -1
  56. package/dist/{start-CINALHxy.js → start-TLIprD74.js} +14 -19
  57. package/dist/start-TLIprD74.js.map +1 -0
  58. package/dist/static-files-Beju9riB.js +302 -0
  59. package/dist/static-files-Beju9riB.js.map +1 -0
  60. package/dist/tanstack-start-vite.d.ts +6 -5
  61. package/dist/tanstack-start-vite.js +2 -23
  62. package/dist/tanstack-start.d.ts +19 -2
  63. package/dist/tanstack-start.js +5 -14
  64. package/dist/tanstack-start.js.map +1 -1
  65. package/dist/{tcp-C-9AmFuM.js → tcp-Dd1Mt6sN.js} +6 -5
  66. package/dist/{tcp-C-9AmFuM.js.map → tcp-Dd1Mt6sN.js.map} +1 -1
  67. package/dist/trailing-slash-DX7NB88H.d.ts +36 -0
  68. package/dist/types-DLYxYS6M.d.ts +392 -0
  69. package/dist/vercel-vite.d.ts +35 -0
  70. package/dist/vercel-vite.js +142 -0
  71. package/dist/vercel-vite.js.map +1 -0
  72. package/dist/vercel.d.ts +35 -0
  73. package/dist/vercel.js +89 -0
  74. package/dist/vercel.js.map +1 -0
  75. package/dist/vite-B-GfswoH.js +22 -0
  76. package/dist/vite-B-GfswoH.js.map +1 -0
  77. package/dist/vite-D4hfj3ph.js +19 -0
  78. package/dist/vite-D4hfj3ph.js.map +1 -0
  79. package/dist/vite-DyrhyKEr.js +25 -0
  80. package/dist/vite-DyrhyKEr.js.map +1 -0
  81. package/dist/vite-iioAoxSt.js +752 -0
  82. package/dist/vite-iioAoxSt.js.map +1 -0
  83. package/dist/vite.d.ts +2 -2
  84. package/dist/vite.js +1 -1
  85. package/package.json +24 -4
  86. package/dist/build-manifest-8NfD1wnO.js.map +0 -1
  87. package/dist/deno-DNRgzHrk.js.map +0 -1
  88. package/dist/entry-BkdUub2S.js +0 -638
  89. package/dist/entry-BkdUub2S.js.map +0 -1
  90. package/dist/log-CsjaKM8U.js +0 -59
  91. package/dist/log-CsjaKM8U.js.map +0 -1
  92. package/dist/node-CG7qXuWZ.js +0 -58
  93. package/dist/node-CG7qXuWZ.js.map +0 -1
  94. package/dist/node-YWPGmzAk.js +0 -215
  95. package/dist/node-YWPGmzAk.js.map +0 -1
  96. package/dist/node-ZMowKZDB.js +0 -3
  97. package/dist/node-vite.js.map +0 -1
  98. package/dist/react-router-vite.js.map +0 -1
  99. package/dist/start-CINALHxy.js.map +0 -1
  100. package/dist/tanstack-start-vite.js.map +0 -1
  101. package/dist/types-BfCkS7kQ.d.ts +0 -203
  102. package/dist/vite-mYZ2Y69u.js +0 -144
  103. package/dist/vite-mYZ2Y69u.js.map +0 -1
package/dist/index.d.ts CHANGED
@@ -1,194 +1,7 @@
1
- import { _ as ServerBindings, a as FrameworkRuntimeFactory, b as StaticFiles, c as Listener, d as LogSink, f as Mode, g as RequestStore, h as RequestLogger, i as FrameworkRuntime, l as ListenerBindings, m as RequestContext, n as FetchHandler, o as HostRuntime, p as Plugin, r as FileInfo, s as Lifecycle, t as AppServerEnv, u as LogLevel, v as SetupInfo, y as StartedListener } from "./types-BfCkS7kQ.js";
2
- import { Context, Hono, MiddlewareHandler } from "hono";
3
- /** Options for {@link accessLog}. */
4
- type AccessLogOptions = {
5
- /**
6
- * Replace each query value with `REDACTED`, so a single-use code in a URL
7
- * never reaches a log.
8
- * @default true
9
- */
10
- redactQuery?: boolean;
11
- };
12
- /**
13
- * One log line per request, static hits included, with Datadog standard
14
- * attribute names. The line goes out when the body ends or the client
15
- * disconnects, so a streamed response logs its full duration and size.
16
- *
17
- * @example
18
- * createServer({ plugins: [requestId(), accessLog({ redactQuery: false })] });
19
- * // {"level":"info","message":"request","http.status_code":200,"network.bytes_written":5120,"duration":1830000,...}
20
- */
21
- export declare function accessLog({ redactQuery }?: AccessLogOptions): Plugin;
22
- /** Options for {@link requestId}. */
23
- type RequestIdOptions = {
24
- /** @default "X-Request-Id" */
25
- headerName?: string;
26
- };
27
- /**
28
- * Gives each request an ID: a valid incoming header (up to 255 word
29
- * characters, `-`, and `=`), else a new UUID. The ID goes on the response, on
30
- * every log line, and into the framework's context.
31
- *
32
- * @example
33
- * const app = createServer({ plugins: [requestId()] });
34
- * const response = await app.request("/", { headers: { "X-Request-Id": "abc-123" } });
35
- * response.headers.get("X-Request-Id"); // => "abc-123"
36
- */
37
- export declare function requestId({ headerName }?: RequestIdOptions): Plugin;
38
- /**
39
- * Serves the hashed files under `/assets/` with a one-year immutable cache.
40
- * A missing asset gets a plain 404, not a rendered page. In development,
41
- * the dev server serves the source modules, the HMR client, and the CSS here
42
- * instead.
43
- *
44
- * @example
45
- * createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });
46
- */
47
- export declare function assets(): Plugin;
48
- /** Options for {@link prerendered}. */
49
- type PrerenderedOptions = {
50
- /**
51
- * Extra headers for a served file, by its URL path. They replace the
52
- * headers captured at build time.
53
- */
54
- headers?: (path: string, context: Context<AppServerEnv>) => Readonly<Record<string, string>> | undefined;
55
- /**
56
- * Maps a request path to the URL path of the file to serve, for content
57
- * negotiation. Return the path unchanged to serve the usual file. The
58
- * returned path follows the rules of a request path: one URL for each
59
- * file, no dotfiles, and nothing outside the client build. When the
60
- * answer depends on a request header, add a `Vary` for it in a plugin.
61
- */
62
- rewrite?: (path: string, context: Context<AppServerEnv>) => string;
63
- };
64
- /**
65
- * Serves the client build: prerendered pages at their own URL with a 200 and
66
- * no trailing-slash redirect, plus every other file in it. Each response gets
67
- * the headers its loader sent at build time (the `appServer` Vite plugin
68
- * captures them), an ETag, and a 304 for a matching `If-None-Match`. A path
69
- * with no file goes on to the framework. Off in development.
70
- *
71
- * At startup, it warns about each prerendered path that has no file.
72
- *
73
- * @example
74
- * prerendered({
75
- * headers: (path) => (path.startsWith("/api/") ? { "Access-Control-Allow-Origin": "*" } : undefined),
76
- * });
77
- */
78
- export declare function prerendered(options?: PrerenderedOptions): Plugin;
79
- /** A Hono app from {@link createServer}. Add routes to it before you export it. */
80
- type AppServer = Hono<AppServerEnv>;
81
- /** A server that listens. */
82
- type RunningServer = {
83
- /** The URL of each listener. */
84
- urls: readonly string[];
85
- /**
86
- * Aborts `shutdownSignal()`, then runs each plugin's `onShutdown` while the
87
- * listeners stop and drain open requests. Both stop at the deadline.
88
- */
89
- shutdown: () => Promise<void>;
90
- };
91
- /** Options for {@link defaultPlugins}. */
92
- type DefaultPluginsOptions = {
93
- requestId?: RequestIdOptions;
94
- accessLog?: AccessLogOptions;
95
- prerendered?: PrerenderedOptions;
96
- /**
97
- * Plugins that go after compression and before the static stages, so they
98
- * see every response, prerendered pages included. `runtimeEnv` and
99
- * `buildId` go here.
100
- */
101
- beforeStatic?: readonly Plugin[];
102
- };
103
- /**
104
- * The default pipeline, in order: `requestId`, `accessLog`,
105
- * `streamingCompress`, the `beforeStatic` plugins, `assets`, and
106
- * `prerendered`. It is a plain array, so an app can filter it or splice into it.
107
- *
108
- * @example
109
- * createServer({ plugins: defaultPlugins({ accessLog: { redactQuery: false }, beforeStatic: [env] }) });
110
- */
111
- export declare function defaultPlugins(options?: DefaultPluginsOptions): Plugin[];
112
- /** Options for {@link createServer}. */
113
- type CreateServerOptions = {
114
- /** @default defaultPlugins() */
115
- plugins?: readonly Plugin[];
116
- /** @default jsonSink() */
117
- logger?: LogSink;
118
- /** @default the host's listeners, such as `[tcp()]` on the node host */
119
- listeners?: readonly Listener[];
120
- /**
121
- * Read the request scheme from `X-Forwarded-Proto`. Set it only behind a
122
- * proxy that overwrites that header, else a client can spoof it.
123
- * @default false
124
- */
125
- trustForwardedProto?: boolean;
126
- /**
127
- * How long open requests get to finish after a stop signal.
128
- * @default 10000
129
- */
130
- shutdownDeadlineMs?: number;
131
- };
132
- /**
133
- * Builds an app server: a Hono app that runs the plugins in list order, then
134
- * the app's own routes, then the framework. It does not listen; the
135
- * `app-server` CLI starts it.
136
- *
137
- * @example
138
- * // server.ts
139
- * const app = createServer({ logger: slogSink, plugins: defaultPlugins({ beforeStatic: [env] }) });
140
- * app.get("/livez", (c) => c.text("ok"));
141
- * export default app;
142
- */
143
- export declare function createServer({ plugins, logger, listeners, trustForwardedProto, shutdownDeadlineMs }?: CreateServerOptions): AppServer;
144
- /** The version of the contract between the CLI and the `appServer` export of a build. */
145
- declare const ENTRY_PROTOCOL = 2;
146
- /**
147
- * What a server build exports as `appServer`. The CLI calls it, so the copy
148
- * of this package in the build runs the server, and the CLI's copy runs
149
- * nothing.
150
- */
151
- type AppServerEntry = {
152
- /** The CLI refuses an entry with another version. */
153
- protocol: typeof ENTRY_PROTOCOL;
154
- /** The app. Two entries with the same app share its plugins. */
155
- app: AppServer;
156
- /**
157
- * Production: runs each plugin's `setup` and listens. When the host's
158
- * lifecycle stops, such as on `SIGTERM`, it shuts down.
159
- */
160
- start: () => Promise<void>;
161
- /** Development: answers one request with the dev server inside the pipeline. */
162
- fetchDev: (request: Request, bindings: ListenerBindings, devServer: MiddlewareHandler<AppServerEnv>) => Promise<Response>;
163
- /** Runs each plugin's `onShutdown` once, up to the shutdown deadline. */
164
- stopPlugins: () => Promise<void>;
165
- /** Aborts `shutdownSignal()` of this copy of the package. */
166
- abortShutdownSignal: () => void;
167
- };
168
- /** Options for {@link createEntry}. */
169
- type CreateEntryOptions = {
170
- /** The app from `createServer`. */
171
- app: AppServer;
172
- /** The run side of the host adapter, such as `host` from `@ngrok/app-server/node`. */
173
- host: HostRuntime;
174
- /** Makes the run side of the framework adapter for a mode. */
175
- framework: (mode: Mode) => FrameworkRuntime;
176
- /**
177
- * The client build, as a file path or a `file:` URL. The entry that the
178
- * Vite plugin generates sets it.
179
- * @default the framework's `clientDirectory`
180
- */
181
- clientDirectory?: string;
182
- };
183
- /**
184
- * The `appServer` export of a server build: an app from `createServer`, the
185
- * host, and the framework adapter for each mode. The `appServer` Vite plugin
186
- * generates this export. Call this for a build without the plugin.
187
- *
188
- * @example
189
- * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });
190
- */
191
- export declare function createEntry({ app, host, framework, clientDirectory }: CreateEntryOptions): AppServerEntry;
1
+ import { C as SetupInfo, E as ResponseEdge, S as ServerBindings, T as StaticFiles, _ as RequestContext, a as FrameworkRuntime, b as ResponseHeaders, c as HostRuntime, d as ListenerBindings, f as ListenerStartOptions, g as Plugin, h as Mode, i as FileInfo, l as Lifecycle, m as LogSink, n as ByteRange, o as FrameworkRuntimeFactory, p as LogLevel, r as FetchHandler, s as HeaderHook, t as AppServerEnv, u as Listener, v as RequestLogger, w as StartedListener, x as SentResponse, y as RequestStore } from "./types-DLYxYS6M.js";
2
+ import { A as BuildIdOptions, C as SecurityHeadersOptions, D as redirects, E as RedirectRule, M as AccessLogOptions, N as accessLog, O as HealthOptions, S as SecurityHeaderValues, T as securityHeaders, _ as StandardSchemaV1, a as CreateServerOptions, b as requestId, c as createServer, d as assets, f as prerendered, g as RuntimeEnvOptions, h as RuntimeEnv, i as AppServer, j as buildId, k as health, l as defaultPlugins, m as PUBLIC_ENV_SCRIPT_ID, n as CreateEntryOptions, o as DefaultPluginsOptions, p as InferOutput, r as createEntry, s as RunningServer, t as AppServerEntry, u as PrerenderedOptions, v as runtimeEnv, w as contentSecurityPolicy, x as ContentSecurityPolicyOptions, y as RequestIdOptions } from "./entry-DmJEqVfd.js";
3
+ import { n as TrailingSlashOptions, r as trailingSlash, t as TrailingSlash } from "./trailing-slash-DX7NB88H.js";
4
+ import { Context, Next } from "hono";
192
5
  /** One server-sent event. */
193
6
  type ServerSentEvent = {
194
7
  data: string;
@@ -229,10 +42,29 @@ type EventStreamOptions = {
229
42
  * }
230
43
  */
231
44
  export declare function eventStream({ signal, heartbeatMs, headers }: EventStreamOptions, produce: (sink: EventStreamSink) => void | Promise<void>): Response;
45
+ /**
46
+ * Runs `hook` on the response headers after the later stages. In an app
47
+ * server, the hook changes the head once, where the response leaves, so the
48
+ * response needs no copy. That run comes after the code that each stage runs
49
+ * after its `next()`, so a stage can decide there what its hook does. A hook
50
+ * that throws gives a 500. See {@link HeaderHook} for the order of the hooks
51
+ * and the views that also run them.
52
+ *
53
+ * @example
54
+ * const frameOptions: Plugin = {
55
+ * name: "frame-options",
56
+ * middleware: async (c, next) =>
57
+ * withHeaderHook(c, next, (response) => {
58
+ * response.set("X-Frame-Options", "DENY");
59
+ * }),
60
+ * };
61
+ */
62
+ export declare function withHeaderHook(context: Context<AppServerEnv>, next: Next, hook: HeaderHook): Promise<void>;
232
63
  /**
233
64
  * A log sink that writes one JSON object per line. Each line has `time`,
234
65
  * `level`, `message`, and the flat attributes, which Datadog reads as its
235
- * standard attributes.
66
+ * standard attributes. The default writes the lines of one event-loop turn
67
+ * to stdout at the end of the turn.
236
68
  *
237
69
  * @param write - Where each line goes. Defaults to stdout.
238
70
  *
@@ -241,94 +73,60 @@ export declare function eventStream({ signal, heartbeatMs, headers }: EventStrea
241
73
  * // {"time":"2026-10-28T12:00:00.000Z","level":"info","message":"request","http.status_code":200}
242
74
  */
243
75
  export declare function jsonSink(write?: (line: string) => void): LogSink;
244
- /** Options for {@link buildId}. */
245
- type BuildIdOptions = {
246
- /** @default "X-Build-Id" */
247
- header?: string;
248
- /** The deployed build, such as the image tag. Read it from the runtime env, not the build. */
249
- value: string;
76
+ /** Options for {@link bodyLimit}. */
77
+ type BodyLimitOptions = {
78
+ /** The largest request body, in bytes. */
79
+ maxBytes: number;
250
80
  };
251
81
  /**
252
- * Sets a build ID header on documents and on the framework's data responses,
253
- * such as React Router `.data` files, so a client can see that a deploy
254
- * happened under it.
82
+ * Sends a 413 for a request body that is larger than `maxBytes`. A request
83
+ * whose `Content-Length` is too large gets the 413 before the app reads the
84
+ * body, and a request whose `Content-Length` fits goes on unchanged. A
85
+ * streamed body with no `Content-Length` errors when it passes the limit. When the app reads the body before it answers, the response
86
+ * becomes a 413. When the app streams the body into its response, the
87
+ * response stream errors. A `maxBytes` that is not a whole number of 0 or
88
+ * more stops startup.
89
+ *
90
+ * Why not `hono/body-limit`: it reads a streamed body into memory before the
91
+ * next stage runs, so an upload cannot stream.
255
92
  *
256
93
  * @example
257
- * buildId({ value: env.values.PUBLIC_APP_VERSION });
94
+ * createServer({ plugins: [requestId(), accessLog(), bodyLimit({ maxBytes: 1_048_576 })] });
258
95
  */
259
- export declare function buildId({ header, value }: BuildIdOptions): Plugin;
260
- type StandardIssue = {
261
- readonly message: string;
262
- readonly path?: readonly (PropertyKey | {
263
- readonly key: PropertyKey;
264
- })[] | undefined;
265
- };
266
- type StandardResult<Output> = {
267
- readonly value: Output;
268
- readonly issues?: undefined;
269
- } | {
270
- readonly issues: readonly StandardIssue[];
271
- };
272
- /** A schema that follows the Standard Schema interface, such as a zod object. */
273
- type StandardSchemaV1<Input = unknown, Output = Input> = {
274
- readonly "~standard": {
275
- readonly version: 1;
276
- readonly vendor: string;
277
- readonly validate: (value: unknown) => StandardResult<Output> | Promise<StandardResult<Output>>;
278
- readonly types?: {
279
- readonly input: Input;
280
- readonly output: Output;
281
- } | undefined;
282
- };
283
- };
284
- /** The parsed type of a Standard Schema. */
285
- type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
286
- /** The `id` of the JSON `<script>` that carries the public values into each HTML document. */
287
- export declare const PUBLIC_ENV_SCRIPT_ID = "app-server-public-env";
288
- /** Options for {@link runtimeEnv}. */
289
- type RuntimeEnvOptions = {
290
- /** @default process.env */
291
- source?: Readonly<Record<string, string | undefined>>;
292
- /**
293
- * Values whose names start with this prefix reach the browser.
294
- * @default "PUBLIC_"
295
- */
296
- publicPrefix?: string;
297
- };
298
- /** The plugin that {@link runtimeEnv} returns, with the parsed values. */
299
- type RuntimeEnv<Values> = Plugin & {
300
- /** The parsed values. The first read parses, and a bad value throws. */
301
- readonly values: Values;
302
- /** The parsed values whose names start with the public prefix. */
303
- readonly publicValues: Readonly<Record<string, unknown>>;
304
- };
96
+ export declare function bodyLimit({ maxBytes }: BodyLimitOptions): Plugin;
305
97
  /**
306
- * Validates the environment once, at startup, against a schema. A missing or
307
- * bad value stops the server with a message that names it. The typed values
308
- * are on `.values`.
309
- *
310
- * The values whose names start with `PUBLIC_` go into each HTML document,
311
- * prerendered or rendered, as a JSON `<script id="app-server-public-env">`.
312
- * So one image serves every environment, and a prerendered page never keeps
313
- * the values of the build. Put this plugin before the static stages, so it
314
- * sees the prerendered pages.
98
+ * Sets `X-Robots-Tag: noindex, nofollow` on each response, so a search
99
+ * engine does not index a preview deploy. Turn it on from the environment
100
+ * with the `noindex` option of `defaultPlugins()`, which puts it before the
101
+ * static stages, so it also sees prerendered pages.
315
102
  *
316
103
  * @example
317
- * export const env = runtimeEnv(
318
- * z.object({ PUBLIC_API_URL: z.url(), SESSION_KEY: z.string().min(32) }),
319
- * );
320
- * env.values.SESSION_KEY; // => string
104
+ * defaultPlugins({ noindex: process.env.PREVIEW === "1" });
105
+ */
106
+ export declare function noindex(): Plugin;
107
+ /**
108
+ * Sets `Cache-Control: private, no-cache` on each HTML document and each
109
+ * framework data response, such as a React Router `.data` request, that has
110
+ * no `Cache-Control`. A shared cache then never keeps a page or loader data
111
+ * that the server rendered for one user. A response with its own
112
+ * `Cache-Control` keeps it. A resource route that sends per-user JSON sets
113
+ * its own `Cache-Control`.
321
114
  *
322
- * // In the browser:
323
- * const publicEnv = JSON.parse(document.getElementById("app-server-public-env")?.textContent ?? "{}");
115
+ * Put it after the static stages, so it sees only the responses of the app's
116
+ * routes and the framework. `defaultPlugins()` puts it last.
117
+ *
118
+ * @example
119
+ * createServer({ plugins: [requestId(), accessLog(), assets(), prerendered(), privateDocuments()] });
324
120
  */
325
- export declare function runtimeEnv<Schema extends StandardSchemaV1>(schema: Schema, { source, publicPrefix }?: RuntimeEnvOptions): RuntimeEnv<InferOutput<Schema>>;
121
+ export declare function privateDocuments(): Plugin;
326
122
  /**
327
123
  * Gzips text responses and flushes after each chunk, so a streamed page shell
328
- * or a server-sent event reaches the client at once. `hono/compress` holds a
124
+ * or a server-sent event reaches the client at once. Chunks that the body has
125
+ * queued together are one chunk, up to 16 KiB. `hono/compress` holds a
329
126
  * stream until it ends. Skips a response that is already encoded, a partial
330
- * response, and one marked `no-transform`. It sets `Vary: Accept-Encoding` on
331
- * each response. The host gives the gzip stream. On a host with none, the
127
+ * response, one marked `no-transform`, and one whose `Content-Length` is
128
+ * under 1 KiB. It adds `Accept-Encoding` to the `Vary` of each response that
129
+ * it can gzip. The host gives the gzip stream. On a host with none, the
332
130
  * plugin does nothing.
333
131
  *
334
132
  * @example
@@ -336,7 +134,39 @@ export declare function runtimeEnv<Schema extends StandardSchemaV1>(schema: Sche
336
134
  */
337
135
  export declare function streamingCompress(): Plugin;
338
136
  /**
339
- * The request ID and logger of the request that runs. It gives `undefined`
137
+ * Whether a request asks for markdown before HTML, per
138
+ * https://acceptmarkdown.com. Use it to choose between the HTML and the
139
+ * markdown answer for one URL.
140
+ *
141
+ * The rules:
142
+ *
143
+ * - Only an explicit `text/markdown` range counts for markdown. A wildcard,
144
+ * such as `*\/*` or `text/*`, never selects markdown, so a browser and a
145
+ * client with no `Accept` get HTML.
146
+ * - `text/markdown;q=0` refuses markdown.
147
+ * - The `q` of markdown must be equal to or higher than the `q` of HTML. The
148
+ * `q` of HTML comes from the most specific range that matches it:
149
+ * `text/html`, then `text/*`, then `*\/*`. A tie selects markdown, because
150
+ * the client named it.
151
+ * - Both answers are UTF-8. A range with `charset=utf-8` is more specific
152
+ * than a range with no charset, and a range with another charset does not
153
+ * match. Other parameters, such as `variant`, do not change the match.
154
+ * - Media types and parameter names are not case-sensitive. A quoted
155
+ * parameter value can hold a `,` or a `;`.
156
+ *
157
+ * When the answer for a URL depends on this function, send `Vary: Accept` on
158
+ * both the HTML and the markdown answer. Else a shared cache can give the
159
+ * markdown to a browser.
160
+ *
161
+ * @example
162
+ * prefersMarkdown(new Request("https://example.com/", { headers: { Accept: "text/markdown" } }));
163
+ * // => true
164
+ * prefersMarkdown(new Request("https://example.com/", { headers: { Accept: "text/html, text/markdown;q=0.5" } }));
165
+ * // => false
166
+ */
167
+ export declare function prefersMarkdown(request: Request): boolean;
168
+ /**
169
+ * The request ID, logger, and CSP nonce of the request that runs. It gives `undefined`
340
170
  * outside a server request, such as in a prerender pass, or on a host with no
341
171
  * request storage.
342
172
  *
@@ -357,5 +187,5 @@ export declare function requestContext(): RequestContext | undefined;
357
187
  * shutdownSignal().addEventListener("abort", () => clearInterval(timer), { once: true });
358
188
  */
359
189
  export declare function shutdownSignal(): AbortSignal;
360
- export type { AccessLogOptions, AppServer, AppServerEntry, AppServerEnv, BuildIdOptions, CreateEntryOptions, CreateServerOptions, DefaultPluginsOptions, EventStreamOptions, EventStreamSink, FetchHandler, FileInfo, FrameworkRuntime, FrameworkRuntimeFactory, HostRuntime, InferOutput, Lifecycle, Listener, ListenerBindings, LogLevel, LogSink, Mode, Plugin, PrerenderedOptions, RequestContext, RequestIdOptions, RequestLogger, RequestStore, RunningServer, RuntimeEnv, RuntimeEnvOptions, ServerBindings, ServerSentEvent, SetupInfo, StandardSchemaV1, StartedListener, StaticFiles };
190
+ 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 LogSink, type Mode, 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, prerendered, redirects, requestId, runtimeEnv, securityHeaders, trailingSlash };
361
191
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,5 +1,10 @@
1
- import { n as jsonSink } from "./log-CsjaKM8U.js";
2
- import { a as shutdownSignal, c as assets, d as accessLog, i as defaultPlugins, l as prerendered, o as requestContext, r as createServer, s as streamingCompress, t as createEntry, u as requestId } from "./entry-BkdUub2S.js";
1
+ import { a as replaceResponse, o as withHeaderHook, s as writableHeaders } from "./header-hook-Vzw9J9BY.js";
2
+ import { r as buildId, s as optionPlugin } from "./build-id-C6sYO9Yp.js";
3
+ import { r as jsonSink } from "./log-BP6xXXZl.js";
4
+ import { t as ResponseEdge } from "./response-edge-Bc1-C_Cx.js";
5
+ import { a as streamingCompress, b as accessLog, c as prefersMarkdown, d as securityHeaders, f as redirects, g as health, h as noindex, l as requestId, m as privateDocuments, n as defaultPlugins, o as assets, p as trailingSlash, s as prerendered, t as createServer, u as contentSecurityPolicy, v as shutdownSignal, y as bodyLimit } from "./create-server-iE1-s6Bi.js";
6
+ import { t as requestContext } from "./request-context-BtQ87VYb.js";
7
+ import { t as createEntry } from "./entry-DZ3qo7qF.js";
3
8
 
4
9
  // src/core/event-stream.ts
5
10
  function formatEvent({ data, event, id }) {
@@ -79,34 +84,6 @@ function eventStream({ signal, heartbeatMs = 15e3, headers }, produce) {
79
84
  return new Response(body, { headers: responseHeaders });
80
85
  }
81
86
 
82
- // src/core/plugins/build-id.ts
83
- /** The data check before `setup` runs. */
84
- function noDataRequests() {
85
- return false;
86
- }
87
- /**
88
- * Sets a build ID header on documents and on the framework's data responses,
89
- * such as React Router `.data` files, so a client can see that a deploy
90
- * happened under it.
91
- *
92
- * @example
93
- * buildId({ value: env.values.PUBLIC_APP_VERSION });
94
- */
95
- function buildId({ header = "X-Build-Id", value }) {
96
- let isDataRequest = noDataRequests;
97
- return {
98
- name: "build-id",
99
- setup: (info) => {
100
- ({isDataRequest} = info);
101
- },
102
- etagPart: () => value,
103
- middleware: async (context, next) => {
104
- await next();
105
- if ((context.res.headers.get("Content-Type")?.startsWith("text/html") ?? false) || isDataRequest(context.req.path)) context.header(header, value);
106
- }
107
- };
108
- }
109
-
110
87
  // src/core/plugins/runtime-env.ts
111
88
  /** The `id` of the JSON `<script>` that carries the public values into each HTML document. */
112
89
  const PUBLIC_ENV_SCRIPT_ID = "app-server-public-env";
@@ -125,29 +102,37 @@ function publicEnvScript(values) {
125
102
  function injectBeforeHeadEnd(body, html) {
126
103
  const decoder = new TextDecoder();
127
104
  const encoder = new TextEncoder();
105
+ const reader = body.getReader();
128
106
  let pending = "";
129
- return body.pipeThrough(new TransformStream({
130
- transform(chunk, controller) {
131
- const text = decoder.decode(chunk, { stream: true });
132
- if (pending == null) {
133
- controller.enqueue(encoder.encode(text));
134
- return;
135
- }
136
- pending += text;
137
- const index = pending.search(/<\/head>/iu);
138
- if (index !== -1) {
139
- controller.enqueue(encoder.encode(`${pending.slice(0, index)}${html}${pending.slice(index)}`));
140
- pending = void 0;
141
- } else if (pending.length > HEAD_SEARCH_LIMIT) {
142
- controller.enqueue(encoder.encode(pending));
143
- pending = void 0;
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;
116
+ };
117
+ return new ReadableStream({
118
+ async pull(controller) {
119
+ for (;;) {
120
+ const { done, value } = await reader.read();
121
+ if (done) {
122
+ const rest = `${pending ?? ""}${decoder.decode()}`;
123
+ if (rest !== "") controller.enqueue(encoder.encode(rest));
124
+ controller.close();
125
+ return;
126
+ }
127
+ const out = transform(decoder.decode(value, { stream: true }));
128
+ if (out != null) {
129
+ controller.enqueue(encoder.encode(out));
130
+ return;
131
+ }
144
132
  }
145
133
  },
146
- flush(controller) {
147
- const rest = `${pending ?? ""}${decoder.decode()}`;
148
- if (rest !== "") controller.enqueue(encoder.encode(rest));
149
- }
150
- }));
134
+ cancel: async (reason) => reader.cancel(reason)
135
+ }, { highWaterMark: 0 });
151
136
  }
152
137
  /**
153
138
  * Validates the environment once, at startup, against a schema. A missing or
@@ -157,14 +142,15 @@ function injectBeforeHeadEnd(body, html) {
157
142
  * The values whose names start with `PUBLIC_` go into each HTML document,
158
143
  * prerendered or rendered, as a JSON `<script id="app-server-public-env">`.
159
144
  * So one image serves every environment, and a prerendered page never keeps
160
- * the values of the build. Put this plugin before the static stages, so it
161
- * sees the prerendered pages.
145
+ * the values of the build. Give it to the `env` option of `defaultPlugins()`,
146
+ * which puts it before the static stages, so it sees the prerendered pages.
162
147
  *
163
148
  * @example
164
149
  * export const env = runtimeEnv(
165
150
  * z.object({ PUBLIC_API_URL: z.url(), SESSION_KEY: z.string().min(32) }),
166
151
  * );
167
152
  * env.values.SESSION_KEY; // => string
153
+ * createServer({ plugins: defaultPlugins({ env }) });
168
154
  *
169
155
  * // In the browser:
170
156
  * const publicEnv = JSON.parse(document.getElementById("app-server-public-env")?.textContent ?? "{}");
@@ -185,7 +171,7 @@ function runtimeEnv(schema, { source = process.env, publicPrefix = "PUBLIC_" } =
185
171
  };
186
172
  return parsed;
187
173
  };
188
- return {
174
+ return optionPlugin("env", {
189
175
  name: "runtime-env",
190
176
  get values() {
191
177
  return parse().values;
@@ -198,16 +184,18 @@ function runtimeEnv(schema, { source = process.env, publicPrefix = "PUBLIC_" } =
198
184
  },
199
185
  etagPart: () => parse().script,
200
186
  middleware: async (context, next) => {
201
- await next();
202
187
  const { script } = parse();
188
+ if (script != null) context.set("rewritesHtml", true);
189
+ await next();
203
190
  const response = context.res;
204
191
  if (script == null || response.headers.has("Content-Encoding") || response.headers.has("Content-Range") || !(response.headers.get("Content-Type")?.startsWith("text/html") ?? false)) return;
205
- if (response.body != null) context.res = new Response(injectBeforeHeadEnd(response.body, script), response);
206
- context.header("Content-Length", void 0);
207
- context.header("ETag", void 0);
192
+ if (response.body != null) replaceResponse(context, new Response(injectBeforeHeadEnd(response.body, script), response));
193
+ const headers = writableHeaders(context);
194
+ headers.delete("Content-Length");
195
+ headers.delete("ETag");
208
196
  }
209
- };
197
+ });
210
198
  }
211
199
 
212
- export { PUBLIC_ENV_SCRIPT_ID, accessLog, assets, buildId, createEntry, createServer, defaultPlugins, eventStream, jsonSink, prerendered, requestContext, requestId, runtimeEnv, shutdownSignal, streamingCompress };
200
+ export { PUBLIC_ENV_SCRIPT_ID, ResponseEdge, accessLog, assets, bodyLimit, buildId, contentSecurityPolicy, createEntry, createServer, defaultPlugins, eventStream, health, jsonSink, noindex, prefersMarkdown, prerendered, privateDocuments, redirects, requestContext, requestId, runtimeEnv, securityHeaders, shutdownSignal, streamingCompress, trailingSlash, withHeaderHook };
213
201
  //# sourceMappingURL=index.js.map