@sourceregistry/node-webserver 1.2.0 → 1.2.2

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,134 +1,23 @@
1
- import { createReadStream as I } from "node:fs";
2
- import { stat as L, realpath as O, lstat as D } from "node:fs/promises";
3
- import { sep as $, resolve as v, relative as U, isAbsolute as F, extname as z } from "node:path";
4
- import { Readable as B } from "node:stream";
5
- import { createServer as q } from "http";
6
- import { createServer as X } from "https";
7
- import { TLSSocket as G } from "tls";
8
- import { Readable as J, Transform as V, Writable as K } from "stream";
9
- import { WebSocketServer as Y, WebSocket as E } from "ws";
10
- import { parse as T, serialize as Q } from "cookie";
11
- const Z = {
12
- ".avif": "image/avif",
13
- ".css": "text/css; charset=utf-8",
14
- ".gif": "image/gif",
15
- ".html": "text/html; charset=utf-8",
16
- ".ico": "image/x-icon",
17
- ".jpg": "image/jpeg",
18
- ".jpeg": "image/jpeg",
19
- ".js": "text/javascript; charset=utf-8",
20
- ".json": "application/json; charset=utf-8",
21
- ".mjs": "text/javascript; charset=utf-8",
22
- ".pdf": "application/pdf",
23
- ".png": "image/png",
24
- ".svg": "image/svg+xml; charset=utf-8",
25
- ".txt": "text/plain; charset=utf-8",
26
- ".wasm": "application/wasm",
27
- ".webp": "image/webp",
28
- ".xml": "application/xml; charset=utf-8"
29
- }, ee = {
30
- index: "index.html",
31
- cacheControl: "public, max-age=0",
32
- dotFiles: "ignore"
33
- };
34
- async function te(a, e, t = {}) {
35
- const s = ae(e), r = {
36
- ...ee,
37
- ...t
38
- }, n = await se(a), o = re(s, r.dotFiles);
39
- if (o instanceof Response)
40
- return o;
41
- const i = o.length > 0 ? o.join($) : "", u = v(n, i);
42
- if (!_(n, u))
43
- return new Response("Forbidden", { status: 403 });
44
- const c = await ne(u, n, r.index);
45
- if (c instanceof Response)
46
- return c;
47
- const l = await L(c), d = new Headers({
48
- "content-length": String(l.size),
49
- "content-type": oe(c),
50
- "cache-control": r.cacheControl,
51
- "last-modified": l.mtime.toUTCString(),
52
- "x-content-type-options": "nosniff"
53
- });
54
- if (t.headers) {
55
- const h = typeof t.headers == "function" ? t.headers(c, l) : t.headers;
56
- new Headers(h).forEach((f, y) => {
57
- d.set(y, f);
58
- });
59
- }
60
- return new Response(B.toWeb(I(c)), {
61
- status: 200,
62
- headers: d
63
- });
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";
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";
10
+ import { Readable as Q } from "node:stream";
11
+ function _(o) {
12
+ return x(o) && o.status >= 400 && o.status < 600;
64
13
  }
65
- async function se(a) {
66
- return O(a);
14
+ function N(o) {
15
+ return x(o) && o.status >= 300 && o.status < 400;
67
16
  }
68
- function re(a, e) {
69
- if (a.includes("\0"))
70
- return new Response("Bad Request", { status: 400 });
71
- const t = a.replace(/\\/g, "/").split("/").filter(Boolean), s = [];
72
- for (const r of t) {
73
- let n;
74
- try {
75
- n = decodeURIComponent(r);
76
- } catch {
77
- return new Response("Bad Request", { status: 400 });
78
- }
79
- if (!(!n || n === ".")) {
80
- if (n === ".." || n.includes("/") || n.includes("\\") || n.includes("\0"))
81
- return new Response("Forbidden", { status: 403 });
82
- if (n.startsWith(".")) {
83
- if (e === "deny")
84
- return new Response("Forbidden", { status: 403 });
85
- if (e !== "allow")
86
- return new Response("Not Found", { status: 404 });
87
- }
88
- s.push(n);
89
- }
90
- }
91
- return s;
17
+ function x(o) {
18
+ return o instanceof Response;
92
19
  }
93
- async function ne(a, e, t) {
94
- try {
95
- if ((await D(a)).isDirectory()) {
96
- const r = v(a, t);
97
- return C(r, e);
98
- }
99
- return C(a, e);
100
- } catch {
101
- return new Response("Not Found", { status: 404 });
102
- }
103
- }
104
- async function C(a, e) {
105
- try {
106
- const t = await O(a);
107
- return _(e, t) ? (await L(t)).isFile() ? t : new Response("Not Found", { status: 404 }) : new Response("Forbidden", { status: 403 });
108
- } catch {
109
- return new Response("Not Found", { status: 404 });
110
- }
111
- }
112
- function _(a, e) {
113
- const t = U(a, e);
114
- return t === "" || !t.startsWith("..") && !F(t);
115
- }
116
- function oe(a) {
117
- return Z[z(a).toLowerCase()] ?? "application/octet-stream";
118
- }
119
- function ae(a) {
120
- return typeof a.params.path == "string" ? a.params.path : a.url.pathname.replace(/^\/+/, "");
121
- }
122
- function N(a) {
123
- return x(a) && a.status >= 400 && a.status < 600;
124
- }
125
- function j(a) {
126
- return x(a) && a.status >= 300 && a.status < 400;
127
- }
128
- function x(a) {
129
- return a instanceof Response;
130
- }
131
- class ie {
20
+ class Z {
132
21
  constructor(e) {
133
22
  this.data = /* @__PURE__ */ new Map(), this.windowMs = e.windowMs, this.startCleanup();
134
23
  }
@@ -151,54 +40,54 @@ class ie {
151
40
  this.data.clear();
152
41
  }
153
42
  }
154
- function ce(a) {
43
+ function ee(o) {
155
44
  const {
156
45
  windowMs: e = 6e4,
157
46
  max: t,
158
47
  key: s = (c) => c.getClientAddress(),
159
48
  message: r = "Too many requests, please try again later.",
160
49
  statusCode: n = 429,
161
- headers: o = "include",
50
+ headers: a = "include",
162
51
  onRateLimit: i,
163
- store: u = new ie({ windowMs: e })
164
- } = a;
52
+ store: u = new Z({ windowMs: e })
53
+ } = o;
165
54
  return async (c, l) => {
166
55
  const d = `rl:${s(c)}`, { current: h, reset: f } = await u.incr(d), y = Math.ceil((f - Date.now()) / 1e3);
167
56
  if (h > t) {
168
57
  i && i(c, { current: h, max: t, key: d });
169
- const w = {
58
+ const g = {
170
59
  status: n,
171
60
  headers: new Headers()
172
- }, p = w.headers;
173
- o === "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)));
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)));
174
63
  let m;
175
- 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, w);
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);
176
65
  }
177
66
  if (c.rateLimit = {
178
67
  current: h,
179
68
  limit: t,
180
69
  reset: new Date(f),
181
70
  remaining: t - h
182
- }, o === "include") {
183
- const w = {
71
+ }, a === "include") {
72
+ const g = {
184
73
  "X-RateLimit-Limit": String(t),
185
74
  "X-RateLimit-Remaining": String(t - h),
186
75
  "X-RateLimit-Reset": String(Math.floor(f / 1e3))
187
76
  }, p = c.setHeaders;
188
77
  c.setHeaders = (m) => {
189
78
  p({
190
- ...w,
79
+ ...g,
191
80
  ...m
192
81
  });
193
- }, p(w);
82
+ }, p(g);
194
83
  }
195
84
  return l();
196
85
  };
197
86
  }
198
- const Te = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
87
+ const be = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
199
88
  __proto__: null,
200
- fixedWindowLimit: ce
201
- }, Symbol.toStringTag, { value: "Module" })), ue = [
89
+ fixedWindowLimit: ee
90
+ }, Symbol.toStringTag, { value: "Module" })), te = [
202
91
  "GET",
203
92
  "POST",
204
93
  "PUT",
@@ -206,13 +95,13 @@ const Te = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
206
95
  "PATCH",
207
96
  "HEAD",
208
97
  "OPTIONS"
209
- ], le = [
98
+ ], se = [
210
99
  "Accept",
211
100
  "Accept-Language",
212
101
  "Content-Language",
213
102
  "Content-Type",
214
103
  "Range"
215
- ], de = [
104
+ ], re = [
216
105
  "Authorization",
217
106
  "X-Auth-Token",
218
107
  "X-Requested-With",
@@ -222,55 +111,55 @@ const Te = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
222
111
  "X-Real-IP",
223
112
  "X-Custom-Header"
224
113
  ];
225
- function M(a, e) {
226
- return !a || !e ? !1 : e === "*" ? !0 : e === "null" ? a === "null" : Array.isArray(e) ? e.some((t) => M(a, t)) : typeof e == "function" ? e(a) : e instanceof RegExp ? e.test(a) : a === e;
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;
227
116
  }
228
- function he(a, e) {
117
+ function ne(o, e) {
229
118
  const { origin: t = "*" } = e;
230
- return a ? t === "*" ? e.credentials ? a : "*" : M(a, t) ? a : null : t === "*" ? "*" : null;
119
+ return o ? t === "*" ? e.credentials ? o : "*" : j(o, t) ? o : null : t === "*" ? "*" : null;
231
120
  }
232
- function fe(a = {}) {
121
+ function ae(o = {}) {
233
122
  const {
234
- methods: e = ue,
235
- allowedHeaders: t = de,
123
+ methods: e = te,
124
+ allowedHeaders: t = re,
236
125
  exposedHeaders: s,
237
126
  credentials: r = !1,
238
127
  maxAge: n = 86400,
239
- onResponse: o
240
- } = a, i = "Origin,Access-Control-Request-Method,Access-Control-Request-Headers", u = e.join(","), c = [...le, ...t].join(","), l = [
128
+ onResponse: a
129
+ } = o, i = "Origin,Access-Control-Request-Method,Access-Control-Request-Headers", u = e.join(","), c = [...se, ...t].join(","), l = [
241
130
  ["Vary", i],
242
131
  ["Access-Control-Allow-Methods", u],
243
132
  ["Access-Control-Allow-Headers", c]
244
133
  ];
245
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) => {
246
- const f = d.request, y = f.headers.get("Origin"), w = f.method === "OPTIONS" && y !== null && f.headers.has("Access-Control-Request-Method"), p = he(y, a);
247
- if (w) {
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) {
248
137
  if (!p)
249
138
  return new Response(null, { status: 403 });
250
- const g = new Response(null, { status: 204 });
251
- for (const [H, k] of l)
252
- g.headers.set(H, k);
253
- return g.headers.set("Access-Control-Allow-Origin", p), g;
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;
254
143
  }
255
144
  const m = await h();
256
145
  if (!m) return;
257
146
  if (!p) return m;
258
147
  const S = new Response(m.body, m);
259
- for (const [g, H] of l)
260
- S.headers.set(g, H);
148
+ for (const [w, H] of l)
149
+ S.headers.set(w, H);
261
150
  S.headers.set("Access-Control-Allow-Origin", p);
262
151
  let A = S;
263
- if (o) {
264
- const g = o(A);
265
- g && (A = g);
152
+ if (a) {
153
+ const w = a(A);
154
+ w && (A = w);
266
155
  }
267
156
  return A;
268
157
  };
269
158
  }
270
159
  const Ce = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
271
160
  __proto__: null,
272
- policy: fe
273
- }, Symbol.toStringTag, { value: "Module" })), pe = ["GET", "PUT", "POST", "DELETE", "PATCH", "HEAD", "OPTIONS"];
161
+ policy: ae
162
+ }, Symbol.toStringTag, { value: "Module" })), oe = ["GET", "PUT", "POST", "DELETE", "PATCH", "HEAD", "OPTIONS"];
274
163
  class b {
275
164
  static {
276
165
  this.cache = /* @__PURE__ */ new Map();
@@ -282,7 +171,7 @@ class b {
282
171
  this.cache.set(e, t);
283
172
  }
284
173
  }
285
- class P {
174
+ class E {
286
175
  constructor() {
287
176
  this._routes = [], this._wsRoutes = [], this._nestedRouters = [], this._middlewares = [], this._preHandlers = [], this._postHandlers = [], this.routesSorted = !1, this.wsRoutesSorted = !1;
288
177
  }
@@ -316,23 +205,23 @@ class P {
316
205
  }
317
206
  // Universal method
318
207
  USE(e, t, ...s) {
319
- return pe.forEach((r) => this.addHandler(r, e, t, s)), this;
208
+ return oe.forEach((r) => this.addHandler(r, e, t, s)), this;
320
209
  }
321
210
  // Action handler (POST only)
322
211
  action(e, t, ...s) {
323
212
  const r = async (n) => {
324
213
  try {
325
- const o = await t(n);
326
- return this.formatActionResult(o);
327
- } catch (o) {
328
- return this.handleActionError(o);
214
+ const a = await t(n);
215
+ return this.formatActionResult(a);
216
+ } catch (a) {
217
+ return this.handleActionError(a);
329
218
  }
330
219
  };
331
220
  return this.addHandler("POST", e, r, s);
332
221
  }
333
222
  use(e, t, ...s) {
334
- let r, n, o = s;
335
- Array.isArray(e) ? ([r, n] = e, o = e.length > 2 ? e.slice(2) : []) : (r = e, n = t);
223
+ let r, n, a = s;
224
+ Array.isArray(e) ? ([r, n] = e, a = e.length > 2 ? e.slice(2) : []) : (r = e, n = t);
336
225
  const i = this.normalizePrefix(r), { regex: u, paramNames: c, isCatchAll: l, priority: d } = this.createPrefixRegex(i);
337
226
  return this._nestedRouters.push({
338
227
  prefix: i,
@@ -341,7 +230,7 @@ class P {
341
230
  paramNames: c,
342
231
  isCatchAll: l,
343
232
  priority: d,
344
- middlewares: o
233
+ middlewares: a
345
234
  }), this;
346
235
  }
347
236
  // Global middleware
@@ -362,12 +251,12 @@ class P {
362
251
  }
363
252
  // WebSocket route
364
253
  WS(e, t, ...s) {
365
- const { regex: r, paramNames: n, isCatchAll: o, priority: i } = this.createPathRegex(e);
254
+ const { regex: r, paramNames: n, isCatchAll: a, priority: i } = this.createPathRegex(e);
366
255
  return this._wsRoutes.push({
367
256
  path: e,
368
257
  regex: r,
369
258
  paramNames: n,
370
- isCatchAll: o,
259
+ isCatchAll: a,
371
260
  priority: i,
372
261
  handler: t,
373
262
  middlewares: s
@@ -386,11 +275,11 @@ class P {
386
275
  for (const s of [...this._nestedRouters].sort((r, n) => n.priority - r.priority)) {
387
276
  const r = t.match(s.regex);
388
277
  if (!r || r.index !== 0) continue;
389
- const n = r[0], o = t.slice(n.length) || "/", i = {
278
+ const n = r[0], a = t.slice(n.length) || "/", i = {
390
279
  ...e,
391
280
  params: { ...e.params, ...this.extractPrefixParams(s, n) }
392
281
  };
393
- if (await s.router.canHandleWebSocketAtPath(i, o))
282
+ if (await s.router.canHandleWebSocketAtPath(i, a))
394
283
  return !0;
395
284
  }
396
285
  for (const s of this._wsRoutes)
@@ -404,10 +293,10 @@ class P {
404
293
  }
405
294
  async handleWebSocketAtPath(e, t, s) {
406
295
  this.wsRoutesSorted || this.sortWsRoutes();
407
- for (const r of [...this._nestedRouters].sort((n, o) => o.priority - n.priority)) {
296
+ for (const r of [...this._nestedRouters].sort((n, a) => a.priority - n.priority)) {
408
297
  const n = s.match(r.regex);
409
298
  if (!n || n.index !== 0) continue;
410
- const o = n[0], i = s.slice(o.length) || "/", u = this.extractPrefixParams(r, o), c = {
299
+ const a = n[0], i = s.slice(a.length) || "/", u = this.extractPrefixParams(r, a), c = {
411
300
  ...e,
412
301
  params: { ...e.params, ...u }
413
302
  }, l = [...this._middlewares, ...r.middlewares], d = () => r.router.handleWebSocketAtPath(c, t, i);
@@ -417,11 +306,11 @@ class P {
417
306
  if (!r.regex.test(s)) continue;
418
307
  const n = s.match(r.regex);
419
308
  if (!n) continue;
420
- const o = Object.fromEntries(
309
+ const a = Object.fromEntries(
421
310
  r.paramNames.map((l, d) => [l, n[d + 1] || ""])
422
311
  ), i = {
423
312
  ...e,
424
- params: { ...e.params, ...o },
313
+ params: { ...e.params, ...a },
425
314
  route: { ...e.route, id: r.path },
426
315
  websocket: t
427
316
  }, u = [...this._middlewares, ...r.middlewares];
@@ -439,11 +328,11 @@ class P {
439
328
  const s = e.request.method;
440
329
  let r = await this.runPreHandlers(e);
441
330
  if (!r) {
442
- const o = async () => {
331
+ const a = async () => {
443
332
  const i = await this.handleNestedRouters(e, t);
444
333
  return i || (this.routesSorted || this.sortRoutes(), this.handleLocalRoutes(e, s, t));
445
334
  };
446
- r = await this.applyMiddlewaresWithList(e, this._middlewares, o);
335
+ r = await this.applyMiddlewaresWithList(e, this._middlewares, a);
447
336
  }
448
337
  const n = r || new Response("No Content", { status: 204 });
449
338
  return await this.runPostHandlers(e, n);
@@ -454,7 +343,7 @@ class P {
454
343
  }
455
344
  // Apply middlewares utility
456
345
  async applyMiddlewaresWithList(e, t, s) {
457
- const r = [...t], n = async (o) => o >= r.length ? s() : r[o](e, () => n(o + 1));
346
+ const r = [...t], n = async (a) => a >= r.length ? s() : r[a](e, () => n(a + 1));
458
347
  return n(0);
459
348
  }
460
349
  async runPreHandlers(e) {
@@ -474,12 +363,12 @@ class P {
474
363
  }
475
364
  // Add route handler
476
365
  addHandler(e, t, s, r = []) {
477
- const { regex: n, paramNames: o, isCatchAll: i, priority: u } = this.createPathRegex(t);
366
+ const { regex: n, paramNames: a, isCatchAll: i, priority: u } = this.createPathRegex(t);
478
367
  return this._routes.push({
479
368
  method: e,
480
369
  path: t,
481
370
  regex: n,
482
- paramNames: o,
371
+ paramNames: a,
483
372
  isCatchAll: i,
484
373
  priority: u,
485
374
  handler: s,
@@ -492,10 +381,10 @@ class P {
492
381
  if (t) return t;
493
382
  const s = [];
494
383
  let r = !1, n;
495
- const o = e.split("/").filter(Boolean);
496
- n = o.reduce((c, l) => l.startsWith("[...") ? c - 10 : l.startsWith("[[") ? c - 5 : l.startsWith("[") ? c - 1 : c + 1, 0);
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);
497
386
  let i = "^";
498
- for (const c of o)
387
+ for (const c of a)
499
388
  if (c.startsWith("[...") && c.endsWith("]")) {
500
389
  r = !0;
501
390
  const l = c.slice(4, -1);
@@ -518,21 +407,21 @@ class P {
518
407
  let s = !1, r;
519
408
  const n = e.split("/").filter(Boolean);
520
409
  r = n.reduce((i, u) => u.startsWith("[...") ? i - 10 : u.startsWith("[[") ? i - 5 : u.startsWith("[") ? i - 1 : i + 1, 0);
521
- let o = "^";
410
+ let a = "^";
522
411
  for (const i of n)
523
412
  if (i.startsWith("[...") && i.endsWith("]")) {
524
413
  s = !0;
525
414
  const u = i.slice(4, -1);
526
- t.push(u), o += "/(.+)";
415
+ t.push(u), a += "/(.+)";
527
416
  } else if (i.startsWith("[[") && i.endsWith("]]")) {
528
417
  const u = i.slice(2, -2);
529
- t.push(u), o += "(?:/([^/]+))?";
418
+ t.push(u), a += "(?:/([^/]+))?";
530
419
  } else if (i.startsWith("[") && i.endsWith("]")) {
531
420
  const u = i.slice(1, -1);
532
- t.push(u), o += "/([^/]+)";
421
+ t.push(u), a += "/([^/]+)";
533
422
  } else
534
- o += "/" + i.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
535
- return o += "(?=/|$)", { regex: new RegExp(o), paramNames: t, isCatchAll: s, priority: r };
423
+ a += "/" + i.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
424
+ return a += "(?=/|$)", { regex: new RegExp(a), paramNames: t, isCatchAll: s, priority: r };
536
425
  }
537
426
  normalizePrefix(e) {
538
427
  return e.startsWith("/") ? e.replace(/\/$/, "") : `/${e.replace(/\/$/, "")}`;
@@ -541,8 +430,8 @@ class P {
541
430
  const s = t.match(e.regex);
542
431
  if (!s) return {};
543
432
  const r = {};
544
- return e.isCatchAll && e.paramNames.length === 1 ? r[e.paramNames[0]] = s[1]?.replace(/^\//, "") || "" : e.paramNames.forEach((n, o) => {
545
- r[n] = s[o + 1] || "";
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] || "";
546
435
  }), r;
547
436
  }
548
437
  // FIXED: Nested router handling without duplicate middleware application
@@ -551,7 +440,7 @@ class P {
551
440
  for (const r of s) {
552
441
  const n = t.match(r.regex);
553
442
  if (!n || n.index !== 0) continue;
554
- const o = n[0], i = t.slice(o.length) || "/", u = this.extractPrefixParams(r, o), c = {
443
+ const a = n[0], i = t.slice(a.length) || "/", u = this.extractPrefixParams(r, a), c = {
555
444
  ...e,
556
445
  params: { ...e.params, ...u }
557
446
  }, l = async () => await r.router.handleAtPath(c, i), d = await this.applyMiddlewaresWithList(c, r.middlewares, l);
@@ -563,25 +452,25 @@ class P {
563
452
  async handleLocalRoutes(e, t, s) {
564
453
  const r = /* @__PURE__ */ new Set();
565
454
  let n = !1;
566
- for (const o of this._routes) {
567
- 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;
568
- const u = s.match(o.regex);
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);
569
458
  if (!u) continue;
570
459
  const c = Object.fromEntries(
571
- o.paramNames.map((d, h) => [d, u[h + 1] || ""])
460
+ a.paramNames.map((d, h) => [d, u[h + 1] || ""])
572
461
  );
573
- e.params = { ...e.params, ...c }, e.route = { ...e.route, id: o.path };
574
- const l = () => o.handler(e);
575
- return await this.applyMiddlewaresWithList(e, o.middlewares, l);
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);
576
465
  }
577
466
  if (r.size > 0 || t === "HEAD" && n) {
578
- const o = [...r].join(", ");
467
+ const a = [...r].join(", ");
579
468
  return t === "OPTIONS" ? new Response(null, {
580
469
  status: 200,
581
- headers: { Allow: o }
470
+ headers: { Allow: a }
582
471
  }) : new Response("Method Not Allowed", {
583
472
  status: 405,
584
- headers: { Allow: o }
473
+ headers: { Allow: a }
585
474
  });
586
475
  }
587
476
  return new Response("Not Found", { status: 404 });
@@ -596,37 +485,37 @@ class P {
596
485
  return e instanceof Response ? e : e?.type === "failure" && "status" in e ? R.fail(e.status, e.data) : R.success(200, e ?? void 0);
597
486
  }
598
487
  handleActionError(e) {
599
- if (N(e))
488
+ if (_(e))
600
489
  return R.error(e.status, { message: e.statusText || "Error" });
601
- if (j(e)) {
490
+ if (N(e)) {
602
491
  const t = e.headers.get("Location") || "/";
603
492
  return R.redirect(e.status, t);
604
493
  }
605
494
  return console.error(e), R.error(500, { message: "Internal Server Error" });
606
495
  }
607
496
  static New() {
608
- return new P();
497
+ return new E();
609
498
  }
610
499
  }
611
500
  const R = {
612
- success: (a = 200, e) => new Response(JSON.stringify({ data: e, type: "success", status: a }), {
613
- status: a,
501
+ success: (o = 200, e) => new Response(JSON.stringify({ data: e, type: "success", status: o }), {
502
+ status: o,
614
503
  headers: { "Content-Type": "application/json" }
615
504
  }),
616
- redirect: (a = 302, e) => new Response(JSON.stringify({ location: e, type: "redirect", status: a }), {
617
- status: a,
505
+ redirect: (o = 302, e) => new Response(JSON.stringify({ location: e, type: "redirect", status: o }), {
506
+ status: o,
618
507
  headers: { "Content-Type": "application/json" }
619
508
  }),
620
- error: (a = 500, e) => new Response(JSON.stringify({ error: e, type: "error", status: a }), {
621
- status: a,
509
+ error: (o = 500, e) => new Response(JSON.stringify({ error: e, type: "error", status: o }), {
510
+ status: o,
622
511
  headers: { "Content-Type": "application/json" }
623
512
  }),
624
- fail: (a = 400, e) => new Response(JSON.stringify({ data: e, type: "failure", status: a }), {
625
- status: a,
513
+ fail: (o = 400, e) => new Response(JSON.stringify({ data: e, type: "failure", status: o }), {
514
+ status: o,
626
515
  headers: { "Content-Type": "application/json" }
627
516
  })
628
517
  };
629
- class me {
518
+ class ie {
630
519
  constructor(e, t) {
631
520
  this.raw = e.headers.get("cookie") ?? "", this.setCookieHeader = t;
632
521
  }
@@ -637,20 +526,20 @@ class me {
637
526
  return Object.entries(T(this.raw, e)).filter(([, t]) => t !== void 0).map(([t, s]) => ({ name: t, value: s }));
638
527
  }
639
528
  set(e, t, s) {
640
- this.setCookieHeader(Q(e, t, s));
529
+ this.setCookieHeader(B(e, t, s));
641
530
  }
642
531
  delete(e, t) {
643
532
  this.set(e, "", { ...t, maxAge: 0 });
644
533
  }
645
534
  }
646
- class W extends Error {
535
+ class C extends Error {
647
536
  constructor(e = "Payload Too Large") {
648
537
  super(e), this.status = 413, this.name = "PayloadTooLargeError";
649
538
  }
650
539
  }
651
- class be extends P {
540
+ class We extends E {
652
541
  constructor(e) {
653
- super(), this.upgradeHandlerInstalled = !1, this.config = e ?? { type: "http", options: {} }, this.wss = new Y({
542
+ super(), this.upgradeHandlerInstalled = !1, this.config = e ?? { type: "http", options: {} }, this.wss = new q({
654
543
  noServer: !0,
655
544
  maxPayload: this.config.security?.maxWebSocketPayload ?? 1024 * 1024
656
545
  });
@@ -662,7 +551,7 @@ class be extends P {
662
551
  console.error("Unhandled request error:", r), s.statusCode = 500, s.end("Internal Server Error");
663
552
  });
664
553
  };
665
- this._server = this.config.type === "https" ? X(this.config.options, e) : q(this.config.options, e);
554
+ this._server = this.config.type === "https" ? I(this.config.options, e) : $(this.config.options, e);
666
555
  }
667
556
  return this._server;
668
557
  }
@@ -682,23 +571,23 @@ class be extends P {
682
571
  t.destroy();
683
572
  return;
684
573
  }
685
- const o = this.toRequestEvent(n, r, {
574
+ const a = this.toRequestEvent(n, r, {
686
575
  getClientAddress: () => e.socket.remoteAddress ?? "127.0.0.1",
687
576
  setHeader: () => {
688
577
  },
689
578
  pushSetCookie: () => {
690
579
  }
691
580
  });
692
- this.canHandleWebSocket(o).then((i) => {
581
+ this.canHandleWebSocket(a).then((i) => {
693
582
  if (!i || !this.isAllowedWebSocketOrigin(e)) {
694
583
  t.destroy();
695
584
  return;
696
585
  }
697
586
  this.wss.handleUpgrade(e, t, s, (u) => {
698
- this.handleWebSocket(o, u).then((c) => {
699
- !c && u.readyState === E.OPEN && u.close(1008, "Route not found");
587
+ this.handleWebSocket(a, u).then((c) => {
588
+ !c && u.readyState === P.OPEN && u.close(1008, "Route not found");
700
589
  }).catch((c) => {
701
- console.error("WebSocket routing error:", c), u.readyState === E.OPEN && u.close(1011, "Internal error");
590
+ console.error("WebSocket routing error:", c), u.readyState === P.OPEN && u.close(1011, "Internal error");
702
591
  });
703
592
  });
704
593
  }).catch(() => t.destroy());
@@ -720,13 +609,13 @@ class be extends P {
720
609
  t.statusCode = 413, t.end("Payload Too Large");
721
610
  return;
722
611
  }
723
- const s = this.toWebRequest(e), r = new URL(s.url), n = {}, o = [], i = this.toRequestEvent(s, r, {
612
+ const s = this.toWebRequest(e), r = new URL(s.url), n = {}, a = [], i = this.toRequestEvent(s, r, {
724
613
  getClientAddress: () => e.socket.remoteAddress ?? "127.0.0.1",
725
614
  setHeader: (c, l) => {
726
615
  n[c.toLowerCase()] = l;
727
616
  },
728
617
  pushSetCookie: (c) => {
729
- o.push(c);
618
+ a.push(c);
730
619
  }
731
620
  });
732
621
  let u;
@@ -737,7 +626,7 @@ class be extends P {
737
626
  }
738
627
  for (const [c, l] of Object.entries(n))
739
628
  t.setHeader(c, l);
740
- o.length > 0 && t.setHeader("Set-Cookie", o), await this.sendWebResponse(t, u);
629
+ a.length > 0 && t.setHeader("Set-Cookie", a), await this.sendWebResponse(t, u);
741
630
  }
742
631
  toWebRequest(e) {
743
632
  const t = this.toURL(e, !1);
@@ -750,17 +639,17 @@ class be extends P {
750
639
  // @ts-ignore
751
640
  duplex: "half"
752
641
  };
753
- return !s && e.method !== "GET" && e.method !== "HEAD" && (r.body = J.toWeb(this.wrapRequestBody(e))), new Request(t, r);
642
+ return !s && e.method !== "GET" && e.method !== "HEAD" && (r.body = U.toWeb(this.wrapRequestBody(e))), new Request(t, r);
754
643
  }
755
644
  wrapRequestBody(e) {
756
645
  const t = this.config.security?.maxRequestBodySize;
757
646
  if (!t)
758
647
  return e;
759
648
  let s = 0;
760
- const r = new V({
761
- transform(n, o, i) {
649
+ const r = new F({
650
+ transform(n, a, i) {
762
651
  if (s += Buffer.byteLength(n), s > t) {
763
- i(new W());
652
+ i(new C());
764
653
  return;
765
654
  }
766
655
  i(null, n);
@@ -769,7 +658,7 @@ class be extends P {
769
658
  return e.on("aborted", () => r.destroy(new Error("Request aborted"))), e.on("error", (n) => r.destroy(n)), e.pipe(r), r;
770
659
  }
771
660
  toURL(e, t) {
772
- const s = e.socket instanceof G ? t ? "wss" : "https" : t ? "ws" : "http", r = this.resolveAuthority(e);
661
+ const s = e.socket instanceof D ? t ? "wss" : "https" : t ? "ws" : "http", r = this.resolveAuthority(e);
773
662
  return new URL(e.url ?? "/", `${s}://${r}`);
774
663
  }
775
664
  resolveAuthority(e) {
@@ -817,9 +706,9 @@ class be extends P {
817
706
  return Number.isFinite(r) && r <= t;
818
707
  }
819
708
  handleError(e) {
820
- if (e instanceof W)
709
+ if (e instanceof C)
821
710
  return new Response(e.message, { status: e.status });
822
- if (N(e))
711
+ if (_(e))
823
712
  return new Response(JSON.stringify({
824
713
  error: e.statusText || "Error",
825
714
  status: e.status
@@ -827,7 +716,7 @@ class be extends P {
827
716
  status: e.status,
828
717
  headers: { "Content-Type": "application/json" }
829
718
  });
830
- if (j(e)) {
719
+ if (N(e)) {
831
720
  const t = e.headers.get("Location") || "/";
832
721
  return new Response(null, {
833
722
  status: e.status,
@@ -837,18 +726,18 @@ class be extends P {
837
726
  return console.error("Unhandled error:", e), new Response("Internal Server Error", { status: 500 });
838
727
  }
839
728
  async sendWebResponse(e, t) {
840
- if (e.statusCode = t.status, t.headers.forEach((n, o) => {
841
- e.setHeader(o, n);
729
+ if (e.statusCode = t.status, t.headers.forEach((n, a) => {
730
+ e.setHeader(a, n);
842
731
  }), e.hasHeader("Server") || e.setHeader("Server", "WebHTTPServer"), !t.body || this.shouldOmitResponseBody(t, e.req?.method)) {
843
732
  e.end();
844
733
  return;
845
734
  }
846
- const s = t.body.getReader(), r = K.toWeb(e).getWriter();
735
+ const s = t.body.getReader(), r = z.toWeb(e).getWriter();
847
736
  try {
848
737
  for (; ; ) {
849
- const { done: n, value: o } = await s.read();
738
+ const { done: n, value: a } = await s.read();
850
739
  if (n) break;
851
- await r.write(o);
740
+ await r.write(a);
852
741
  }
853
742
  } finally {
854
743
  await r.close().catch(() => {
@@ -865,13 +754,13 @@ class be extends P {
865
754
  return s ? this.matchesValue(t, s) : !0;
866
755
  }
867
756
  toRequestEvent(e, t, s) {
868
- const r = new me(e, s.pushSetCookie), n = this.config, o = {}, i = { name: "WebHTTPServer" }, u = /* @__PURE__ */ new Set(), c = {
757
+ const r = new ie(e, s.pushSetCookie), n = this.config, a = {}, i = { name: "WebHTTPServer" }, u = /* @__PURE__ */ new Set(), c = {
869
758
  request: e,
870
759
  url: t,
871
760
  cookies: r,
872
761
  getClientAddress: s.getClientAddress,
873
762
  get locals() {
874
- return o;
763
+ return a;
875
764
  },
876
765
  get platform() {
877
766
  return i;
@@ -889,11 +778,180 @@ class be extends P {
889
778
  }
890
779
  }
891
780
  };
892
- return n.locals && Object.assign(o, n.locals(c)), n.platform && Object.assign(i, n.platform(c)), c;
781
+ return n.locals && Object.assign(a, n.locals(c)), n.platform && Object.assign(i, n.platform(c)), c;
893
782
  }
894
783
  }
895
- const We = async (a, e) => {
896
- const t = JSON.stringify(await a);
784
+ const ce = {
785
+ ".avif": "image/avif",
786
+ ".css": "text/css; charset=utf-8",
787
+ ".gif": "image/gif",
788
+ ".html": "text/html; charset=utf-8",
789
+ ".ico": "image/x-icon",
790
+ ".jpg": "image/jpeg",
791
+ ".jpeg": "image/jpeg",
792
+ ".js": "text/javascript; charset=utf-8",
793
+ ".json": "application/json; charset=utf-8",
794
+ ".mjs": "text/javascript; charset=utf-8",
795
+ ".pdf": "application/pdf",
796
+ ".png": "image/png",
797
+ ".svg": "image/svg+xml; charset=utf-8",
798
+ ".txt": "text/plain; charset=utf-8",
799
+ ".wasm": "application/wasm",
800
+ ".webp": "image/webp",
801
+ ".xml": "application/xml; charset=utf-8"
802
+ }, ue = {
803
+ index: "index.html",
804
+ cacheControl: "public, max-age=0",
805
+ dotFiles: "ignore"
806
+ };
807
+ async function le(o, e, t = {}) {
808
+ const s = me(e), r = {
809
+ ...ue,
810
+ ...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);
815
+ if (!k(n, u))
816
+ return new Response("Forbidden", { status: 403 });
817
+ const c = await fe(u, n, r.index);
818
+ if (c instanceof Response)
819
+ return c;
820
+ const l = await L(c), d = new Headers({
821
+ "content-length": String(l.size),
822
+ "content-type": pe(c),
823
+ "cache-control": r.cacheControl,
824
+ "last-modified": l.mtime.toUTCString(),
825
+ "x-content-type-options": "nosniff"
826
+ });
827
+ if (t.headers) {
828
+ const h = typeof t.headers == "function" ? t.headers(c, l) : t.headers;
829
+ new Headers(h).forEach((f, y) => {
830
+ d.set(y, f);
831
+ });
832
+ }
833
+ return new Response(Q.toWeb(X(c)), {
834
+ status: 200,
835
+ headers: d
836
+ });
837
+ }
838
+ async function de(o) {
839
+ return O(o);
840
+ }
841
+ function he(o, e) {
842
+ if (o.includes("\0"))
843
+ return new Response("Bad Request", { status: 400 });
844
+ const t = o.replace(/\\/g, "/").split("/").filter(Boolean), s = [];
845
+ for (const r of t) {
846
+ let n;
847
+ try {
848
+ n = decodeURIComponent(r);
849
+ } catch {
850
+ return new Response("Bad Request", { status: 400 });
851
+ }
852
+ if (!(!n || n === ".")) {
853
+ if (n === ".." || n.includes("/") || n.includes("\\") || n.includes("\0"))
854
+ return new Response("Forbidden", { status: 403 });
855
+ if (n.startsWith(".")) {
856
+ if (e === "deny")
857
+ return new Response("Forbidden", { status: 403 });
858
+ if (e !== "allow")
859
+ return new Response("Not Found", { status: 404 });
860
+ }
861
+ s.push(n);
862
+ }
863
+ }
864
+ return s;
865
+ }
866
+ async function fe(o, e, t) {
867
+ try {
868
+ if ((await J(o)).isDirectory()) {
869
+ const r = v(o, t);
870
+ return W(r, e);
871
+ }
872
+ return W(o, e);
873
+ } catch {
874
+ return new Response("Not Found", { status: 404 });
875
+ }
876
+ }
877
+ async function W(o, e) {
878
+ 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 });
881
+ } catch {
882
+ return new Response("Not Found", { status: 404 });
883
+ }
884
+ }
885
+ function k(o, e) {
886
+ const t = V(o, e);
887
+ return t === "" || !t.startsWith("..") && !K(t);
888
+ }
889
+ function pe(o) {
890
+ return ce[Y(o).toLowerCase()] ?? "application/octet-stream";
891
+ }
892
+ function me(o) {
893
+ return typeof o.params.path == "string" ? o.params.path : o.url.pathname.replace(/^\/+/, "");
894
+ }
895
+ const Le = (o, e = {}) => (t) => le(o, t, e);
896
+ function we(o, e = {}) {
897
+ const t = [];
898
+ if (e.comment)
899
+ for (const s of e.comment.split(/\r?\n/))
900
+ 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);
903
+ for (const r of s.split(/\r?\n/))
904
+ t.push(`data: ${r}`);
905
+ }
906
+ return `${t.join(`
907
+ `)}
908
+
909
+ `;
910
+ }
911
+ const Oe = (o, e = {}) => (t) => {
912
+ const s = new TextEncoder();
913
+ let r = null, n = !1, a;
914
+ const i = async () => {
915
+ if (!n) {
916
+ n = !0;
917
+ try {
918
+ await a?.();
919
+ } finally {
920
+ r?.close();
921
+ }
922
+ }
923
+ }, u = new ReadableStream({
924
+ async start(c) {
925
+ r = c;
926
+ const l = (d, h = {}) => {
927
+ n || c.enqueue(s.encode(we(d, h)));
928
+ };
929
+ t.request.signal.addEventListener("abort", () => {
930
+ i();
931
+ }, { once: !0 });
932
+ try {
933
+ if (a = await o(t, l), !t.request.signal.aborted && a === void 0)
934
+ return;
935
+ t.request.signal.aborted && await i();
936
+ } catch (d) {
937
+ n || c.error(d);
938
+ }
939
+ },
940
+ async cancel() {
941
+ await i();
942
+ }
943
+ });
944
+ return new Response(u, {
945
+ ...e,
946
+ headers: {
947
+ "content-type": "text/event-stream",
948
+ "cache-control": "no-cache",
949
+ connection: "keep-alive",
950
+ ...e.headers
951
+ }
952
+ });
953
+ }, ve = async (o, e) => {
954
+ const t = JSON.stringify(await o);
897
955
  return new Response(t, {
898
956
  ...e,
899
957
  headers: {
@@ -903,24 +961,24 @@ const We = async (a, e) => {
903
961
  }
904
962
  });
905
963
  };
906
- function Le(a, e) {
964
+ function _e(o, e) {
907
965
  throw new Response(null, {
908
- status: a,
966
+ status: o,
909
967
  headers: {
910
968
  location: e.toString()
911
969
  }
912
970
  });
913
971
  }
914
- function Oe(a, e) {
972
+ function Ne(o, e) {
915
973
  throw new Response(JSON.stringify(typeof e == "string" ? { message: e } : e), {
916
- status: a,
974
+ status: o,
917
975
  headers: {
918
976
  "content-type": "application/json"
919
977
  }
920
978
  });
921
979
  }
922
- const ve = async (a, e) => {
923
- const t = await a;
980
+ const je = async (o, e) => {
981
+ const t = await o;
924
982
  return new Response(t, {
925
983
  ...e,
926
984
  headers: {
@@ -929,8 +987,8 @@ const ve = async (a, e) => {
929
987
  ...e?.headers
930
988
  }
931
989
  });
932
- }, _e = async (a, e) => {
933
- const t = await a;
990
+ }, ke = async (o, e) => {
991
+ const t = await o;
934
992
  return new Response(t, {
935
993
  ...e,
936
994
  headers: {
@@ -939,23 +997,24 @@ const ve = async (a, e) => {
939
997
  ...e?.headers
940
998
  }
941
999
  });
942
- }, Ne = (a, e = {}) => (t) => te(a, t, e);
1000
+ };
943
1001
  export {
944
1002
  R as Action,
945
1003
  Ce as CORS,
946
- Te as RateLimiter,
947
- pe as RequestMethods,
948
- P as Router,
949
- be as WebServer,
950
- Ne as dir,
951
- Oe as error,
952
- _e as html,
953
- N as isHttpError,
954
- j as isRedirect,
1004
+ be as RateLimiter,
1005
+ oe as RequestMethods,
1006
+ E as Router,
1007
+ We as WebServer,
1008
+ Le as dir,
1009
+ Ne as error,
1010
+ ke as html,
1011
+ _ as isHttpError,
1012
+ N as isRedirect,
955
1013
  x as isResponse,
956
- We as json,
957
- Le as redirect,
958
- te as serveStatic,
959
- ve as text
1014
+ ve as json,
1015
+ _e as redirect,
1016
+ le as serveStatic,
1017
+ Oe as sse,
1018
+ je as text
960
1019
  };
961
1020
  //# sourceMappingURL=index.es.js.map