@plitzi/sdk-kernel 0.0.0-stage → 0.39.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +80 -2
  3. package/dist/build/esbuild.d.ts +16 -0
  4. package/dist/build/index.d.ts +1 -0
  5. package/dist/build/index.mjs +35 -0
  6. package/dist/cache/CompressedFileCache.d.ts +18 -0
  7. package/dist/cache/TtlCache.d.ts +65 -0
  8. package/dist/cache/index.d.ts +3 -0
  9. package/dist/cache/index.mjs +1 -0
  10. package/dist/chunks/TtlCache-J_jG9oL9.mjs +200 -0
  11. package/dist/chunks/channel-DnVf7PJB.mjs +190 -0
  12. package/dist/chunks/csrf-BLWcaYOV.mjs +295 -0
  13. package/dist/chunks/link-C9wyDS9H.mjs +124 -0
  14. package/dist/chunks/query-DGbrN3mN.mjs +20 -0
  15. package/dist/chunks/scopes-Co6ZjhAm.mjs +46 -0
  16. package/dist/chunks/serverLog-BKaKjjc4.mjs +137 -0
  17. package/dist/chunks/session-B-dTEjeG.mjs +253 -0
  18. package/dist/chunks/sessionActivity-Ch7xuQ_o.mjs +43 -0
  19. package/dist/chunks/spaceDeployment-J2IMLfij.mjs +76 -0
  20. package/dist/chunks/stage-y6deE9LJ.mjs +345 -0
  21. package/dist/chunks/supervisor-Dh34v1vq.mjs +117 -0
  22. package/dist/chunks/tail-D-USrZIR.mjs +55 -0
  23. package/dist/chunks/tokens-BAV5YeT9.mjs +273 -0
  24. package/dist/data/index.d.ts +2 -0
  25. package/dist/data/index.mjs +68 -0
  26. package/dist/data/projectData.d.ts +21 -0
  27. package/dist/deployment/hostDeployment.d.ts +8 -0
  28. package/dist/deployment/index.d.ts +3 -0
  29. package/dist/deployment/index.mjs +19 -0
  30. package/dist/deployment/spaceDeployment.d.ts +11 -0
  31. package/dist/engine/index.d.ts +2 -0
  32. package/dist/engine/index.mjs +1 -0
  33. package/dist/engine/page.d.ts +49 -0
  34. package/dist/engine/rsc.d.ts +32 -0
  35. package/dist/files/atomicFile.d.ts +10 -0
  36. package/dist/files/index.d.ts +1 -0
  37. package/dist/files/index.mjs +32 -0
  38. package/dist/http/bearer.d.ts +5 -0
  39. package/dist/http/buildResponseHelpers.d.ts +23 -0
  40. package/dist/http/closeOnSignals.d.ts +28 -0
  41. package/dist/http/compress.d.ts +20 -0
  42. package/dist/http/dispatcher.d.ts +15 -0
  43. package/dist/http/drain.d.ts +18 -0
  44. package/dist/http/fleet/channel.d.ts +103 -0
  45. package/dist/http/fleet/link.d.ts +28 -0
  46. package/dist/http/fleet/role.d.ts +46 -0
  47. package/dist/http/fleet/supervisor.d.ts +29 -0
  48. package/dist/http/freePort.d.ts +24 -0
  49. package/dist/http/health.d.ts +21 -0
  50. package/dist/http/index.d.ts +48 -0
  51. package/dist/http/index.mjs +1313 -0
  52. package/dist/http/middlewares/auth.d.ts +2 -0
  53. package/dist/http/middlewares/basicAuth.d.ts +6 -0
  54. package/dist/http/mimeTypes.d.ts +13 -0
  55. package/dist/http/navigation.d.ts +14 -0
  56. package/dist/http/onAbort.d.ts +12 -0
  57. package/dist/http/probes.d.ts +4 -0
  58. package/dist/http/requestParser.d.ts +22 -0
  59. package/dist/http/runMiddlewares.d.ts +6 -0
  60. package/dist/http/securityHeaders.d.ts +18 -0
  61. package/dist/http/server.d.ts +39 -0
  62. package/dist/http/socketResponse.d.ts +18 -0
  63. package/dist/http/sse.d.ts +26 -0
  64. package/dist/http/stages/crossSiteWrites.d.ts +24 -0
  65. package/dist/http/stages/health.d.ts +11 -0
  66. package/dist/http/stages/middlewares.d.ts +3 -0
  67. package/dist/http/stages/static.d.ts +4 -0
  68. package/dist/http/staticFiles.d.ts +3 -0
  69. package/dist/http/stopping.d.ts +11 -0
  70. package/dist/http/transports.d.ts +31 -0
  71. package/dist/http/types.d.ts +29 -0
  72. package/dist/http/unusedPort.d.ts +10 -0
  73. package/dist/http/webExchange.d.ts +18 -0
  74. package/dist/http/wsFrame.d.ts +3 -0
  75. package/dist/identity/accounts.d.ts +278 -0
  76. package/dist/identity/authorize.d.ts +96 -0
  77. package/dist/identity/credentials.d.ts +40 -0
  78. package/dist/identity/csrf.d.ts +139 -0
  79. package/dist/identity/debugAuthorization.d.ts +24 -0
  80. package/dist/identity/domains.d.ts +41 -0
  81. package/dist/identity/identity.d.ts +119 -0
  82. package/dist/identity/index.d.ts +21 -0
  83. package/dist/identity/index.mjs +731 -0
  84. package/dist/identity/passwords.d.ts +15 -0
  85. package/dist/identity/previewToken.d.ts +21 -0
  86. package/dist/identity/requestIdentity.d.ts +14 -0
  87. package/dist/identity/scopes.d.ts +56 -0
  88. package/dist/identity/session.d.ts +185 -0
  89. package/dist/identity/sessionActivity.d.ts +11 -0
  90. package/dist/identity/spaceTokens.d.ts +174 -0
  91. package/dist/index.d.ts +17 -0
  92. package/dist/index.mjs +1 -0
  93. package/dist/log/index.d.ts +3 -0
  94. package/dist/log/index.mjs +3 -0
  95. package/dist/log/serverLog.d.ts +49 -0
  96. package/dist/log/tail.d.ts +43 -0
  97. package/dist/mysql/accounts.d.ts +4 -0
  98. package/dist/mysql/admin.d.ts +58 -0
  99. package/dist/mysql/config.d.ts +82 -0
  100. package/dist/mysql/identities.d.ts +35 -0
  101. package/dist/mysql/index.d.ts +7 -0
  102. package/dist/mysql/index.mjs +1203 -0
  103. package/dist/mysql/pool.d.ts +3 -0
  104. package/dist/mysql/query.d.ts +12 -0
  105. package/dist/mysql/schema.d.ts +43 -0
  106. package/dist/mysql/sessions.d.ts +23 -0
  107. package/dist/mysql/spaceTokens.d.ts +11 -0
  108. package/dist/mysql/store.d.ts +66 -0
  109. package/dist/outbound/index.d.ts +4 -0
  110. package/dist/outbound/index.mjs +314 -0
  111. package/dist/outbound/inside.d.ts +36 -0
  112. package/dist/outbound/outboundGuard.d.ts +69 -0
  113. package/dist/pubsub/index.d.ts +3 -0
  114. package/dist/pubsub/index.mjs +76 -0
  115. package/dist/pubsub/memoryPubSub.d.ts +10 -0
  116. package/dist/pubsub/redisPubSub.d.ts +24 -0
  117. package/dist/stats/index.d.ts +9 -0
  118. package/dist/stats/index.mjs +228 -0
  119. package/dist/stats/load.d.ts +31 -0
  120. package/dist/stats/memory.d.ts +20 -0
  121. package/dist/stats/pools.d.ts +15 -0
  122. package/dist/stats/recorder.d.ts +34 -0
  123. package/dist/stats/stage.d.ts +15 -0
  124. package/dist/stats/types.d.ts +309 -0
  125. package/dist/testing/certificates.d.ts +21 -0
  126. package/dist/testing/fleet.d.ts +28 -0
  127. package/dist/testing/goneRuns.d.ts +5 -0
  128. package/dist/testing/index.d.ts +5 -0
  129. package/dist/testing/index.mjs +270 -0
  130. package/dist/testing/keys.d.ts +2 -0
  131. package/dist/testing/runNames.d.ts +10 -0
  132. package/dist/tokens/index.d.ts +2 -0
  133. package/dist/tokens/index.mjs +1 -0
  134. package/dist/tokens/tokens.d.ts +195 -0
  135. package/dist/types/adapters.d.ts +388 -0
  136. package/dist/types/config.d.ts +240 -0
  137. package/dist/types/index.d.ts +5 -0
  138. package/dist/types/index.mjs +1 -0
  139. package/dist/types/log.d.ts +119 -0
  140. package/dist/types/oauth.d.ts +246 -0
  141. package/dist/types/pipeline.d.ts +239 -0
  142. package/package.json +67 -3
@@ -0,0 +1,1313 @@
1
+ import { a as isLogged, c as serverLog, s as renderLogEvent } from "../chunks/serverLog-BKaKjjc4.mjs";
2
+ import { c as isStopping, i as bearerMatches, l as markStopping, s as SHUTDOWN_ANNOUNCE_MS, t as statsConfigProblem, u as shutdownOf } from "../chunks/stage-y6deE9LJ.mjs";
3
+ import { i as hstsFor, n as applySecurityHeaders, r as frameAncestorsOf, t as spaceDeploymentMiddleware } from "../chunks/spaceDeployment-J2IMLfij.mjs";
4
+ import { n as keepLogEvent } from "../chunks/tail-D-USrZIR.mjs";
5
+ import { a as hostable, i as createStoreHost, n as createFleetHub, o as isFleetMessage, r as createListeners, t as createFleetClient } from "../chunks/channel-DnVf7PJB.mjs";
6
+ import { a as startHub, c as isFleetWorker, i as onBroadcast, l as resolveWorkers, n as channelName, o as fleetRole, r as fleetStore, s as fleetWorkerEnv, t as broadcast, u as runsFleetJobs } from "../chunks/link-C9wyDS9H.mjs";
7
+ import { n as CompressedFileCache, t as TtlCache } from "../chunks/TtlCache-J_jG9oL9.mjs";
8
+ import { r as crossSiteRequest, t as carrierOf } from "../chunks/csrf-BLWcaYOV.mjs";
9
+ import path from "node:path";
10
+ import { connect, createServer } from "node:net";
11
+ import crypto from "node:crypto";
12
+ import { brotliCompressSync, constants, gzipSync } from "node:zlib";
13
+ import http, { STATUS_CODES } from "node:http";
14
+ import os from "node:os";
15
+ import fs, { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
16
+ import http2 from "node:http2";
17
+ import https from "node:https";
18
+ // src/http/compress.ts
19
+ /** What the server does when the deployment says nothing: Brotli where the client takes it, gzip otherwise. */
20
+ var DEFAULT_COMPRESSION = {
21
+ encodings: ["br", "gzip"],
22
+ threshold: 1024,
23
+ brotliQuality: 5,
24
+ keptBrotliQuality: 6,
25
+ gzipLevel: 6
26
+ };
27
+ /**
28
+ * The deployment's compression policy, with the gaps filled in. `false` means never compress, and is expressed as
29
+ * an empty encoding list so there is one shape downstream rather than a boolean to re-test at every use.
30
+ */
31
+ var resolveCompression = (config) => {
32
+ if (config === false) return {
33
+ ...DEFAULT_COMPRESSION,
34
+ encodings: []
35
+ };
36
+ return {
37
+ ...DEFAULT_COMPRESSION,
38
+ ...config
39
+ };
40
+ };
41
+ /**
42
+ * What the client will accept, as a set of tokens it did NOT refuse.
43
+ *
44
+ * `q=0` is a refusal, and the header is the one place a client can say "not Brotli" — a proxy that mangles it, an
45
+ * old client that decodes it wrongly. Matching on substrings alone honoured the offer and ignored the refusal,
46
+ * which is the one way this can produce a body the caller cannot read.
47
+ */
48
+ var acceptedEncodings = (acceptEncoding) => {
49
+ const accepted = /* @__PURE__ */ new Set();
50
+ for (const part of acceptEncoding.split(",")) {
51
+ const [token, ...params] = part.trim().split(";");
52
+ const quality = params.map((param) => /^\s*q=([\d.]+)\s*$/iu.exec(param)).find((match) => match !== null)?.[1];
53
+ if (quality === void 0 || Number(quality) > 0) accepted.add(token.trim().toLowerCase());
54
+ }
55
+ return accepted;
56
+ };
57
+ /** The first encoding this server prefers that the client actually takes. `*` counts as taking anything. */
58
+ var selectEncoding = (acceptEncoding, compression = DEFAULT_COMPRESSION) => {
59
+ if (!acceptEncoding || compression.encodings.length === 0) return "identity";
60
+ const accepted = acceptedEncodings(acceptEncoding);
61
+ return compression.encodings.find((encoding) => accepted.has(encoding) || accepted.has("*")) ?? "identity";
62
+ };
63
+ /** `kept`: the result is stored and served again, so it is worth compressing harder once. */
64
+ var compressBody = (body, encoding, compression = DEFAULT_COMPRESSION, kept = false) => {
65
+ if (encoding === "identity" || body.length < compression.threshold) return body;
66
+ const buf = Buffer.from(body, "utf-8");
67
+ if (encoding === "br") {
68
+ const quality = kept ? compression.keptBrotliQuality : compression.brotliQuality;
69
+ return brotliCompressSync(buf, { params: {
70
+ [constants.BROTLI_PARAM_QUALITY]: quality,
71
+ [constants.BROTLI_PARAM_SIZE_HINT]: buf.length
72
+ } });
73
+ }
74
+ return gzipSync(buf, { level: compression.gzipLevel });
75
+ };
76
+ // src/http/buildResponseHelpers.ts
77
+ /**
78
+ * Adds `name` to what the response varies by, beside what a stage already said (a page varies by its scheme hint too):
79
+ * set whole, the encoding's `Vary` put the page's out.
80
+ */
81
+ var varyOn = (raw, name) => {
82
+ const said = raw.getHeaders().vary;
83
+ const names = (Array.isArray(said) ? said.join(",") : String(said ?? "")).split(",").map((part) => part.trim()).filter(Boolean);
84
+ if (!names.some((part) => part.toLowerCase() === name.toLowerCase())) raw.setHeader("Vary", [...names, name].join(", "));
85
+ };
86
+ /**
87
+ * `compressBody`, remembered in `store` when the caller keeps one: the same body in the same encoding is compressed
88
+ * once. What comes back uncompressed (identity, or a body under the threshold) is never stored — there is nothing to
89
+ * reuse, and a stored copy would only be the body again.
90
+ */
91
+ var compressOnce = (body, encoding, compression, store) => {
92
+ if (!store || encoding === "identity") return compressBody(body, encoding, compression);
93
+ const kept = store[encoding];
94
+ if (kept) return kept;
95
+ const compressed = compressBody(body, encoding, compression, true);
96
+ if (typeof compressed !== "string") store[encoding] = compressed;
97
+ return compressed;
98
+ };
99
+ var buildResponseHelpers = (raw, acceptEncoding, compression = DEFAULT_COMPRESSION) => {
100
+ let statusCode = 200;
101
+ const encoding = selectEncoding(acceptEncoding, compression);
102
+ /**
103
+ * `Cache-Control: no-transform` means what it says, and this server is one of the parties it addresses.
104
+ *
105
+ * A stage sets it on a response whose body must reach the client byte for byte — the OAuth token endpoint above
106
+ * all, where a credential travels beside a value the caller chose (the `scope` it echoes back). Compressing the
107
+ * two together is the shape a BREACH-style attack needs, and the stage that knows this is the one that has
108
+ * already said so in a header.
109
+ */
110
+ const transformable = () => !String(raw.getHeaders()["cache-control"]).includes("no-transform");
111
+ /** A stored form this request can take as it is, without the body it was made from. */
112
+ const storedFor = (store) => encoding === "identity" || !transformable() ? void 0 : store?.[encoding];
113
+ const writeBody = (payload, encoded) => {
114
+ if (encoded) {
115
+ raw.setHeader("Content-Encoding", encoding);
116
+ varyOn(raw, "Accept-Encoding");
117
+ }
118
+ raw.setHeader("Content-Length", Buffer.byteLength(payload).toString());
119
+ if (!raw.headersSent) raw.writeHead(statusCode);
120
+ raw.end(payload);
121
+ };
122
+ const writeSend = (content, store) => {
123
+ const stored = typeof content === "function" ? storedFor(store) : void 0;
124
+ if (stored) {
125
+ writeBody(stored, true);
126
+ return;
127
+ }
128
+ const body = typeof content === "function" ? content() : content;
129
+ /**
130
+ * A Buffer goes out untouched.
131
+ *
132
+ * It is the only way a binary reaches the wire — this response object had `send(body: string)` and every
133
+ * caller went through a UTF-8 round trip, which silently replaces every byte that is not valid UTF-8 and so
134
+ * corrupts any font, image or archive served through it. What a Buffer holds is also compressed already
135
+ * (woff2, png), so re-encoding it would cost CPU to make it bigger.
136
+ */
137
+ const compressed = typeof body === "string" && transformable() ? compressOnce(body, encoding, compression, store) : body;
138
+ writeBody(compressed, compressed !== body);
139
+ };
140
+ return {
141
+ get status() {
142
+ return statusCode;
143
+ },
144
+ get headers() {
145
+ return raw.getHeaders();
146
+ },
147
+ setHeader(name, value) {
148
+ raw.setHeader(name, value);
149
+ },
150
+ setStatus(code) {
151
+ statusCode = code;
152
+ },
153
+ send(body, options) {
154
+ writeSend(body, options?.compressed);
155
+ },
156
+ write(chunk) {
157
+ if (!raw.headersSent) raw.writeHead(statusCode);
158
+ raw.write(chunk);
159
+ },
160
+ end() {
161
+ if (!raw.headersSent) raw.writeHead(statusCode);
162
+ raw.end();
163
+ },
164
+ earlyHints(links) {
165
+ if (links.length === 0 || raw.headersSent || !raw.writeEarlyHints) return;
166
+ raw.writeEarlyHints({ link: links });
167
+ }
168
+ };
169
+ };
170
+ // src/http/closeOnSignals.ts
171
+ /**
172
+ * Closes the server when the process is told to stop, and only then lets the process exit.
173
+ *
174
+ * `close()` already does the waiting — the page server stops claiming jobs, finishes the ones it is running and lets
175
+ * go of its sockets — but nothing calls it when a deploy sends SIGTERM, and a process that simply exits leaves every
176
+ * running job to be retried by somebody else. This is that call, for a deployment that has no signal handling of its
177
+ * own. Opt in: a host that already manages its process's signals keeps doing so, and calls `close()` from there.
178
+ *
179
+ * ```ts
180
+ * const server = createServer(config);
181
+ * server.listen(3000);
182
+ * closeOnSignals(server, { afterClose: () => pool.end() });
183
+ * ```
184
+ *
185
+ * A second signal while it is closing exits at once — the ^C a person presses when waiting is not what they want.
186
+ * Answers a function that removes the handlers again.
187
+ */
188
+ var closeOnSignals = (server, { signals = ["SIGTERM", "SIGINT"], afterClose } = {}) => {
189
+ let closing = false;
190
+ const onSignal = (signal) => {
191
+ if (closing) {
192
+ serverLog.warn("server", `${signal} again: exiting without waiting`);
193
+ process.exit(1);
194
+ return;
195
+ }
196
+ closing = true;
197
+ serverLog.info("server", `${signal}: finishing what is running, then exiting`);
198
+ (async () => {
199
+ try {
200
+ await server.close();
201
+ await afterClose?.();
202
+ process.exit(0);
203
+ } catch (error) {
204
+ serverLog.error("server", "could not close cleanly", error);
205
+ process.exit(1);
206
+ }
207
+ })();
208
+ };
209
+ for (const signal of signals) process.on(signal, onSignal);
210
+ return () => {
211
+ for (const signal of signals) process.off(signal, onSignal);
212
+ };
213
+ };
214
+ // src/http/requestParser.ts
215
+ var HOSTNAME_RE = /^[a-zA-Z0-9.-]{1,253}$/u;
216
+ var parseRequest = (raw) => {
217
+ const headers = raw.headers;
218
+ const rawHostname = (headers[":authority"] ?? headers["host"] ?? "").split(":")[0] ?? "";
219
+ const hostname = HOSTNAME_RE.test(rawHostname) ? rawHostname : "";
220
+ const scheme = headers[":scheme"];
221
+ const forwarded = headers["x-forwarded-proto"];
222
+ const encrypted = !scheme && !forwarded && "encrypted" in raw.socket && raw.socket.encrypted === true;
223
+ const protocol = scheme === "https" || forwarded === "https" || encrypted ? "https" : "http";
224
+ const rawUrl = headers[":path"] ?? raw.url ?? "/";
225
+ const qIndex = rawUrl.indexOf("?");
226
+ const rawPath = qIndex === -1 ? rawUrl : rawUrl.slice(0, qIndex);
227
+ const path = rawPath.includes("\0") ? "\0" : rawPath;
228
+ const search = qIndex === -1 ? "" : rawUrl.slice(qIndex);
229
+ const query = {};
230
+ if (search) {
231
+ const sp = new URLSearchParams(search.slice(1));
232
+ for (const [k, v] of sp.entries()) query[k] = v;
233
+ }
234
+ const method = (headers[":method"] ?? raw.method ?? "GET").toUpperCase();
235
+ const ip = forwardedIp(headers) || unmapIpv4(raw.socket.remoteAddress ?? "");
236
+ return {
237
+ method,
238
+ path,
239
+ search,
240
+ url: rawUrl,
241
+ hostname,
242
+ protocol,
243
+ headers,
244
+ query,
245
+ ...ip ? { ip } : {},
246
+ ctx: {}
247
+ };
248
+ };
249
+ var AUTHORITY_RE = /^[a-zA-Z0-9.-]{1,253}(?::\d{1,5})?$/u;
250
+ /**
251
+ * The host the request was addressed to, port included (`localhost:8080`): HTTP/2's `:authority` — an HTTP/2
252
+ * request has no `Host` header at all — else `Host`. What names this origin's cookies (`debugCookieName` and the
253
+ * rest carry the port), so a server reached over HTTP/2 must read it here, never `req.headers.host`.
254
+ */
255
+ var requestAuthority = (req) => req.headers[":authority"] ?? req.headers["host"] ?? "";
256
+ /** The public origin the request was addressed to (proxy-aware via x-forwarded-proto, port included), or an empty
257
+ * string when the request carries no usable authority. */
258
+ var requestOrigin = (req) => {
259
+ const authority = requestAuthority(req);
260
+ return AUTHORITY_RE.test(authority) ? `${req.protocol}://${authority}` : "";
261
+ };
262
+ var headerValue = (value) => (Array.isArray(value) ? value[0] : value)?.trim() ?? "";
263
+ var unmapIpv4 = (address) => address.startsWith("::ffff:") && address.includes(".") ? address.slice(7) : address;
264
+ /** The address the request came from, seen through the proxies a deployment sits behind: Cloudflare states the
265
+ * peer it accepted in `cf-connecting-ip`, the ingress in `x-real-ip`, and `x-forwarded-for` lists the chain with
266
+ * the original client first. All three are plain headers a direct client can forge, so this is log/diagnostic
267
+ * material — never an authorisation input. Falls back to the socket peer, which no client controls. */
268
+ var clientIp = (raw, req) => forwardedIp(req.headers) || unmapIpv4(raw.socket.remoteAddress ?? "");
269
+ /** The proxies' account of the client address, without the socket — for a caller that has headers and nothing else. */
270
+ var forwardedIp = (headers) => {
271
+ const forwardedFor = headerValue(headers["x-forwarded-for"]).split(",")[0] ?? "";
272
+ return unmapIpv4(headerValue(headers["cf-connecting-ip"]) || headerValue(headers["x-real-ip"]) || forwardedFor.trim());
273
+ };
274
+ var MAX_BODY_BYTES = 1048576;
275
+ /** A request's body as it arrived, byte for byte — what a binary upload to a function's route needs. */
276
+ var readRawBytes = (raw) => new Promise((resolve, reject) => {
277
+ const chunks = [];
278
+ let size = 0;
279
+ raw.on("data", (chunk) => {
280
+ size += chunk.length;
281
+ if (size > MAX_BODY_BYTES) {
282
+ reject(/* @__PURE__ */ new Error("Request body too large"));
283
+ return;
284
+ }
285
+ chunks.push(chunk);
286
+ });
287
+ raw.on("end", () => resolve(Buffer.concat(chunks)));
288
+ raw.on("error", reject);
289
+ });
290
+ var readRawBody = async (raw) => (await readRawBytes(raw)).toString("utf8");
291
+ // src/http/socketResponse.ts
292
+ /**
293
+ * An HTTP response written straight to a socket — what an upgrade request gets when it is NOT upgraded.
294
+ *
295
+ * An upgrade arrives with no `ServerResponse`: node hands over the socket and expects whoever listens to speak for
296
+ * it. Every stage of the pipeline writes to a `RawResponse`, so this is one: a refusal (a 403, a 404, a redirect)
297
+ * reaches the client as the stage wrote it, and the socket closes after it — a connection that asked to switch
298
+ * protocols and was answered in HTTP has nothing left to say.
299
+ */
300
+ var socketResponse = (socket) => {
301
+ const headers = {};
302
+ const body = [];
303
+ let statusCode = 200;
304
+ let headersSent = false;
305
+ let finished = false;
306
+ const flush = () => {
307
+ if (finished) return;
308
+ finished = true;
309
+ headersSent = true;
310
+ const payload = Buffer.concat(body);
311
+ const lines = Object.entries({
312
+ ...headers,
313
+ Connection: "close",
314
+ "Content-Length": payload.length
315
+ }).flatMap(([name, value]) => (Array.isArray(value) ? value : [value]).map((entry) => `${name}: ${String(entry)}`));
316
+ const head = `HTTP/1.1 ${statusCode} ${STATUS_CODES[statusCode] ?? ""}\r\n${lines.join("\r\n")}\r\n\r\n`;
317
+ socket.end(Buffer.concat([Buffer.from(head), payload]));
318
+ };
319
+ return {
320
+ get headersSent() {
321
+ return headersSent;
322
+ },
323
+ get statusCode() {
324
+ return statusCode;
325
+ },
326
+ get writableFinished() {
327
+ return finished;
328
+ },
329
+ setHeader: (name, value) => {
330
+ headers[name] = value;
331
+ },
332
+ getHeaders: () => ({ ...headers }),
333
+ writeHead: (code, extra) => {
334
+ statusCode = code;
335
+ Object.assign(headers, extra);
336
+ },
337
+ write: (chunk) => {
338
+ body.push(Buffer.from(chunk));
339
+ },
340
+ end: (chunk) => {
341
+ if (chunk !== void 0) body.push(Buffer.from(chunk));
342
+ flush();
343
+ },
344
+ once: (_event, listener) => socket.once("close", listener)
345
+ };
346
+ };
347
+ // src/http/dispatcher.ts
348
+ var safePath = (url) => {
349
+ const [path = "/", query] = url.split("?");
350
+ if (!query) return path;
351
+ const keys = [...new Set(new URLSearchParams(query).keys())];
352
+ return keys.length > 0 ? `${path}?${keys.join("&")}` : path;
353
+ };
354
+ var errorText = (error) => error instanceof Error ? error.message : String(error);
355
+ var statusOf = (rawRes, res) => rawRes.headersSent ? rawRes.statusCode : res.status;
356
+ var runPipeline = async (raw, rawRes, buildContext, stages, server, compression, upgrade) => {
357
+ const startedAt = Date.now();
358
+ const req = parseRequest(raw);
359
+ const res = buildResponseHelpers(rawRes, req.headers["accept-encoding"], compression);
360
+ /**
361
+ * One controller per request, aborted when the PEER goes away.
362
+ *
363
+ * Watched on the RESPONSE, not on the request: `IncomingMessage` emits `close` as soon as its body has been
364
+ * read, so a POST aborted itself the millisecond the server finished parsing it — measurably, at 9ms of a
365
+ * 300ms request. Everything downstream either ignored that (a listener attached after the event never fires,
366
+ * which is what kept actions working at all) or acted on it and cancelled work nobody had abandoned.
367
+ *
368
+ * `writableFinished` is what tells the two apart: a response that closed after finishing was SERVED, and one
369
+ * that closed before is a caller who left. `once` so a request that ends normally leaves no listener on a
370
+ * socket the runtime may keep alive for the next one.
371
+ */
372
+ const controller = new AbortController();
373
+ rawRes.once?.("close", () => {
374
+ if (!rawRes.writableFinished) controller.abort();
375
+ });
376
+ const ctx = {
377
+ ...buildContext(raw, rawRes, req, res),
378
+ signal: controller.signal,
379
+ ...upgrade ? { upgrade } : {}
380
+ };
381
+ const logger = ctx.config.logger;
382
+ const ip = clientIp(raw, req);
383
+ const logRequest = (error) => {
384
+ const status = statusOf(rawRes, res);
385
+ const failed = !!error || status >= 500;
386
+ if (req.path === "/_stats/logs" && status < 400) return;
387
+ const probe = status < 400 && (req.path === "/_stats" || req.path === (ctx.config.health?.path ?? "/health"));
388
+ const level = failed ? "error" : probe ? "debug" : "info";
389
+ const event = {
390
+ kind: "request",
391
+ server,
392
+ method: req.method,
393
+ path: safePath(req.url),
394
+ ...ip ? { clientIp: ip } : {},
395
+ ...ctx.operation === void 0 ? {} : { operation: ctx.operation },
396
+ status,
397
+ durationMs: Date.now() - startedAt,
398
+ ok: !error && status < 500,
399
+ ...error ? { error: errorText(error) } : {},
400
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
401
+ };
402
+ keepLogEvent(event, level, renderLogEvent(event));
403
+ if (logger && isLogged(ctx.config.logLevel ?? "error", level)) logger(event);
404
+ };
405
+ try {
406
+ if (req.path === "\0") {
407
+ res.setStatus(400);
408
+ res.end();
409
+ logRequest();
410
+ return;
411
+ }
412
+ applySecurityHeaders(req, res, ctx.config, ctx.port);
413
+ for (const stage of stages) if (await stage(ctx)) {
414
+ logRequest();
415
+ return;
416
+ }
417
+ logRequest();
418
+ } catch (error) {
419
+ logRequest(error);
420
+ throw error;
421
+ }
422
+ };
423
+ var pathOf = (url) => (url ?? "/").split("?")[0];
424
+ var makeHandler = (label, buildContext, stages, { compression: compressionConfig, upgrades } = {}) => {
425
+ const compression = resolveCompression(compressionConfig);
426
+ const fail = (rawRes) => (err) => {
427
+ serverLog.error(label, "Unhandled error", err);
428
+ try {
429
+ if (!rawRes.headersSent) rawRes.writeHead(500, { "Content-Type": "text/plain" });
430
+ rawRes.end("Internal Server Error");
431
+ } catch {}
432
+ };
433
+ const handler = (raw, rawRes) => {
434
+ runPipeline(raw, rawRes, buildContext, stages, label, compression).catch(fail(rawRes));
435
+ };
436
+ if (upgrades) handler.upgrade = (raw, socket, head) => {
437
+ const rawRes = socketResponse(socket);
438
+ if (!upgrades(pathOf(raw.url))) {
439
+ rawRes.writeHead(404, { "Content-Type": "text/plain" });
440
+ rawRes.end("Not Found");
441
+ return;
442
+ }
443
+ const upgrade = {
444
+ socket,
445
+ head,
446
+ taken: false
447
+ };
448
+ runPipeline(raw, rawRes, buildContext, stages, label, compression, upgrade).then(() => {
449
+ if (!upgrade.taken && !rawRes.writableFinished) {
450
+ rawRes.writeHead(404, { "Content-Type": "text/plain" });
451
+ rawRes.end("Not Found");
452
+ }
453
+ }).catch(fail(rawRes));
454
+ };
455
+ return handler;
456
+ };
457
+ // src/http/drain.ts
458
+ /**
459
+ * How long a server shutting down lets what it is answering finish before it cuts it: a render, an upload, an action
460
+ * called a moment ago. Well under the 30 seconds a cluster gives a pod between SIGTERM and SIGKILL.
461
+ */
462
+ var SHUTDOWN_GRACE_MS = 1e4;
463
+ /** A WebSocket close frame, as a server sends it (unmasked): status 1001, "going away". */
464
+ var GOING_AWAY = Buffer.from([
465
+ 136,
466
+ 2,
467
+ 3,
468
+ 233
469
+ ]);
470
+ /**
471
+ * Whether a response is an event stream: said by its content type — or, since headers written with `writeHead(status,
472
+ * headers)` are not kept where `getHeader` looks, by what it answers: a GET that asked for one, as an EventSource and
473
+ * an MCP client's listening stream do.
474
+ */
475
+ var isEventStream = (asking, answering) => {
476
+ const type = answering.getHeader("content-type");
477
+ const accept = asking.headers.accept;
478
+ return typeof type === "string" && type.startsWith("text/event-stream") || asking.method === "GET" && [accept].flat().some((value) => value?.includes("text/event-stream"));
479
+ };
480
+ /**
481
+ * The connections a server holds, watched from the moment it is built, so it can be shut down.
482
+ *
483
+ * Node's `server.close()` stops taking connections and then waits for every open one to end. A request ends; a
484
+ * WebSocket or an event stream does not — a board open in a tab, an agent's app listening — so a server with one open
485
+ * waited for ever, and a Ctrl+C or a SIGTERM hung until something killed it. `drain` stops taking connections, closes
486
+ * the idle ones, ends every event stream and WebSocket at once (neither has anything left to finish), gives what is
487
+ * still being answered `graceMs`, and then cuts what remains.
488
+ */
489
+ var watchConnections = (server) => {
490
+ const sockets = /* @__PURE__ */ new Set();
491
+ const answering = /* @__PURE__ */ new Map();
492
+ let draining = false;
493
+ const closeIdle = () => {
494
+ if ("closeIdleConnections" in server) server.closeIdleConnections();
495
+ };
496
+ server.on("connection", (socket) => {
497
+ sockets.add(socket);
498
+ socket.once("close", () => sockets.delete(socket));
499
+ });
500
+ const websockets = /* @__PURE__ */ new Set();
501
+ server.on("upgrade", (request, socket) => {
502
+ if ([request.headers.upgrade].flat().some((value) => value?.toLowerCase() === "websocket")) {
503
+ websockets.add(socket);
504
+ socket.once("close", () => websockets.delete(socket));
505
+ }
506
+ });
507
+ server.on("request", (request, response) => {
508
+ answering.set(response, request);
509
+ response.once("close", () => {
510
+ answering.delete(response);
511
+ if (draining) closeIdle();
512
+ });
513
+ });
514
+ return { drain: (label, graceMs = SHUTDOWN_GRACE_MS) => new Promise((resolve, reject) => {
515
+ draining = true;
516
+ const cut = setTimeout(() => {
517
+ if (sockets.size) serverLog.warn(label, `${sockets.size} connection(s) still open after ${graceMs} ms: closing them`);
518
+ sockets.forEach((socket) => socket.destroy());
519
+ }, graceMs);
520
+ cut.unref();
521
+ server.close((error) => {
522
+ clearTimeout(cut);
523
+ if (error && !("code" in error && error.code === "ERR_SERVER_NOT_RUNNING")) {
524
+ reject(error);
525
+ return;
526
+ }
527
+ resolve();
528
+ });
529
+ closeIdle();
530
+ answering.forEach((request, response) => {
531
+ if (isEventStream(request, response)) response.end(closeIdle);
532
+ });
533
+ websockets.forEach((socket) => socket.end(GOING_AWAY));
534
+ }) };
535
+ };
536
+ // src/http/freePort.ts
537
+ /** Whether something already answers at `port` — the one test that sees a listener on every address, not just `host`. */
538
+ var portAnswers = (port, host) => new Promise((resolve) => {
539
+ const socket = connect({
540
+ port,
541
+ host
542
+ });
543
+ socket.once("connect", () => {
544
+ socket.destroy();
545
+ resolve(true);
546
+ });
547
+ socket.once("error", () => resolve(false));
548
+ });
549
+ /** Whether this process could listen at `port` on `host`. */
550
+ var portBindable = (port, host) => new Promise((resolve) => {
551
+ const probe = createServer();
552
+ probe.once("error", () => resolve(false));
553
+ probe.once("listening", () => probe.close(() => resolve(true)));
554
+ probe.listen(port, host);
555
+ });
556
+ /**
557
+ * The first port from `preferred` up that nothing uses — for a development server, which should start beside
558
+ * whatever else is running rather than refuse to.
559
+ *
560
+ * Free means both that nothing answers there and that this process may listen there: a server bound to every
561
+ * address leaves `127.0.0.1` bindable on some systems, and a page server started beside it would never be reached —
562
+ * the other one would answer, with a `200` that looks like success. A deployment that sets its port does not need
563
+ * this: a fixed port that is taken is an error worth stopping for.
564
+ */
565
+ var freePort = async (preferred, host = "127.0.0.1", attempts = 20) => {
566
+ for (let port = preferred; port < preferred + attempts; port += 1) if (!await portAnswers(port, host) && await portBindable(port, host)) return port;
567
+ throw new Error(`No free port between ${preferred} and ${preferred + attempts - 1} on ${host}. Set PORT to one.`);
568
+ };
569
+ /** How long a port reserved by a server starting is held from the others: past it, the one that reserved it died. */
570
+ var RESERVED_MS = 6e4;
571
+ /**
572
+ * A free port as {@link freePort} finds it, held from the other servers starting on this machine until `release`: two
573
+ * development servers started at once both found 8080 free and both bound it — one failed (a run's copies, started by
574
+ * their agents together). Each port taken is a file created only if absent (`wx`), in the system's temporary folder;
575
+ * one left by a process that died is taken again once it is older than a minute.
576
+ */
577
+ var reservePort = async (preferred, host = "127.0.0.1", attempts = 20) => {
578
+ const folder = path.join(os.tmpdir(), "plitzi-ports");
579
+ mkdirSync(folder, { recursive: true });
580
+ for (let port = preferred; port < preferred + attempts; port += 1) {
581
+ const file = path.join(folder, `${String(port)}.lock`);
582
+ if ((() => {
583
+ try {
584
+ return Date.now() - statSync(file).mtimeMs > RESERVED_MS;
585
+ } catch {
586
+ return false;
587
+ }
588
+ })()) rmSync(file, { force: true });
589
+ let reserved = false;
590
+ try {
591
+ writeFileSync(file, String(process.pid), { flag: "wx" });
592
+ reserved = true;
593
+ } catch {}
594
+ if (reserved) {
595
+ if (!await portAnswers(port, host) && await portBindable(port, host)) return {
596
+ port,
597
+ release: () => rmSync(file, { force: true })
598
+ };
599
+ rmSync(file, { force: true });
600
+ }
601
+ }
602
+ throw new Error(`No free port between ${preferred} and ${preferred + attempts - 1} on ${host}. Set PORT to one.`);
603
+ };
604
+ // src/http/health.ts
605
+ var buildHealthPayload = (identity = {}) => ({
606
+ Server: identity.name ?? "SDK Server",
607
+ Version: identity.version ? `v${identity.version}` : "unknown",
608
+ role: identity.role,
609
+ ...identity.instance === void 0 ? {} : { Instance: identity.instance }
610
+ });
611
+ /**
612
+ * Attach the generic /health endpoint to an Express-style app — a deployment whose roles are not all on the sdk-server
613
+ * http pipeline. Servers built on the pipeline get the same endpoint from `healthStage`.
614
+ *
615
+ * `check` is what makes it a readiness probe rather than a liveness one, and it is here for the same reason it is on
616
+ * `healthStage`: a role reports the stores it depends on, and `healthy: false` answers 503 so an orchestrator stops
617
+ * routing to a replica that can serve nothing. Without it the two halves of one deployment answered different
618
+ * questions at the same path — and the Express half's real check ended up as a second, password-guarded endpoint the
619
+ * probes were never pointed at.
620
+ */
621
+ var registerHealthCheck = (app, identity, check) => {
622
+ const payload = buildHealthPayload(identity);
623
+ app.get("/health", (_req, res) => {
624
+ (async () => {
625
+ let live = {};
626
+ if (check) try {
627
+ live = await check();
628
+ } catch (error) {
629
+ live = {
630
+ healthy: false,
631
+ reason: error instanceof Error ? error.message : String(error)
632
+ };
633
+ }
634
+ res.writeHead(live.healthy === false ? 503 : 200, { "Content-Type": "application/json" });
635
+ res.end(JSON.stringify({
636
+ ...payload,
637
+ ...live
638
+ }));
639
+ })();
640
+ });
641
+ };
642
+ // src/http/middlewares/auth.ts
643
+ var authMiddleware = (adapters) => {
644
+ return async (req, res, next) => {
645
+ const user = await adapters.getUser?.(req, res);
646
+ req.ctx.user = user;
647
+ await next();
648
+ };
649
+ };
650
+ // src/http/middlewares/basicAuth.ts
651
+ var sendChallenge = (res, domain, realm) => {
652
+ res.setHeader("WWW-Authenticate", `Basic realm="${realm} - ${domain}", charset="UTF-8"`);
653
+ res.setHeader("Cache-Control", "no-store");
654
+ res.setStatus(401);
655
+ res.end();
656
+ };
657
+ /** How long a checked credential is believed without asking again. */
658
+ var CREDENTIAL_TTL_MS = 3e5;
659
+ var basicAuthMiddleware = (options = {}) => {
660
+ const { realm = "Restricted Area", cacheTtlMs = CREDENTIAL_TTL_MS } = options;
661
+ const authCache = new TtlCache(cacheTtlMs, 1e4);
662
+ return async (req, res, next) => {
663
+ const credential = req.ctx.spaceDeployment?.credential;
664
+ if (!credential || credential.provider !== "ssr") {
665
+ await next();
666
+ return;
667
+ }
668
+ const { data: credentials } = credential;
669
+ if (credentials.type !== "basic") {
670
+ await next();
671
+ return;
672
+ }
673
+ const hostname = req.hostname;
674
+ const authHeader = req.headers["authorization"];
675
+ if (!authHeader || !authHeader.startsWith("Basic ")) {
676
+ sendChallenge(res, hostname, realm);
677
+ return;
678
+ }
679
+ let token;
680
+ let decoded;
681
+ try {
682
+ token = authHeader.slice(6);
683
+ decoded = Buffer.from(token, "base64").toString("utf8");
684
+ } catch {
685
+ sendChallenge(res, hostname, realm);
686
+ return;
687
+ }
688
+ const cacheKey = `${hostname}:${crypto.createHash("sha256").update(token).digest("hex")}`;
689
+ if (authCache.get(cacheKey)) {
690
+ await next();
691
+ return;
692
+ }
693
+ const colonIdx = decoded.indexOf(":");
694
+ if (colonIdx === -1) {
695
+ sendChallenge(res, hostname, realm);
696
+ return;
697
+ }
698
+ const user = decoded.slice(0, colonIdx);
699
+ const pass = decoded.slice(colonIdx + 1);
700
+ const expectedUser = Buffer.from(credentials.user);
701
+ const expectedPass = Buffer.from(credentials.pass);
702
+ const actualUser = Buffer.from(user);
703
+ const actualPass = Buffer.from(pass);
704
+ const userMatch = actualUser.length === expectedUser.length && crypto.timingSafeEqual(actualUser, expectedUser);
705
+ const passMatch = actualPass.length === expectedPass.length && crypto.timingSafeEqual(actualPass, expectedPass);
706
+ if (!userMatch || !passMatch) {
707
+ sendChallenge(res, hostname, realm);
708
+ return;
709
+ }
710
+ authCache.set(cacheKey, true);
711
+ await next();
712
+ };
713
+ };
714
+ // src/http/mimeTypes.ts
715
+ var MIME_TYPES = {
716
+ ".html": "text/html; charset=utf-8",
717
+ ".js": "application/javascript; charset=utf-8",
718
+ ".mjs": "application/javascript; charset=utf-8",
719
+ ".cjs": "application/javascript; charset=utf-8",
720
+ ".css": "text/css; charset=utf-8",
721
+ ".json": "application/json; charset=utf-8",
722
+ ".png": "image/png",
723
+ ".jpg": "image/jpeg",
724
+ ".jpeg": "image/jpeg",
725
+ ".gif": "image/gif",
726
+ ".svg": "image/svg+xml",
727
+ ".webp": "image/webp",
728
+ ".ico": "image/x-icon",
729
+ ".woff": "font/woff",
730
+ ".woff2": "font/woff2",
731
+ ".ttf": "font/ttf",
732
+ ".eot": "application/vnd.ms-fontobject",
733
+ ".txt": "text/plain; charset=utf-8",
734
+ ".xml": "application/xml"
735
+ };
736
+ var IMMUTABLE_EXTS = /* @__PURE__ */ new Set([
737
+ ".js",
738
+ ".mjs",
739
+ ".cjs",
740
+ ".css",
741
+ ".woff",
742
+ ".woff2",
743
+ ".ttf",
744
+ ".eot"
745
+ ]);
746
+ var getMimeType = (filePath) => {
747
+ return MIME_TYPES[filePath.slice(filePath.lastIndexOf(".")).toLowerCase()] ?? "application/octet-stream";
748
+ };
749
+ var getCacheControl = (filePath, policy = "versioned") => {
750
+ if (policy === "revalidate") return "no-cache";
751
+ const ext = filePath.slice(filePath.lastIndexOf(".")).toLowerCase();
752
+ return IMMUTABLE_EXTS.has(ext) ? "public, max-age=31536000, immutable" : "public, max-age=3600";
753
+ };
754
+ // src/http/navigation.ts
755
+ /**
756
+ * A full-page form submission, as opposed to a script's fetch.
757
+ *
758
+ * The difference decides how an auth flow answers: a browser navigating away from a page it has already left shows
759
+ * its own error page for a bodyless 401, and stays on the stale one for a 204. Either way the visitor sees the wrong
760
+ * thing, so a navigation is answered with a redirect and the view re-renders through a GET. A fetch wants the body.
761
+ */
762
+ var isNavigation = (req) => req.headers["sec-fetch-mode"] === "navigate";
763
+ /**
764
+ * Same-origin only: absolute URLs and protocol-relative `//host` are refused, to avoid an open redirect — and so is
765
+ * `/\host`, which a browser reads as `//host`.
766
+ */
767
+ var safeRedirectTarget = (req, param = "redirect") => {
768
+ const target = req.query[param];
769
+ return target && target.startsWith("/") && !/^\/[\\/]/u.test(target) ? target : "/";
770
+ };
771
+ // src/http/onAbort.ts
772
+ /**
773
+ * Subscribes to a signal, and covers the case every hand-rolled subscription misses: one that is ALREADY aborted.
774
+ *
775
+ * `addEventListener('abort', …)` on a signal that has already fired never calls back — the event is long gone — so
776
+ * a listener attached after any `await` is a cancellation silently dropped. That window is not theoretical: an
777
+ * action is READ before its run begins, and a page that gave up during that read left the run to carry on holding
778
+ * a slot and a connection for nobody.
779
+ *
780
+ * Returns the unsubscribe, so a caller that outlives the signal does not leak a listener onto it.
781
+ */
782
+ var onAbort = (signal, stop) => {
783
+ if (!signal) return () => {};
784
+ if (signal.aborted) {
785
+ stop();
786
+ return () => {};
787
+ }
788
+ signal.addEventListener("abort", stop, { once: true });
789
+ return () => signal.removeEventListener("abort", stop);
790
+ };
791
+ // src/http/runMiddlewares.ts
792
+ /**
793
+ * Runs the chain, each middleware handing on by calling `next`. `timed`, when given, is told how long each one took
794
+ * before it handed on — its own time, not the chain's after it — or until it ended the chain.
795
+ */
796
+ var runMiddlewares = async (middlewares, req, res, timed) => {
797
+ let index = 0;
798
+ const state = { stopped: false };
799
+ const next = async () => {
800
+ if (state.stopped) return;
801
+ const mw = index < middlewares.length ? middlewares[index++] : void 0;
802
+ if (!mw) return;
803
+ const nextState = { called: false };
804
+ const at = index - 1;
805
+ const started = timed ? performance.now() : 0;
806
+ await mw(req, res, async () => {
807
+ nextState.called = true;
808
+ timed?.(at, performance.now() - started);
809
+ await next();
810
+ });
811
+ if (!nextState.called) {
812
+ timed?.(at, performance.now() - started);
813
+ state.stopped = true;
814
+ }
815
+ };
816
+ await next();
817
+ if (req.spaceDeployment) req.ctx.spaceDeployment = req.spaceDeployment;
818
+ return state.stopped;
819
+ };
820
+ // src/http/transports.ts
821
+ var tlsOptions = (config, label = "Server") => {
822
+ const { tls } = config;
823
+ if (!tls) throw new Error(`[${label}] TLS config required`);
824
+ return {
825
+ key: tls.key,
826
+ cert: tls.cert,
827
+ minVersion: tls.minVersion ?? "TLSv1.3"
828
+ };
829
+ };
830
+ var protoLabel = (version, hasTls) => {
831
+ if (version >= 3) return "HTTP/2+3 (TLS)";
832
+ if (version >= 2) return hasTls ? "HTTP/2 (TLS)" : "HTTP/1.1 - TLS Missing";
833
+ return hasTls ? "HTTPS/1.1" : "HTTP/1.1";
834
+ };
835
+ /**
836
+ * Upgrades reach HTTP/1.1 servers only. Over HTTP/2 a browser has no way to ask for one — node does not speak the
837
+ * extended CONNECT that WebSockets over h2 need — so a client there stays on what plain requests can do.
838
+ */
839
+ var withUpgrades = (server, handler) => {
840
+ if (handler.upgrade) server.on("upgrade", handler.upgrade);
841
+ return server;
842
+ };
843
+ var buildTransport = (config, handler, port, label = "Server") => {
844
+ const version = config.httpVersion ?? 2;
845
+ let primary;
846
+ let h3;
847
+ if (version >= 3) {
848
+ primary = http2.createSecureServer({
849
+ ...tlsOptions(config, label),
850
+ allowHTTP1: true
851
+ }, handler);
852
+ (async () => {
853
+ try {
854
+ h3 = (await import("node:http3")).createServer(tlsOptions(config, label), handler);
855
+ h3.listen(port, "0.0.0.0", () => {
856
+ serverLog.info(label, `HTTP/3 (QUIC) listening on port ${port}`);
857
+ });
858
+ } catch {
859
+ serverLog.warn(label, "HTTP/3 unavailable — start Node.js with --experimental-quic (requires Node ≥ 23). Falling back to HTTP/2.");
860
+ }
861
+ })();
862
+ } else if (version >= 2) {
863
+ if (config.tls) primary = http2.createSecureServer({
864
+ ...tlsOptions(config, label),
865
+ allowHTTP1: true
866
+ }, handler);
867
+ else primary = withUpgrades(http.createServer(handler), handler);
868
+ } else if (config.tls) primary = withUpgrades(https.createServer(tlsOptions(config, label), handler), handler);
869
+ else primary = withUpgrades(http.createServer(handler), handler);
870
+ return {
871
+ primary,
872
+ h3
873
+ };
874
+ };
875
+ // src/http/server.ts
876
+ /**
877
+ * What went wrong taking the port, and what to do about it.
878
+ *
879
+ * A server that cannot bind used to surface as an unhandled `error` event: a stack trace through `node:net` naming
880
+ * neither the port nor the server, printed as if the process had crashed at random. It is the first thing a new
881
+ * deployment hits — two roles configured on one port, or a previous run still holding it — so it is worth saying
882
+ * plainly.
883
+ */
884
+ var bindFailure = (error, port, label) => {
885
+ if (error.code === "EADDRINUSE") return `[${label}] cannot bind port ${port}: already in use. Another server is running, or the previous one has not released it yet — find it with \`lsof -iTCP:${port} -sTCP:LISTEN\`, or start this one on another port.`;
886
+ if (error.code === "EACCES") return `[${label}] cannot bind port ${port}: permission denied. Ports below 1024 need privileges — run elevated, or use a port above 1024 and put a proxy in front.`;
887
+ if (error.code === "EADDRNOTAVAIL") return `[${label}] cannot bind port ${port}: the requested host is not an address of this machine.`;
888
+ return `[${label}] failed to bind port ${port}: ${error.message}`;
889
+ };
890
+ var createHttpServer = (config, makeHandlerForPort, parts) => {
891
+ const { label } = parts;
892
+ const statsProblem = statsConfigProblem(config);
893
+ if (statsProblem) throw new Error(`[${label}] ${statsProblem}`);
894
+ const version = config.httpVersion ?? (config.tls ? 2 : 1);
895
+ if (version >= 3 && !config.tls) throw new Error(`[${label}] httpVersion: ${version} requires a tls config with key and cert`);
896
+ let primary;
897
+ let connections;
898
+ let h3;
899
+ let fleet;
900
+ let closed = false;
901
+ const plan = resolveWorkers(config.workers);
902
+ const role = fleetRole(plan);
903
+ return {
904
+ channel: role === "single" ? void 0 : channelName(label),
905
+ listen(port, host = "0.0.0.0") {
906
+ if (plan.requested !== void 0 && role !== "worker") serverLog.warn(label, `${plan.requested} workers asked for, ${plan.count} cores to run them on: starting ${plan.count}`);
907
+ if (role === "primary") return new Promise((resolve) => {
908
+ (parts.beforeFork?.() ?? Promise.resolve()).catch((error) => serverLog.error(label, "preparing for the workers failed", error)).then(async () => {
909
+ const { startFleet } = await import("../chunks/supervisor-Dh34v1vq.mjs");
910
+ if (closed) return;
911
+ fleet = startFleet(plan.count, label, parts.fleetStores ?? {});
912
+ serverLog.info(label, `${plan.count} workers on ${host}:${port}`);
913
+ await fleet.listening;
914
+ resolve();
915
+ }).catch((error) => {
916
+ serverLog.error(label, "the workers could not start", error);
917
+ process.exitCode = 1;
918
+ });
919
+ });
920
+ const handler = makeHandlerForPort(port);
921
+ ({primary, h3} = buildTransport(config, handler, port, label));
922
+ connections = watchConnections(primary);
923
+ primary.on("error", (error) => {
924
+ if (config.onListenError) {
925
+ config.onListenError(error, {
926
+ port,
927
+ host,
928
+ label
929
+ });
930
+ return;
931
+ }
932
+ serverLog.error(label, bindFailure(error, port, label));
933
+ process.exitCode = 1;
934
+ process.exit(1);
935
+ });
936
+ const bound = primary;
937
+ return new Promise((resolve) => {
938
+ bound.listen(port, host, () => {
939
+ serverLog.info(label, `${protoLabel(version, !!config.tls)} - listening on ${host}:${port}`);
940
+ parts.onListen?.();
941
+ resolve();
942
+ });
943
+ });
944
+ },
945
+ async close() {
946
+ closed = true;
947
+ const { announceMs, graceMs } = shutdownOf(config, { graceMs: SHUTDOWN_GRACE_MS });
948
+ markStopping(config);
949
+ parts.onStopping?.();
950
+ if (announceMs > 0 && primary) {
951
+ serverLog.info(label, `stopping: /health answers 503 for ${String(announceMs)} ms, then what runs finishes`);
952
+ await new Promise((resolve) => setTimeout(resolve, announceMs));
953
+ }
954
+ await fleet?.stop();
955
+ fleet = void 0;
956
+ const draining = connections?.drain(label, graceMs);
957
+ const quic = h3;
958
+ primary = void 0;
959
+ connections = void 0;
960
+ h3 = void 0;
961
+ parts.onClosing?.();
962
+ await parts.onDestroy?.();
963
+ await Promise.all([draining, quic && new Promise((resolve, reject) => {
964
+ quic.close((error) => {
965
+ if (error && !("code" in error && error.code === "ERR_SERVER_NOT_RUNNING")) {
966
+ reject(error);
967
+ return;
968
+ }
969
+ resolve();
970
+ });
971
+ })]);
972
+ }
973
+ };
974
+ };
975
+ // src/http/sse.ts
976
+ /** How often a comment frame goes out. Short enough that a dead peer is noticed in seconds, long enough that an
977
+ * idle stream costs nothing worth counting. */
978
+ var HEARTBEAT_MS = 15e3;
979
+ /**
980
+ * How much unread body may pile up before the stream is dropped.
981
+ *
982
+ * A `write` that answers `false` has been buffered rather than sent, which is normal for a moment and a leak
983
+ * forever: a peer that stopped reading — a phone that slept, a proxy that wedged — otherwise has everything sent to
984
+ * it accumulated in memory. The socket says nothing, so the only signal is this one.
985
+ */
986
+ var MAX_BUFFERED_BYTES = 1e6;
987
+ /** What the host has written but not yet handed to the socket. Node's own response reports it; the minimum raw
988
+ * response this server accepts does not have to, and a host that cannot say simply never trips the cap. */
989
+ var bufferedBytes = (raw) => {
990
+ const { writableLength } = raw;
991
+ return typeof writableLength === "number" ? writableLength : 0;
992
+ };
993
+ /**
994
+ * Opens a Server-Sent Events response — an action's progress, a realtime channel.
995
+ *
996
+ * Written straight to the RAW response, never through the response helpers: those compress the body, set a
997
+ * Content-Length and end it in one go, which is precisely what a stream cannot do. `no-transform` says the same
998
+ * thing to every proxy in between, and `X-Accel-Buffering: no` says it to nginx, which otherwise holds frames
999
+ * until its buffer fills and turns a live stream into one late burst.
1000
+ */
1001
+ var openEventStream = (raw, { onAbort, headers = {}, retryMs }) => {
1002
+ let open = true;
1003
+ raw.writeHead(200, {
1004
+ "Content-Type": "text/event-stream; charset=utf-8",
1005
+ "Cache-Control": "no-cache, no-transform",
1006
+ Connection: "keep-alive",
1007
+ "X-Accel-Buffering": "no",
1008
+ ...headers
1009
+ });
1010
+ raw.write(`retry: ${retryMs}\n\n`);
1011
+ const drop = () => {
1012
+ open = false;
1013
+ clearInterval(heartbeat);
1014
+ onAbort();
1015
+ };
1016
+ const heartbeat = setInterval(() => {
1017
+ if (!open) return;
1018
+ try {
1019
+ raw.write(": ping\n\n");
1020
+ } catch {
1021
+ drop();
1022
+ }
1023
+ }, HEARTBEAT_MS);
1024
+ const close = () => {
1025
+ if (!open) return;
1026
+ open = false;
1027
+ clearInterval(heartbeat);
1028
+ try {
1029
+ raw.end();
1030
+ } catch {}
1031
+ };
1032
+ return {
1033
+ send: (event, data) => {
1034
+ if (!open) return;
1035
+ try {
1036
+ raw.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
1037
+ if (bufferedBytes(raw) > MAX_BUFFERED_BYTES) {
1038
+ drop();
1039
+ try {
1040
+ raw.end();
1041
+ } catch {}
1042
+ }
1043
+ } catch {
1044
+ drop();
1045
+ }
1046
+ },
1047
+ close,
1048
+ isOpen: () => open
1049
+ };
1050
+ };
1051
+ // src/http/stages/crossSiteWrites.ts
1052
+ /** GET, HEAD and OPTIONS change nothing: a link or an `<img>` from anywhere is how the web works. */
1053
+ var SAFE_METHODS = /* @__PURE__ */ new Set([
1054
+ "GET",
1055
+ "HEAD",
1056
+ "OPTIONS"
1057
+ ]);
1058
+ /**
1059
+ * Whether this request is a write a page of another origin caused, and so is refused — answered here, 403
1060
+ * `reason: 'foreign'`, when it is.
1061
+ *
1062
+ * Not only a write a session cookie could authenticate: a server holding credentials of its own (a token for somebody's
1063
+ * calendar, an API key) or a tool with no sign-in at all acts for whoever reaches it, and a plain form POST from any
1064
+ * page open in the same browser reaches it without a preflight. Passes:
1065
+ *
1066
+ * - a safe method;
1067
+ * - `Authorization` — a page of another origin cannot set it without a preflight this server never allows;
1068
+ * - a request that is not a browser's (no `Sec-Fetch-Site`, no `Origin`): a webhook, `curl`, another server;
1069
+ * - a page of this origin (`same-origin` — never merely `same-site`: another port of this host, or a sibling
1070
+ * sub-domain, is where somebody else's pages are served), or of an origin in `crossSiteWrites.origins`;
1071
+ * - a path in `crossSiteWrites.paths` — a form other sites post to by design.
1072
+ */
1073
+ var refusedCrossSite = (ctx) => {
1074
+ const { req, res, config } = ctx;
1075
+ const allowed = config.crossSiteWrites;
1076
+ if (SAFE_METHODS.has(req.method.toUpperCase()) || req.headers.authorization !== void 0 || allowed?.paths?.(req.path) === true || !crossSiteRequest(carrierOf(req), (origin) => allowed?.origins?.includes(origin) === true)) return false;
1077
+ ctx.operation = "refused:cross-site";
1078
+ res.setStatus(403);
1079
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
1080
+ res.send(JSON.stringify({
1081
+ error: `A page of another origin may not ${req.method} ${req.path} here: name its origin in the server's \`crossSiteWrites.origins\`, or the path in \`crossSiteWrites.paths\``,
1082
+ reason: "foreign"
1083
+ }));
1084
+ return true;
1085
+ };
1086
+ /**
1087
+ * Every write the page server answers after it — server actions, realtime publishes, a space's `/fn/` routes and its
1088
+ * runtime's endpoints, the deployment's own data stages — refused when a page of another origin caused it (see
1089
+ * {@link refusedCrossSite}). After the stages that gate themselves (`preAuth`: the `/auth` flows with their own CSRF,
1090
+ * MCP and its OAuth, the preview's shared secret), before everything else.
1091
+ */
1092
+ var crossSiteWritesStage = refusedCrossSite;
1093
+ // src/http/stages/health.ts
1094
+ /**
1095
+ * Liveness/readiness endpoint for standalone servers (k8s probes). Always answers at /health so every server built
1096
+ * on sdk-server has one without the consumer wiring it. The body is the generic identity payload (from
1097
+ * `config.health.name/version/role`) unless `payload` overrides it entirely.
1098
+ *
1099
+ * `check` is what makes it a readiness probe: it reports live state — the stores this process depends on, most
1100
+ * often — and `healthy: false` answers 503 so an orchestrator stops routing to a replica that cannot serve. A
1101
+ * server that answered 200 while its database was gone is one an orchestrator keeps sending traffic to.
1102
+ */
1103
+ var healthStage = async (ctx) => {
1104
+ const health = ctx.config.health;
1105
+ if (ctx.req.path !== (health?.path ?? "/health")) return false;
1106
+ const payload = health?.payload ?? buildHealthPayload(health);
1107
+ let live = {};
1108
+ if (health?.check) try {
1109
+ live = await health.check();
1110
+ } catch (error) {
1111
+ live = {
1112
+ healthy: false,
1113
+ reason: error instanceof Error ? error.message : String(error)
1114
+ };
1115
+ }
1116
+ if (isStopping(ctx.config)) live = {
1117
+ ...live,
1118
+ healthy: false,
1119
+ stopping: true,
1120
+ reason: "stopping: finishing what it runs, taking nothing new"
1121
+ };
1122
+ ctx.res.setHeader("Content-Type", "application/json");
1123
+ ctx.res.setStatus(live.healthy === false ? 503 : 200);
1124
+ ctx.res.send(JSON.stringify({
1125
+ ...payload,
1126
+ ...live
1127
+ }));
1128
+ return true;
1129
+ };
1130
+ // src/http/stages/middlewares.ts
1131
+ var createMiddlewaresStage = () => {
1132
+ let built;
1133
+ return async (ctx) => {
1134
+ const { config, req, res } = ctx;
1135
+ if (built?.config !== config) built = {
1136
+ config,
1137
+ chain: [
1138
+ spaceDeploymentMiddleware(config.adapters, config),
1139
+ basicAuthMiddleware({ cacheTtlMs: config.cacheTtlMs }),
1140
+ authMiddleware(config.adapters),
1141
+ ...config.middlewares || []
1142
+ ],
1143
+ names: [
1144
+ "deployment",
1145
+ "basicAuth",
1146
+ "auth",
1147
+ ...(config.middlewares ?? []).map((middleware, index) => middleware.name || `middleware${String(index + 1)}`)
1148
+ ]
1149
+ };
1150
+ const { names } = built;
1151
+ return await runMiddlewares(built.chain, req, res, config.devMode ? (index, ms) => {
1152
+ req.ctx.timings = [...req.ctx.timings ?? [], {
1153
+ name: names[index],
1154
+ dur: Math.round(ms)
1155
+ }];
1156
+ } : void 0) || res.status !== 200;
1157
+ };
1158
+ };
1159
+ // src/http/staticFiles.ts
1160
+ var compressedFiles = new CompressedFileCache(16777216);
1161
+ var isText = (mimeType) => /^text\/|javascript|json|xml|svg/.test(mimeType);
1162
+ var buildEtag = (stat) => `"${stat.mtimeMs.toString(36)}-${stat.size.toString(36)}"`;
1163
+ var serveFile = (req, res, filePath, stat, cache) => {
1164
+ const etag = buildEtag(stat);
1165
+ const ifNoneMatch = req.headers["if-none-match"];
1166
+ res.setHeader("ETag", etag);
1167
+ res.setHeader("Cache-Control", getCacheControl(filePath, cache));
1168
+ res.setHeader("Last-Modified", stat.mtime.toUTCString());
1169
+ if (ifNoneMatch === etag) {
1170
+ res.setStatus(304);
1171
+ res.end();
1172
+ return true;
1173
+ }
1174
+ const mimeType = getMimeType(filePath);
1175
+ res.setHeader("Content-Type", mimeType);
1176
+ if (isText(mimeType)) {
1177
+ res.send(() => fs.readFileSync(filePath, "utf-8"), { compressed: compressedFiles.storeFor(filePath, etag) });
1178
+ compressedFiles.trim();
1179
+ return true;
1180
+ }
1181
+ res.send(fs.readFileSync(filePath));
1182
+ return true;
1183
+ };
1184
+ var serveStatic = (req, res, rootDir, cache = "versioned") => {
1185
+ const relative = req.path.replace(/^\/+/, "");
1186
+ const filePath = path.resolve(rootDir, relative);
1187
+ const resolvedRoot = path.resolve(rootDir);
1188
+ if (filePath !== resolvedRoot && !filePath.startsWith(resolvedRoot + path.sep)) {
1189
+ res.setStatus(403);
1190
+ res.send("Forbidden");
1191
+ return true;
1192
+ }
1193
+ if (!fs.existsSync(filePath)) return false;
1194
+ const stat = fs.statSync(filePath);
1195
+ if (stat.isDirectory()) {
1196
+ const indexPath = path.join(filePath, "index.html");
1197
+ if (!fs.existsSync(indexPath)) return false;
1198
+ return serveFile(req, res, indexPath, fs.statSync(indexPath), cache);
1199
+ }
1200
+ return serveFile(req, res, filePath, stat, cache);
1201
+ };
1202
+ // src/http/stages/static.ts
1203
+ var publicDirStage = (ctx) => ctx.config.publicDir ? serveStatic(ctx.req, ctx.res, ctx.config.publicDir, "revalidate") : false;
1204
+ var wellKnownStage = (ctx) => {
1205
+ if (!ctx.req.path.startsWith("/.well-known/")) return false;
1206
+ ctx.res.setStatus(404);
1207
+ ctx.res.end();
1208
+ return true;
1209
+ };
1210
+ var configStaticStage = (ctx) => {
1211
+ const { static: mounts } = ctx.config;
1212
+ if (!mounts) return false;
1213
+ for (const [prefix, rootDir] of Object.entries(mounts)) {
1214
+ const normalizedPrefix = prefix.endsWith("/") ? prefix : `${prefix}/`;
1215
+ if (ctx.req.path === prefix || ctx.req.path.startsWith(normalizedPrefix)) {
1216
+ ctx.res.setHeader("Access-Control-Allow-Origin", "*");
1217
+ ctx.res.setHeader("Cross-Origin-Resource-Policy", "cross-origin");
1218
+ if (serveStatic({
1219
+ ...ctx.req,
1220
+ path: ctx.req.path.slice(prefix.length) || "/"
1221
+ }, ctx.res, rootDir)) return true;
1222
+ }
1223
+ }
1224
+ return false;
1225
+ };
1226
+ // src/http/unusedPort.ts
1227
+ /** The lowest port handed out: above the well-known and the registered ones most local services sit on. */
1228
+ var LOWEST = 1e4;
1229
+ /** Below it, as far as a system lets a port be chosen for nobody: Linux's default, and below macOS's and Windows's. */
1230
+ var EPHEMERAL_DEFAULT = 32768;
1231
+ var ATTEMPTS = 50;
1232
+ /**
1233
+ * Where the system starts handing out ports by itself — to every outgoing connection and every `listen(0)`. Linux says
1234
+ * where in `/proc`; macOS and Windows start at 49152, above Linux's default.
1235
+ */
1236
+ var ephemeralStart = () => {
1237
+ try {
1238
+ const [low] = readFileSync("/proc/sys/net/ipv4/ip_local_port_range", "utf-8").trim().split(/\s+/).map(Number);
1239
+ if (Number.isInteger(low) && low > 10050) return Math.min(low, EPHEMERAL_DEFAULT);
1240
+ } catch {}
1241
+ return EPHEMERAL_DEFAULT;
1242
+ };
1243
+ /**
1244
+ * A port nobody holds, for a test to listen on — chosen where the system never hands one out by itself.
1245
+ *
1246
+ * Not one the system hands out (`listen(0)`): that range is the one every outgoing connection takes its local port
1247
+ * from, so between the moment a port is handed out and the moment the test listens on it, a request of a test running
1248
+ * beside it — another worker's `fetch`, a database connection — can take it, and the listen fails with `EADDRINUSE` on
1249
+ * a run that has nothing wrong with it. Below that range only a port somebody chose explicitly is ever taken, and it is
1250
+ * looked at first: one that answers, or that this process may not listen on, is passed over.
1251
+ */
1252
+ var unusedPort = async (host = "127.0.0.1") => {
1253
+ const span = ephemeralStart() - LOWEST;
1254
+ for (let attempt = 0; attempt < ATTEMPTS; attempt += 1) {
1255
+ const port = LOWEST + Math.floor(Math.random() * span);
1256
+ if (!await portAnswers(port, host) && await portBindable(port, host)) return port;
1257
+ }
1258
+ throw new Error(`No free port between ${String(LOWEST)} and ${String(LOWEST + span)} on ${host} after ${String(ATTEMPTS)} tries`);
1259
+ };
1260
+ // src/http/webExchange.ts
1261
+ var BODYLESS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
1262
+ /**
1263
+ * An incoming request as a web `Request` at `url` — its headers but those named in `without` (lower case), and its
1264
+ * body read whole, within the server's body limit. What a web-standard handler takes: an MCP transport, an endpoint a
1265
+ * space runtime declares.
1266
+ */
1267
+ var webRequestOf = async (raw, url, without = []) => {
1268
+ const headers = new Headers();
1269
+ Object.entries(raw.headers).forEach(([name, value]) => {
1270
+ if (name.startsWith(":") || without.includes(name)) return;
1271
+ (Array.isArray(value) ? value : value === void 0 ? [] : [value]).forEach((one) => headers.append(name, one));
1272
+ });
1273
+ const method = raw.method ?? "GET";
1274
+ return new Request(url, {
1275
+ method,
1276
+ headers,
1277
+ ...BODYLESS.has(method) ? {} : { body: new Uint8Array(await readRawBytes(raw)) }
1278
+ });
1279
+ };
1280
+ /**
1281
+ * A web `Response` written onto a node one: its status and headers, then its body as it comes — a stream too, chunk by
1282
+ * chunk, which is what an event stream needs — until it ends or `signal` says the caller went away.
1283
+ */
1284
+ var writeWebResponse = async (rawRes, response, signal) => {
1285
+ const headers = {};
1286
+ response.headers.forEach((value, name) => {
1287
+ headers[name] = value;
1288
+ });
1289
+ rawRes.writeHead(response.status, headers);
1290
+ if (!response.body) {
1291
+ rawRes.end();
1292
+ return;
1293
+ }
1294
+ const reader = response.body.getReader();
1295
+ const stop = () => {
1296
+ reader.cancel();
1297
+ };
1298
+ signal?.addEventListener("abort", stop, { once: true });
1299
+ try {
1300
+ for (;;) {
1301
+ const { done, value } = await reader.read();
1302
+ if (done) break;
1303
+ rawRes.write(Buffer.from(value));
1304
+ }
1305
+ } catch {} finally {
1306
+ signal?.removeEventListener("abort", stop);
1307
+ rawRes.end();
1308
+ }
1309
+ };
1310
+ // src/http/wsFrame.ts
1311
+ /** A WebSocket frame as text, whichever of its three shapes `ws` delivered it in. */
1312
+ var frameText = (frame) => Buffer.isBuffer(frame) ? frame.toString("utf8") : Array.isArray(frame) ? Buffer.concat(frame).toString("utf8") : Buffer.from(frame).toString("utf8");
1313
+ export { DEFAULT_COMPRESSION, IMMUTABLE_EXTS, MIME_TYPES, SHUTDOWN_ANNOUNCE_MS, SHUTDOWN_GRACE_MS, applySecurityHeaders, authMiddleware, basicAuthMiddleware, bearerMatches, broadcast, buildHealthPayload, buildResponseHelpers, buildTransport, channelName, clientIp, closeOnSignals, compressBody, configStaticStage, createFleetClient, createFleetHub, createHttpServer, createListeners, createMiddlewaresStage, createStoreHost, crossSiteWritesStage, fleetRole, fleetStore, fleetWorkerEnv, forwardedIp, frameAncestorsOf, frameText, freePort, getCacheControl, getMimeType, healthStage, hostable, hstsFor, isFleetMessage, isFleetWorker, isNavigation, isStopping, makeHandler, markStopping, onAbort, onBroadcast, openEventStream, parseRequest, portAnswers, portBindable, protoLabel, publicDirStage, readRawBody, readRawBytes, refusedCrossSite, registerHealthCheck, requestAuthority, requestOrigin, reservePort, resolveCompression, resolveWorkers, runMiddlewares, runsFleetJobs, safeRedirectTarget, selectEncoding, serveStatic, shutdownOf, socketResponse, startHub, tlsOptions, unusedPort, watchConnections, webRequestOf, wellKnownStage, writeWebResponse };