@eidentic/server 0.1.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.
@@ -0,0 +1,1028 @@
1
+ // ../../node_modules/.pnpm/@hono+node-server@2.0.4_hono@4.12.23/node_modules/@hono/node-server/dist/constants-BLSFu_RU.mjs
2
+ var X_ALREADY_SENT = "x-hono-already-sent";
3
+
4
+ // ../../node_modules/.pnpm/@hono+node-server@2.0.4_hono@4.12.23/node_modules/@hono/node-server/dist/index.mjs
5
+ import { STATUS_CODES, createServer } from "node:http";
6
+ import { Http2ServerRequest, constants } from "node:http2";
7
+ import { Readable } from "node:stream";
8
+ import { defineWebSocketHelper } from "hono/ws";
9
+ var RequestError = class extends Error {
10
+ constructor(message, options) {
11
+ super(message, options);
12
+ this.name = "RequestError";
13
+ }
14
+ };
15
+ var reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;
16
+ var reDotSegment = /\/\.\.?(?:[/?#]|$)/;
17
+ var reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;
18
+ var buildUrl = (scheme, host, incomingUrl) => {
19
+ const url = `${scheme}://${host}${incomingUrl}`;
20
+ if (!reValidHost.test(host)) {
21
+ const urlObj = new URL(url);
22
+ if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase()) throw new RequestError("Invalid host header");
23
+ return urlObj.href;
24
+ } else if (incomingUrl.length === 0) return url + "/";
25
+ else {
26
+ if (incomingUrl.charCodeAt(0) !== 47) throw new RequestError("Invalid URL");
27
+ if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) return new URL(url).href;
28
+ return url;
29
+ }
30
+ };
31
+ var toRequestError = (e) => {
32
+ if (e instanceof RequestError) return e;
33
+ return new RequestError(e.message, { cause: e });
34
+ };
35
+ var GlobalRequest = global.Request;
36
+ var Request$1 = class extends GlobalRequest {
37
+ constructor(input, options) {
38
+ if (typeof input === "object" && getRequestCache in input) {
39
+ const hasReplacementBody = options !== void 0 && "body" in options && options.body != null;
40
+ if (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError("Cannot construct a Request with a Request object that has already been used.");
41
+ input = input[getRequestCache]();
42
+ }
43
+ if (typeof options?.body?.getReader !== "undefined") options.duplex ??= "half";
44
+ super(input, options);
45
+ }
46
+ };
47
+ var newHeadersFromIncoming = (incoming) => {
48
+ const headerRecord = [];
49
+ const rawHeaders = incoming.rawHeaders;
50
+ for (let i = 0, len = rawHeaders.length; i < len; i += 2) {
51
+ const key = rawHeaders[i];
52
+ if (key.charCodeAt(0) !== 58) headerRecord.push([key, rawHeaders[i + 1]]);
53
+ }
54
+ return new Headers(headerRecord);
55
+ };
56
+ var wrapBodyStream = /* @__PURE__ */ Symbol("wrapBodyStream");
57
+ var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
58
+ const init = {
59
+ method,
60
+ headers,
61
+ signal: abortController.signal
62
+ };
63
+ if (method === "TRACE") {
64
+ init.method = "GET";
65
+ const req = new Request$1(url, init);
66
+ Object.defineProperty(req, "method", { get() {
67
+ return "TRACE";
68
+ } });
69
+ return req;
70
+ }
71
+ if (!(method === "GET" || method === "HEAD")) if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {
72
+ controller.enqueue(incoming.rawBody);
73
+ controller.close();
74
+ } });
75
+ else if (incoming[wrapBodyStream]) {
76
+ let reader;
77
+ init.body = new ReadableStream({ async pull(controller) {
78
+ try {
79
+ reader ||= Readable.toWeb(incoming).getReader();
80
+ const { done, value } = await reader.read();
81
+ if (done) controller.close();
82
+ else controller.enqueue(value);
83
+ } catch (error) {
84
+ controller.error(error);
85
+ }
86
+ } });
87
+ } else init.body = Readable.toWeb(incoming);
88
+ return new Request$1(url, init);
89
+ };
90
+ var getRequestCache = /* @__PURE__ */ Symbol("getRequestCache");
91
+ var requestCache = /* @__PURE__ */ Symbol("requestCache");
92
+ var incomingKey = /* @__PURE__ */ Symbol("incomingKey");
93
+ var urlKey = /* @__PURE__ */ Symbol("urlKey");
94
+ var methodKey = /* @__PURE__ */ Symbol("methodKey");
95
+ var headersKey = /* @__PURE__ */ Symbol("headersKey");
96
+ var abortControllerKey = /* @__PURE__ */ Symbol("abortControllerKey");
97
+ var getAbortController = /* @__PURE__ */ Symbol("getAbortController");
98
+ var abortRequest = /* @__PURE__ */ Symbol("abortRequest");
99
+ var bodyBufferKey = /* @__PURE__ */ Symbol("bodyBuffer");
100
+ var bodyReadPromiseKey = /* @__PURE__ */ Symbol("bodyReadPromise");
101
+ var bodyConsumedDirectlyKey = /* @__PURE__ */ Symbol("bodyConsumedDirectly");
102
+ var bodyLockReaderKey = /* @__PURE__ */ Symbol("bodyLockReader");
103
+ var abortReasonKey = /* @__PURE__ */ Symbol("abortReason");
104
+ var newBodyUnusableError = () => {
105
+ return /* @__PURE__ */ new TypeError("Body is unusable");
106
+ };
107
+ var rejectBodyUnusable = () => {
108
+ return Promise.reject(newBodyUnusableError());
109
+ };
110
+ var textDecoder = new TextDecoder();
111
+ var consumeBodyDirectOnce = (request) => {
112
+ if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
113
+ request[bodyConsumedDirectlyKey] = true;
114
+ };
115
+ var toArrayBuffer = (buf) => {
116
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
117
+ };
118
+ var contentType = (request) => {
119
+ return (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get("content-type") || "";
120
+ };
121
+ var methodTokenRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
122
+ var normalizeIncomingMethod = (method) => {
123
+ if (typeof method !== "string" || method.length === 0) return "GET";
124
+ switch (method) {
125
+ case "DELETE":
126
+ case "GET":
127
+ case "HEAD":
128
+ case "OPTIONS":
129
+ case "POST":
130
+ case "PUT":
131
+ return method;
132
+ }
133
+ const upper = method.toUpperCase();
134
+ switch (upper) {
135
+ case "DELETE":
136
+ case "GET":
137
+ case "HEAD":
138
+ case "OPTIONS":
139
+ case "POST":
140
+ case "PUT":
141
+ return upper;
142
+ default:
143
+ return method;
144
+ }
145
+ };
146
+ var validateDirectReadMethod = (method) => {
147
+ if (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);
148
+ const normalized = method.toUpperCase();
149
+ if (normalized === "CONNECT" || normalized === "TRACK" || normalized === "TRACE" && method !== "TRACE") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);
150
+ };
151
+ var readBodyWithFastPath = (request, method, fromBuffer) => {
152
+ if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
153
+ const methodName = request.method;
154
+ if (methodName === "GET" || methodName === "HEAD") return request[getRequestCache]()[method]();
155
+ const methodValidationError = validateDirectReadMethod(methodName);
156
+ if (methodValidationError) return Promise.reject(methodValidationError);
157
+ if (request[requestCache]) {
158
+ if (methodName !== "TRACE") return request[requestCache][method]();
159
+ }
160
+ const alreadyUsedError = consumeBodyDirectOnce(request);
161
+ if (alreadyUsedError) return alreadyUsedError;
162
+ const raw = readRawBodyIfAvailable(request);
163
+ if (raw) {
164
+ const result = Promise.resolve(fromBuffer(raw, request));
165
+ request[bodyBufferKey] = void 0;
166
+ return result;
167
+ }
168
+ return readBodyDirect(request).then((buf) => {
169
+ const result = fromBuffer(buf, request);
170
+ request[bodyBufferKey] = void 0;
171
+ return result;
172
+ });
173
+ };
174
+ var readRawBodyIfAvailable = (request) => {
175
+ const incoming = request[incomingKey];
176
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;
177
+ };
178
+ var readBodyDirect = (request) => {
179
+ if (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);
180
+ if (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];
181
+ const incoming = request[incomingKey];
182
+ if (Readable.isDisturbed(incoming)) return rejectBodyUnusable();
183
+ const promise = new Promise((resolve, reject) => {
184
+ const chunks = [];
185
+ let settled = false;
186
+ const finish = (callback) => {
187
+ if (settled) return;
188
+ settled = true;
189
+ cleanup();
190
+ callback();
191
+ };
192
+ const onData = (chunk) => {
193
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
194
+ };
195
+ const onEnd = () => {
196
+ finish(() => {
197
+ const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
198
+ request[bodyBufferKey] = buffer;
199
+ resolve(buffer);
200
+ });
201
+ };
202
+ const onError = (error) => {
203
+ finish(() => {
204
+ reject(error);
205
+ });
206
+ };
207
+ const onClose = () => {
208
+ if (incoming.readableEnded) {
209
+ onEnd();
210
+ return;
211
+ }
212
+ finish(() => {
213
+ if (incoming.errored) {
214
+ reject(incoming.errored);
215
+ return;
216
+ }
217
+ const reason = request[abortReasonKey];
218
+ if (reason !== void 0) {
219
+ reject(reason instanceof Error ? reason : new Error(String(reason)));
220
+ return;
221
+ }
222
+ reject(/* @__PURE__ */ new Error("Client connection prematurely closed."));
223
+ });
224
+ };
225
+ const cleanup = () => {
226
+ incoming.off("data", onData);
227
+ incoming.off("end", onEnd);
228
+ incoming.off("error", onError);
229
+ incoming.off("close", onClose);
230
+ request[bodyReadPromiseKey] = void 0;
231
+ };
232
+ incoming.on("data", onData);
233
+ incoming.on("end", onEnd);
234
+ incoming.on("error", onError);
235
+ incoming.on("close", onClose);
236
+ queueMicrotask(() => {
237
+ if (settled) return;
238
+ if (incoming.readableEnded) onEnd();
239
+ else if (incoming.errored) onError(incoming.errored);
240
+ else if (incoming.destroyed) onClose();
241
+ });
242
+ });
243
+ request[bodyReadPromiseKey] = promise;
244
+ return promise;
245
+ };
246
+ var requestPrototype = {
247
+ get method() {
248
+ return this[methodKey];
249
+ },
250
+ get url() {
251
+ return this[urlKey];
252
+ },
253
+ get headers() {
254
+ return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
255
+ },
256
+ [abortRequest](reason) {
257
+ if (this[abortReasonKey] === void 0) this[abortReasonKey] = reason;
258
+ const abortController = this[abortControllerKey];
259
+ if (abortController && !abortController.signal.aborted) abortController.abort(reason);
260
+ },
261
+ [getAbortController]() {
262
+ this[abortControllerKey] ||= new AbortController();
263
+ if (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]);
264
+ return this[abortControllerKey];
265
+ },
266
+ [getRequestCache]() {
267
+ const abortController = this[getAbortController]();
268
+ if (this[requestCache]) return this[requestCache];
269
+ const method = this.method;
270
+ if (this[bodyConsumedDirectlyKey] && !(method === "GET" || method === "HEAD")) {
271
+ this[bodyBufferKey] = void 0;
272
+ const init = {
273
+ method: method === "TRACE" ? "GET" : method,
274
+ headers: this.headers,
275
+ signal: abortController.signal
276
+ };
277
+ if (method !== "TRACE") {
278
+ init.body = new ReadableStream({ start(c) {
279
+ c.close();
280
+ } });
281
+ init.duplex = "half";
282
+ }
283
+ const req = new Request$1(this[urlKey], init);
284
+ if (method === "TRACE") Object.defineProperty(req, "method", { get() {
285
+ return "TRACE";
286
+ } });
287
+ return this[requestCache] = req;
288
+ }
289
+ return this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);
290
+ },
291
+ get body() {
292
+ if (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body;
293
+ const request = this[getRequestCache]();
294
+ if (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader();
295
+ return request.body;
296
+ },
297
+ get bodyUsed() {
298
+ if (this[bodyConsumedDirectlyKey]) return true;
299
+ if (this[requestCache]) return this[requestCache].bodyUsed;
300
+ return false;
301
+ }
302
+ };
303
+ Object.defineProperty(requestPrototype, "signal", { get() {
304
+ return this[getAbortController]().signal;
305
+ } });
306
+ [
307
+ "cache",
308
+ "credentials",
309
+ "destination",
310
+ "integrity",
311
+ "mode",
312
+ "redirect",
313
+ "referrer",
314
+ "referrerPolicy",
315
+ "keepalive"
316
+ ].forEach((k) => {
317
+ Object.defineProperty(requestPrototype, k, { get() {
318
+ return this[getRequestCache]()[k];
319
+ } });
320
+ });
321
+ ["clone", "formData"].forEach((k) => {
322
+ Object.defineProperty(requestPrototype, k, { value: function() {
323
+ if (this[bodyConsumedDirectlyKey]) {
324
+ if (k === "clone") throw newBodyUnusableError();
325
+ return rejectBodyUnusable();
326
+ }
327
+ return this[getRequestCache]()[k]();
328
+ } });
329
+ });
330
+ Object.defineProperty(requestPrototype, "text", { value: function() {
331
+ return readBodyWithFastPath(this, "text", (buf) => textDecoder.decode(buf));
332
+ } });
333
+ Object.defineProperty(requestPrototype, "arrayBuffer", { value: function() {
334
+ return readBodyWithFastPath(this, "arrayBuffer", (buf) => toArrayBuffer(buf));
335
+ } });
336
+ Object.defineProperty(requestPrototype, "blob", { value: function() {
337
+ return readBodyWithFastPath(this, "blob", (buf, request) => {
338
+ const type = contentType(request);
339
+ const init = type ? { headers: { "content-type": type } } : void 0;
340
+ return new Response(buf, init).blob();
341
+ });
342
+ } });
343
+ Object.defineProperty(requestPrototype, "json", { value: function() {
344
+ if (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
345
+ return this.text().then(JSON.parse);
346
+ } });
347
+ Object.defineProperty(requestPrototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
348
+ return `Request (lightweight) ${inspectFn({
349
+ method: this.method,
350
+ url: this.url,
351
+ headers: this.headers,
352
+ nativeRequest: this[requestCache]
353
+ }, {
354
+ ...options,
355
+ depth: depth == null ? null : depth - 1
356
+ })}`;
357
+ } });
358
+ Object.setPrototypeOf(requestPrototype, Request$1.prototype);
359
+ var newRequest = (incoming, defaultHostname) => {
360
+ const req = Object.create(requestPrototype);
361
+ req[incomingKey] = incoming;
362
+ req[methodKey] = normalizeIncomingMethod(incoming.method);
363
+ const incomingUrl = incoming.url || "";
364
+ if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
365
+ if (incoming instanceof Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
366
+ try {
367
+ req[urlKey] = new URL(incomingUrl).href;
368
+ } catch (e) {
369
+ throw new RequestError("Invalid absolute URL", { cause: e });
370
+ }
371
+ return req;
372
+ }
373
+ const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
374
+ if (!host) throw new RequestError("Missing host header");
375
+ let scheme;
376
+ if (incoming instanceof Http2ServerRequest) {
377
+ scheme = incoming.scheme;
378
+ if (!(scheme === "http" || scheme === "https")) throw new RequestError("Unsupported scheme");
379
+ } else scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
380
+ try {
381
+ req[urlKey] = buildUrl(scheme, host, incomingUrl);
382
+ } catch (e) {
383
+ if (e instanceof RequestError) throw e;
384
+ else throw new RequestError("Invalid URL", { cause: e });
385
+ }
386
+ return req;
387
+ };
388
+ var defaultContentType = "text/plain; charset=UTF-8";
389
+ var responseCache = /* @__PURE__ */ Symbol("responseCache");
390
+ var getResponseCache = /* @__PURE__ */ Symbol("getResponseCache");
391
+ var cacheKey = /* @__PURE__ */ Symbol("cache");
392
+ var GlobalResponse = global.Response;
393
+ var Response$1 = class Response$12 {
394
+ #body;
395
+ #init;
396
+ [getResponseCache]() {
397
+ const cache = this[cacheKey];
398
+ const liveHeaders = cache && cache[2] instanceof Headers ? cache[2] : void 0;
399
+ delete this[cacheKey];
400
+ return this[responseCache] ||= new GlobalResponse(this.#body, liveHeaders ? {
401
+ ...this.#init,
402
+ headers: liveHeaders
403
+ } : this.#init);
404
+ }
405
+ constructor(body, init) {
406
+ let headers;
407
+ this.#body = body;
408
+ if (init instanceof Response$12) {
409
+ const cachedGlobalResponse = init[responseCache];
410
+ if (cachedGlobalResponse) {
411
+ this.#init = cachedGlobalResponse;
412
+ this[getResponseCache]();
413
+ return;
414
+ } else {
415
+ this.#init = init.#init;
416
+ headers = new Headers(init.headers);
417
+ }
418
+ } else this.#init = init;
419
+ if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
420
+ init?.status || 200,
421
+ body ?? null,
422
+ headers || init?.headers
423
+ ];
424
+ }
425
+ get headers() {
426
+ const cache = this[cacheKey];
427
+ if (cache) {
428
+ if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { "content-type": defaultContentType }));
429
+ return cache[2];
430
+ }
431
+ return this[getResponseCache]().headers;
432
+ }
433
+ get status() {
434
+ return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
435
+ }
436
+ get ok() {
437
+ const status = this.status;
438
+ return status >= 200 && status < 300;
439
+ }
440
+ };
441
+ [
442
+ "body",
443
+ "bodyUsed",
444
+ "redirected",
445
+ "statusText",
446
+ "trailers",
447
+ "type",
448
+ "url"
449
+ ].forEach((k) => {
450
+ Object.defineProperty(Response$1.prototype, k, { get() {
451
+ return this[getResponseCache]()[k];
452
+ } });
453
+ });
454
+ [
455
+ "arrayBuffer",
456
+ "blob",
457
+ "clone",
458
+ "formData",
459
+ "json",
460
+ "text"
461
+ ].forEach((k) => {
462
+ Object.defineProperty(Response$1.prototype, k, { value: function() {
463
+ return this[getResponseCache]()[k]();
464
+ } });
465
+ });
466
+ Object.defineProperty(Response$1.prototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
467
+ return `Response (lightweight) ${inspectFn({
468
+ status: this.status,
469
+ headers: this.headers,
470
+ ok: this.ok,
471
+ nativeResponse: this[responseCache]
472
+ }, {
473
+ ...options,
474
+ depth: depth == null ? null : depth - 1
475
+ })}`;
476
+ } });
477
+ Object.setPrototypeOf(Response$1, GlobalResponse);
478
+ Object.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);
479
+ var validRedirectUrl = /^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/;
480
+ var parseRedirectUrl = (url) => {
481
+ if (url instanceof URL) return url.href;
482
+ if (validRedirectUrl.test(url)) return url;
483
+ return new URL(url).href;
484
+ };
485
+ var validRedirectStatuses = /* @__PURE__ */ new Set([
486
+ 301,
487
+ 302,
488
+ 303,
489
+ 307,
490
+ 308
491
+ ]);
492
+ Object.defineProperty(Response$1, "redirect", {
493
+ value: function redirect(url, status = 302) {
494
+ if (!validRedirectStatuses.has(status)) throw new RangeError("Invalid status code");
495
+ return new Response$1(null, {
496
+ status,
497
+ headers: { location: parseRedirectUrl(url) }
498
+ });
499
+ },
500
+ writable: true,
501
+ configurable: true
502
+ });
503
+ Object.defineProperty(Response$1, "json", {
504
+ value: function json(data, init) {
505
+ const body = JSON.stringify(data);
506
+ if (body === void 0) throw new TypeError("The data is not JSON serializable");
507
+ const initHeaders = init?.headers;
508
+ let headers;
509
+ if (initHeaders) {
510
+ headers = new Headers(initHeaders);
511
+ if (!headers.has("content-type")) headers.set("content-type", "application/json");
512
+ } else headers = { "content-type": "application/json" };
513
+ return new Response$1(body, {
514
+ status: init?.status ?? 200,
515
+ statusText: init?.statusText,
516
+ headers
517
+ });
518
+ },
519
+ writable: true,
520
+ configurable: true
521
+ });
522
+ async function readWithoutBlocking(readPromise) {
523
+ return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
524
+ }
525
+ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
526
+ const cancel = (error) => {
527
+ reader.cancel(error).catch(() => {
528
+ });
529
+ };
530
+ writable.on("close", cancel);
531
+ writable.on("error", cancel);
532
+ (currentReadPromise ?? reader.read()).then(flow, handleStreamError);
533
+ return reader.closed.finally(() => {
534
+ writable.off("close", cancel);
535
+ writable.off("error", cancel);
536
+ });
537
+ function handleStreamError(error) {
538
+ if (error) writable.destroy(error);
539
+ }
540
+ function onDrain() {
541
+ reader.read().then(flow, handleStreamError);
542
+ }
543
+ function flow({ done, value }) {
544
+ try {
545
+ if (done) writable.end();
546
+ else if (!writable.write(value)) writable.once("drain", onDrain);
547
+ else return reader.read().then(flow, handleStreamError);
548
+ } catch (e) {
549
+ handleStreamError(e);
550
+ }
551
+ }
552
+ }
553
+ function writeFromReadableStream(stream, writable) {
554
+ if (stream.locked) throw new TypeError("ReadableStream is locked.");
555
+ else if (writable.destroyed) return;
556
+ return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
557
+ }
558
+ var buildOutgoingHttpHeaders = (headers, defaultContentType2) => {
559
+ const res = {};
560
+ if (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);
561
+ if (headers.has("set-cookie")) {
562
+ const cookies = [];
563
+ for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
564
+ else res[k] = v;
565
+ if (cookies.length > 0) res["set-cookie"] = cookies;
566
+ } else for (const [k, v] of headers) res[k] = v;
567
+ if (defaultContentType2) res["content-type"] ??= defaultContentType2;
568
+ return res;
569
+ };
570
+ var outgoingEnded = /* @__PURE__ */ Symbol("outgoingEnded");
571
+ var incomingDraining = /* @__PURE__ */ Symbol("incomingDraining");
572
+ var DRAIN_TIMEOUT_MS = 500;
573
+ var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
574
+ var drainIncoming = (incoming) => {
575
+ const incomingWithDrainState = incoming;
576
+ if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;
577
+ incomingWithDrainState[incomingDraining] = true;
578
+ if (incoming instanceof Http2ServerRequest) {
579
+ try {
580
+ incoming.stream?.close?.(constants.NGHTTP2_NO_ERROR);
581
+ } catch {
582
+ }
583
+ return;
584
+ }
585
+ let bytesRead = 0;
586
+ const cleanup = () => {
587
+ clearTimeout(timer);
588
+ incoming.off("data", onData);
589
+ incoming.off("end", cleanup);
590
+ incoming.off("error", cleanup);
591
+ };
592
+ const forceClose = () => {
593
+ cleanup();
594
+ const socket = incoming.socket;
595
+ if (socket && !socket.destroyed) socket.destroySoon();
596
+ };
597
+ const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
598
+ timer.unref?.();
599
+ const onData = (chunk) => {
600
+ bytesRead += chunk.length;
601
+ if (bytesRead > MAX_DRAIN_BYTES) forceClose();
602
+ };
603
+ incoming.on("data", onData);
604
+ incoming.on("end", cleanup);
605
+ incoming.on("error", cleanup);
606
+ incoming.resume();
607
+ };
608
+ var makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {
609
+ if (incoming.errored) req[abortRequest](incoming.errored.toString());
610
+ else if (!outgoing.writableFinished) req[abortRequest]("Client connection prematurely closed.");
611
+ if (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {
612
+ if (!incoming.readableEnded) setTimeout(() => {
613
+ drainIncoming(incoming);
614
+ });
615
+ });
616
+ };
617
+ var isImmediateCacheableResponse = (res) => {
618
+ if (!(cacheKey in res)) return false;
619
+ const body = res[cacheKey][1];
620
+ return body === null || typeof body === "string" || body instanceof Uint8Array;
621
+ };
622
+ var handleRequestError = () => new Response(null, { status: 400 });
623
+ var handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
624
+ var handleResponseError = (e, outgoing) => {
625
+ const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
626
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") console.info("The user aborted a request.");
627
+ else {
628
+ console.error(e);
629
+ if (!outgoing.headersSent) outgoing.writeHead(500, { "Content-Type": "text/plain" });
630
+ outgoing.end(`Error: ${err.message}`);
631
+ outgoing.destroy(err);
632
+ }
633
+ };
634
+ var flushHeaders = (outgoing) => {
635
+ if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();
636
+ };
637
+ var responseViaCache = async (res, outgoing) => {
638
+ let [status, body, header] = res[cacheKey];
639
+ if (!header) {
640
+ if (body === null) {
641
+ outgoing.writeHead(status);
642
+ outgoing.end();
643
+ } else if (typeof body === "string") {
644
+ outgoing.writeHead(status, {
645
+ "Content-Type": defaultContentType,
646
+ "Content-Length": Buffer.byteLength(body)
647
+ });
648
+ outgoing.end(body);
649
+ } else if (body instanceof Uint8Array) {
650
+ outgoing.writeHead(status, {
651
+ "Content-Type": defaultContentType,
652
+ "Content-Length": body.byteLength
653
+ });
654
+ outgoing.end(body);
655
+ } else if (body instanceof Blob) {
656
+ outgoing.writeHead(status, {
657
+ "Content-Type": defaultContentType,
658
+ "Content-Length": body.size
659
+ });
660
+ outgoing.end(new Uint8Array(await body.arrayBuffer()));
661
+ } else {
662
+ outgoing.writeHead(status, { "Content-Type": defaultContentType });
663
+ flushHeaders(outgoing);
664
+ await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
665
+ }
666
+ outgoing[outgoingEnded]?.();
667
+ return;
668
+ }
669
+ let hasContentLength = false;
670
+ if (header instanceof Headers) {
671
+ hasContentLength = header.has("content-length");
672
+ header = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);
673
+ } else if (Array.isArray(header)) {
674
+ const headerObj = new Headers(header);
675
+ hasContentLength = headerObj.has("content-length");
676
+ header = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);
677
+ } else for (const key in header) if (key.length === 14 && key.toLowerCase() === "content-length") {
678
+ hasContentLength = true;
679
+ break;
680
+ }
681
+ if (!hasContentLength) {
682
+ if (typeof body === "string") header["Content-Length"] = Buffer.byteLength(body);
683
+ else if (body instanceof Uint8Array) header["Content-Length"] = body.byteLength;
684
+ else if (body instanceof Blob) header["Content-Length"] = body.size;
685
+ }
686
+ outgoing.writeHead(status, header);
687
+ if (body == null) outgoing.end();
688
+ else if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
689
+ else if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));
690
+ else {
691
+ flushHeaders(outgoing);
692
+ await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
693
+ }
694
+ outgoing[outgoingEnded]?.();
695
+ };
696
+ var isPromise = (res) => typeof res.then === "function";
697
+ var responseViaResponseObject = async (res, outgoing, options = {}) => {
698
+ if (isPromise(res)) if (options.errorHandler) try {
699
+ res = await res;
700
+ } catch (err) {
701
+ const errRes = await options.errorHandler(err);
702
+ if (!errRes) return;
703
+ res = errRes;
704
+ }
705
+ else res = await res.catch(handleFetchError);
706
+ if (cacheKey in res) return responseViaCache(res, outgoing);
707
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? void 0 : defaultContentType);
708
+ if (res.body) {
709
+ const reader = res.body.getReader();
710
+ const values = [];
711
+ let done = false;
712
+ let currentReadPromise = void 0;
713
+ if (resHeaderRecord["transfer-encoding"] !== "chunked") {
714
+ let maxReadCount = 2;
715
+ for (let i = 0; i < maxReadCount; i++) {
716
+ currentReadPromise ||= reader.read();
717
+ const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
718
+ console.error(e);
719
+ done = true;
720
+ });
721
+ if (!chunk) {
722
+ if (i === 1) {
723
+ await new Promise((resolve) => setTimeout(resolve));
724
+ maxReadCount = 3;
725
+ continue;
726
+ }
727
+ break;
728
+ }
729
+ currentReadPromise = void 0;
730
+ if (chunk.value) values.push(chunk.value);
731
+ if (chunk.done) {
732
+ done = true;
733
+ break;
734
+ }
735
+ }
736
+ if (done && !("content-length" in resHeaderRecord)) resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
737
+ }
738
+ outgoing.writeHead(res.status, resHeaderRecord);
739
+ values.forEach((value) => {
740
+ outgoing.write(value);
741
+ });
742
+ if (done) outgoing.end();
743
+ else {
744
+ if (values.length === 0) flushHeaders(outgoing);
745
+ await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
746
+ }
747
+ } else if (resHeaderRecord[X_ALREADY_SENT]) {
748
+ } else {
749
+ outgoing.writeHead(res.status, resHeaderRecord);
750
+ outgoing.end();
751
+ }
752
+ outgoing[outgoingEnded]?.();
753
+ };
754
+ var getRequestListener = (fetchCallback, options = {}) => {
755
+ const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
756
+ if (options.overrideGlobalObjects !== false && global.Request !== Request$1) {
757
+ Object.defineProperty(global, "Request", { value: Request$1 });
758
+ Object.defineProperty(global, "Response", { value: Response$1 });
759
+ }
760
+ return async (incoming, outgoing) => {
761
+ let res, req;
762
+ let needsBodyCleanup = false;
763
+ let closeHandlerAttached = false;
764
+ const ensureCloseHandler = () => {
765
+ if (!req || closeHandlerAttached) return;
766
+ closeHandlerAttached = true;
767
+ outgoing.on("close", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));
768
+ };
769
+ try {
770
+ req = newRequest(incoming, options.hostname);
771
+ needsBodyCleanup = autoCleanupIncoming && !(incoming.method === "GET" || incoming.method === "HEAD");
772
+ if (needsBodyCleanup) {
773
+ incoming[wrapBodyStream] = true;
774
+ if (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => {
775
+ if (!incoming.readableEnded) setTimeout(() => {
776
+ if (!incoming.readableEnded) setTimeout(() => {
777
+ incoming.destroy();
778
+ outgoing.destroy();
779
+ });
780
+ });
781
+ };
782
+ }
783
+ res = fetchCallback(req, {
784
+ incoming,
785
+ outgoing
786
+ });
787
+ if (!isPromise(res) && isImmediateCacheableResponse(res)) {
788
+ if (needsBodyCleanup && !incoming.readableEnded) outgoing.once("finish", () => {
789
+ if (!incoming.readableEnded) drainIncoming(incoming);
790
+ });
791
+ return responseViaCache(res, outgoing);
792
+ }
793
+ ensureCloseHandler();
794
+ } catch (e) {
795
+ if (!res) if (options.errorHandler) {
796
+ ensureCloseHandler();
797
+ res = await options.errorHandler(req ? e : toRequestError(e));
798
+ if (!res) return;
799
+ } else if (!req) res = handleRequestError();
800
+ else res = handleFetchError(e);
801
+ else return handleResponseError(e, outgoing);
802
+ }
803
+ try {
804
+ return await responseViaResponseObject(res, outgoing, options);
805
+ } catch (e) {
806
+ return handleResponseError(e, outgoing);
807
+ }
808
+ };
809
+ };
810
+ var CloseEvent = globalThis.CloseEvent ?? class extends Event {
811
+ #eventInitDict;
812
+ constructor(type, eventInitDict = {}) {
813
+ super(type, eventInitDict);
814
+ this.#eventInitDict = eventInitDict;
815
+ }
816
+ get wasClean() {
817
+ return this.#eventInitDict.wasClean ?? false;
818
+ }
819
+ get code() {
820
+ return this.#eventInitDict.code ?? 0;
821
+ }
822
+ get reason() {
823
+ return this.#eventInitDict.reason ?? "";
824
+ }
825
+ };
826
+ var generateConnectionSymbol = () => /* @__PURE__ */ Symbol("connection");
827
+ var CONNECTION_SYMBOL_KEY = /* @__PURE__ */ Symbol("CONNECTION_SYMBOL_KEY");
828
+ var WAIT_FOR_WEBSOCKET_SYMBOL = /* @__PURE__ */ Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");
829
+ var responseHeadersToSkip = /* @__PURE__ */ new Set([
830
+ "connection",
831
+ "content-length",
832
+ "keep-alive",
833
+ "proxy-authenticate",
834
+ "proxy-authorization",
835
+ "te",
836
+ "trailer",
837
+ "transfer-encoding",
838
+ "upgrade",
839
+ "sec-websocket-accept",
840
+ "sec-websocket-extensions",
841
+ "sec-websocket-protocol"
842
+ ]);
843
+ var appendResponseHeaders = (headers, responseHeaders) => {
844
+ if (!responseHeaders) return;
845
+ responseHeaders.forEach((value, key) => {
846
+ if (responseHeadersToSkip.has(key.toLowerCase())) return;
847
+ headers.push(`${key}: ${value}`);
848
+ });
849
+ };
850
+ var rejectUpgradeRequest = (socket, status, responseHeaders) => {
851
+ const responseLines = ["Connection: close", "Content-Length: 0"];
852
+ appendResponseHeaders(responseLines, responseHeaders);
853
+ socket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? ""}\r
854
+ ${responseLines.join("\r\n")}\r
855
+ \r
856
+ `);
857
+ };
858
+ var createUpgradeRequest = (request) => {
859
+ const protocol = request.socket.encrypted ? "https" : "http";
860
+ const url = new URL(request.url ?? "/", `${protocol}://${request.headers.host ?? "localhost"}`);
861
+ const headers = new Headers();
862
+ for (const key in request.headers) {
863
+ const value = request.headers[key];
864
+ if (!value) continue;
865
+ headers.append(key, Array.isArray(value) ? value[0] : value);
866
+ }
867
+ return new Request(url, { headers });
868
+ };
869
+ var setupWebSocket = (options) => {
870
+ const { server, fetchCallback, wss } = options;
871
+ const waiterMap = /* @__PURE__ */ new Map();
872
+ wss.on("connection", (ws, request) => {
873
+ const waiter = waiterMap.get(request);
874
+ if (waiter) {
875
+ waiter.resolve(ws);
876
+ waiterMap.delete(request);
877
+ }
878
+ });
879
+ const waitForWebSocket = (request, connectionSymbol) => {
880
+ return new Promise((resolve) => {
881
+ waiterMap.set(request, {
882
+ resolve,
883
+ connectionSymbol
884
+ });
885
+ });
886
+ };
887
+ server.on("upgrade", async (request, socket, head) => {
888
+ if (request.headers.upgrade?.toLowerCase() !== "websocket") return;
889
+ const env = {
890
+ incoming: request,
891
+ outgoing: void 0,
892
+ wss,
893
+ [WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket
894
+ };
895
+ let status = 400;
896
+ let responseHeaders;
897
+ try {
898
+ const response = await fetchCallback(createUpgradeRequest(request), env);
899
+ if (response instanceof Response) {
900
+ status = response.status;
901
+ responseHeaders = response.headers;
902
+ }
903
+ } catch {
904
+ if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, 500);
905
+ return;
906
+ }
907
+ const waiter = waiterMap.get(request);
908
+ if (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {
909
+ waiterMap.delete(request);
910
+ if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, status, responseHeaders);
911
+ return;
912
+ }
913
+ const addResponseHeaders = (headers) => {
914
+ appendResponseHeaders(headers, responseHeaders);
915
+ };
916
+ wss.on("headers", addResponseHeaders);
917
+ try {
918
+ wss.handleUpgrade(request, socket, head, (ws) => {
919
+ wss.emit("connection", ws, request);
920
+ });
921
+ } finally {
922
+ wss.off("headers", addResponseHeaders);
923
+ }
924
+ });
925
+ server.on("close", () => {
926
+ wss.close();
927
+ });
928
+ };
929
+ var upgradeWebSocket = defineWebSocketHelper(async (c, events, options) => {
930
+ if (c.req.header("upgrade")?.toLowerCase() !== "websocket") return;
931
+ const env = c.env;
932
+ const waitForWebSocket = env[WAIT_FOR_WEBSOCKET_SYMBOL];
933
+ if (!waitForWebSocket || !env.incoming) return new Response(null, { status: 500 });
934
+ const connectionSymbol = generateConnectionSymbol();
935
+ env[CONNECTION_SYMBOL_KEY] = connectionSymbol;
936
+ (async () => {
937
+ const ws = await waitForWebSocket(env.incoming, connectionSymbol);
938
+ const messagesReceivedInStarting = [];
939
+ const bufferMessage = (data, isBinary) => {
940
+ messagesReceivedInStarting.push([data, isBinary]);
941
+ };
942
+ ws.on("message", bufferMessage);
943
+ const ctx = {
944
+ binaryType: "arraybuffer",
945
+ close(code, reason) {
946
+ ws.close(code, reason);
947
+ },
948
+ protocol: ws.protocol,
949
+ raw: ws,
950
+ get readyState() {
951
+ return ws.readyState;
952
+ },
953
+ send(source, opts) {
954
+ ws.send(source, { compress: opts?.compress });
955
+ },
956
+ url: new URL(c.req.url)
957
+ };
958
+ try {
959
+ events?.onOpen?.(new Event("open"), ctx);
960
+ } catch (e) {
961
+ (options?.onError ?? console.error)(e);
962
+ }
963
+ const handleMessage = (data, isBinary) => {
964
+ const datas = Array.isArray(data) ? data : [data];
965
+ for (const data2 of datas) try {
966
+ events?.onMessage?.(new MessageEvent("message", { data: isBinary ? data2 instanceof ArrayBuffer ? data2 : data2.buffer.slice(data2.byteOffset, data2.byteOffset + data2.byteLength) : typeof data2 === "string" ? data2 : Buffer.from(data2).toString("utf-8") }), ctx);
967
+ } catch (e) {
968
+ (options?.onError ?? console.error)(e);
969
+ }
970
+ };
971
+ ws.off("message", bufferMessage);
972
+ for (const message of messagesReceivedInStarting) handleMessage(...message);
973
+ ws.on("message", (data, isBinary) => {
974
+ handleMessage(data, isBinary);
975
+ });
976
+ ws.on("close", (code, reason) => {
977
+ try {
978
+ events?.onClose?.(new CloseEvent("close", {
979
+ code,
980
+ reason: reason.toString()
981
+ }), ctx);
982
+ } catch (e) {
983
+ (options?.onError ?? console.error)(e);
984
+ }
985
+ });
986
+ ws.on("error", (error) => {
987
+ try {
988
+ events?.onError?.(new ErrorEvent("error", { error }), ctx);
989
+ } catch (e) {
990
+ (options?.onError ?? console.error)(e);
991
+ }
992
+ });
993
+ })();
994
+ return new Response();
995
+ });
996
+ var createAdaptorServer = (options) => {
997
+ const fetchCallback = options.fetch;
998
+ const requestListener = getRequestListener(fetchCallback, {
999
+ hostname: options.hostname,
1000
+ overrideGlobalObjects: options.overrideGlobalObjects,
1001
+ autoCleanupIncoming: options.autoCleanupIncoming
1002
+ });
1003
+ const server = (options.createServer || createServer)(options.serverOptions || {}, requestListener);
1004
+ if (options.websocket && options.websocket.server) {
1005
+ if (options.websocket.server.options.noServer !== true) throw new Error("WebSocket server must be created with { noServer: true } option");
1006
+ setupWebSocket({
1007
+ server,
1008
+ fetchCallback,
1009
+ wss: options.websocket.server
1010
+ });
1011
+ }
1012
+ return server;
1013
+ };
1014
+ var serve = (options, listeningListener) => {
1015
+ const server = createAdaptorServer(options);
1016
+ server.listen(options?.port ?? 3e3, options.hostname, () => {
1017
+ const serverInfo = server.address();
1018
+ listeningListener && listeningListener(serverInfo);
1019
+ });
1020
+ return server;
1021
+ };
1022
+ export {
1023
+ RequestError,
1024
+ createAdaptorServer,
1025
+ getRequestListener,
1026
+ serve,
1027
+ upgradeWebSocket
1028
+ };