@ngrok/app-server 0.1.1 → 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.
- package/README.md +659 -70
- package/dist/build-id-C6sYO9Yp.js +126 -0
- package/dist/build-id-C6sYO9Yp.js.map +1 -0
- package/dist/build-manifest-UDNk81Ce.js +63 -0
- package/dist/build-manifest-UDNk81Ce.js.map +1 -0
- package/dist/{bun-DCGnDEPn.js → bun-BCz6K_Xv.js} +12 -8
- package/dist/bun-BCz6K_Xv.js.map +1 -0
- package/dist/cli.js +47 -27
- package/dist/cli.js.map +1 -1
- package/dist/client.d.ts +141 -0
- package/dist/client.js +326 -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-iE1-s6Bi.js +1409 -0
- package/dist/create-server-iE1-s6Bi.js.map +1 -0
- package/dist/{deno-BnMfk2n1.js → deno-aqhikNMG.js} +5 -5
- package/dist/deno-aqhikNMG.js.map +1 -0
- package/dist/entry-DZ3qo7qF.js +116 -0
- package/dist/entry-DZ3qo7qF.js.map +1 -0
- package/dist/entry-DmJEqVfd.d.ts +622 -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-Bo5G9LuQ.d.ts +127 -0
- package/dist/index.d.ts +110 -95
- package/dist/index.js +56 -57
- package/dist/index.js.map +1 -1
- package/dist/{listen-options-DHWmSWGi.js → listen-options-7TaXjyrk.js} +2 -2
- package/dist/listen-options-7TaXjyrk.js.map +1 -0
- package/dist/load-entry-AfYS_zS9.js +37 -0
- package/dist/load-entry-AfYS_zS9.js.map +1 -0
- 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 +11 -0
- package/dist/node-vite.js +3 -0
- package/dist/node.d.ts +86 -0
- package/dist/node.js +4 -0
- package/dist/react-router-vite.d.ts +10 -0
- package/dist/react-router-vite.js +3 -0
- package/dist/react-router.d.ts +11 -24
- package/dist/react-router.js +21 -30
- 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-CDNgThjk.js +29 -0
- package/dist/serve-CDNgThjk.js.map +1 -0
- package/dist/{start-BVMb8Pyt.js → start-TLIprD74.js} +96 -81
- package/dist/start-TLIprD74.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 +12 -0
- package/dist/tanstack-start-vite.js +3 -0
- package/dist/tanstack-start.d.ts +34 -0
- package/dist/tanstack-start.js +41 -0
- package/dist/tanstack-start.js.map +1 -0
- package/dist/{tcp-Dau_IONd.js → tcp-Dd1Mt6sN.js} +8 -7
- package/dist/tcp-Dd1Mt6sN.js.map +1 -0
- 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 -27
- package/dist/vite.js +2 -2
- package/package.json +50 -4
- package/dist/bun-DCGnDEPn.js.map +0 -1
- package/dist/captured-headers-ewL_t3MQ.js +0 -48
- package/dist/captured-headers-ewL_t3MQ.js.map +0 -1
- package/dist/deno-BnMfk2n1.js.map +0 -1
- package/dist/entry-CIpwaayZ.d.ts +0 -293
- package/dist/entry-ChjmFwX5.js +0 -755
- package/dist/entry-ChjmFwX5.js.map +0 -1
- package/dist/listen-options-DHWmSWGi.js.map +0 -1
- package/dist/node-2wWBMFeO.js +0 -3
- package/dist/node-79my3Uix.js +0 -58
- package/dist/node-79my3Uix.js.map +0 -1
- package/dist/serve-ByeedcRB.js +0 -16
- package/dist/serve-ByeedcRB.js.map +0 -1
- package/dist/start-BVMb8Pyt.js.map +0 -1
- package/dist/tcp-Dau_IONd.js.map +0 -1
- package/dist/vite-CrNqpoeK.js +0 -102
- package/dist/vite-CrNqpoeK.js.map +0 -1
|
@@ -1,13 +1,65 @@
|
|
|
1
|
-
import { t as parsePort } from "./tcp-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { t as
|
|
5
|
-
import { t as
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
1
|
+
import { t as parsePort } from "./tcp-Dd1Mt6sN.js";
|
|
2
|
+
import { r as jsonSink, t as errorAttributes } from "./log-BP6xXXZl.js";
|
|
3
|
+
import { i as exitAfterFlush, n as devServerStage } from "./node-BFH82eeL.js";
|
|
4
|
+
import { t as requestListener } from "./response-writer-B7FoJjEE.js";
|
|
5
|
+
import { t as SERVER_ENTRY_ID } from "./vite-iioAoxSt.js";
|
|
6
|
+
import { t as loadEntry } from "./load-entry-AfYS_zS9.js";
|
|
7
|
+
import { t as listenerUrl } from "./listen-options-7TaXjyrk.js";
|
|
8
|
+
import { createServer } from "node:http";
|
|
8
9
|
import { createServer as createServer$1 } from "node:net";
|
|
9
10
|
|
|
10
|
-
// src/
|
|
11
|
+
// src/cli/served-apps.ts
|
|
12
|
+
/**
|
|
13
|
+
* Tracks the apps that `app-server start` serves. An edit to `server.ts` makes a
|
|
14
|
+
* new app, and the old app's plugins still hold what their `setup` opened.
|
|
15
|
+
* When the last request that the old app took returns, its `onShutdown` hooks
|
|
16
|
+
* run, and the tracker lets go of it. A route edit makes a new entry with the
|
|
17
|
+
* same app, which keeps its plugins.
|
|
18
|
+
*/
|
|
19
|
+
function servedApps() {
|
|
20
|
+
let current;
|
|
21
|
+
const served = /* @__PURE__ */ new Set();
|
|
22
|
+
const retire = async (app) => {
|
|
23
|
+
try {
|
|
24
|
+
await app.entry.stopPlugins();
|
|
25
|
+
} finally {
|
|
26
|
+
served.delete(app);
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
return {
|
|
30
|
+
serve: async (entry, handle) => {
|
|
31
|
+
if (current?.entry.app === entry.app) current.entry = entry;
|
|
32
|
+
else {
|
|
33
|
+
if (current != null) {
|
|
34
|
+
current.replaced = true;
|
|
35
|
+
if (current.pending === 0) retire(current);
|
|
36
|
+
}
|
|
37
|
+
current = {
|
|
38
|
+
entry,
|
|
39
|
+
pending: 0,
|
|
40
|
+
replaced: false
|
|
41
|
+
};
|
|
42
|
+
served.add(current);
|
|
43
|
+
}
|
|
44
|
+
const app = current;
|
|
45
|
+
app.pending += 1;
|
|
46
|
+
try {
|
|
47
|
+
return await handle(entry);
|
|
48
|
+
} finally {
|
|
49
|
+
app.pending -= 1;
|
|
50
|
+
if (app.replaced && app.pending === 0) retire(app);
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
stopAll: async () => {
|
|
54
|
+
await Promise.all(Array.from(served, async (app) => {
|
|
55
|
+
app.entry.abortShutdownSignal();
|
|
56
|
+
await retire(app);
|
|
57
|
+
}));
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/cli/start-port.ts
|
|
11
63
|
const MAX_PORT = 65535;
|
|
12
64
|
/**
|
|
13
65
|
* Starts `server` on `port`. When the port is in use, it tries each next port
|
|
@@ -37,16 +89,16 @@ async function listenFromPort(server, { port, hostname, strictPort, onPortInUse,
|
|
|
37
89
|
}
|
|
38
90
|
throw new Error(`No open port from ${port} to ${MAX_PORT}.`);
|
|
39
91
|
}
|
|
40
|
-
function bind(server, port, hostname) {
|
|
92
|
+
async function bind(server, port, hostname) {
|
|
41
93
|
return new Promise((resolve, reject) => {
|
|
42
|
-
|
|
94
|
+
function onError(error) {
|
|
43
95
|
server.off("listening", onListening);
|
|
44
96
|
reject(error);
|
|
45
|
-
}
|
|
46
|
-
|
|
97
|
+
}
|
|
98
|
+
function onListening() {
|
|
47
99
|
server.off("error", onError);
|
|
48
100
|
resolve();
|
|
49
|
-
}
|
|
101
|
+
}
|
|
50
102
|
server.once("error", onError);
|
|
51
103
|
server.once("listening", onListening);
|
|
52
104
|
server.listen(port, hostname);
|
|
@@ -75,57 +127,7 @@ function isAddressInUse(error) {
|
|
|
75
127
|
return error instanceof Error && "code" in error && error.code === "EADDRINUSE";
|
|
76
128
|
}
|
|
77
129
|
|
|
78
|
-
// src/
|
|
79
|
-
/**
|
|
80
|
-
* Tracks the apps that `app-server start` serves. An edit to `server.ts` makes a
|
|
81
|
-
* new app, and the old app's plugins still hold what their `setup` opened.
|
|
82
|
-
* When the last request that the old app took returns, its `onShutdown` hooks
|
|
83
|
-
* run, and the tracker lets go of it. A route edit makes a new entry with the
|
|
84
|
-
* same app, which keeps its plugins.
|
|
85
|
-
*/
|
|
86
|
-
function servedApps() {
|
|
87
|
-
let current;
|
|
88
|
-
const served = /* @__PURE__ */ new Set();
|
|
89
|
-
const retire = (app) => {
|
|
90
|
-
served.delete(app);
|
|
91
|
-
app.entry.stopPlugins();
|
|
92
|
-
};
|
|
93
|
-
return {
|
|
94
|
-
/** Runs `handle` for a request that `entry` serves. */
|
|
95
|
-
serve: async (entry, handle) => {
|
|
96
|
-
if (current?.entry.app === entry.app) current.entry = entry;
|
|
97
|
-
else {
|
|
98
|
-
if (current != null) {
|
|
99
|
-
current.replaced = true;
|
|
100
|
-
if (current.pending === 0) retire(current);
|
|
101
|
-
}
|
|
102
|
-
current = {
|
|
103
|
-
entry,
|
|
104
|
-
pending: 0,
|
|
105
|
-
replaced: false
|
|
106
|
-
};
|
|
107
|
-
served.add(current);
|
|
108
|
-
}
|
|
109
|
-
const app = current;
|
|
110
|
-
app.pending += 1;
|
|
111
|
-
try {
|
|
112
|
-
return await handle(entry);
|
|
113
|
-
} finally {
|
|
114
|
-
app.pending -= 1;
|
|
115
|
-
if (app.replaced && app.pending === 0) retire(app);
|
|
116
|
-
}
|
|
117
|
-
},
|
|
118
|
-
/** At exit: aborts `shutdownSignal()` and runs the `onShutdown` hooks of each app still held. */
|
|
119
|
-
stopAll: () => {
|
|
120
|
-
for (const app of served) {
|
|
121
|
-
app.entry.abortShutdownSignal();
|
|
122
|
-
retire(app);
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
};
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
// src/start.ts
|
|
130
|
+
// src/cli/start.ts
|
|
129
131
|
/**
|
|
130
132
|
* Runs the app in development: the same pipeline as production, with Vite in
|
|
131
133
|
* middleware mode inside it. Each request loads the server entry through
|
|
@@ -147,24 +149,24 @@ async function start() {
|
|
|
147
149
|
appType: "custom"
|
|
148
150
|
});
|
|
149
151
|
const ssrRunner = () => {
|
|
150
|
-
const ssr = viteServer.environments
|
|
152
|
+
const { ssr } = viteServer.environments;
|
|
151
153
|
if (ssr == null || !vite.isRunnableDevEnvironment(ssr)) throw new Error("Vite's SSR environment cannot run modules.");
|
|
152
154
|
return ssr.runner;
|
|
153
155
|
};
|
|
154
156
|
ssrRunner();
|
|
155
|
-
|
|
157
|
+
if (!viteServer.config.plugins.some((plugin) => plugin.name === "@ngrok/app-server")) {
|
|
158
|
+
await viteServer.close();
|
|
159
|
+
throw new Error("`app-server start` needs the `appServer` plugin from @ngrok/app-server/vite in the Vite config.");
|
|
160
|
+
}
|
|
161
|
+
const devServer = devServerStage(viteServer.middlewares, { publicFiles: () => ({
|
|
162
|
+
directory: viteServer.config.publicDir,
|
|
163
|
+
base: viteServer.config.base
|
|
164
|
+
}) });
|
|
156
165
|
const sink = jsonSink();
|
|
157
166
|
const apps = servedApps();
|
|
158
|
-
const listener =
|
|
167
|
+
const listener = requestListener(async (request, bindings) => {
|
|
159
168
|
try {
|
|
160
|
-
|
|
161
|
-
remoteAddress: incoming.socket.remoteAddress,
|
|
162
|
-
...incoming instanceof IncomingMessage && outgoing instanceof ServerResponse ? {
|
|
163
|
-
incoming,
|
|
164
|
-
outgoing
|
|
165
|
-
} : {}
|
|
166
|
-
}, viteServer.middlewares));
|
|
167
|
-
return await cancelIfClosed(response, outgoing);
|
|
169
|
+
return await apps.serve(await loadEntry(await ssrRunner().import(SERVER_ENTRY_ID)), async (entry) => entry.fetchDev(request, bindings, devServer));
|
|
168
170
|
} catch (error) {
|
|
169
171
|
if (error instanceof Error) viteServer.ssrFixStacktrace(error);
|
|
170
172
|
sink.log("error", "dev request failed", errorAttributes(error));
|
|
@@ -178,8 +180,7 @@ async function start() {
|
|
|
178
180
|
listener(request, response);
|
|
179
181
|
});
|
|
180
182
|
const port = process.env.PORT == null ? viteServer.config.server.port : parsePort(process.env.PORT);
|
|
181
|
-
const
|
|
182
|
-
const hostname = process.env.HOST || (configuredHost === true ? void 0 : configuredHost || "localhost");
|
|
183
|
+
const hostname = process.env.HOST || viteHostname(viteServer.config.server.host);
|
|
183
184
|
const boundPort = await listenFromPort(httpServer, {
|
|
184
185
|
port,
|
|
185
186
|
hostname,
|
|
@@ -196,15 +197,29 @@ async function start() {
|
|
|
196
197
|
});
|
|
197
198
|
sink.log("info", "listening", { "app_server.urls": [listenerUrl(hostname, boundPort)] });
|
|
198
199
|
for (const signal of ["SIGTERM", "SIGINT"]) process.once(signal, () => {
|
|
199
|
-
apps.stopAll();
|
|
200
|
+
const pluginsStopped = apps.stopAll();
|
|
200
201
|
httpServer.closeAllConnections();
|
|
201
|
-
|
|
202
|
-
|
|
202
|
+
const httpClosed = new Promise((resolve) => {
|
|
203
|
+
httpServer.close(() => {
|
|
204
|
+
resolve();
|
|
205
|
+
});
|
|
206
|
+
});
|
|
207
|
+
const viteClosed = viteServer.close().catch((error) => {
|
|
203
208
|
sink.log("error", "Vite close failed", errorAttributes(error));
|
|
204
209
|
process.exitCode = 1;
|
|
205
210
|
});
|
|
211
|
+
Promise.all([
|
|
212
|
+
pluginsStopped,
|
|
213
|
+
httpClosed,
|
|
214
|
+
viteClosed
|
|
215
|
+
]).finally(exitAfterFlush);
|
|
206
216
|
});
|
|
207
217
|
}
|
|
218
|
+
/** The hostname for Vite's `server.host`: `true` is every interface, and no value is `localhost`. */
|
|
219
|
+
function viteHostname(host) {
|
|
220
|
+
if (host === true) return;
|
|
221
|
+
return typeof host === "string" && host !== "" ? host : "localhost";
|
|
222
|
+
}
|
|
208
223
|
|
|
209
224
|
export { start };
|
|
210
|
-
//# sourceMappingURL=start-
|
|
225
|
+
//# sourceMappingURL=start-TLIprD74.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"start-TLIprD74.js","names":["createServer","createHttpServer"],"sources":["../src/cli/served-apps.ts","../src/cli/start-port.ts","../src/cli/start.ts"],"sourcesContent":["import type { AppServerEntry } from \"../core/entry.js\";\n\ntype ServedApp = { entry: AppServerEntry; pending: number; replaced: boolean };\n\n/** What {@link servedApps} returns. */\ntype ServedApps = {\n\t/** Runs `handle` for a request that `entry` serves. */\n\tserve: <Result>(\n\t\tentry: AppServerEntry,\n\t\thandle: (entry: AppServerEntry) => Promise<Result>,\n\t) => Promise<Result>;\n\t/**\n\t * At exit: aborts `shutdownSignal()` and runs the `onShutdown` hooks of each\n\t * app still held. Resolves when the hooks finish or pass the deadline.\n\t */\n\tstopAll: () => Promise<void>;\n};\n\n/**\n * Tracks the apps that `app-server start` serves. An edit to `server.ts` makes a\n * new app, and the old app's plugins still hold what their `setup` opened.\n * When the last request that the old app took returns, its `onShutdown` hooks\n * run, and the tracker lets go of it. A route edit makes a new entry with the\n * same app, which keeps its plugins.\n */\nexport function servedApps(): ServedApps {\n\tlet current: ServedApp | undefined;\n\tconst served = new Set<ServedApp>();\n\t// Why keep the app until its hooks settle: `stopAll` must wait for hooks that already run.\n\t// `stopPlugins` runs the hooks once, so a second call only waits.\n\tconst retire = async (app: ServedApp) => {\n\t\ttry {\n\t\t\tawait app.entry.stopPlugins();\n\t\t} finally {\n\t\t\tserved.delete(app);\n\t\t}\n\t};\n\treturn {\n\t\tserve: async (entry, handle) => {\n\t\t\tif (current?.entry.app === entry.app) {\n\t\t\t\tcurrent.entry = entry;\n\t\t\t} else {\n\t\t\t\tif (current != null) {\n\t\t\t\t\tcurrent.replaced = true;\n\t\t\t\t\tif (current.pending === 0) {\n\t\t\t\t\t\tvoid retire(current);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent = { entry, pending: 0, replaced: false };\n\t\t\t\tserved.add(current);\n\t\t\t}\n\t\t\tconst app = current;\n\t\t\tapp.pending += 1;\n\t\t\ttry {\n\t\t\t\treturn await handle(entry);\n\t\t\t} finally {\n\t\t\t\tapp.pending -= 1;\n\t\t\t\tif (app.replaced && app.pending === 0) {\n\t\t\t\t\tvoid retire(app);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tstopAll: async () => {\n\t\t\tawait Promise.all(\n\t\t\t\tArray.from(served, async (app) => {\n\t\t\t\t\tapp.entry.abortShutdownSignal();\n\t\t\t\t\tawait retire(app);\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t};\n}\n","import { createServer } from \"node:net\";\nimport type { Server } from \"node:net\";\n\nconst MAX_PORT = 65_535;\n\n/** Options for {@link listenFromPort}. */\nexport type ListenFromPortOptions = {\n\t/** The first port to try. 0 lets the OS pick one. */\n\tport: number;\n\t/** @default every interface */\n\thostname?: string | undefined;\n\t/** When true, a port in use throws and no other port is tried. */\n\tstrictPort: boolean;\n\t/** Runs for each port in use before the next port is tried. */\n\tonPortInUse?: (port: number) => void;\n\t/**\n\t * Runs when `strictPort` is true and the server listens on `hostname`, but\n\t * another server holds the port on a wildcard address.\n\t */\n\tonWildcardInUse?: (port: number) => void;\n};\n\n/**\n * Starts `server` on `port`. When the port is in use, it tries each next port\n * up to 65535, like Vite and `react-router-serve` do in development.\n *\n * @returns the port that the server listens on\n */\nexport async function listenFromPort(\n\tserver: Server,\n\t{ port, hostname, strictPort, onPortInUse, onWildcardInUse }: ListenFromPortOptions,\n): Promise<number> {\n\tif (port === 0) {\n\t\tawait bind(server, port, hostname);\n\t\treturn boundPort(server, port);\n\t}\n\tif (strictPort) {\n\t\t// Why a warning and not an error: a server on one other address also fails the wildcard\n\t\t// check, and that server does not share `hostname`. Vite warns for the same reason.\n\t\tconst freeOnWildcard = hostname == null || (await isFreeOnWildcard(port));\n\t\tawait bind(server, port, hostname);\n\t\tif (!freeOnWildcard) {\n\t\t\tonWildcardInUse?.(port);\n\t\t}\n\t\treturn port;\n\t}\n\tfor (let candidate = port; candidate <= MAX_PORT; candidate++) {\n\t\t// Why the wildcard check: a server on `::` and a server on `localhost` can share a port, and\n\t\t// then the browser can reach the other server.\n\t\tif (hostname == null || (await isFreeOnWildcard(candidate))) {\n\t\t\ttry {\n\t\t\t\tawait bind(server, candidate, hostname);\n\t\t\t\treturn candidate;\n\t\t\t} catch (error) {\n\t\t\t\tif (!isAddressInUse(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tonPortInUse?.(candidate);\n\t}\n\tthrow new Error(`No open port from ${port} to ${MAX_PORT}.`);\n}\n\nasync function bind(server: Server, port: number, hostname: string | undefined): Promise<void> {\n\treturn new Promise<void>((resolve, reject) => {\n\t\tfunction onError(error: Error) {\n\t\t\tserver.off(\"listening\", onListening);\n\t\t\treject(error);\n\t\t}\n\t\tfunction onListening() {\n\t\t\tserver.off(\"error\", onError);\n\t\t\tresolve();\n\t\t}\n\t\tserver.once(\"error\", onError);\n\t\tserver.once(\"listening\", onListening);\n\t\tserver.listen(port, hostname);\n\t});\n}\n\nasync function isFreeOnWildcard(port: number): Promise<boolean> {\n\tconst probe = createServer();\n\ttry {\n\t\tawait bind(probe, port, undefined);\n\t} catch (error) {\n\t\tif (isAddressInUse(error)) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow error;\n\t}\n\tawait new Promise<void>((resolve) => {\n\t\tprobe.close(() => {\n\t\t\tresolve();\n\t\t});\n\t});\n\treturn true;\n}\n\nfunction boundPort(server: Server, fallback: number): number {\n\tconst address = server.address();\n\treturn typeof address === \"object\" && address != null ? address.port : fallback;\n}\n\nfunction isAddressInUse(error: unknown): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === \"EADDRINUSE\";\n}\n","import { createServer as createHttpServer } from \"node:http\";\nimport { errorAttributes, jsonSink } from \"../core/log.js\";\nimport { devServerStage } from \"../node/dev-server.js\";\nimport { exitAfterFlush } from \"../node/exit.js\";\nimport { listenerUrl } from \"../node/runtimes/listen-options.js\";\nimport { requestListener } from \"../node/response-writer.js\";\nimport { parsePort } from \"../node/tcp.js\";\nimport { SERVER_ENTRY_ID } from \"../vite/index.js\";\nimport { loadEntry } from \"./load-entry.js\";\nimport { servedApps } from \"./served-apps.js\";\nimport { listenFromPort } from \"./start-port.js\";\n\n/**\n * Runs the app in development: the same pipeline as production, with Vite in\n * middleware mode inside it. Each request loads the server entry through\n * Vite's SSR runner, so an edit to a route or to the app's `server.ts` applies\n * at once. HMR shares the port.\n *\n * The port is `--port`, else `PORT`, else Vite's `server.port`. When that port is in use, the\n * server tries each next port, unless Vite's `server.strictPort` is true. The\n * host is `HOST`, else Vite's `server.host`.\n */\nexport async function start(): Promise<void> {\n\tconst vite = await import(\"vite\");\n\tconst httpServer = createHttpServer();\n\tconst viteServer = await vite.createServer({\n\t\tserver: { middlewareMode: true, ws: { server: httpServer } },\n\t\tappType: \"custom\",\n\t});\n\t// Why read it for each request: a Vite restart, such as after a config edit, replaces the environments.\n\tconst ssrRunner = () => {\n\t\tconst { ssr } = viteServer.environments;\n\t\tif (ssr == null || !vite.isRunnableDevEnvironment(ssr)) {\n\t\t\tthrow new Error(\"Vite's SSR environment cannot run modules.\");\n\t\t}\n\t\treturn ssr.runner;\n\t};\n\tssrRunner();\n\tif (!viteServer.config.plugins.some((plugin) => plugin.name === \"@ngrok/app-server\")) {\n\t\tawait viteServer.close();\n\t\tthrow new Error(\n\t\t\t\"`app-server start` needs the `appServer` plugin from @ngrok/app-server/vite in the Vite config.\",\n\t\t);\n\t}\n\tconst devServer = devServerStage(viteServer.middlewares, {\n\t\tpublicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),\n\t});\n\tconst sink = jsonSink();\n\tconst apps = servedApps();\n\n\tconst listener = requestListener(async (request, bindings) => {\n\t\ttry {\n\t\t\treturn await apps.serve(\n\t\t\t\tawait loadEntry(await ssrRunner().import(SERVER_ENTRY_ID)),\n\t\t\t\tasync (entry) => entry.fetchDev(request, bindings, devServer),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tviteServer.ssrFixStacktrace(error);\n\t\t\t}\n\t\t\tsink.log(\"error\", \"dev request failed\", errorAttributes(error));\n\t\t\treturn new Response(error instanceof Error ? (error.stack ?? error.message) : String(error), {\n\t\t\t\tstatus: 500,\n\t\t\t\theaders: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n\t\t\t});\n\t\t}\n\t});\n\thttpServer.on(\"request\", (request, response) => {\n\t\tvoid listener(request, response);\n\t});\n\n\tconst port =\n\t\tprocess.env.PORT == null ? viteServer.config.server.port : parsePort(process.env.PORT);\n\tconst hostname = process.env.HOST || viteHostname(viteServer.config.server.host);\n\tconst boundPort = await listenFromPort(httpServer, {\n\t\tport,\n\t\thostname,\n\t\tstrictPort: viteServer.config.server.strictPort,\n\t\tonPortInUse: (inUse) => {\n\t\t\tsink.log(\"info\", \"port in use, trying the next port\", { \"server.port\": inUse });\n\t\t},\n\t\tonWildcardInUse: (inUse) => {\n\t\t\tsink.log(\"warn\", \"port in use on a wildcard address\", {\n\t\t\t\t\"server.port\": inUse,\n\t\t\t\t\"server.address\": hostname,\n\t\t\t});\n\t\t},\n\t});\n\tsink.log(\"info\", \"listening\", { \"app_server.urls\": [listenerUrl(hostname, boundPort)] });\n\n\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\tprocess.once(signal, () => {\n\t\t\tconst pluginsStopped = apps.stopAll();\n\t\t\thttpServer.closeAllConnections();\n\t\t\tconst httpClosed = new Promise<void>((resolve) => {\n\t\t\t\thttpServer.close(() => {\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t});\n\t\t\tconst viteClosed = viteServer.close().catch((error: unknown) => {\n\t\t\t\tsink.log(\"error\", \"Vite close failed\", errorAttributes(error));\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t});\n\t\t\tvoid Promise.all([pluginsStopped, httpClosed, viteClosed]).finally(exitAfterFlush);\n\t\t});\n\t}\n}\n\n/** The hostname for Vite's `server.host`: `true` is every interface, and no value is `localhost`. */\nfunction viteHostname(host: string | boolean | undefined): string | undefined {\n\tif (host === true) {\n\t\treturn undefined;\n\t}\n\treturn typeof host === \"string\" && host !== \"\" ? host : \"localhost\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyBA,SAAgB,aAAyB;CACxC,IAAI;CACJ,MAAM,yBAAS,IAAI,IAAe;CAGlC,MAAM,SAAS,OAAO,QAAmB;EACxC,IAAI;GACH,MAAM,IAAI,MAAM,YAAY;EAC7B,UAAU;GACT,OAAO,OAAO,GAAG;EAClB;CACD;CACA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eAAe;IACf,kBAAkB;GACnB,CAAC;EACF;CACD,CAAC;CACD,KAAK,IAAI,QAAQ,aAAa,EAAE,mBAAmB,CAAC,YAAY,UAAU,SAAS,CAAC,EAAE,CAAC;CAEvF,KAAK,MAAM,UAAU,CAAC,WAAW,QAAQ,GACxC,QAAQ,KAAK,cAAc;EAC1B,MAAM,iBAAiB,KAAK,QAAQ;EACpC,WAAW,oBAAoB;EAC/B,MAAM,aAAa,IAAI,SAAe,YAAY;GACjD,WAAW,YAAY;IACtB,QAAQ;GACT,CAAC;EACF,CAAC;EACD,MAAM,aAAa,WAAW,MAAM,CAAC,CAAC,OAAO,UAAmB;GAC/D,KAAK,IAAI,SAAS,qBAAqB,gBAAgB,KAAK,CAAC;GAC7D,QAAQ,WAAW;EACpB,CAAC;EACD,AAAK,QAAQ,IAAI;GAAC;GAAgB;GAAY;EAAU,CAAC,CAAC,CAAC,QAAQ,cAAc;CAClF,CAAC;AAEH;;AAGA,SAAS,aAAa,MAAwD;CAC7E,IAAI,SAAS,MACZ;CAED,OAAO,OAAO,SAAS,YAAY,SAAS,KAAK,OAAO;AACzD"}
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import { r as hookedHeaders } from "./header-hook-Vzw9J9BY.js";
|
|
2
|
+
import { i as forbidsTransform, o as preferredEncoding, r as copyName, t as COPY_ENCODINGS } from "./compression-7_gToa8R.js";
|
|
3
|
+
import { getMimeType } from "hono/utils/mime";
|
|
4
|
+
|
|
5
|
+
// src/core/vary.ts
|
|
6
|
+
/**
|
|
7
|
+
* A `Vary` value with `name` added, or `undefined` when `vary` already covers
|
|
8
|
+
* it. The existing values stay as they are.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* withVary("Accept", "Accept-Encoding"); // => "Accept, Accept-Encoding"
|
|
12
|
+
* withVary("accept-encoding", "Accept-Encoding"); // => undefined
|
|
13
|
+
*/
|
|
14
|
+
function withVary(vary, name) {
|
|
15
|
+
if (vary == null || vary.trim() === "") return name;
|
|
16
|
+
const values = new Set(vary.split(",").map((value) => value.trim().toLowerCase()));
|
|
17
|
+
return values.has(name.toLowerCase()) || values.has("*") ? void 0 : `${vary}, ${name}`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// src/core/static-files.ts
|
|
21
|
+
/** The content types that `mime` lacks and that no framework owns. */
|
|
22
|
+
const CORE_CONTENT_TYPES = { ".md": "text/markdown; charset=utf-8" };
|
|
23
|
+
/**
|
|
24
|
+
* Whether a URL path names a dotfile or goes through a dot directory.
|
|
25
|
+
* `/.well-known/` stays reachable.
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* hasDotSegment("/assets/.private/key.json"); // => true
|
|
29
|
+
* hasDotSegment("/.well-known/security.txt"); // => false
|
|
30
|
+
*/
|
|
31
|
+
function hasDotSegment(path) {
|
|
32
|
+
return path.split("/").some((segment, index) => segment.startsWith(".") && !(index === 1 && segment === ".well-known"));
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Whether a decoded URL path, such as Hono's `context.req.path`, can name a
|
|
36
|
+
* file of the client build. Dotfiles, paths that leave the client build, and
|
|
37
|
+
* a second URL for a file, such as `/a//b` or `/a/index.html`, cannot.
|
|
38
|
+
*/
|
|
39
|
+
function isFilePath(path) {
|
|
40
|
+
return path.startsWith("/") && !path.includes("\0") && !path.includes("\\") && !path.split("/").includes("..") && !path.includes("//") && !path.endsWith("/index.html") && !hasDotSegment(path);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Finds the file in `files` that answers a decoded URL path, such as Hono's
|
|
44
|
+
* `context.req.path`. A directory answers with its `index.html` and no
|
|
45
|
+
* redirect, so a prerendered page keeps its URL. A path that fails
|
|
46
|
+
* `isFilePath` finds nothing.
|
|
47
|
+
*
|
|
48
|
+
* Each file has one URL, because the headers for a file are keyed by that
|
|
49
|
+
* URL. So `/a//b`, `/a/index.html`, and `/a%2Fb` find nothing. Hono decodes
|
|
50
|
+
* the path but keeps an encoded `/` as `%2F`, so this function does not
|
|
51
|
+
* decode it again.
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* await findStaticFile(files, "/components/button");
|
|
55
|
+
* // => { path: "/components/button/index.html", size: 5120, mtimeMs: 1761652800000 }
|
|
56
|
+
*/
|
|
57
|
+
async function findStaticFile(files, path) {
|
|
58
|
+
if (!isFilePath(path)) return;
|
|
59
|
+
const info = await files.stat(path);
|
|
60
|
+
if (info?.kind === "file") return {
|
|
61
|
+
path,
|
|
62
|
+
size: info.size,
|
|
63
|
+
mtimeMs: info.mtimeMs
|
|
64
|
+
};
|
|
65
|
+
if (info?.kind === "directory") {
|
|
66
|
+
const index = `${path.replace(/\/$/u, "")}/index.html`;
|
|
67
|
+
const indexInfo = await files.stat(index);
|
|
68
|
+
if (indexInfo?.kind === "file") return {
|
|
69
|
+
path: index,
|
|
70
|
+
size: indexInfo.size,
|
|
71
|
+
mtimeMs: indexInfo.mtimeMs
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** The content type of a file, by its extension. `contentTypes` win over `mime`. */
|
|
76
|
+
function contentType(path, contentTypes) {
|
|
77
|
+
const extension = /\.[^./]+$/u.exec(path)?.[0] ?? "";
|
|
78
|
+
return contentTypes[extension] ?? CORE_CONTENT_TYPES[extension] ?? getMimeType(path) ?? "application/octet-stream";
|
|
79
|
+
}
|
|
80
|
+
/** An ETag without its weak prefix, for the weak comparison that `If-None-Match` uses. */
|
|
81
|
+
function opaqueTag(etag) {
|
|
82
|
+
return etag.trim().replace(/^W\//u, "");
|
|
83
|
+
}
|
|
84
|
+
/** Whether an `If-None-Match` header lists an ETag. */
|
|
85
|
+
function matchesEtag(ifNoneMatch, etag) {
|
|
86
|
+
return ifNoneMatch?.split(",").some((candidate) => {
|
|
87
|
+
const trimmed = candidate.trim();
|
|
88
|
+
return trimmed === "*" || opaqueTag(trimmed) === opaqueTag(etag);
|
|
89
|
+
}) ?? false;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The last `etagParts` and their hash. Why one entry: each request has the
|
|
93
|
+
* same parts for the life of the process.
|
|
94
|
+
*/
|
|
95
|
+
let lastParts;
|
|
96
|
+
/** A short hash of the request's `etagParts`. */
|
|
97
|
+
async function partsHash(parts) {
|
|
98
|
+
const key = parts.join("\0");
|
|
99
|
+
if (lastParts?.key === key) return lastParts.hash;
|
|
100
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(key));
|
|
101
|
+
const hash = btoa(String.fromCodePoint(...new Uint8Array(digest))).replaceAll("+", "-").replaceAll("/", "_").slice(0, 16);
|
|
102
|
+
lastParts = {
|
|
103
|
+
key,
|
|
104
|
+
hash
|
|
105
|
+
};
|
|
106
|
+
return hash;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* A weak ETag from a file's size, its modification time, the request's
|
|
110
|
+
* `etagParts`, and the encoding of the body. Why the encoding: after a 304,
|
|
111
|
+
* a cache that holds more than one encoding of the file picks the stored
|
|
112
|
+
* response by its ETag (RFC 9111, section 4.3.4).
|
|
113
|
+
*/
|
|
114
|
+
async function fileEtag(file, parts, encoding) {
|
|
115
|
+
return `W/"${[
|
|
116
|
+
file.size.toString(16),
|
|
117
|
+
Math.trunc(file.mtimeMs).toString(16),
|
|
118
|
+
...parts.length === 0 ? [] : [await partsHash(parts)],
|
|
119
|
+
...encoding == null ? [] : [encoding]
|
|
120
|
+
].join("-")}"`;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* The byte range that a `Range` header asks for in a file of `size` bytes.
|
|
124
|
+
* It gives `"unsatisfiable"` for a range that starts after the end of the
|
|
125
|
+
* file, and `undefined` for a header to ignore: a header that is not valid,
|
|
126
|
+
* or one with more than one range.
|
|
127
|
+
*
|
|
128
|
+
* @example
|
|
129
|
+
* byteRange("bytes=-100", 1000); // => { start: 900, end: 999 }
|
|
130
|
+
*/
|
|
131
|
+
function byteRange(header, size) {
|
|
132
|
+
const groups = /^bytes=(?<first>\d*)-(?<last>\d*)$/u.exec(header.trim())?.groups;
|
|
133
|
+
const first = groups?.first ?? "";
|
|
134
|
+
const last = groups?.last ?? "";
|
|
135
|
+
if (first === "" && last === "") return;
|
|
136
|
+
if (first === "") {
|
|
137
|
+
const suffix = Number(last);
|
|
138
|
+
return suffix === 0 || size === 0 ? "unsatisfiable" : {
|
|
139
|
+
start: Math.max(0, size - suffix),
|
|
140
|
+
end: size - 1
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
const start = Number(first);
|
|
144
|
+
const end = last === "" ? Number.POSITIVE_INFINITY : Number(last);
|
|
145
|
+
if (end < start) return;
|
|
146
|
+
return start >= size ? "unsatisfiable" : {
|
|
147
|
+
start,
|
|
148
|
+
end: Math.min(end, size - 1)
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
/** Why these caps: they hold the hashed chunks of a typical app, and they limit the memory of each process. */
|
|
152
|
+
const KEPT_FILE_BYTES = 262144;
|
|
153
|
+
const KEPT_TOTAL_BYTES = 33554432;
|
|
154
|
+
/**
|
|
155
|
+
* `files` that keep the bytes of each small file in memory after the first
|
|
156
|
+
* read, up to {@link KEPT_TOTAL_BYTES} in all. Use it only for files that
|
|
157
|
+
* do not change while the server runs, such as a `StaticFiles.snapshot()`.
|
|
158
|
+
*
|
|
159
|
+
* @example
|
|
160
|
+
* const files = keptFiles(await nodeFiles("build/client").snapshot());
|
|
161
|
+
*/
|
|
162
|
+
function keptFiles(files) {
|
|
163
|
+
const kept = /* @__PURE__ */ new Map();
|
|
164
|
+
let total = 0;
|
|
165
|
+
return {
|
|
166
|
+
stat: files.stat,
|
|
167
|
+
open: async (path, range) => {
|
|
168
|
+
let bytes = kept.get(path);
|
|
169
|
+
const info = bytes == null ? await files.stat(path) : void 0;
|
|
170
|
+
bytes ??= kept.get(path);
|
|
171
|
+
if (bytes == null) {
|
|
172
|
+
if (info?.kind !== "file" || info.size > KEPT_FILE_BYTES || total + info.size > KEPT_TOTAL_BYTES) return files.open(path, range);
|
|
173
|
+
total += info.size;
|
|
174
|
+
bytes = files.open(path, {
|
|
175
|
+
start: 0,
|
|
176
|
+
end: info.size - 1
|
|
177
|
+
}).then(async (stream) => new Uint8Array(await new Response(stream).arrayBuffer()));
|
|
178
|
+
kept.set(path, bytes);
|
|
179
|
+
bytes.catch(() => {
|
|
180
|
+
kept.delete(path);
|
|
181
|
+
total -= info.size;
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
const chunk = (await bytes).slice(range?.start ?? 0, range == null ? void 0 : range.end + 1);
|
|
185
|
+
return new ReadableStream({ start(controller) {
|
|
186
|
+
controller.enqueue(chunk);
|
|
187
|
+
controller.close();
|
|
188
|
+
} });
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* The copy of the file at `path` that the request prefers, from the copies
|
|
194
|
+
* that the build wrote. When a copy exists, it adds `Accept-Encoding` to the
|
|
195
|
+
* `Vary` in `headers`, also for a request that gets no copy.
|
|
196
|
+
*/
|
|
197
|
+
async function preferredCopy(context, { files, path, headers }) {
|
|
198
|
+
if (headers.has("Content-Encoding") || context.get("rewritesHtml") === true && (headers.get("Content-Type")?.startsWith("text/html") ?? false)) return;
|
|
199
|
+
const copies = [];
|
|
200
|
+
for (const encoding of COPY_ENCODINGS) {
|
|
201
|
+
const copyPath = path.replace(/[^/]*$/u, (name) => copyName(name, encoding));
|
|
202
|
+
const info = await files.stat(copyPath);
|
|
203
|
+
if (info?.kind === "file") copies.push({
|
|
204
|
+
path: copyPath,
|
|
205
|
+
size: info.size,
|
|
206
|
+
mtimeMs: info.mtimeMs,
|
|
207
|
+
encoding
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
if (copies.length === 0) return;
|
|
211
|
+
const vary = withVary(headers.get("Vary"), "Accept-Encoding");
|
|
212
|
+
if (vary != null) headers.set("Vary", vary);
|
|
213
|
+
if (forbidsTransform(hookedHeaders(context, headers).get("Cache-Control"))) return;
|
|
214
|
+
const encoding = preferredEncoding(context.req.header("Accept-Encoding"), copies.map((copy) => copy.encoding));
|
|
215
|
+
return copies.find((copy) => copy.encoding === encoding);
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* All bytes of a file. Why the size as a range: the body then never has more
|
|
219
|
+
* bytes than its `Content-Length`, even when the file grew after `stat`, and
|
|
220
|
+
* a small file reads into a small buffer.
|
|
221
|
+
*/
|
|
222
|
+
async function wholeFile(files, file) {
|
|
223
|
+
return file.size === 0 ? null : files.open(file.path, {
|
|
224
|
+
start: 0,
|
|
225
|
+
end: file.size - 1
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* The response for a static file, with a weak ETag from its size,
|
|
230
|
+
* modification time, the request's `etagParts`, and its encoding. A matching
|
|
231
|
+
* `If-None-Match` gets a 304, and `HEAD` gets the headers only.
|
|
232
|
+
*
|
|
233
|
+
* A GET with one `bytes` range gets a 206 with those bytes, and a range
|
|
234
|
+
* after the end of the file gets a 416. A request with `If-Range` gets the
|
|
235
|
+
* full file. Why: the ETag is weak, and `If-Range` needs a strong match. An
|
|
236
|
+
* HTML file gets no ranges.
|
|
237
|
+
*
|
|
238
|
+
* When the build wrote a compressed copy of the file (`.<file>.br` or
|
|
239
|
+
* `.<file>.gz`), the response gets `Vary: Accept-Encoding`. A request gets
|
|
240
|
+
* the copy that its `Accept-Encoding` prefers, brotli before gzip, with its
|
|
241
|
+
* `Content-Encoding`, an ETag for that encoding, and no range. A response
|
|
242
|
+
* marked `no-transform`, also by the header hook of an earlier stage, and a
|
|
243
|
+
* response that `headers` encode, never get a copy. An HTML file gets no
|
|
244
|
+
* copy when an earlier stage sets `rewritesHtml`.
|
|
245
|
+
*
|
|
246
|
+
* @example
|
|
247
|
+
* const file = await findStaticFile(files, "/llms.txt");
|
|
248
|
+
* if (file != null) {
|
|
249
|
+
* return staticResponse(context, { files, file, headers: {}, contentTypes: {} });
|
|
250
|
+
* }
|
|
251
|
+
*/
|
|
252
|
+
async function staticResponse(context, { files, file, headers, contentTypes }) {
|
|
253
|
+
const responseHeaders = new Headers({ "Content-Type": contentType(file.path, contentTypes) });
|
|
254
|
+
for (const [name, value] of Object.entries(headers)) responseHeaders.set(name, value);
|
|
255
|
+
const html = responseHeaders.get("Content-Type")?.startsWith("text/html") ?? false;
|
|
256
|
+
if (html) context.set("staticDocument", file.path);
|
|
257
|
+
const copy = await preferredCopy(context, {
|
|
258
|
+
files,
|
|
259
|
+
path: file.path,
|
|
260
|
+
headers: responseHeaders
|
|
261
|
+
});
|
|
262
|
+
const etag = responseHeaders.get("ETag") ?? await fileEtag(file, context.get("etagParts") ?? [], copy?.encoding);
|
|
263
|
+
responseHeaders.set("ETag", etag);
|
|
264
|
+
if (matchesEtag(context.req.header("If-None-Match"), etag)) {
|
|
265
|
+
responseHeaders.delete("Content-Type");
|
|
266
|
+
return new Response(null, {
|
|
267
|
+
status: 304,
|
|
268
|
+
headers: responseHeaders
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
if (copy != null) {
|
|
272
|
+
responseHeaders.set("Content-Encoding", copy.encoding);
|
|
273
|
+
responseHeaders.set("Content-Length", String(copy.size));
|
|
274
|
+
const body = context.req.method === "HEAD" ? null : await wholeFile(files, copy);
|
|
275
|
+
return new Response(body, { headers: responseHeaders });
|
|
276
|
+
}
|
|
277
|
+
if (!html) responseHeaders.set("Accept-Ranges", "bytes");
|
|
278
|
+
responseHeaders.set("Content-Length", String(file.size));
|
|
279
|
+
if (context.req.method === "HEAD") return new Response(null, { headers: responseHeaders });
|
|
280
|
+
const rangeHeader = context.req.header("Range");
|
|
281
|
+
const range = html || rangeHeader == null || context.req.header("If-Range") != null ? void 0 : byteRange(rangeHeader, file.size);
|
|
282
|
+
if (range === "unsatisfiable") {
|
|
283
|
+
responseHeaders.set("Content-Range", `bytes */${file.size}`);
|
|
284
|
+
responseHeaders.delete("Content-Length");
|
|
285
|
+
return new Response(null, {
|
|
286
|
+
status: 416,
|
|
287
|
+
headers: responseHeaders
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
if (range != null) {
|
|
291
|
+
responseHeaders.set("Content-Range", `bytes ${range.start}-${range.end}/${file.size}`);
|
|
292
|
+
responseHeaders.set("Content-Length", String(range.end - range.start + 1));
|
|
293
|
+
return new Response(await files.open(file.path, range), {
|
|
294
|
+
status: 206,
|
|
295
|
+
headers: responseHeaders
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
return new Response(await wholeFile(files, file), { headers: responseHeaders });
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
export { keptFiles as a, isFilePath as i, findStaticFile as n, staticResponse as o, hasDotSegment as r, withVary as s, contentType as t };
|
|
302
|
+
//# sourceMappingURL=static-files-Beju9riB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"static-files-Beju9riB.js","names":[],"sources":["../src/core/vary.ts","../src/core/static-files.ts"],"sourcesContent":["/**\n * A `Vary` value with `name` added, or `undefined` when `vary` already covers\n * it. The existing values stay as they are.\n *\n * @example\n * withVary(\"Accept\", \"Accept-Encoding\"); // => \"Accept, Accept-Encoding\"\n * withVary(\"accept-encoding\", \"Accept-Encoding\"); // => undefined\n */\nexport function withVary(vary: string | null, name: string): string | undefined {\n\tif (vary == null || vary.trim() === \"\") {\n\t\treturn name;\n\t}\n\tconst values = new Set(vary.split(\",\").map((value) => value.trim().toLowerCase()));\n\treturn values.has(name.toLowerCase()) || values.has(\"*\") ? undefined : `${vary}, ${name}`;\n}\n","import type { Context } from \"hono\";\nimport { getMimeType } from \"hono/utils/mime\";\nimport { COPY_ENCODINGS, copyName, forbidsTransform, preferredEncoding } from \"./compression.js\";\nimport type { Encoding } from \"./compression.js\";\nimport { hookedHeaders } from \"./header-hook.js\";\nimport type { AppServerEnv, ByteRange, StaticFiles } from \"./types.js\";\nimport { withVary } from \"./vary.js\";\n\n/** A file under the client build that answers a request. */\nexport type StaticFile = {\n\t/** The URL path of the file, such as `/components/button/index.html`. */\n\tpath: string;\n\tsize: number;\n\tmtimeMs: number;\n};\n\n/** The content types that `mime` lacks and that no framework owns. */\nconst CORE_CONTENT_TYPES: Readonly<Record<string, string>> = {\n\t\".md\": \"text/markdown; charset=utf-8\",\n};\n\n/**\n * Whether a URL path names a dotfile or goes through a dot directory.\n * `/.well-known/` stays reachable.\n *\n * @example\n * hasDotSegment(\"/assets/.private/key.json\"); // => true\n * hasDotSegment(\"/.well-known/security.txt\"); // => false\n */\nexport function hasDotSegment(path: string): boolean {\n\treturn path\n\t\t.split(\"/\")\n\t\t.some(\n\t\t\t(segment, index) => segment.startsWith(\".\") && !(index === 1 && segment === \".well-known\"),\n\t\t);\n}\n\n/**\n * Whether a decoded URL path, such as Hono's `context.req.path`, can name a\n * file of the client build. Dotfiles, paths that leave the client build, and\n * a second URL for a file, such as `/a//b` or `/a/index.html`, cannot.\n */\nexport function isFilePath(path: string): boolean {\n\treturn (\n\t\tpath.startsWith(\"/\") &&\n\t\t!path.includes(\"\\0\") &&\n\t\t!path.includes(\"\\\\\") &&\n\t\t!path.split(\"/\").includes(\"..\") &&\n\t\t!path.includes(\"//\") &&\n\t\t!path.endsWith(\"/index.html\") &&\n\t\t!hasDotSegment(path)\n\t);\n}\n\n/**\n * Finds the file in `files` that answers a decoded URL path, such as Hono's\n * `context.req.path`. A directory answers with its `index.html` and no\n * redirect, so a prerendered page keeps its URL. A path that fails\n * `isFilePath` finds nothing.\n *\n * Each file has one URL, because the headers for a file are keyed by that\n * URL. So `/a//b`, `/a/index.html`, and `/a%2Fb` find nothing. Hono decodes\n * the path but keeps an encoded `/` as `%2F`, so this function does not\n * decode it again.\n *\n * @example\n * await findStaticFile(files, \"/components/button\");\n * // => { path: \"/components/button/index.html\", size: 5120, mtimeMs: 1761652800000 }\n */\nexport async function findStaticFile(\n\tfiles: StaticFiles,\n\tpath: string,\n): Promise<StaticFile | undefined> {\n\tif (!isFilePath(path)) {\n\t\treturn undefined;\n\t}\n\tconst info = await files.stat(path);\n\tif (info?.kind === \"file\") {\n\t\treturn { path, size: info.size, mtimeMs: info.mtimeMs };\n\t}\n\tif (info?.kind === \"directory\") {\n\t\tconst index = `${path.replace(/\\/$/u, \"\")}/index.html`;\n\t\tconst indexInfo = await files.stat(index);\n\t\tif (indexInfo?.kind === \"file\") {\n\t\t\treturn { path: index, size: indexInfo.size, mtimeMs: indexInfo.mtimeMs };\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** The content type of a file, by its extension. `contentTypes` win over `mime`. */\nexport function contentType(path: string, contentTypes: Readonly<Record<string, string>>): string {\n\tconst extension = /\\.[^./]+$/u.exec(path)?.[0] ?? \"\";\n\treturn (\n\t\tcontentTypes[extension] ??\n\t\tCORE_CONTENT_TYPES[extension] ??\n\t\tgetMimeType(path) ??\n\t\t\"application/octet-stream\"\n\t);\n}\n\n/** An ETag without its weak prefix, for the weak comparison that `If-None-Match` uses. */\nfunction opaqueTag(etag: string): string {\n\treturn etag.trim().replace(/^W\\//u, \"\");\n}\n\n/** Whether an `If-None-Match` header lists an ETag. */\nfunction matchesEtag(ifNoneMatch: string | undefined, etag: string): boolean {\n\treturn (\n\t\tifNoneMatch?.split(\",\").some((candidate) => {\n\t\t\tconst trimmed = candidate.trim();\n\t\t\treturn trimmed === \"*\" || opaqueTag(trimmed) === opaqueTag(etag);\n\t\t}) ?? false\n\t);\n}\n\n/**\n * The last `etagParts` and their hash. Why one entry: each request has the\n * same parts for the life of the process.\n */\nlet lastParts: { key: string; hash: string } | undefined;\n\n/** A short hash of the request's `etagParts`. */\nasync function partsHash(parts: readonly string[]): Promise<string> {\n\tconst key = parts.join(\"\\0\");\n\tif (lastParts?.key === key) {\n\t\treturn lastParts.hash;\n\t}\n\t// Why Web Crypto: each host has it, and the core imports no Node module.\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(key));\n\tconst hash = btoa(String.fromCodePoint(...new Uint8Array(digest)))\n\t\t.replaceAll(\"+\", \"-\")\n\t\t.replaceAll(\"/\", \"_\")\n\t\t.slice(0, 16);\n\tlastParts = { key, hash };\n\treturn hash;\n}\n\n/**\n * A weak ETag from a file's size, its modification time, the request's\n * `etagParts`, and the encoding of the body. Why the encoding: after a 304,\n * a cache that holds more than one encoding of the file picks the stored\n * response by its ETag (RFC 9111, section 4.3.4).\n */\nasync function fileEtag(\n\tfile: StaticFile,\n\tparts: readonly string[],\n\tencoding: Encoding | undefined,\n): Promise<string> {\n\tconst tag = [\n\t\tfile.size.toString(16),\n\t\tMath.trunc(file.mtimeMs).toString(16),\n\t\t...(parts.length === 0 ? [] : [await partsHash(parts)]),\n\t\t...(encoding == null ? [] : [encoding]),\n\t];\n\treturn `W/\"${tag.join(\"-\")}\"`;\n}\n\n/**\n * The byte range that a `Range` header asks for in a file of `size` bytes.\n * It gives `\"unsatisfiable\"` for a range that starts after the end of the\n * file, and `undefined` for a header to ignore: a header that is not valid,\n * or one with more than one range.\n *\n * @example\n * byteRange(\"bytes=-100\", 1000); // => { start: 900, end: 999 }\n */\nexport function byteRange(header: string, size: number): ByteRange | \"unsatisfiable\" | undefined {\n\tconst groups = /^bytes=(?<first>\\d*)-(?<last>\\d*)$/u.exec(header.trim())?.groups;\n\tconst first = groups?.first ?? \"\";\n\tconst last = groups?.last ?? \"\";\n\tif (first === \"\" && last === \"\") {\n\t\treturn undefined;\n\t}\n\tif (first === \"\") {\n\t\tconst suffix = Number(last);\n\t\treturn suffix === 0 || size === 0\n\t\t\t? \"unsatisfiable\"\n\t\t\t: { start: Math.max(0, size - suffix), end: size - 1 };\n\t}\n\tconst start = Number(first);\n\tconst end = last === \"\" ? Number.POSITIVE_INFINITY : Number(last);\n\tif (end < start) {\n\t\treturn undefined;\n\t}\n\treturn start >= size ? \"unsatisfiable\" : { start, end: Math.min(end, size - 1) };\n}\n\n/** Why these caps: they hold the hashed chunks of a typical app, and they limit the memory of each process. */\nconst KEPT_FILE_BYTES = 256 * 1024;\nconst KEPT_TOTAL_BYTES = 32 * 1024 * 1024;\n\n/**\n * `files` that keep the bytes of each small file in memory after the first\n * read, up to {@link KEPT_TOTAL_BYTES} in all. Use it only for files that\n * do not change while the server runs, such as a `StaticFiles.snapshot()`.\n *\n * @example\n * const files = keptFiles(await nodeFiles(\"build/client\").snapshot());\n */\nexport function keptFiles(files: StaticFiles): StaticFiles {\n\tconst kept = new Map<string, Promise<Uint8Array>>();\n\tlet total = 0;\n\treturn {\n\t\tstat: files.stat,\n\t\topen: async (path, range) => {\n\t\t\tlet bytes = kept.get(path);\n\t\t\tconst info = bytes == null ? await files.stat(path) : undefined;\n\t\t\t// Why again: another request can start to read the file during the `stat`.\n\t\t\tbytes ??= kept.get(path);\n\t\t\tif (bytes == null) {\n\t\t\t\tif (\n\t\t\t\t\tinfo?.kind !== \"file\" ||\n\t\t\t\t\tinfo.size > KEPT_FILE_BYTES ||\n\t\t\t\t\ttotal + info.size > KEPT_TOTAL_BYTES\n\t\t\t\t) {\n\t\t\t\t\treturn files.open(path, range);\n\t\t\t\t}\n\t\t\t\ttotal += info.size;\n\t\t\t\t// Why the size as a range: the kept bytes then match the `Content-Length` from the lookup.\n\t\t\t\tbytes = files\n\t\t\t\t\t.open(path, { start: 0, end: info.size - 1 })\n\t\t\t\t\t.then(async (stream) => new Uint8Array(await new Response(stream).arrayBuffer()));\n\t\t\t\tkept.set(path, bytes);\n\t\t\t\tbytes.catch(() => {\n\t\t\t\t\tkept.delete(path);\n\t\t\t\t\ttotal -= info.size;\n\t\t\t\t});\n\t\t\t}\n\t\t\t// Why a copy: a later stage can change the bytes that it reads.\n\t\t\tconst chunk = (await bytes).slice(\n\t\t\t\trange?.start ?? 0,\n\t\t\t\trange == null ? undefined : range.end + 1,\n\t\t\t);\n\t\t\treturn new ReadableStream<Uint8Array>({\n\t\t\t\tstart(controller) {\n\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\tcontroller.close();\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t};\n}\n\n/** A compressed copy of a static file that the build wrote. */\ntype Copy = StaticFile & { encoding: Encoding };\n\n/**\n * The copy of the file at `path` that the request prefers, from the copies\n * that the build wrote. When a copy exists, it adds `Accept-Encoding` to the\n * `Vary` in `headers`, also for a request that gets no copy.\n */\nasync function preferredCopy(\n\tcontext: Context<AppServerEnv>,\n\t{ files, path, headers }: { files: StaticFiles; path: string; headers: Headers },\n): Promise<Copy | undefined> {\n\t// Why not for an encoded file: the copy would encode it again, under one `Content-Encoding`.\n\tif (\n\t\theaders.has(\"Content-Encoding\") ||\n\t\t(context.get(\"rewritesHtml\") === true &&\n\t\t\t(headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false))\n\t) {\n\t\treturn undefined;\n\t}\n\tconst copies: Copy[] = [];\n\tfor (const encoding of COPY_ENCODINGS) {\n\t\tconst copyPath = path.replace(/[^/]*$/u, (name) => copyName(name, encoding));\n\t\t// oxlint-disable-next-line no-await-in-loop -- two lookups, and a snapshot answers each at once.\n\t\tconst info = await files.stat(copyPath);\n\t\tif (info?.kind === \"file\") {\n\t\t\tcopies.push({ path: copyPath, size: info.size, mtimeMs: info.mtimeMs, encoding });\n\t\t}\n\t}\n\tif (copies.length === 0) {\n\t\treturn undefined;\n\t}\n\tconst vary = withVary(headers.get(\"Vary\"), \"Accept-Encoding\");\n\tif (vary != null) {\n\t\theaders.set(\"Vary\", vary);\n\t}\n\tif (forbidsTransform(hookedHeaders(context, headers).get(\"Cache-Control\"))) {\n\t\treturn undefined;\n\t}\n\tconst encoding = preferredEncoding(\n\t\tcontext.req.header(\"Accept-Encoding\"),\n\t\tcopies.map((copy) => copy.encoding),\n\t);\n\treturn copies.find((copy) => copy.encoding === encoding);\n}\n\n/**\n * All bytes of a file. Why the size as a range: the body then never has more\n * bytes than its `Content-Length`, even when the file grew after `stat`, and\n * a small file reads into a small buffer.\n */\nasync function wholeFile(\n\tfiles: StaticFiles,\n\tfile: StaticFile,\n): Promise<ReadableStream<Uint8Array> | null> {\n\treturn file.size === 0 ? null : files.open(file.path, { start: 0, end: file.size - 1 });\n}\n\n/** What {@link staticResponse} needs besides the request. */\nexport type StaticResponseOptions = {\n\tfiles: StaticFiles;\n\tfile: StaticFile;\n\t/** Headers that replace the defaults, so a captured `Content-Type` wins over the one from the file name. */\n\theaders: Readonly<Record<string, string>>;\n\tcontentTypes: Readonly<Record<string, string>>;\n};\n\n/**\n * The response for a static file, with a weak ETag from its size,\n * modification time, the request's `etagParts`, and its encoding. A matching\n * `If-None-Match` gets a 304, and `HEAD` gets the headers only.\n *\n * A GET with one `bytes` range gets a 206 with those bytes, and a range\n * after the end of the file gets a 416. A request with `If-Range` gets the\n * full file. Why: the ETag is weak, and `If-Range` needs a strong match. An\n * HTML file gets no ranges.\n *\n * When the build wrote a compressed copy of the file (`.<file>.br` or\n * `.<file>.gz`), the response gets `Vary: Accept-Encoding`. A request gets\n * the copy that its `Accept-Encoding` prefers, brotli before gzip, with its\n * `Content-Encoding`, an ETag for that encoding, and no range. A response\n * marked `no-transform`, also by the header hook of an earlier stage, and a\n * response that `headers` encode, never get a copy. An HTML file gets no\n * copy when an earlier stage sets `rewritesHtml`.\n *\n * @example\n * const file = await findStaticFile(files, \"/llms.txt\");\n * if (file != null) {\n * return staticResponse(context, { files, file, headers: {}, contentTypes: {} });\n * }\n */\nexport async function staticResponse(\n\tcontext: Context<AppServerEnv>,\n\t{ files, file, headers, contentTypes }: StaticResponseOptions,\n): Promise<Response> {\n\tconst responseHeaders = new Headers({ \"Content-Type\": contentType(file.path, contentTypes) });\n\tfor (const [name, value] of Object.entries(headers)) {\n\t\tresponseHeaders.set(name, value);\n\t}\n\t// Why no ranges for HTML: a stage such as `runtimeEnv` can change the bytes of a page.\n\tconst html = responseHeaders.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false;\n\tif (html) {\n\t\tcontext.set(\"staticDocument\", file.path);\n\t}\n\t// Why before the 304: a 304 sends the `Vary` and the ETag of its 200.\n\tconst copy = await preferredCopy(context, { files, path: file.path, headers: responseHeaders });\n\t// Why the header first: `headers` can replace the ETag.\n\tconst etag =\n\t\tresponseHeaders.get(\"ETag\") ??\n\t\t(await fileEtag(file, context.get(\"etagParts\") ?? [], copy?.encoding));\n\tresponseHeaders.set(\"ETag\", etag);\n\tif (matchesEtag(context.req.header(\"If-None-Match\"), etag)) {\n\t\tresponseHeaders.delete(\"Content-Type\");\n\t\treturn new Response(null, { status: 304, headers: responseHeaders });\n\t}\n\tif (copy != null) {\n\t\t// Why no ranges: a client asks for a range of the file, not of its compressed copy.\n\t\tresponseHeaders.set(\"Content-Encoding\", copy.encoding);\n\t\tresponseHeaders.set(\"Content-Length\", String(copy.size));\n\t\tconst body = context.req.method === \"HEAD\" ? null : await wholeFile(files, copy);\n\t\treturn new Response(body, { headers: responseHeaders });\n\t}\n\tif (!html) {\n\t\tresponseHeaders.set(\"Accept-Ranges\", \"bytes\");\n\t}\n\tresponseHeaders.set(\"Content-Length\", String(file.size));\n\tif (context.req.method === \"HEAD\") {\n\t\treturn new Response(null, { headers: responseHeaders });\n\t}\n\tconst rangeHeader = context.req.header(\"Range\");\n\tconst range =\n\t\thtml || rangeHeader == null || context.req.header(\"If-Range\") != null\n\t\t\t? undefined\n\t\t\t: byteRange(rangeHeader, file.size);\n\tif (range === \"unsatisfiable\") {\n\t\tresponseHeaders.set(\"Content-Range\", `bytes */${file.size}`);\n\t\tresponseHeaders.delete(\"Content-Length\");\n\t\treturn new Response(null, { status: 416, headers: responseHeaders });\n\t}\n\tif (range != null) {\n\t\tresponseHeaders.set(\"Content-Range\", `bytes ${range.start}-${range.end}/${file.size}`);\n\t\tresponseHeaders.set(\"Content-Length\", String(range.end - range.start + 1));\n\t\treturn new Response(await files.open(file.path, range), {\n\t\t\tstatus: 206,\n\t\t\theaders: responseHeaders,\n\t\t});\n\t}\n\treturn new Response(await wholeFile(files, file), { headers: responseHeaders });\n}\n"],"mappings":";;;;;;;;;;;;;AAQA,SAAgB,SAAS,MAAqB,MAAkC;CAC/E,IAAI,QAAQ,QAAQ,KAAK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,QAAQ,IAAI,OAAO,UAAU,KAAK,OAC9D,SACA,UAAU,aAAa,KAAK,IAAI;CACpC,IAAI,UAAU,iBAAiB;EAC9B,gBAAgB,IAAI,iBAAiB,WAAW,KAAK,MAAM;EAC3D,gBAAgB,OAAO,gBAAgB;EACvC,OAAO,IAAI,SAAS,MAAM;GAAE,QAAQ;GAAK,SAAS;EAAgB,CAAC;CACpE;CACA,IAAI,SAAS,MAAM;EAClB,gBAAgB,IAAI,iBAAiB,SAAS,MAAM,MAAM,GAAG,MAAM,IAAI,GAAG,KAAK,MAAM;EACrF,gBAAgB,IAAI,kBAAkB,OAAO,MAAM,MAAM,MAAM,QAAQ,CAAC,CAAC;EACzE,OAAO,IAAI,SAAS,MAAM,MAAM,KAAK,KAAK,MAAM,KAAK,GAAG;GACvD,QAAQ;GACR,SAAS;EACV,CAAC;CACF;CACA,OAAO,IAAI,SAAS,MAAM,UAAU,OAAO,IAAI,GAAG,EAAE,SAAS,gBAAgB,CAAC;AAC/E"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { n as FrameworkBuild } from "./index-Bo5G9LuQ.js";
|
|
2
|
+
/**
|
|
3
|
+
* The build side of the TanStack Start adapter. `appServer` uses it when the
|
|
4
|
+
* Vite config has the TanStack Start plugin, so pass it only to override that.
|
|
5
|
+
* In `app-server start`, Vite runs in middleware mode, so Start skips its own
|
|
6
|
+
* SSR middleware, and the pipeline renders each page.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* appServer({ framework: tanstackStartAdapter() });
|
|
10
|
+
*/
|
|
11
|
+
export declare function tanstackStartAdapter(): FrameworkBuild;
|
|
12
|
+
//# sourceMappingURL=tanstack-start-vite.d.ts.map
|