@sourceregistry/node-webserver 1.2.3 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js CHANGED
@@ -1,21 +1,21 @@
1
- import { createServer as $ } from "http";
2
- import { createServer as I } from "https";
3
- import { TLSSocket as D } from "tls";
4
- import { Readable as U, Transform as F, Writable as z } from "stream";
5
- import { WebSocketServer as q, WebSocket as P } from "ws";
6
- import { parse as T, serialize as B } from "cookie";
1
+ import { createServer as M } from "http";
2
+ import { createServer as $ } from "https";
3
+ import { TLSSocket as I } from "tls";
4
+ import { Readable as F, Transform as D, Writable as U } from "stream";
5
+ import { WebSocketServer as z, WebSocket as P } from "ws";
6
+ import { parse as b, serialize as B } from "cookie";
7
7
  import { createReadStream as X } from "node:fs";
8
- import { stat as L, realpath as O, lstat as J } from "node:fs/promises";
9
- import { sep as G, resolve as v, relative as V, isAbsolute as K, extname as Y } from "node:path";
8
+ import { stat as W, realpath as v, lstat as J } from "node:fs/promises";
9
+ import { sep as G, resolve as O, relative as V, isAbsolute as K, extname as Y } from "node:path";
10
10
  import { Readable as Q } from "node:stream";
11
- function _(o) {
12
- return x(o) && o.status >= 400 && o.status < 600;
11
+ function _(a) {
12
+ return S(a) && a.status >= 400 && a.status < 600;
13
13
  }
14
- function N(o) {
15
- return x(o) && o.status >= 300 && o.status < 400;
14
+ function N(a) {
15
+ return S(a) && a.status >= 300 && a.status < 400;
16
16
  }
17
- function x(o) {
18
- return o instanceof Response;
17
+ function S(a) {
18
+ return a instanceof Response;
19
19
  }
20
20
  class Z {
21
21
  constructor(e) {
@@ -40,51 +40,51 @@ class Z {
40
40
  this.data.clear();
41
41
  }
42
42
  }
43
- function ee(o) {
43
+ function ee(a) {
44
44
  const {
45
45
  windowMs: e = 6e4,
46
46
  max: t,
47
47
  key: s = (c) => c.getClientAddress(),
48
48
  message: r = "Too many requests, please try again later.",
49
49
  statusCode: n = 429,
50
- headers: a = "include",
50
+ headers: o = "include",
51
51
  onRateLimit: i,
52
52
  store: u = new Z({ windowMs: e })
53
- } = o;
53
+ } = a;
54
54
  return async (c, l) => {
55
- const d = `rl:${s(c)}`, { current: h, reset: f } = await u.incr(d), y = Math.ceil((f - Date.now()) / 1e3);
55
+ const d = `rl:${s(c)}`, { current: h, reset: p } = await u.incr(d), m = Math.ceil((p - Date.now()) / 1e3);
56
56
  if (h > t) {
57
57
  i && i(c, { current: h, max: t, key: d });
58
- const g = {
58
+ const y = {
59
59
  status: n,
60
60
  headers: new Headers()
61
- }, p = g.headers;
62
- a === "include" && (p.set("X-RateLimit-Limit", String(t)), p.set("X-RateLimit-Remaining", "0"), p.set("X-RateLimit-Reset", String(Math.floor(f / 1e3))), p.set("Retry-After", String(y)));
63
- let m;
64
- return typeof r == "string" ? (m = r, p.set("Content-Type", "text/plain")) : (m = JSON.stringify(r), p.set("Content-Type", "application/json")), new Response(m, g);
61
+ }, f = y.headers;
62
+ o === "include" && (f.set("X-RateLimit-Limit", String(t)), f.set("X-RateLimit-Remaining", "0"), f.set("X-RateLimit-Reset", String(Math.floor(p / 1e3))), f.set("Retry-After", String(m)));
63
+ let w;
64
+ return typeof r == "string" ? (w = r, f.set("Content-Type", "text/plain")) : (w = JSON.stringify(r), f.set("Content-Type", "application/json")), new Response(w, y);
65
65
  }
66
66
  if (c.rateLimit = {
67
67
  current: h,
68
68
  limit: t,
69
- reset: new Date(f),
69
+ reset: new Date(p),
70
70
  remaining: t - h
71
- }, a === "include") {
72
- const g = {
71
+ }, o === "include") {
72
+ const y = {
73
73
  "X-RateLimit-Limit": String(t),
74
74
  "X-RateLimit-Remaining": String(t - h),
75
- "X-RateLimit-Reset": String(Math.floor(f / 1e3))
76
- }, p = c.setHeaders;
77
- c.setHeaders = (m) => {
78
- p({
79
- ...g,
80
- ...m
75
+ "X-RateLimit-Reset": String(Math.floor(p / 1e3))
76
+ }, f = c.setHeaders;
77
+ c.setHeaders = (w) => {
78
+ f({
79
+ ...y,
80
+ ...w
81
81
  });
82
- }, p(g);
82
+ }, f(y);
83
83
  }
84
84
  return l();
85
85
  };
86
86
  }
87
- const be = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
87
+ const Te = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
88
88
  __proto__: null,
89
89
  fixedWindowLimit: ee
90
90
  }, Symbol.toStringTag, { value: "Module" })), te = [
@@ -111,56 +111,56 @@ const be = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
111
111
  "X-Real-IP",
112
112
  "X-Custom-Header"
113
113
  ];
114
- function j(o, e) {
115
- return !o || !e ? !1 : e === "*" ? !0 : e === "null" ? o === "null" : Array.isArray(e) ? e.some((t) => j(o, t)) : typeof e == "function" ? e(o) : e instanceof RegExp ? e.test(o) : o === e;
114
+ function j(a, e) {
115
+ return !a || !e ? !1 : e === "*" ? !0 : e === "null" ? a === "null" : Array.isArray(e) ? e.some((t) => j(a, t)) : typeof e == "function" ? e(a) : e instanceof RegExp ? e.test(a) : a === e;
116
116
  }
117
- function ne(o, e) {
117
+ function ne(a, e) {
118
118
  const { origin: t = "*" } = e;
119
- return o ? t === "*" ? e.credentials ? o : "*" : j(o, t) ? o : null : t === "*" ? "*" : null;
119
+ return a ? t === "*" ? e.credentials ? a : "*" : j(a, t) ? a : null : t === "*" ? "*" : null;
120
120
  }
121
- function ae(o = {}) {
121
+ function oe(a = {}) {
122
122
  const {
123
123
  methods: e = te,
124
124
  allowedHeaders: t = re,
125
125
  exposedHeaders: s,
126
126
  credentials: r = !1,
127
127
  maxAge: n = 86400,
128
- onResponse: a
129
- } = o, i = "Origin,Access-Control-Request-Method,Access-Control-Request-Headers", u = e.join(","), c = [...se, ...t].join(","), l = [
128
+ onResponse: o
129
+ } = a, i = "Origin,Access-Control-Request-Method,Access-Control-Request-Headers", u = e.join(","), c = [...se, ...t].join(","), l = [
130
130
  ["Vary", i],
131
131
  ["Access-Control-Allow-Methods", u],
132
132
  ["Access-Control-Allow-Headers", c]
133
133
  ];
134
134
  return s && l.push(["Access-Control-Expose-Headers", s.join(",")]), r && l.push(["Access-Control-Allow-Credentials", "true"]), n && l.push(["Access-Control-Max-Age", n.toString()]), async (d, h) => {
135
- const f = d.request, y = f.headers.get("Origin"), g = f.method === "OPTIONS" && y !== null && f.headers.has("Access-Control-Request-Method"), p = ne(y, o);
136
- if (g) {
137
- if (!p)
135
+ const p = d.request, m = p.headers.get("Origin"), y = p.method === "OPTIONS" && m !== null && p.headers.has("Access-Control-Request-Method"), f = ne(m, a);
136
+ if (y) {
137
+ if (!f)
138
138
  return new Response(null, { status: 403 });
139
- const w = new Response(null, { status: 204 });
140
- for (const [H, M] of l)
141
- w.headers.set(H, M);
142
- return w.headers.set("Access-Control-Allow-Origin", p), w;
143
- }
144
- const m = await h();
145
- if (!m) return;
146
- if (!p) return m;
147
- const S = new Response(m.body, m);
148
- for (const [w, H] of l)
149
- S.headers.set(w, H);
150
- S.headers.set("Access-Control-Allow-Origin", p);
151
- let A = S;
152
- if (a) {
153
- const w = a(A);
154
- w && (A = w);
139
+ const g = new Response(null, { status: 204 });
140
+ for (const [x, q] of l)
141
+ g.headers.set(x, q);
142
+ return g.headers.set("Access-Control-Allow-Origin", f), g;
143
+ }
144
+ const w = await h();
145
+ if (!w) return;
146
+ if (!f) return w;
147
+ const H = new Response(w.body, w);
148
+ for (const [g, x] of l)
149
+ H.headers.set(g, x);
150
+ H.headers.set("Access-Control-Allow-Origin", f);
151
+ let A = H;
152
+ if (o) {
153
+ const g = o(A);
154
+ g && (A = g);
155
155
  }
156
156
  return A;
157
157
  };
158
158
  }
159
159
  const Ce = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
160
160
  __proto__: null,
161
- policy: ae
162
- }, Symbol.toStringTag, { value: "Module" })), oe = ["GET", "PUT", "POST", "DELETE", "PATCH", "HEAD", "OPTIONS"];
163
- class b {
161
+ policy: oe
162
+ }, Symbol.toStringTag, { value: "Module" })), ae = ["GET", "PUT", "POST", "DELETE", "PATCH", "HEAD", "OPTIONS"];
163
+ class T {
164
164
  static {
165
165
  this.cache = /* @__PURE__ */ new Map();
166
166
  }
@@ -205,23 +205,23 @@ class E {
205
205
  }
206
206
  // Universal method
207
207
  USE(e, t, ...s) {
208
- return oe.forEach((r) => this.addHandler(r, e, t, s)), this;
208
+ return ae.forEach((r) => this.addHandler(r, e, t, s)), this;
209
209
  }
210
210
  // Action handler (POST only)
211
211
  action(e, t, ...s) {
212
212
  const r = async (n) => {
213
213
  try {
214
- const a = await t(n);
215
- return this.formatActionResult(a);
216
- } catch (a) {
217
- return this.handleActionError(a);
214
+ const o = await t(n);
215
+ return this.formatActionResult(o);
216
+ } catch (o) {
217
+ return this.handleActionError(o);
218
218
  }
219
219
  };
220
220
  return this.addHandler("POST", e, r, s);
221
221
  }
222
222
  use(e, t, ...s) {
223
- let r, n, a = s;
224
- Array.isArray(e) ? ([r, n] = e, a = e.length > 2 ? e.slice(2) : []) : (r = e, n = t);
223
+ let r, n, o = s;
224
+ Array.isArray(e) ? ([r, n] = e, o = e.length > 2 ? e.slice(2) : []) : (r = e, n = t);
225
225
  const i = this.normalizePrefix(r), { regex: u, paramNames: c, isCatchAll: l, priority: d } = this.createPrefixRegex(i);
226
226
  return this._nestedRouters.push({
227
227
  prefix: i,
@@ -230,7 +230,7 @@ class E {
230
230
  paramNames: c,
231
231
  isCatchAll: l,
232
232
  priority: d,
233
- middlewares: a
233
+ middlewares: o
234
234
  }), this;
235
235
  }
236
236
  // Global middleware
@@ -251,12 +251,12 @@ class E {
251
251
  }
252
252
  // WebSocket route
253
253
  WS(e, t, ...s) {
254
- const { regex: r, paramNames: n, isCatchAll: a, priority: i } = this.createPathRegex(e);
254
+ const { regex: r, paramNames: n, isCatchAll: o, priority: i } = this.createPathRegex(e);
255
255
  return this._wsRoutes.push({
256
256
  path: e,
257
257
  regex: r,
258
258
  paramNames: n,
259
- isCatchAll: a,
259
+ isCatchAll: o,
260
260
  priority: i,
261
261
  handler: t,
262
262
  middlewares: s
@@ -275,11 +275,11 @@ class E {
275
275
  for (const s of [...this._nestedRouters].sort((r, n) => n.priority - r.priority)) {
276
276
  const r = t.match(s.regex);
277
277
  if (!r || r.index !== 0) continue;
278
- const n = r[0], a = t.slice(n.length) || "/", i = {
278
+ const n = r[0], o = t.slice(n.length) || "/", i = {
279
279
  ...e,
280
280
  params: { ...e.params, ...this.extractPrefixParams(s, n) }
281
281
  };
282
- if (await s.router.canHandleWebSocketAtPath(i, a))
282
+ if (await s.router.canHandleWebSocketAtPath(i, o))
283
283
  return !0;
284
284
  }
285
285
  for (const s of this._wsRoutes)
@@ -293,10 +293,10 @@ class E {
293
293
  }
294
294
  async handleWebSocketAtPath(e, t, s) {
295
295
  this.wsRoutesSorted || this.sortWsRoutes();
296
- for (const r of [...this._nestedRouters].sort((n, a) => a.priority - n.priority)) {
296
+ for (const r of [...this._nestedRouters].sort((n, o) => o.priority - n.priority)) {
297
297
  const n = s.match(r.regex);
298
298
  if (!n || n.index !== 0) continue;
299
- const a = n[0], i = s.slice(a.length) || "/", u = this.extractPrefixParams(r, a), c = {
299
+ const o = n[0], i = s.slice(o.length) || "/", u = this.extractPrefixParams(r, o), c = {
300
300
  ...e,
301
301
  params: { ...e.params, ...u }
302
302
  }, l = [...this._middlewares, ...r.middlewares], d = () => r.router.handleWebSocketAtPath(c, t, i);
@@ -306,11 +306,11 @@ class E {
306
306
  if (!r.regex.test(s)) continue;
307
307
  const n = s.match(r.regex);
308
308
  if (!n) continue;
309
- const a = Object.fromEntries(
309
+ const o = Object.fromEntries(
310
310
  r.paramNames.map((l, d) => [l, n[d + 1] || ""])
311
311
  ), i = {
312
312
  ...e,
313
- params: { ...e.params, ...a },
313
+ params: { ...e.params, ...o },
314
314
  route: { ...e.route, id: r.path },
315
315
  websocket: t
316
316
  }, u = [...this._middlewares, ...r.middlewares];
@@ -328,22 +328,22 @@ class E {
328
328
  const s = e.request.method;
329
329
  let r = await this.runPreHandlers(e);
330
330
  if (!r) {
331
- const a = async () => {
331
+ const o = async () => {
332
332
  const i = await this.handleNestedRouters(e, t);
333
333
  return i || (this.routesSorted || this.sortRoutes(), this.handleLocalRoutes(e, s, t));
334
334
  };
335
- r = await this.applyMiddlewaresWithList(e, this._middlewares, a);
335
+ r = await this.applyMiddlewaresWithList(e, this._middlewares, o);
336
336
  }
337
337
  const n = r || new Response("No Content", { status: 204 });
338
338
  return await this.runPostHandlers(e, n);
339
339
  } catch (s) {
340
- if (x(s)) return s;
340
+ if (S(s)) return s;
341
341
  throw s;
342
342
  }
343
343
  }
344
344
  // Apply middlewares utility
345
345
  async applyMiddlewaresWithList(e, t, s) {
346
- const r = [...t], n = async (a) => a >= r.length ? s() : r[a](e, () => n(a + 1));
346
+ const r = [...t], n = async (o) => o >= r.length ? s() : r[o](e, () => n(o + 1));
347
347
  return n(0);
348
348
  }
349
349
  async runPreHandlers(e) {
@@ -363,12 +363,12 @@ class E {
363
363
  }
364
364
  // Add route handler
365
365
  addHandler(e, t, s, r = []) {
366
- const { regex: n, paramNames: a, isCatchAll: i, priority: u } = this.createPathRegex(t);
366
+ const { regex: n, paramNames: o, isCatchAll: i, priority: u } = this.createPathRegex(t);
367
367
  return this._routes.push({
368
368
  method: e,
369
369
  path: t,
370
370
  regex: n,
371
- paramNames: a,
371
+ paramNames: o,
372
372
  isCatchAll: i,
373
373
  priority: u,
374
374
  handler: s,
@@ -377,14 +377,14 @@ class E {
377
377
  }
378
378
  // Create regex for route path
379
379
  createPathRegex(e) {
380
- const t = b.get(e);
380
+ const t = T.get(e);
381
381
  if (t) return t;
382
382
  const s = [];
383
383
  let r = !1, n;
384
- const a = e.split("/").filter(Boolean);
385
- n = a.reduce((c, l) => l.startsWith("[...") ? c - 10 : l.startsWith("[[") ? c - 5 : l.startsWith("[") ? c - 1 : c + 1, 0);
384
+ const o = e.split("/").filter(Boolean);
385
+ n = o.reduce((c, l) => l.startsWith("[...") ? c - 10 : l.startsWith("[[") ? c - 5 : l.startsWith("[") ? c - 1 : c + 1, 0);
386
386
  let i = "^";
387
- for (const c of a)
387
+ for (const c of o)
388
388
  if (c.startsWith("[...") && c.endsWith("]")) {
389
389
  r = !0;
390
390
  const l = c.slice(4, -1);
@@ -399,7 +399,7 @@ class E {
399
399
  i += "/" + c.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
400
400
  i += "/?$";
401
401
  const u = { regex: new RegExp(i), paramNames: s, isCatchAll: r, priority: n };
402
- return b.set(e, u), u;
402
+ return T.set(e, u), u;
403
403
  }
404
404
  // Create regex for prefix
405
405
  createPrefixRegex(e) {
@@ -407,21 +407,21 @@ class E {
407
407
  let s = !1, r;
408
408
  const n = e.split("/").filter(Boolean);
409
409
  r = n.reduce((i, u) => u.startsWith("[...") ? i - 10 : u.startsWith("[[") ? i - 5 : u.startsWith("[") ? i - 1 : i + 1, 0);
410
- let a = "^";
410
+ let o = "^";
411
411
  for (const i of n)
412
412
  if (i.startsWith("[...") && i.endsWith("]")) {
413
413
  s = !0;
414
414
  const u = i.slice(4, -1);
415
- t.push(u), a += "/(.+)";
415
+ t.push(u), o += "/(.+)";
416
416
  } else if (i.startsWith("[[") && i.endsWith("]]")) {
417
417
  const u = i.slice(2, -2);
418
- t.push(u), a += "(?:/([^/]+))?";
418
+ t.push(u), o += "(?:/([^/]+))?";
419
419
  } else if (i.startsWith("[") && i.endsWith("]")) {
420
420
  const u = i.slice(1, -1);
421
- t.push(u), a += "/([^/]+)";
421
+ t.push(u), o += "/([^/]+)";
422
422
  } else
423
- a += "/" + i.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
424
- return a += "(?=/|$)", { regex: new RegExp(a), paramNames: t, isCatchAll: s, priority: r };
423
+ o += "/" + i.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
424
+ return o += "(?=/|$)", { regex: new RegExp(o), paramNames: t, isCatchAll: s, priority: r };
425
425
  }
426
426
  normalizePrefix(e) {
427
427
  return e.startsWith("/") ? e.replace(/\/$/, "") : `/${e.replace(/\/$/, "")}`;
@@ -430,8 +430,8 @@ class E {
430
430
  const s = t.match(e.regex);
431
431
  if (!s) return {};
432
432
  const r = {};
433
- return e.isCatchAll && e.paramNames.length === 1 ? r[e.paramNames[0]] = s[1]?.replace(/^\//, "") || "" : e.paramNames.forEach((n, a) => {
434
- r[n] = s[a + 1] || "";
433
+ return e.isCatchAll && e.paramNames.length === 1 ? r[e.paramNames[0]] = s[1]?.replace(/^\//, "") || "" : e.paramNames.forEach((n, o) => {
434
+ r[n] = s[o + 1] || "";
435
435
  }), r;
436
436
  }
437
437
  // FIXED: Nested router handling without duplicate middleware application
@@ -440,7 +440,7 @@ class E {
440
440
  for (const r of s) {
441
441
  const n = t.match(r.regex);
442
442
  if (!n || n.index !== 0) continue;
443
- const a = n[0], i = t.slice(a.length) || "/", u = this.extractPrefixParams(r, a), c = {
443
+ const o = n[0], i = t.slice(o.length) || "/", u = this.extractPrefixParams(r, o), c = {
444
444
  ...e,
445
445
  params: { ...e.params, ...u }
446
446
  }, l = async () => await r.router.handleAtPath(c, i), d = await this.applyMiddlewaresWithList(c, r.middlewares, l);
@@ -452,25 +452,25 @@ class E {
452
452
  async handleLocalRoutes(e, t, s) {
453
453
  const r = /* @__PURE__ */ new Set();
454
454
  let n = !1;
455
- for (const a of this._routes) {
456
- if (!a.regex.test(s) || (r.add(a.method), a.method === "GET" && (n = !0, r.add("HEAD")), !(a.method === t || t === "HEAD" && a.method === "GET"))) continue;
457
- const u = s.match(a.regex);
455
+ for (const o of this._routes) {
456
+ if (!o.regex.test(s) || (r.add(o.method), o.method === "GET" && (n = !0, r.add("HEAD")), !(o.method === t || t === "HEAD" && o.method === "GET"))) continue;
457
+ const u = s.match(o.regex);
458
458
  if (!u) continue;
459
459
  const c = Object.fromEntries(
460
- a.paramNames.map((d, h) => [d, u[h + 1] || ""])
460
+ o.paramNames.map((d, h) => [d, u[h + 1] || ""])
461
461
  );
462
- e.params = { ...e.params, ...c }, e.route = { ...e.route, id: a.path };
463
- const l = () => a.handler(e);
464
- return await this.applyMiddlewaresWithList(e, a.middlewares, l);
462
+ e.params = { ...e.params, ...c }, e.route = { ...e.route, id: o.path };
463
+ const l = () => o.handler(e);
464
+ return await this.applyMiddlewaresWithList(e, o.middlewares, l);
465
465
  }
466
466
  if (r.size > 0 || t === "HEAD" && n) {
467
- const a = [...r].join(", ");
467
+ const o = [...r].join(", ");
468
468
  return t === "OPTIONS" ? new Response(null, {
469
469
  status: 200,
470
- headers: { Allow: a }
470
+ headers: { Allow: o }
471
471
  }) : new Response("Method Not Allowed", {
472
472
  status: 405,
473
- headers: { Allow: a }
473
+ headers: { Allow: o }
474
474
  });
475
475
  }
476
476
  return new Response("Not Found", { status: 404 });
@@ -498,20 +498,20 @@ class E {
498
498
  }
499
499
  }
500
500
  const R = {
501
- success: (o = 200, e) => new Response(JSON.stringify({ data: e, type: "success", status: o }), {
502
- status: o,
501
+ success: (a = 200, e) => new Response(JSON.stringify({ data: e, type: "success", status: a }), {
502
+ status: a,
503
503
  headers: { "Content-Type": "application/json" }
504
504
  }),
505
- redirect: (o = 302, e) => new Response(JSON.stringify({ location: e, type: "redirect", status: o }), {
506
- status: o,
505
+ redirect: (a = 302, e) => new Response(JSON.stringify({ location: e, type: "redirect", status: a }), {
506
+ status: a,
507
507
  headers: { "Content-Type": "application/json" }
508
508
  }),
509
- error: (o = 500, e) => new Response(JSON.stringify({ error: e, type: "error", status: o }), {
510
- status: o,
509
+ error: (a = 500, e) => new Response(JSON.stringify({ error: e, type: "error", status: a }), {
510
+ status: a,
511
511
  headers: { "Content-Type": "application/json" }
512
512
  }),
513
- fail: (o = 400, e) => new Response(JSON.stringify({ data: e, type: "failure", status: o }), {
514
- status: o,
513
+ fail: (a = 400, e) => new Response(JSON.stringify({ data: e, type: "failure", status: a }), {
514
+ status: a,
515
515
  headers: { "Content-Type": "application/json" }
516
516
  })
517
517
  };
@@ -520,10 +520,10 @@ class ie {
520
520
  this.raw = e.headers.get("cookie") ?? "", this.setCookieHeader = t;
521
521
  }
522
522
  get(e, t) {
523
- return T(this.raw, t)[e];
523
+ return b(this.raw, t)[e];
524
524
  }
525
525
  getAll(e) {
526
- return Object.entries(T(this.raw, e)).filter(([, t]) => t !== void 0).map(([t, s]) => ({ name: t, value: s }));
526
+ return Object.entries(b(this.raw, e)).filter(([, t]) => t !== void 0).map(([t, s]) => ({ name: t, value: s }));
527
527
  }
528
528
  set(e, t, s) {
529
529
  this.setCookieHeader(B(e, t, s));
@@ -537,9 +537,9 @@ class C extends Error {
537
537
  super(e), this.status = 413, this.name = "PayloadTooLargeError";
538
538
  }
539
539
  }
540
- class We extends E {
540
+ class Le extends E {
541
541
  constructor(e) {
542
- super(), this.upgradeHandlerInstalled = !1, this.config = e ?? { type: "http", options: {} }, this.wss = new q({
542
+ super(), this.upgradeHandlerInstalled = !1, this.config = e ?? { type: "http", options: {} }, this.wss = new z({
543
543
  noServer: !0,
544
544
  maxPayload: this.config.security?.maxWebSocketPayload ?? 1024 * 1024
545
545
  });
@@ -551,7 +551,7 @@ class We extends E {
551
551
  console.error("Unhandled request error:", r), s.statusCode = 500, s.end("Internal Server Error");
552
552
  });
553
553
  };
554
- this._server = this.config.type === "https" ? I(this.config.options, e) : $(this.config.options, e);
554
+ this._server = this.config.type === "https" ? $(this.config.options, e) : M(this.config.options, e);
555
555
  }
556
556
  return this._server;
557
557
  }
@@ -571,20 +571,20 @@ class We extends E {
571
571
  t.destroy();
572
572
  return;
573
573
  }
574
- const a = this.toRequestEvent(n, r, {
574
+ const o = this.toRequestEvent(n, r, {
575
575
  getClientAddress: () => e.socket.remoteAddress ?? "127.0.0.1",
576
576
  setHeader: () => {
577
577
  },
578
578
  pushSetCookie: () => {
579
579
  }
580
580
  });
581
- this.canHandleWebSocket(a).then((i) => {
581
+ this.canHandleWebSocket(o).then((i) => {
582
582
  if (!i || !this.isAllowedWebSocketOrigin(e)) {
583
583
  t.destroy();
584
584
  return;
585
585
  }
586
586
  this.wss.handleUpgrade(e, t, s, (u) => {
587
- this.handleWebSocket(a, u).then((c) => {
587
+ this.handleWebSocket(o, u).then((c) => {
588
588
  !c && u.readyState === P.OPEN && u.close(1008, "Route not found");
589
589
  }).catch((c) => {
590
590
  console.error("WebSocket routing error:", c), u.readyState === P.OPEN && u.close(1011, "Internal error");
@@ -609,13 +609,13 @@ class We extends E {
609
609
  t.statusCode = 413, t.end("Payload Too Large");
610
610
  return;
611
611
  }
612
- const s = this.toWebRequest(e), r = new URL(s.url), n = {}, a = [], i = this.toRequestEvent(s, r, {
612
+ const s = this.toWebRequest(e), r = new URL(s.url), n = {}, o = [], i = this.toRequestEvent(s, r, {
613
613
  getClientAddress: () => e.socket.remoteAddress ?? "127.0.0.1",
614
614
  setHeader: (c, l) => {
615
615
  n[c.toLowerCase()] = l;
616
616
  },
617
617
  pushSetCookie: (c) => {
618
- a.push(c);
618
+ o.push(c);
619
619
  }
620
620
  });
621
621
  let u;
@@ -626,7 +626,7 @@ class We extends E {
626
626
  }
627
627
  for (const [c, l] of Object.entries(n))
628
628
  t.setHeader(c, l);
629
- a.length > 0 && t.setHeader("Set-Cookie", a), await this.sendWebResponse(t, u);
629
+ o.length > 0 && t.setHeader("Set-Cookie", o), await this.sendWebResponse(t, u);
630
630
  }
631
631
  toWebRequest(e) {
632
632
  const t = this.toURL(e, !1);
@@ -639,15 +639,15 @@ class We extends E {
639
639
  // @ts-ignore
640
640
  duplex: "half"
641
641
  };
642
- return !s && e.method !== "GET" && e.method !== "HEAD" && (r.body = U.toWeb(this.wrapRequestBody(e))), new Request(t, r);
642
+ return !s && e.method !== "GET" && e.method !== "HEAD" && (r.body = F.toWeb(this.wrapRequestBody(e))), new Request(t, r);
643
643
  }
644
644
  wrapRequestBody(e) {
645
645
  const t = this.config.security?.maxRequestBodySize;
646
646
  if (!t)
647
647
  return e;
648
648
  let s = 0;
649
- const r = new F({
650
- transform(n, a, i) {
649
+ const r = new D({
650
+ transform(n, o, i) {
651
651
  if (s += Buffer.byteLength(n), s > t) {
652
652
  i(new C());
653
653
  return;
@@ -658,7 +658,7 @@ class We extends E {
658
658
  return e.on("aborted", () => r.destroy(new Error("Request aborted"))), e.on("error", (n) => r.destroy(n)), e.pipe(r), r;
659
659
  }
660
660
  toURL(e, t) {
661
- const s = e.socket instanceof D ? t ? "wss" : "https" : t ? "ws" : "http", r = this.resolveAuthority(e);
661
+ const s = e.socket instanceof I ? t ? "wss" : "https" : t ? "ws" : "http", r = this.resolveAuthority(e);
662
662
  return new URL(e.url ?? "/", `${s}://${r}`);
663
663
  }
664
664
  resolveAuthority(e) {
@@ -726,18 +726,18 @@ class We extends E {
726
726
  return console.error("Unhandled error:", e), new Response("Internal Server Error", { status: 500 });
727
727
  }
728
728
  async sendWebResponse(e, t) {
729
- if (e.statusCode = t.status, t.headers.forEach((n, a) => {
730
- e.setHeader(a, n);
729
+ if (e.statusCode = t.status, t.headers.forEach((n, o) => {
730
+ e.setHeader(o, n);
731
731
  }), e.hasHeader("Server") || e.setHeader("Server", "WebHTTPServer"), !t.body || this.shouldOmitResponseBody(t, e.req?.method)) {
732
732
  e.end();
733
733
  return;
734
734
  }
735
- const s = t.body.getReader(), r = z.toWeb(e).getWriter();
735
+ const s = t.body.getReader(), r = U.toWeb(e).getWriter();
736
736
  try {
737
737
  for (; ; ) {
738
- const { done: n, value: a } = await s.read();
738
+ const { done: n, value: o } = await s.read();
739
739
  if (n) break;
740
- await r.write(a);
740
+ await r.write(o);
741
741
  }
742
742
  } finally {
743
743
  await r.close().catch(() => {
@@ -753,32 +753,74 @@ class We extends E {
753
753
  const s = this.config.security?.allowedWebSocketOrigins;
754
754
  return s ? this.matchesValue(t, s) : !0;
755
755
  }
756
+ createEventFetch(e, t) {
757
+ return async (s, r) => {
758
+ const n = this.toEventFetchRequest(e, s, r);
759
+ if (n.url.startsWith(`${e.url.origin}/`)) {
760
+ const o = this.toRequestEvent(n, new URL(n.url), t);
761
+ try {
762
+ return await this.handle(o);
763
+ } catch (i) {
764
+ return this.handleError(i);
765
+ }
766
+ }
767
+ return fetch(n);
768
+ };
769
+ }
770
+ toEventFetchRequest(e, t, s) {
771
+ const r = t instanceof URL ? t.toString() : t, n = r instanceof Request ? r : new Request(new URL(String(r), e.url), s);
772
+ if (r instanceof Request && !s)
773
+ return this.withInheritedRequestHeaders(e, r);
774
+ const o = new Headers(r instanceof Request ? r.headers : s?.headers), i = s?.method ?? (r instanceof Request ? r.method : void 0), u = s?.body ?? (r instanceof Request ? r.body : void 0), c = u ? "half" : void 0;
775
+ return this.inheritRequestHeader(e.request.headers, o, "cookie"), this.inheritRequestHeader(e.request.headers, o, "authorization"), new Request(n.url, {
776
+ ...s,
777
+ method: i,
778
+ headers: o,
779
+ body: u,
780
+ // @ts-ignore
781
+ duplex: c
782
+ });
783
+ }
784
+ withInheritedRequestHeaders(e, t) {
785
+ const s = new Headers(t.headers);
786
+ return this.inheritRequestHeader(e.request.headers, s, "cookie"), this.inheritRequestHeader(e.request.headers, s, "authorization"), new Request(t, {
787
+ headers: s,
788
+ // @ts-ignore
789
+ duplex: t.body ? "half" : void 0
790
+ });
791
+ }
792
+ inheritRequestHeader(e, t, s) {
793
+ if (t.has(s)) return;
794
+ const r = e.get(s);
795
+ r && t.set(s, r);
796
+ }
756
797
  toRequestEvent(e, t, s) {
757
- const r = new ie(e, s.pushSetCookie), n = this.config, a = {}, i = { name: "WebHTTPServer" }, u = /* @__PURE__ */ new Set(), c = {
798
+ const r = new ie(e, s.pushSetCookie), n = this.config, o = {}, i = { name: "WebHTTPServer" }, u = /* @__PURE__ */ new Set(), c = {
758
799
  request: e,
759
800
  url: t,
760
801
  cookies: r,
761
802
  getClientAddress: s.getClientAddress,
762
803
  get locals() {
763
- return a;
804
+ return o;
764
805
  },
765
806
  get platform() {
766
807
  return i;
767
808
  },
809
+ fetch: async (d, h) => l(d, h),
768
810
  params: {},
769
- route: { id: "" },
770
- setHeaders: (l) => {
771
- for (const [d, h] of Object.entries(l)) {
772
- const f = d.toLowerCase();
773
- if (f === "set-cookie")
811
+ route: { id: null },
812
+ setHeaders: (d) => {
813
+ for (const [h, p] of Object.entries(d)) {
814
+ const m = h.toLowerCase();
815
+ if (m === "set-cookie")
774
816
  throw new TypeError("Use event.cookies for Set-Cookie headers");
775
- if (u.has(f))
776
- throw new TypeError(`Header "${d}" has already been set`);
777
- u.add(f), s.setHeader(d, h);
817
+ if (u.has(m))
818
+ throw new TypeError(`Header "${h}" has already been set`);
819
+ u.add(m), s.setHeader(h, p);
778
820
  }
779
821
  }
780
- };
781
- return n.locals && Object.assign(a, n.locals(c)), n.platform && Object.assign(i, n.platform(c)), c;
822
+ }, l = this.createEventFetch(c, s);
823
+ return n.locals && Object.assign(o, n.locals(c)), n.platform && Object.assign(i, n.platform(c)), c;
782
824
  }
783
825
  }
784
826
  const ce = {
@@ -804,20 +846,20 @@ const ce = {
804
846
  cacheControl: "public, max-age=0",
805
847
  dotFiles: "ignore"
806
848
  };
807
- async function le(o, e, t = {}) {
849
+ async function le(a, e, t = {}) {
808
850
  const s = me(e), r = {
809
851
  ...ue,
810
852
  ...t
811
- }, n = await de(o), a = he(s, r.dotFiles);
812
- if (a instanceof Response)
813
- return a;
814
- const i = a.length > 0 ? a.join(G) : "", u = v(n, i);
853
+ }, n = await de(a), o = he(s, r.dotFiles);
854
+ if (o instanceof Response)
855
+ return o;
856
+ const i = o.length > 0 ? o.join(G) : "", u = O(n, i);
815
857
  if (!k(n, u))
816
858
  return new Response("Forbidden", { status: 403 });
817
859
  const c = await fe(u, n, r.index);
818
860
  if (c instanceof Response)
819
861
  return c;
820
- const l = await L(c), d = new Headers({
862
+ const l = await W(c), d = new Headers({
821
863
  "content-length": String(l.size),
822
864
  "content-type": pe(c),
823
865
  "cache-control": r.cacheControl,
@@ -826,8 +868,8 @@ async function le(o, e, t = {}) {
826
868
  });
827
869
  if (t.headers) {
828
870
  const h = typeof t.headers == "function" ? t.headers(c, l) : t.headers;
829
- new Headers(h).forEach((f, y) => {
830
- d.set(y, f);
871
+ new Headers(h).forEach((p, m) => {
872
+ d.set(m, p);
831
873
  });
832
874
  }
833
875
  return new Response(Q.toWeb(X(c)), {
@@ -835,13 +877,13 @@ async function le(o, e, t = {}) {
835
877
  headers: d
836
878
  });
837
879
  }
838
- async function de(o) {
839
- return O(o);
880
+ async function de(a) {
881
+ return v(a);
840
882
  }
841
- function he(o, e) {
842
- if (o.includes("\0"))
883
+ function he(a, e) {
884
+ if (a.includes("\0"))
843
885
  return new Response("Bad Request", { status: 400 });
844
- const t = o.replace(/\\/g, "/").split("/").filter(Boolean), s = [];
886
+ const t = a.replace(/\\/g, "/").split("/").filter(Boolean), s = [];
845
887
  for (const r of t) {
846
888
  let n;
847
889
  try {
@@ -863,43 +905,52 @@ function he(o, e) {
863
905
  }
864
906
  return s;
865
907
  }
866
- async function fe(o, e, t) {
908
+ async function fe(a, e, t) {
867
909
  try {
868
- if ((await J(o)).isDirectory()) {
869
- const r = v(o, t);
870
- return W(r, e);
910
+ if ((await J(a)).isDirectory()) {
911
+ const r = O(a, t);
912
+ return L(r, e);
871
913
  }
872
- return W(o, e);
914
+ return L(a, e);
873
915
  } catch {
874
916
  return new Response("Not Found", { status: 404 });
875
917
  }
876
918
  }
877
- async function W(o, e) {
919
+ async function L(a, e) {
878
920
  try {
879
- const t = await O(o);
880
- return k(e, t) ? (await L(t)).isFile() ? t : new Response("Not Found", { status: 404 }) : new Response("Forbidden", { status: 403 });
921
+ const t = await v(a);
922
+ return k(e, t) ? (await W(t)).isFile() ? t : new Response("Not Found", { status: 404 }) : new Response("Forbidden", { status: 403 });
881
923
  } catch {
882
924
  return new Response("Not Found", { status: 404 });
883
925
  }
884
926
  }
885
- function k(o, e) {
886
- const t = V(o, e);
927
+ function k(a, e) {
928
+ const t = V(a, e);
887
929
  return t === "" || !t.startsWith("..") && !K(t);
888
930
  }
889
- function pe(o) {
890
- return ce[Y(o).toLowerCase()] ?? "application/octet-stream";
931
+ function pe(a) {
932
+ return ce[Y(a).toLowerCase()] ?? "application/octet-stream";
891
933
  }
892
- function me(o) {
893
- return typeof o.params.path == "string" ? o.params.path : o.url.pathname.replace(/^\/+/, "");
934
+ function me(a) {
935
+ return typeof a.params.path == "string" ? a.params.path : a.url.pathname.replace(/^\/+/, "");
894
936
  }
895
- const Le = (o, e = {}) => (t) => le(o, t, e);
896
- function we(o, e = {}) {
937
+ const We = (a, e = {}) => (t) => le(a, t, e), ve = (a, ...e) => async (t) => {
938
+ const s = {};
939
+ for (const r of e) {
940
+ const n = await r(t);
941
+ if (S(n))
942
+ return n;
943
+ n && typeof n == "object" && Object.assign(s, n);
944
+ }
945
+ return a(Object.assign(t, { context: s }));
946
+ };
947
+ function we(a, e = {}) {
897
948
  const t = [];
898
949
  if (e.comment)
899
950
  for (const s of e.comment.split(/\r?\n/))
900
951
  t.push(`: ${s}`);
901
- if (e.event && t.push(`event: ${e.event}`), e.id && t.push(`id: ${e.id}`), e.retry !== void 0 && t.push(`retry: ${e.retry}`), o !== void 0) {
902
- const s = typeof o == "string" ? o : JSON.stringify(o);
952
+ if (e.event && t.push(`event: ${e.event}`), e.id && t.push(`id: ${e.id}`), e.retry !== void 0 && t.push(`retry: ${e.retry}`), a !== void 0) {
953
+ const s = typeof a == "string" ? a : JSON.stringify(a);
903
954
  for (const r of s.split(/\r?\n/))
904
955
  t.push(`data: ${r}`);
905
956
  }
@@ -908,14 +959,14 @@ function we(o, e = {}) {
908
959
 
909
960
  `;
910
961
  }
911
- const Oe = (o, e = {}) => (t) => {
962
+ const Oe = (a, e = {}) => (t) => {
912
963
  const s = new TextEncoder();
913
- let r = null, n = !1, a;
964
+ let r = null, n = !1, o;
914
965
  const i = async () => {
915
966
  if (!n) {
916
967
  n = !0;
917
968
  try {
918
- await a?.();
969
+ await o?.();
919
970
  } finally {
920
971
  r?.close();
921
972
  }
@@ -930,7 +981,7 @@ const Oe = (o, e = {}) => (t) => {
930
981
  i();
931
982
  }, { once: !0 });
932
983
  try {
933
- if (a = await o(t, l), !t.request.signal.aborted && a === void 0)
984
+ if (o = await a(t, l), !t.request.signal.aborted && o === void 0)
934
985
  return;
935
986
  t.request.signal.aborted && await i();
936
987
  } catch (d) {
@@ -950,8 +1001,8 @@ const Oe = (o, e = {}) => (t) => {
950
1001
  ...e.headers
951
1002
  }
952
1003
  });
953
- }, ve = async (o, e) => {
954
- const t = JSON.stringify(await o);
1004
+ }, _e = async (a, e) => {
1005
+ const t = JSON.stringify(await a);
955
1006
  return new Response(t, {
956
1007
  ...e,
957
1008
  headers: {
@@ -961,24 +1012,24 @@ const Oe = (o, e = {}) => (t) => {
961
1012
  }
962
1013
  });
963
1014
  };
964
- function _e(o, e) {
1015
+ function Ne(a, e) {
965
1016
  throw new Response(null, {
966
- status: o,
1017
+ status: a,
967
1018
  headers: {
968
1019
  location: e.toString()
969
1020
  }
970
1021
  });
971
1022
  }
972
- function Ne(o, e) {
1023
+ function je(a, e) {
973
1024
  throw new Response(JSON.stringify(typeof e == "string" ? { message: e } : e), {
974
- status: o,
1025
+ status: a,
975
1026
  headers: {
976
1027
  "content-type": "application/json"
977
1028
  }
978
1029
  });
979
1030
  }
980
- const je = async (o, e) => {
981
- const t = await o;
1031
+ const ke = async (a, e) => {
1032
+ const t = await a;
982
1033
  return new Response(t, {
983
1034
  ...e,
984
1035
  headers: {
@@ -987,8 +1038,8 @@ const je = async (o, e) => {
987
1038
  ...e?.headers
988
1039
  }
989
1040
  });
990
- }, ke = async (o, e) => {
991
- const t = await o;
1041
+ }, qe = async (a, e) => {
1042
+ const t = await a;
992
1043
  return new Response(t, {
993
1044
  ...e,
994
1045
  headers: {
@@ -1001,20 +1052,21 @@ const je = async (o, e) => {
1001
1052
  export {
1002
1053
  R as Action,
1003
1054
  Ce as CORS,
1004
- be as RateLimiter,
1005
- oe as RequestMethods,
1055
+ Te as RateLimiter,
1056
+ ae as RequestMethods,
1006
1057
  E as Router,
1007
- We as WebServer,
1008
- Le as dir,
1009
- Ne as error,
1010
- ke as html,
1058
+ Le as WebServer,
1059
+ We as dir,
1060
+ ve as enhance,
1061
+ je as error,
1062
+ qe as html,
1011
1063
  _ as isHttpError,
1012
1064
  N as isRedirect,
1013
- x as isResponse,
1014
- ve as json,
1015
- _e as redirect,
1065
+ S as isResponse,
1066
+ _e as json,
1067
+ Ne as redirect,
1016
1068
  le as serveStatic,
1017
1069
  Oe as sse,
1018
- je as text
1070
+ ke as text
1019
1071
  };
1020
1072
  //# sourceMappingURL=index.es.js.map