@ngrok/app-server 0.2.0 → 0.3.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.
- package/README.md +652 -77
- package/dist/build-id-C6sYO9Yp.js +126 -0
- package/dist/build-id-C6sYO9Yp.js.map +1 -0
- package/dist/{build-manifest-8NfD1wnO.js → build-manifest-UDNk81Ce.js} +24 -6
- package/dist/build-manifest-UDNk81Ce.js.map +1 -0
- package/dist/cli.js +45 -25
- package/dist/cli.js.map +1 -1
- package/dist/client-browser.d.ts +12 -0
- package/dist/client-browser.js +3 -0
- package/dist/client.d.ts +21 -0
- package/dist/client.js +27 -0
- package/dist/client.js.map +1 -0
- package/dist/compression-7_gToa8R.js +97 -0
- package/dist/compression-7_gToa8R.js.map +1 -0
- package/dist/create-server-DkTeIJ8L.js +1409 -0
- package/dist/create-server-DkTeIJ8L.js.map +1 -0
- package/dist/{deno-DNRgzHrk.js → deno-aqhikNMG.js} +2 -2
- package/dist/deno-aqhikNMG.js.map +1 -0
- package/dist/entry-CM6Ma-Tv.d.ts +626 -0
- package/dist/entry-CenmvESk.js +116 -0
- package/dist/entry-CenmvESk.js.map +1 -0
- package/dist/gzip-Doi4wqjX.js +294 -0
- package/dist/gzip-Doi4wqjX.js.map +1 -0
- package/dist/header-hook-Vzw9J9BY.js +159 -0
- package/dist/header-hook-Vzw9J9BY.js.map +1 -0
- package/dist/{index-oSE-tYRW.d.ts → index-Bo5G9LuQ.d.ts} +53 -14
- package/dist/index.d.ts +99 -269
- package/dist/index.js +47 -59
- package/dist/index.js.map +1 -1
- package/dist/listen-options-7TaXjyrk.js.map +1 -1
- package/dist/{load-entry-C03qqmhr.js → load-entry-CmkdlmDX.js} +8 -4
- package/dist/{load-entry-C03qqmhr.js.map → load-entry-CmkdlmDX.js.map} +1 -1
- package/dist/log-BP6xXXZl.js +122 -0
- package/dist/log-BP6xXXZl.js.map +1 -0
- package/dist/node-BFH82eeL.js +333 -0
- package/dist/node-BFH82eeL.js.map +1 -0
- package/dist/node-tBVQPjQv.js +41 -0
- package/dist/node-tBVQPjQv.js.map +1 -0
- package/dist/node-vite.d.ts +5 -4
- package/dist/node-vite.js +2 -17
- package/dist/node.d.ts +23 -4
- package/dist/node.js +2 -2
- package/dist/react-router-vite.d.ts +4 -3
- package/dist/react-router-vite.js +2 -20
- package/dist/react-router.d.ts +1 -1
- package/dist/react-router.js +8 -7
- package/dist/react-router.js.map +1 -1
- package/dist/request-context-BtQ87VYb.js +40 -0
- package/dist/request-context-BtQ87VYb.js.map +1 -0
- package/dist/response-edge-Bc1-C_Cx.js +327 -0
- package/dist/response-edge-Bc1-C_Cx.js.map +1 -0
- package/dist/response-writer-B7FoJjEE.js +289 -0
- package/dist/response-writer-B7FoJjEE.js.map +1 -0
- package/dist/script-hashes-hqUk6kG7.js +53 -0
- package/dist/script-hashes-hqUk6kG7.js.map +1 -0
- package/dist/{serve-Cleo8RMO.js → serve-Cc-ADdhZ.js} +3 -3
- package/dist/{serve-Cleo8RMO.js.map → serve-Cc-ADdhZ.js.map} +1 -1
- package/dist/stale-build-navigation-PnMLtTF8.js +339 -0
- package/dist/stale-build-navigation-PnMLtTF8.js.map +1 -0
- package/dist/stale-build-navigation-ypV7Ow4o.d.ts +141 -0
- package/dist/{start-CINALHxy.js → start-Cb3kknlF.js} +14 -19
- package/dist/start-Cb3kknlF.js.map +1 -0
- package/dist/static-files-Beju9riB.js +302 -0
- package/dist/static-files-Beju9riB.js.map +1 -0
- package/dist/tanstack-start-vite.d.ts +6 -5
- package/dist/tanstack-start-vite.js +2 -23
- package/dist/tanstack-start.d.ts +19 -2
- package/dist/tanstack-start.js +5 -14
- package/dist/tanstack-start.js.map +1 -1
- package/dist/{tcp-C-9AmFuM.js → tcp-Dd1Mt6sN.js} +6 -5
- package/dist/{tcp-C-9AmFuM.js.map → tcp-Dd1Mt6sN.js.map} +1 -1
- package/dist/trailing-slash-DX7NB88H.d.ts +36 -0
- package/dist/types-DLYxYS6M.d.ts +392 -0
- package/dist/vercel-vite.d.ts +35 -0
- package/dist/vercel-vite.js +142 -0
- package/dist/vercel-vite.js.map +1 -0
- package/dist/vercel.d.ts +35 -0
- package/dist/vercel.js +89 -0
- package/dist/vercel.js.map +1 -0
- package/dist/vite-B-GfswoH.js +22 -0
- package/dist/vite-B-GfswoH.js.map +1 -0
- package/dist/vite-D4hfj3ph.js +19 -0
- package/dist/vite-D4hfj3ph.js.map +1 -0
- package/dist/vite-DyrhyKEr.js +25 -0
- package/dist/vite-DyrhyKEr.js.map +1 -0
- package/dist/vite-iioAoxSt.js +752 -0
- package/dist/vite-iioAoxSt.js.map +1 -0
- package/dist/vite.d.ts +2 -2
- package/dist/vite.js +1 -1
- package/package.json +25 -4
- package/dist/build-manifest-8NfD1wnO.js.map +0 -1
- package/dist/deno-DNRgzHrk.js.map +0 -1
- package/dist/entry-BkdUub2S.js +0 -638
- package/dist/entry-BkdUub2S.js.map +0 -1
- package/dist/log-CsjaKM8U.js +0 -59
- package/dist/log-CsjaKM8U.js.map +0 -1
- package/dist/node-CG7qXuWZ.js +0 -58
- package/dist/node-CG7qXuWZ.js.map +0 -1
- package/dist/node-YWPGmzAk.js +0 -215
- package/dist/node-YWPGmzAk.js.map +0 -1
- package/dist/node-ZMowKZDB.js +0 -3
- package/dist/node-vite.js.map +0 -1
- package/dist/react-router-vite.js.map +0 -1
- package/dist/start-CINALHxy.js.map +0 -1
- package/dist/tanstack-start-vite.js.map +0 -1
- package/dist/types-BfCkS7kQ.d.ts +0 -203
- package/dist/vite-mYZ2Y69u.js +0 -144
- package/dist/vite-mYZ2Y69u.js.map +0 -1
package/dist/entry-BkdUub2S.js
DELETED
|
@@ -1,638 +0,0 @@
|
|
|
1
|
-
import { n as jsonSink, r as requestLogger, t as errorAttributes } from "./log-CsjaKM8U.js";
|
|
2
|
-
import { n as manifestKey, r as readBuildManifest } from "./build-manifest-8NfD1wnO.js";
|
|
3
|
-
import { Hono } from "hono";
|
|
4
|
-
import { requestId } from "hono/request-id";
|
|
5
|
-
import { getMimeType } from "hono/utils/mime";
|
|
6
|
-
import { accepts } from "hono/accepts";
|
|
7
|
-
|
|
8
|
-
// src/core/plugins/access-log.ts
|
|
9
|
-
/**
|
|
10
|
-
* A URL's path and query, with each query value replaced when `redact` is set.
|
|
11
|
-
*
|
|
12
|
-
* @example
|
|
13
|
-
* loggedUrl(new URL("https://example.com/verify?code=123"), { redact: true }); // => "/verify?code=REDACTED"
|
|
14
|
-
*/
|
|
15
|
-
function loggedUrl(url, { redact }) {
|
|
16
|
-
if (!redact || url.search === "") return `${url.pathname}${url.search}`;
|
|
17
|
-
const query = [...url.searchParams.keys()].map((key) => `${encodeURIComponent(key)}=REDACTED`).join("&");
|
|
18
|
-
return `${url.pathname}?${query}`;
|
|
19
|
-
}
|
|
20
|
-
/** A `Referer` with its query redacted like {@link loggedUrl}. A value that is not a URL is dropped. */
|
|
21
|
-
function loggedReferer(referer, { redact }) {
|
|
22
|
-
if (referer == null || !redact) return referer;
|
|
23
|
-
const url = URL.parse(referer);
|
|
24
|
-
return url == null ? void 0 : `${url.origin}${loggedUrl(url, { redact })}`;
|
|
25
|
-
}
|
|
26
|
-
/**
|
|
27
|
-
* One log line per request, static hits included, with Datadog standard
|
|
28
|
-
* attribute names. The line goes out when the body ends or the client
|
|
29
|
-
* disconnects, so a streamed response logs its full duration and size.
|
|
30
|
-
*
|
|
31
|
-
* @example
|
|
32
|
-
* createServer({ plugins: [requestId(), accessLog({ redactQuery: false })] });
|
|
33
|
-
* // {"level":"info","message":"request","http.status_code":200,"network.bytes_written":5120,"duration":1830000,...}
|
|
34
|
-
*/
|
|
35
|
-
function accessLog({ redactQuery = true } = {}) {
|
|
36
|
-
return {
|
|
37
|
-
name: "access-log",
|
|
38
|
-
middleware: async (context, next) => {
|
|
39
|
-
const started = performance.now();
|
|
40
|
-
await next();
|
|
41
|
-
const write = ({ bytes, aborted }) => {
|
|
42
|
-
context.var.logger.info("request", lineAttributes(context, {
|
|
43
|
-
bytes,
|
|
44
|
-
aborted,
|
|
45
|
-
started
|
|
46
|
-
}));
|
|
47
|
-
};
|
|
48
|
-
const response = context.res;
|
|
49
|
-
if (context.req.method === "HEAD") {
|
|
50
|
-
write({
|
|
51
|
-
bytes: 0,
|
|
52
|
-
aborted: false
|
|
53
|
-
});
|
|
54
|
-
return;
|
|
55
|
-
}
|
|
56
|
-
if (response.body == null) {
|
|
57
|
-
write({
|
|
58
|
-
bytes: Number(response.headers.get("Content-Length") ?? 0),
|
|
59
|
-
aborted: false
|
|
60
|
-
});
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
const reader = response.body.getReader();
|
|
64
|
-
let bytes = 0;
|
|
65
|
-
const counted = new ReadableStream({
|
|
66
|
-
async pull(controller) {
|
|
67
|
-
let result;
|
|
68
|
-
try {
|
|
69
|
-
result = await reader.read();
|
|
70
|
-
} catch (error) {
|
|
71
|
-
write({
|
|
72
|
-
bytes,
|
|
73
|
-
aborted: true
|
|
74
|
-
});
|
|
75
|
-
throw error;
|
|
76
|
-
}
|
|
77
|
-
const { done, value } = result;
|
|
78
|
-
if (done) {
|
|
79
|
-
controller.close();
|
|
80
|
-
write({
|
|
81
|
-
bytes,
|
|
82
|
-
aborted: false
|
|
83
|
-
});
|
|
84
|
-
return;
|
|
85
|
-
}
|
|
86
|
-
bytes += value.byteLength;
|
|
87
|
-
controller.enqueue(value);
|
|
88
|
-
},
|
|
89
|
-
async cancel(reason) {
|
|
90
|
-
write({
|
|
91
|
-
bytes,
|
|
92
|
-
aborted: true
|
|
93
|
-
});
|
|
94
|
-
await reader.cancel(reason);
|
|
95
|
-
}
|
|
96
|
-
});
|
|
97
|
-
context.res = new Response(counted, response);
|
|
98
|
-
}
|
|
99
|
-
};
|
|
100
|
-
function lineAttributes(context, { bytes, aborted, started }) {
|
|
101
|
-
return {
|
|
102
|
-
"http.url": loggedUrl(new URL(context.req.url), { redact: redactQuery }),
|
|
103
|
-
"http.status_code": context.res.status,
|
|
104
|
-
"http.useragent": context.req.header("User-Agent"),
|
|
105
|
-
"http.referer": loggedReferer(context.req.header("Referer"), { redact: redactQuery }),
|
|
106
|
-
"network.client.ip": context.env.remoteAddress,
|
|
107
|
-
"network.bytes_written": bytes,
|
|
108
|
-
duration: Math.round((performance.now() - started) * 1e6),
|
|
109
|
-
...aborted ? { "http.client_aborted": true } : {}
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
// src/core/plugins/request-id.ts
|
|
115
|
-
/**
|
|
116
|
-
* Gives each request an ID: a valid incoming header (up to 255 word
|
|
117
|
-
* characters, `-`, and `=`), else a new UUID. The ID goes on the response, on
|
|
118
|
-
* every log line, and into the framework's context.
|
|
119
|
-
*
|
|
120
|
-
* @example
|
|
121
|
-
* const app = createServer({ plugins: [requestId()] });
|
|
122
|
-
* const response = await app.request("/", { headers: { "X-Request-Id": "abc-123" } });
|
|
123
|
-
* response.headers.get("X-Request-Id"); // => "abc-123"
|
|
124
|
-
*/
|
|
125
|
-
function requestId$1({ headerName = "X-Request-Id" } = {}) {
|
|
126
|
-
const assign = requestId({ headerName });
|
|
127
|
-
return {
|
|
128
|
-
name: "request-id",
|
|
129
|
-
middleware: async (context, next) => {
|
|
130
|
-
await assign(context, next);
|
|
131
|
-
const id = context.get("requestId");
|
|
132
|
-
if (id != null) context.header(headerName, id);
|
|
133
|
-
}
|
|
134
|
-
};
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
// src/core/static-files.ts
|
|
138
|
-
/** The content types that `mime` lacks and that no framework owns. */
|
|
139
|
-
const CORE_CONTENT_TYPES = { ".md": "text/markdown; charset=utf-8" };
|
|
140
|
-
/**
|
|
141
|
-
* Whether a URL path names a dotfile or goes through a dot directory.
|
|
142
|
-
* `/.well-known/` stays reachable.
|
|
143
|
-
*/
|
|
144
|
-
function hasDotSegment(path) {
|
|
145
|
-
return path.split("/").some((segment, index) => segment.startsWith(".") && !(index === 1 && segment === ".well-known"));
|
|
146
|
-
}
|
|
147
|
-
/**
|
|
148
|
-
* Finds the file in `files` that answers a decoded URL path, such as Hono's
|
|
149
|
-
* `context.req.path`. A directory answers with its `index.html` and no
|
|
150
|
-
* redirect, so a prerendered page keeps its URL. Dotfiles and paths that
|
|
151
|
-
* leave the client build find nothing.
|
|
152
|
-
*
|
|
153
|
-
* Each file has one URL, because the headers for a file are keyed by that
|
|
154
|
-
* URL. So `/a//b`, `/a/index.html`, and `/a%2Fb` find nothing. Hono decodes
|
|
155
|
-
* the path but keeps an encoded `/` as `%2F`, so this function does not
|
|
156
|
-
* decode it again.
|
|
157
|
-
*
|
|
158
|
-
* @example
|
|
159
|
-
* await findStaticFile(files, "/components/button");
|
|
160
|
-
* // => { path: "/components/button/index.html", size: 5120, mtimeMs: 1761652800000 }
|
|
161
|
-
*/
|
|
162
|
-
async function findStaticFile(files, path) {
|
|
163
|
-
if (!path.startsWith("/") || path.includes("\0") || path.includes("\\") || path.split("/").includes("..") || path.includes("//") || path.endsWith("/index.html") || hasDotSegment(path)) return;
|
|
164
|
-
const info = await files.stat(path);
|
|
165
|
-
if (info?.kind === "file") return {
|
|
166
|
-
path,
|
|
167
|
-
size: info.size,
|
|
168
|
-
mtimeMs: info.mtimeMs
|
|
169
|
-
};
|
|
170
|
-
if (info?.kind === "directory") {
|
|
171
|
-
const index = `${path.replace(/\/$/u, "")}/index.html`;
|
|
172
|
-
const indexInfo = await files.stat(index);
|
|
173
|
-
if (indexInfo?.kind === "file") return {
|
|
174
|
-
path: index,
|
|
175
|
-
size: indexInfo.size,
|
|
176
|
-
mtimeMs: indexInfo.mtimeMs
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
/** The content type of a file, by its extension. `contentTypes` win over `mime`. */
|
|
181
|
-
function contentType(path, contentTypes) {
|
|
182
|
-
const extension = /\.[^./]+$/u.exec(path)?.[0] ?? "";
|
|
183
|
-
return contentTypes[extension] ?? CORE_CONTENT_TYPES[extension] ?? getMimeType(path) ?? "application/octet-stream";
|
|
184
|
-
}
|
|
185
|
-
/** An ETag without its weak prefix, for the weak comparison that `If-None-Match` uses. */
|
|
186
|
-
function opaqueTag(etag) {
|
|
187
|
-
return etag.trim().replace(/^W\//u, "");
|
|
188
|
-
}
|
|
189
|
-
/** Whether an `If-None-Match` header lists an ETag. */
|
|
190
|
-
function matchesEtag(ifNoneMatch, etag) {
|
|
191
|
-
return ifNoneMatch?.split(",").some((candidate) => {
|
|
192
|
-
const trimmed = candidate.trim();
|
|
193
|
-
return trimmed === "*" || opaqueTag(trimmed) === opaqueTag(etag);
|
|
194
|
-
}) ?? false;
|
|
195
|
-
}
|
|
196
|
-
/** A weak ETag from a file's size, its modification time, and the request's `etagParts`. */
|
|
197
|
-
async function fileEtag(file, parts) {
|
|
198
|
-
const base = `${file.size.toString(16)}-${Math.trunc(file.mtimeMs).toString(16)}`;
|
|
199
|
-
if (parts.length === 0) return `W/"${base}"`;
|
|
200
|
-
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(parts.join("\0")));
|
|
201
|
-
return `W/"${base}-${btoa(String.fromCodePoint(...new Uint8Array(digest))).replaceAll("+", "-").replaceAll("/", "_").slice(0, 16)}"`;
|
|
202
|
-
}
|
|
203
|
-
/**
|
|
204
|
-
* The response for a static file, with a weak ETag from its size,
|
|
205
|
-
* modification time, and the request's `etagParts`. A matching
|
|
206
|
-
* `If-None-Match` gets a 304, and `HEAD` gets the headers only.
|
|
207
|
-
*/
|
|
208
|
-
async function staticResponse(context, { files, file, headers, contentTypes }) {
|
|
209
|
-
const etag = await fileEtag(file, context.get("etagParts") ?? []);
|
|
210
|
-
const responseHeaders = new Headers({
|
|
211
|
-
"Content-Type": contentType(file.path, contentTypes),
|
|
212
|
-
ETag: etag
|
|
213
|
-
});
|
|
214
|
-
for (const [name, value] of Object.entries(headers)) responseHeaders.set(name, value);
|
|
215
|
-
if (matchesEtag(context.req.header("If-None-Match"), responseHeaders.get("ETag") ?? etag)) {
|
|
216
|
-
responseHeaders.delete("Content-Type");
|
|
217
|
-
return new Response(null, {
|
|
218
|
-
status: 304,
|
|
219
|
-
headers: responseHeaders
|
|
220
|
-
});
|
|
221
|
-
}
|
|
222
|
-
responseHeaders.set("Content-Length", String(file.size));
|
|
223
|
-
if (context.req.method === "HEAD") return new Response(null, { headers: responseHeaders });
|
|
224
|
-
return new Response(await files.open(file.path), { headers: responseHeaders });
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
// src/core/plugins/static.ts
|
|
228
|
-
const IMMUTABLE = "public, max-age=31536000, immutable";
|
|
229
|
-
/**
|
|
230
|
-
* Serves the hashed files under `/assets/` with a one-year immutable cache.
|
|
231
|
-
* A missing asset gets a plain 404, not a rendered page. In development,
|
|
232
|
-
* the dev server serves the source modules, the HMR client, and the CSS here
|
|
233
|
-
* instead.
|
|
234
|
-
*
|
|
235
|
-
* @example
|
|
236
|
-
* createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });
|
|
237
|
-
*/
|
|
238
|
-
function assets() {
|
|
239
|
-
let stage;
|
|
240
|
-
return {
|
|
241
|
-
name: "assets",
|
|
242
|
-
setup: (info) => {
|
|
243
|
-
if (info.mode === "development") {
|
|
244
|
-
stage = info.devServer;
|
|
245
|
-
return;
|
|
246
|
-
}
|
|
247
|
-
const { files, contentTypes } = info;
|
|
248
|
-
stage = async (context, next) => {
|
|
249
|
-
const { method, path } = context.req;
|
|
250
|
-
if (!path.startsWith("/assets/") || method !== "GET" && method !== "HEAD") return next();
|
|
251
|
-
const file = await findStaticFile(files, path);
|
|
252
|
-
if (file == null) return context.text("Not Found", 404);
|
|
253
|
-
return staticResponse(context, {
|
|
254
|
-
files,
|
|
255
|
-
file,
|
|
256
|
-
headers: { "Cache-Control": IMMUTABLE },
|
|
257
|
-
contentTypes
|
|
258
|
-
});
|
|
259
|
-
};
|
|
260
|
-
},
|
|
261
|
-
middleware: async (context, next) => stage == null ? next() : stage(context, next)
|
|
262
|
-
};
|
|
263
|
-
}
|
|
264
|
-
/**
|
|
265
|
-
* Serves the client build: prerendered pages at their own URL with a 200 and
|
|
266
|
-
* no trailing-slash redirect, plus every other file in it. Each response gets
|
|
267
|
-
* the headers its loader sent at build time (the `appServer` Vite plugin
|
|
268
|
-
* captures them), an ETag, and a 304 for a matching `If-None-Match`. A path
|
|
269
|
-
* with no file goes on to the framework. Off in development.
|
|
270
|
-
*
|
|
271
|
-
* At startup, it warns about each prerendered path that has no file.
|
|
272
|
-
*
|
|
273
|
-
* @example
|
|
274
|
-
* prerendered({
|
|
275
|
-
* headers: (path) => (path.startsWith("/api/") ? { "Access-Control-Allow-Origin": "*" } : undefined),
|
|
276
|
-
* });
|
|
277
|
-
*/
|
|
278
|
-
function prerendered(options = {}) {
|
|
279
|
-
let stage;
|
|
280
|
-
return {
|
|
281
|
-
name: "prerendered",
|
|
282
|
-
setup: async (info) => {
|
|
283
|
-
if (info.mode === "development") return;
|
|
284
|
-
const { files, contentTypes, capturedHeaders } = info;
|
|
285
|
-
const missing = [];
|
|
286
|
-
for (const path of info.prerenderedPaths) if (await findStaticFile(files, path) == null) missing.push(path);
|
|
287
|
-
if (missing.length > 0) info.logger.log("warn", "prerendered paths with no file", { "app_server.missing_paths": missing });
|
|
288
|
-
stage = async (context, next) => {
|
|
289
|
-
const { method } = context.req;
|
|
290
|
-
if (method !== "GET" && method !== "HEAD") return next();
|
|
291
|
-
const path = options.rewrite?.(context.req.path, context) ?? context.req.path;
|
|
292
|
-
const file = await findStaticFile(files, path);
|
|
293
|
-
if (file == null) return next();
|
|
294
|
-
return staticResponse(context, {
|
|
295
|
-
files,
|
|
296
|
-
file,
|
|
297
|
-
headers: {
|
|
298
|
-
...capturedHeaders.get(manifestKey(path)),
|
|
299
|
-
...options.headers?.(path, context)
|
|
300
|
-
},
|
|
301
|
-
contentTypes
|
|
302
|
-
});
|
|
303
|
-
};
|
|
304
|
-
},
|
|
305
|
-
middleware: async (context, next) => stage == null ? next() : stage(context, next)
|
|
306
|
-
};
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
// src/core/plugins/streaming-compress.ts
|
|
310
|
-
const COMPRESSIBLE = /^(?:text\/|application\/(?:json|javascript|xml|schema\+json|manifest\+json|x-ndjson|connect\+json)|image\/svg\+xml)/u;
|
|
311
|
-
/**
|
|
312
|
-
* Gzips text responses and flushes after each chunk, so a streamed page shell
|
|
313
|
-
* or a server-sent event reaches the client at once. `hono/compress` holds a
|
|
314
|
-
* stream until it ends. Skips a response that is already encoded, a partial
|
|
315
|
-
* response, and one marked `no-transform`. It sets `Vary: Accept-Encoding` on
|
|
316
|
-
* each response. The host gives the gzip stream. On a host with none, the
|
|
317
|
-
* plugin does nothing.
|
|
318
|
-
*
|
|
319
|
-
* @example
|
|
320
|
-
* createServer({ plugins: [requestId(), accessLog(), streamingCompress()] });
|
|
321
|
-
*/
|
|
322
|
-
function streamingCompress() {
|
|
323
|
-
let gzip;
|
|
324
|
-
return {
|
|
325
|
-
name: "streaming-compress",
|
|
326
|
-
setup: (info) => {
|
|
327
|
-
({gzip} = info);
|
|
328
|
-
},
|
|
329
|
-
middleware: async (context, next) => {
|
|
330
|
-
await next();
|
|
331
|
-
if (gzip == null) return;
|
|
332
|
-
context.header("Vary", "Accept-Encoding", { append: true });
|
|
333
|
-
const response = context.res;
|
|
334
|
-
if (response.body == null || context.req.method === "HEAD" || accepts(context, {
|
|
335
|
-
header: "Accept-Encoding",
|
|
336
|
-
supports: ["gzip"],
|
|
337
|
-
default: "identity"
|
|
338
|
-
}) !== "gzip" || response.headers.has("Content-Encoding") || response.headers.has("Content-Range") || /\bno-transform\b/u.test(response.headers.get("Cache-Control") ?? "") || !COMPRESSIBLE.test(response.headers.get("Content-Type") ?? "")) return;
|
|
339
|
-
context.res = new Response(gzip(response.body), response);
|
|
340
|
-
context.res.headers.set("Content-Encoding", "gzip");
|
|
341
|
-
context.res.headers.delete("Content-Length");
|
|
342
|
-
}
|
|
343
|
-
};
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
// src/core/request-context.ts
|
|
347
|
-
/**
|
|
348
|
-
* Each store that a request ran in. Why a set: two entries in one process can
|
|
349
|
-
* have two hosts, and each request uses the store of its own app.
|
|
350
|
-
*/
|
|
351
|
-
const stores = /* @__PURE__ */ new Set();
|
|
352
|
-
/** Runs `work` in `store` with `context` as the request that {@link requestContext} reads. */
|
|
353
|
-
async function withRequestContext(store, context, work) {
|
|
354
|
-
if (store == null) return work();
|
|
355
|
-
stores.add(store);
|
|
356
|
-
return store.run(context, work);
|
|
357
|
-
}
|
|
358
|
-
/**
|
|
359
|
-
* The request ID and logger of the request that runs. It gives `undefined`
|
|
360
|
-
* outside a server request, such as in a prerender pass, or on a host with no
|
|
361
|
-
* request storage.
|
|
362
|
-
*
|
|
363
|
-
* @example
|
|
364
|
-
* export async function loader() {
|
|
365
|
-
* requestContext()?.logger.info("loading the dashboard");
|
|
366
|
-
* }
|
|
367
|
-
*/
|
|
368
|
-
function requestContext() {
|
|
369
|
-
for (const store of stores) {
|
|
370
|
-
const context = store.get();
|
|
371
|
-
if (context != null) return {
|
|
372
|
-
requestId: context.get("requestId"),
|
|
373
|
-
logger: context.var.logger
|
|
374
|
-
};
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
// src/core/shutdown.ts
|
|
379
|
-
let controller = new AbortController();
|
|
380
|
-
/**
|
|
381
|
-
* A signal that aborts when the server starts to shut down. Read it for each
|
|
382
|
-
* request: each start of a server makes a new one. A handler that
|
|
383
|
-
* holds a response open, such as an event stream, stops on it so that the
|
|
384
|
-
* drain does not wait for the deadline.
|
|
385
|
-
*
|
|
386
|
-
* @example
|
|
387
|
-
* const timer = setInterval(sendUpdate, 1_000);
|
|
388
|
-
* shutdownSignal().addEventListener("abort", () => clearInterval(timer), { once: true });
|
|
389
|
-
*/
|
|
390
|
-
function shutdownSignal() {
|
|
391
|
-
return controller.signal;
|
|
392
|
-
}
|
|
393
|
-
/** Replaces {@link shutdownSignal} with a new one that has not aborted. */
|
|
394
|
-
function renewShutdownSignal() {
|
|
395
|
-
controller = new AbortController();
|
|
396
|
-
}
|
|
397
|
-
/** Aborts {@link shutdownSignal}. */
|
|
398
|
-
function abortShutdownSignal() {
|
|
399
|
-
controller.abort();
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
// src/core/create-server.ts
|
|
403
|
-
const appInternals = /* @__PURE__ */ new WeakMap();
|
|
404
|
-
/**
|
|
405
|
-
* The default pipeline, in order: `requestId`, `accessLog`,
|
|
406
|
-
* `streamingCompress`, the `beforeStatic` plugins, `assets`, and
|
|
407
|
-
* `prerendered`. It is a plain array, so an app can filter it or splice into it.
|
|
408
|
-
*
|
|
409
|
-
* @example
|
|
410
|
-
* createServer({ plugins: defaultPlugins({ accessLog: { redactQuery: false }, beforeStatic: [env] }) });
|
|
411
|
-
*/
|
|
412
|
-
function defaultPlugins(options = {}) {
|
|
413
|
-
return [
|
|
414
|
-
requestId$1(options.requestId),
|
|
415
|
-
accessLog(options.accessLog),
|
|
416
|
-
streamingCompress(),
|
|
417
|
-
...options.beforeStatic ?? [],
|
|
418
|
-
assets(),
|
|
419
|
-
prerendered(options.prerendered)
|
|
420
|
-
];
|
|
421
|
-
}
|
|
422
|
-
/** The request with the scheme from `X-Forwarded-Proto`, when that header holds one. */
|
|
423
|
-
function withForwardedProto(request) {
|
|
424
|
-
const proto = request.headers.get("X-Forwarded-Proto");
|
|
425
|
-
if (proto !== "http" && proto !== "https") return request;
|
|
426
|
-
const url = new URL(request.url);
|
|
427
|
-
url.protocol = `${proto}:`;
|
|
428
|
-
return new Request(url, request);
|
|
429
|
-
}
|
|
430
|
-
/**
|
|
431
|
-
* Runs `step`, and rethrows a thrown value that is not an `Error` as one.
|
|
432
|
-
* Hono sends only an `Error` to `onError`, and rethrows any other value.
|
|
433
|
-
*/
|
|
434
|
-
async function asError(step) {
|
|
435
|
-
try {
|
|
436
|
-
return await step();
|
|
437
|
-
} catch (error) {
|
|
438
|
-
throw error instanceof Error ? error : new Error(`A non-Error value was thrown: ${String(error)}`, { cause: error });
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
/** Whether `work` settles before `ms` pass. */
|
|
442
|
-
async function settlesWithin(work, ms) {
|
|
443
|
-
let timer;
|
|
444
|
-
const settled = await Promise.race([work.then(() => true), new Promise((resolve) => {
|
|
445
|
-
timer = setTimeout(resolve, ms, false);
|
|
446
|
-
})]);
|
|
447
|
-
clearTimeout(timer);
|
|
448
|
-
return settled;
|
|
449
|
-
}
|
|
450
|
-
/**
|
|
451
|
-
* Builds an app server: a Hono app that runs the plugins in list order, then
|
|
452
|
-
* the app's own routes, then the framework. It does not listen; the
|
|
453
|
-
* `app-server` CLI starts it.
|
|
454
|
-
*
|
|
455
|
-
* @example
|
|
456
|
-
* // server.ts
|
|
457
|
-
* const app = createServer({ logger: slogSink, plugins: defaultPlugins({ beforeStatic: [env] }) });
|
|
458
|
-
* app.get("/livez", (c) => c.text("ok"));
|
|
459
|
-
* export default app;
|
|
460
|
-
*/
|
|
461
|
-
function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listeners, trustForwardedProto = false, shutdownDeadlineMs = 1e4 } = {}) {
|
|
462
|
-
const app = new Hono();
|
|
463
|
-
let requestStore;
|
|
464
|
-
if (trustForwardedProto) {
|
|
465
|
-
const dispatch = app.fetch;
|
|
466
|
-
app.fetch = async (request, ...rest) => dispatch(withForwardedProto(request), ...rest);
|
|
467
|
-
}
|
|
468
|
-
app.use(async (context, next) => {
|
|
469
|
-
context.set("logger", requestLogger(logger, context));
|
|
470
|
-
await withRequestContext(requestStore, context, next);
|
|
471
|
-
if (context.req.method === "HEAD") await context.res.body?.cancel();
|
|
472
|
-
});
|
|
473
|
-
for (const { middleware, etagPart } of plugins) app.use(async (context, next) => {
|
|
474
|
-
const part = etagPart?.();
|
|
475
|
-
if (part != null) context.set("etagParts", [...context.get("etagParts") ?? [], part]);
|
|
476
|
-
return asError(async () => middleware == null ? next() : middleware(context, next));
|
|
477
|
-
});
|
|
478
|
-
app.use(async (_, next) => asError(next));
|
|
479
|
-
app.onError((error, context) => {
|
|
480
|
-
if ("getResponse" in error && typeof error.getResponse === "function") {
|
|
481
|
-
const response = error.getResponse();
|
|
482
|
-
if (response instanceof Response) return response;
|
|
483
|
-
}
|
|
484
|
-
context.var.logger.error("unhandled error", errorAttributes(error));
|
|
485
|
-
return context.text("Internal Server Error", 500);
|
|
486
|
-
});
|
|
487
|
-
let prepared;
|
|
488
|
-
let running;
|
|
489
|
-
let stoppingPlugins;
|
|
490
|
-
const internals = {
|
|
491
|
-
logger,
|
|
492
|
-
setRequestStore: (store) => {
|
|
493
|
-
requestStore = store;
|
|
494
|
-
},
|
|
495
|
-
prepare: async (info) => {
|
|
496
|
-
prepared ??= (async () => {
|
|
497
|
-
for (const plugin of plugins) await plugin.setup?.(info);
|
|
498
|
-
app.all("*", async (context) => context.env.framework.fetch(context.req.raw, context));
|
|
499
|
-
})();
|
|
500
|
-
return prepared;
|
|
501
|
-
},
|
|
502
|
-
listen: async (framework, defaultListeners) => {
|
|
503
|
-
if (running != null) throw new Error("This app server is already listening.");
|
|
504
|
-
renewShutdownSignal();
|
|
505
|
-
let deadlinePassed = false;
|
|
506
|
-
const fetch = async (request, bindings) => {
|
|
507
|
-
const response = await app.fetch(request, {
|
|
508
|
-
...bindings,
|
|
509
|
-
framework
|
|
510
|
-
});
|
|
511
|
-
if (deadlinePassed) await response.body?.cancel();
|
|
512
|
-
return response;
|
|
513
|
-
};
|
|
514
|
-
const starts = await Promise.allSettled((listeners ?? defaultListeners).map(async (listener) => listener.start(fetch)));
|
|
515
|
-
const started = starts.flatMap((start) => start.status === "fulfilled" ? [start.value] : []);
|
|
516
|
-
const failed = starts.find((start) => start.status === "rejected");
|
|
517
|
-
if (failed != null) {
|
|
518
|
-
await Promise.all(started.map(async (listener) => listener.stop({ deadlineMs: 0 })));
|
|
519
|
-
throw failed.reason;
|
|
520
|
-
}
|
|
521
|
-
const urls = started.map((listener) => listener.url);
|
|
522
|
-
logger.log("info", "listening", { "app_server.urls": urls });
|
|
523
|
-
let stopping;
|
|
524
|
-
running = {
|
|
525
|
-
urls,
|
|
526
|
-
shutdown: async () => {
|
|
527
|
-
stopping ??= (async () => {
|
|
528
|
-
logger.log("info", "draining", { "app_server.deadline_ms": shutdownDeadlineMs });
|
|
529
|
-
abortShutdownSignal();
|
|
530
|
-
const deadline = setTimeout(() => {
|
|
531
|
-
deadlinePassed = true;
|
|
532
|
-
}, shutdownDeadlineMs);
|
|
533
|
-
const results = await Promise.allSettled([internals.stopPlugins(), ...started.map(async (listener) => listener.stop({ deadlineMs: shutdownDeadlineMs }))]);
|
|
534
|
-
clearTimeout(deadline);
|
|
535
|
-
const rejected = results.find((result) => result.status === "rejected");
|
|
536
|
-
if (rejected != null) throw rejected.reason;
|
|
537
|
-
logger.log("info", "stopped", {});
|
|
538
|
-
})();
|
|
539
|
-
return stopping;
|
|
540
|
-
}
|
|
541
|
-
};
|
|
542
|
-
return running;
|
|
543
|
-
},
|
|
544
|
-
stopPlugins: async () => {
|
|
545
|
-
stoppingPlugins ??= (async () => {
|
|
546
|
-
if (!await settlesWithin((async () => {
|
|
547
|
-
const results = await Promise.allSettled(plugins.map(async (plugin) => plugin.onShutdown?.()));
|
|
548
|
-
for (const result of results) if (result.status === "rejected") logger.log("error", "plugin shutdown failed", errorAttributes(result.reason));
|
|
549
|
-
})(), shutdownDeadlineMs)) logger.log("warn", "plugin shutdown passed the deadline", { "app_server.deadline_ms": shutdownDeadlineMs });
|
|
550
|
-
})();
|
|
551
|
-
return stoppingPlugins;
|
|
552
|
-
}
|
|
553
|
-
};
|
|
554
|
-
appInternals.set(app, internals);
|
|
555
|
-
return app;
|
|
556
|
-
}
|
|
557
|
-
/** The internals of an app from {@link createServer} of this copy of the package, else `undefined`. */
|
|
558
|
-
function serverInternals(app) {
|
|
559
|
-
return appInternals.get(app);
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
// src/core/entry.ts
|
|
563
|
-
/** The version of the contract between the CLI and the `appServer` export of a build. */
|
|
564
|
-
const ENTRY_PROTOCOL = 2;
|
|
565
|
-
/**
|
|
566
|
-
* The `appServer` export of a server build: an app from `createServer`, the
|
|
567
|
-
* host, and the framework adapter for each mode. The `appServer` Vite plugin
|
|
568
|
-
* generates this export. Call this for a build without the plugin.
|
|
569
|
-
*
|
|
570
|
-
* @example
|
|
571
|
-
* export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });
|
|
572
|
-
*/
|
|
573
|
-
function createEntry({ app, host, framework, clientDirectory }) {
|
|
574
|
-
const internals = serverInternals(app);
|
|
575
|
-
if (internals == null) throw new Error("The app is not from `createServer()` of the copy of @ngrok/app-server in this build.");
|
|
576
|
-
internals.setRequestStore(host.storage);
|
|
577
|
-
const setupInfo = async (runtime) => {
|
|
578
|
-
const directory = clientDirectory ?? runtime.clientDirectory;
|
|
579
|
-
if (directory == null) throw new Error(`Give createEntry a clientDirectory: the ${runtime.name} adapter does not know the client build.`);
|
|
580
|
-
return {
|
|
581
|
-
files: host.files(directory),
|
|
582
|
-
isDataRequest: runtime.isDataRequest ?? (() => false),
|
|
583
|
-
contentTypes: runtime.contentTypes ?? {},
|
|
584
|
-
gzip: host.gzip,
|
|
585
|
-
logger: internals.logger
|
|
586
|
-
};
|
|
587
|
-
};
|
|
588
|
-
let development;
|
|
589
|
-
return {
|
|
590
|
-
protocol: 2,
|
|
591
|
-
app,
|
|
592
|
-
start: async () => {
|
|
593
|
-
const runtime = framework("production");
|
|
594
|
-
const shared = await setupInfo(runtime);
|
|
595
|
-
const { prerendered, headers } = await readBuildManifest(shared.files);
|
|
596
|
-
const info = {
|
|
597
|
-
...shared,
|
|
598
|
-
mode: "production",
|
|
599
|
-
prerenderedPaths: runtime.prerenderedPaths ?? prerendered,
|
|
600
|
-
capturedHeaders: new Map(Object.entries(headers))
|
|
601
|
-
};
|
|
602
|
-
await internals.prepare(info);
|
|
603
|
-
const server = await internals.listen(runtime, host.listeners());
|
|
604
|
-
host.lifecycle?.onStop(async () => server.shutdown().catch((error) => {
|
|
605
|
-
internals.logger.log("error", "shutdown failed", errorAttributes(error));
|
|
606
|
-
throw error;
|
|
607
|
-
}));
|
|
608
|
-
},
|
|
609
|
-
fetchDev: async (request, bindings, devServer) => {
|
|
610
|
-
development ??= framework("development");
|
|
611
|
-
await internals.prepare({
|
|
612
|
-
...await setupInfo(development),
|
|
613
|
-
mode: "development",
|
|
614
|
-
devServer,
|
|
615
|
-
prerenderedPaths: development.prerenderedPaths ?? [],
|
|
616
|
-
capturedHeaders: /* @__PURE__ */ new Map()
|
|
617
|
-
});
|
|
618
|
-
return app.fetch(request, {
|
|
619
|
-
...bindings,
|
|
620
|
-
framework: development
|
|
621
|
-
});
|
|
622
|
-
},
|
|
623
|
-
stopPlugins: internals.stopPlugins,
|
|
624
|
-
abortShutdownSignal
|
|
625
|
-
};
|
|
626
|
-
}
|
|
627
|
-
/**
|
|
628
|
-
* Whether a value is an entry of this protocol version.
|
|
629
|
-
*
|
|
630
|
-
* @example
|
|
631
|
-
* isAppServerEntry((await import("./build/server/app-server.js")).appServer); // => true
|
|
632
|
-
*/
|
|
633
|
-
function isAppServerEntry(value) {
|
|
634
|
-
return typeof value === "object" && value != null && "protocol" in value && value.protocol === 2;
|
|
635
|
-
}
|
|
636
|
-
|
|
637
|
-
export { shutdownSignal as a, assets as c, accessLog as d, defaultPlugins as i, prerendered as l, isAppServerEntry as n, requestContext as o, createServer as r, streamingCompress as s, createEntry as t, requestId$1 as u };
|
|
638
|
-
//# sourceMappingURL=entry-BkdUub2S.js.map
|