hono 4.13.3 → 4.13.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/cjs/client/client.js +25 -11
  2. package/dist/cjs/client/utils.js +3 -0
  3. package/dist/cjs/helper/accepts/accepts.js +36 -2
  4. package/dist/cjs/helper/ssg/ssg.js +1 -1
  5. package/dist/cjs/helper/ssg/utils.js +30 -10
  6. package/dist/cjs/jsx/dom/render.js +2 -0
  7. package/dist/cjs/middleware/cache/index.js +1 -1
  8. package/dist/cjs/middleware/etag/index.js +1 -1
  9. package/dist/cjs/request.js +8 -4
  10. package/dist/cjs/router/reg-exp-router/node.js +10 -3
  11. package/dist/cjs/router/reg-exp-router/router.js +47 -83
  12. package/dist/cjs/router/reg-exp-router/trie.js +2 -1
  13. package/dist/cjs/router/trie-router/node.js +4 -3
  14. package/dist/cjs/router/utils.js +27 -0
  15. package/dist/cjs/utils/body.js +15 -3
  16. package/dist/cjs/utils/cookie.js +1 -1
  17. package/dist/cjs/utils/stream.js +7 -1
  18. package/dist/cjs/utils/url.js +9 -1
  19. package/dist/client/client.js +25 -11
  20. package/dist/client/utils.js +3 -0
  21. package/dist/helper/accepts/accepts.js +36 -2
  22. package/dist/helper/ssg/ssg.js +1 -1
  23. package/dist/helper/ssg/utils.js +30 -10
  24. package/dist/jsx/dom/render.js +2 -0
  25. package/dist/middleware/cache/index.js +1 -1
  26. package/dist/middleware/etag/index.js +1 -1
  27. package/dist/request.js +8 -4
  28. package/dist/router/reg-exp-router/node.js +6 -2
  29. package/dist/router/reg-exp-router/router.js +53 -84
  30. package/dist/router/reg-exp-router/trie.js +2 -1
  31. package/dist/router/trie-router/node.js +4 -3
  32. package/dist/router/utils.js +5 -0
  33. package/dist/types/router/reg-exp-router/node.d.ts +3 -0
  34. package/dist/types/router/utils.d.ts +1 -0
  35. package/dist/types/utils/url.d.ts +4 -0
  36. package/dist/utils/body.js +15 -3
  37. package/dist/utils/cookie.js +1 -1
  38. package/dist/utils/stream.js +7 -1
  39. package/dist/utils/url.js +9 -1
  40. package/package.json +1 -1
@@ -21,6 +21,8 @@ __export(body_exports, {
21
21
  });
22
22
  module.exports = __toCommonJS(body_exports);
23
23
  var import_buffer = require("./buffer");
24
+ const MAX_NESTING_DEPTH = 32;
25
+ const MAX_NESTED_OBJECTS = 1e4;
24
26
  const isRawRequest = (request) => "headers" in request;
25
27
  const parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
26
28
  const { all = false, dot = false } = options;
@@ -53,6 +55,7 @@ async function parseFormData(request, options) {
53
55
  }
54
56
  function convertFormDataToBodyData(formData, options) {
55
57
  const form = /* @__PURE__ */ Object.create(null);
58
+ const nestingState = { count: 0 };
56
59
  formData.forEach((value, key) => {
57
60
  const shouldParseAllValues = options.all || key.endsWith("[]");
58
61
  if (!shouldParseAllValues) {
@@ -65,7 +68,7 @@ function convertFormDataToBodyData(formData, options) {
65
68
  Object.entries(form).forEach(([key, value]) => {
66
69
  const shouldParseDotValues = key.includes(".");
67
70
  if (shouldParseDotValues) {
68
- handleParsingNestedValues(form, key, value);
71
+ handleParsingNestedValues(form, key, value, nestingState);
69
72
  delete form[key];
70
73
  }
71
74
  });
@@ -88,23 +91,32 @@ const handleParsingAllValues = (form, key, value) => {
88
91
  }
89
92
  }
90
93
  };
91
- const handleParsingNestedValues = (form, key, value) => {
94
+ const handleParsingNestedValues = (form, key, value, state) => {
92
95
  if (/(?:^|\.)__proto__\./.test(key)) {
93
96
  return;
94
97
  }
95
98
  let nestedForm = form;
96
- const keys = key.split(".");
99
+ const keys = key.split(".", MAX_NESTING_DEPTH + 2);
100
+ if (keys.length > MAX_NESTING_DEPTH + 1) {
101
+ throwNestingLimitExceeded();
102
+ }
97
103
  keys.forEach((key2, index) => {
98
104
  if (index === keys.length - 1) {
99
105
  nestedForm[key2] = value;
100
106
  } else {
101
107
  if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
108
+ if (state.count++ >= MAX_NESTED_OBJECTS) {
109
+ throwNestingLimitExceeded();
110
+ }
102
111
  nestedForm[key2] = /* @__PURE__ */ Object.create(null);
103
112
  }
104
113
  nestedForm = nestedForm[key2];
105
114
  }
106
115
  });
107
116
  };
117
+ const throwNestingLimitExceeded = () => {
118
+ throw new Error("Nesting limit exceeded");
119
+ };
108
120
  // Annotate the CommonJS export names for ESM import in node:
109
121
  0 && (module.exports = {
110
122
  parseBody
@@ -101,7 +101,7 @@ const parseSigned = async (cookie, secret, name) => {
101
101
  const secretKey = await getCryptoKey(secret);
102
102
  for (const [key, value] of Object.entries(parse(cookie, name))) {
103
103
  const signatureStartPos = value.lastIndexOf(".");
104
- if (signatureStartPos < 1) {
104
+ if (signatureStartPos < 0) {
105
105
  continue;
106
106
  }
107
107
  const signedValue = value.substring(0, signatureStartPos);
@@ -96,7 +96,13 @@ class StreamingApi {
96
96
  abort() {
97
97
  if (!this.aborted) {
98
98
  this.aborted = true;
99
- this.abortSubscribers.forEach((subscriber) => subscriber());
99
+ this.abortSubscribers.forEach((subscriber) => {
100
+ try {
101
+ void Promise.resolve(subscriber()).catch(() => {
102
+ });
103
+ } catch {
104
+ }
105
+ });
100
106
  }
101
107
  }
102
108
  }
@@ -119,7 +119,11 @@ const getPath = (request) => {
119
119
  };
120
120
  const getQueryStrings = (url) => {
121
121
  const queryIndex = url.indexOf("?", 8);
122
- return queryIndex === -1 ? "" : "?" + url.slice(queryIndex + 1);
122
+ if (queryIndex === -1) {
123
+ return "";
124
+ }
125
+ const hashIndex = url.indexOf("#", 8);
126
+ return hashIndex === -1 ? url.slice(queryIndex) : queryIndex < hashIndex ? url.slice(queryIndex, hashIndex) : "";
123
127
  };
124
128
  const getPathNoStrict = (request) => {
125
129
  const result = getPath(request);
@@ -166,6 +170,10 @@ const _decodeURI = (value) => {
166
170
  return tryDecodeURIComponent(value);
167
171
  };
168
172
  const _getQueryParam = (url, key, multiple) => {
173
+ const hashIndex = url.indexOf("#", 8);
174
+ if (hashIndex !== -1) {
175
+ url = url.slice(0, hashIndex);
176
+ }
169
177
  let encoded;
170
178
  if (!multiple && key && key.indexOf("%") === -1 && key.indexOf("+") === -1) {
171
179
  let keyIndex2 = url.indexOf("?", 8);
@@ -26,6 +26,10 @@ var createProxy = (callback, path) => {
26
26
  });
27
27
  return proxy;
28
28
  };
29
+ var appendQueryParams = (url, searchParams) => {
30
+ const queryString = searchParams.toString();
31
+ return queryString ? `${url}?${queryString}` : url;
32
+ };
29
33
  var ClientRequestImpl = class {
30
34
  url;
31
35
  method;
@@ -52,6 +56,9 @@ var ClientRequestImpl = class {
52
56
  }
53
57
  if (Array.isArray(v)) {
54
58
  for (const v2 of v) {
59
+ if (v2 === void 0) {
60
+ continue;
61
+ }
55
62
  form.append(k, v2);
56
63
  }
57
64
  } else {
@@ -76,19 +83,29 @@ var ClientRequestImpl = class {
76
83
  if (args?.cookie) {
77
84
  const cookies = [];
78
85
  for (const [key, value] of Object.entries(args.cookie)) {
86
+ if (value === void 0) {
87
+ continue;
88
+ }
79
89
  cookies.push(serialize(key, value));
80
90
  }
81
- headerValues["Cookie"] = cookies.join("; ");
91
+ if (cookies.length > 0) {
92
+ headerValues["Cookie"] = cookies.join("; ");
93
+ }
82
94
  }
83
95
  if (this.cType) {
84
96
  headerValues["Content-Type"] = this.cType;
85
97
  }
86
- const headers = new Headers(headerValues ?? void 0);
98
+ const headers = new Headers();
99
+ for (const [key, value] of Object.entries(headerValues)) {
100
+ if (value !== void 0) {
101
+ headers.set(key, value);
102
+ }
103
+ }
87
104
  let url = this.url;
88
105
  url = removeIndexString(url);
89
106
  url = replaceUrlParam(url, this.pathParams);
90
107
  if (this.queryParams) {
91
- url = url + "?" + this.queryParams.toString();
108
+ url = appendQueryParams(url, this.queryParams);
92
109
  }
93
110
  methodUpperCase = this.method.toUpperCase();
94
111
  const setBody = !(methodUpperCase === "GET" || methodUpperCase === "HEAD");
@@ -132,7 +149,7 @@ var hc = (baseUrl, options) => createProxy(function proxyCallback(opts) {
132
149
  result = replaceUrlParam(url, opts.args[0].param);
133
150
  }
134
151
  if (opts.args[0].query) {
135
- result = result + "?" + buildSearchParamsOption(opts.args[0].query).toString();
152
+ result = appendQueryParams(result, buildSearchParamsOption(opts.args[0].query));
136
153
  }
137
154
  }
138
155
  result = removeIndexString(result);
@@ -143,18 +160,15 @@ var hc = (baseUrl, options) => createProxy(function proxyCallback(opts) {
143
160
  }
144
161
  if (method === "ws") {
145
162
  const webSocketUrl = replaceUrlProtocol(
146
- opts.args[0] && opts.args[0].param ? replaceUrlParam(url, opts.args[0].param) : url,
163
+ opts.args[0]?.param ? replaceUrlParam(url, opts.args[0].param) : url,
147
164
  "ws"
148
165
  );
149
166
  const targetUrl = new URL(webSocketUrl);
150
167
  const queryParams = opts.args[0]?.query;
151
168
  if (queryParams) {
152
- Object.entries(queryParams).forEach(([key, value]) => {
153
- if (Array.isArray(value)) {
154
- value.forEach((item) => targetUrl.searchParams.append(key, item));
155
- } else {
156
- targetUrl.searchParams.set(key, value);
157
- }
169
+ const searchParams = buildSearchParamsOption(queryParams);
170
+ searchParams.forEach((value, key) => {
171
+ targetUrl.searchParams.append(key, value);
158
172
  });
159
173
  }
160
174
  const establishWebSocket = (...args) => {
@@ -21,6 +21,9 @@ var buildSearchParams = (query) => {
21
21
  }
22
22
  if (Array.isArray(v)) {
23
23
  for (const v2 of v) {
24
+ if (v2 === void 0) {
25
+ continue;
26
+ }
24
27
  searchParams.append(k, v2);
25
28
  }
26
29
  } else {
@@ -1,9 +1,43 @@
1
1
  // src/helper/accepts/accepts.ts
2
2
  import { parseAccept } from "../../utils/accept.js";
3
+ var matchType = (acceptType, supportedType) => {
4
+ if (acceptType === supportedType) {
5
+ return true;
6
+ }
7
+ if (acceptType === "*/*" || acceptType === "*") {
8
+ return false;
9
+ }
10
+ if (acceptType.endsWith("/*")) {
11
+ const [acceptMain] = acceptType.split("/");
12
+ const [supportedMain] = supportedType.split("/");
13
+ return acceptMain === supportedMain;
14
+ }
15
+ return false;
16
+ };
17
+ var getSpecificity = (type) => {
18
+ if (type === "*/*" || type === "*") {
19
+ return 1;
20
+ }
21
+ if (type.endsWith("/*")) {
22
+ return 2;
23
+ }
24
+ return 3;
25
+ };
3
26
  var defaultMatch = (accepts2, config) => {
4
27
  const { supports, default: defaultSupport } = config;
5
- const accept = accepts2.sort((a, b) => b.q - a.q).find((accept2) => supports.includes(accept2.type));
6
- return accept ? accept.type : defaultSupport;
28
+ const sortedAccepts = accepts2.slice().sort((a, b) => {
29
+ if (b.q !== a.q) {
30
+ return b.q - a.q;
31
+ }
32
+ return getSpecificity(b.type) - getSpecificity(a.type);
33
+ });
34
+ for (const accept of sortedAccepts) {
35
+ const matched = supports.find((supported) => matchType(accept.type, supported));
36
+ if (matched) {
37
+ return matched;
38
+ }
39
+ }
40
+ return defaultSupport;
7
41
  };
8
42
  var accepts = (c, options) => {
9
43
  const acceptHeader = c.req.header(options.header);
@@ -184,7 +184,7 @@ var saveContentToFile = async (data, fsModule, outDir, extensionMap) => {
184
184
  const { routePath, content, mimeType } = awaitedData;
185
185
  const filePath = generateFilePath(routePath, outDir, mimeType, extensionMap);
186
186
  const dirPath = dirname(filePath);
187
- if (!createdDirs.has(dirPath)) {
187
+ if (dirPath !== "" && !createdDirs.has(dirPath)) {
188
188
  await fsModule.mkdir(dirPath, { recursive: true });
189
189
  createdDirs.add(dirPath);
190
190
  }
@@ -8,8 +8,14 @@ var dirname = (path) => {
8
8
  var normalizePath = (path) => {
9
9
  return path.replace(/(\\)/g, "/").replace(/\/$/g, "");
10
10
  };
11
- var handleParent = (resultPaths, beforeParentFlag) => {
12
- if (resultPaths.length === 0 || beforeParentFlag) {
11
+ var getUncRoot = (path) => {
12
+ const uncRoot = path.replace(/\\/g, "/").match(/^\/\/([^/]+)\/([^/]+)/);
13
+ if (uncRoot) {
14
+ return `${uncRoot[1].toLowerCase()}/${uncRoot[2].toLowerCase()}`;
15
+ }
16
+ };
17
+ var handleParent = (resultPaths) => {
18
+ if (resultPaths.length === 0 || resultPaths[resultPaths.length - 1] === "..") {
13
19
  resultPaths.push("..");
14
20
  } else {
15
21
  resultPaths.pop();
@@ -22,22 +28,20 @@ var handleNonDot = (path, resultPaths) => {
22
28
  }
23
29
  };
24
30
  var handleSegments = (paths, resultPaths) => {
25
- let beforeParentFlag = false;
26
31
  for (const path of paths) {
27
32
  if (path === "..") {
28
- handleParent(resultPaths, beforeParentFlag);
29
- beforeParentFlag = true;
33
+ handleParent(resultPaths);
30
34
  } else {
31
35
  handleNonDot(path, resultPaths);
32
- beforeParentFlag = false;
33
36
  }
34
37
  }
35
38
  };
36
39
  var joinPaths = (...paths) => {
40
+ const hasUncPrefix = getUncRoot(paths[0]) !== void 0;
37
41
  paths = paths.map(normalizePath);
38
42
  const resultPaths = [];
39
43
  handleSegments(paths.join("/").split("/"), resultPaths);
40
- return (paths[0][0] === "/" ? "/" : "") + resultPaths.join("/");
44
+ return (hasUncPrefix ? "//" : paths[0][0] === "/" ? "/" : "") + resultPaths.join("/");
41
45
  };
42
46
  var filterStaticGenerateRoutes = (hono) => {
43
47
  return hono.routes.reduce((acc, { method, handler, path }) => {
@@ -51,10 +55,26 @@ var filterStaticGenerateRoutes = (hono) => {
51
55
  var isDynamicRoute = (path) => {
52
56
  return path.split("/").some((segment) => segment.startsWith(":") || segment.includes("*"));
53
57
  };
58
+ var toSegments = (path) => path === "" ? [] : path.split("/");
59
+ var getPathRoot = (path) => {
60
+ const normalizedPath = path.replace(/\\/g, "/");
61
+ const uncRoot = getUncRoot(normalizedPath);
62
+ if (uncRoot) {
63
+ return `unc:${uncRoot}`;
64
+ }
65
+ const driveRoot = normalizedPath.match(/^([A-Za-z]):/);
66
+ if (driveRoot) {
67
+ const kind = normalizedPath[2] === "/" ? "drive-absolute" : "drive-relative";
68
+ return `${kind}:${driveRoot[1].toLowerCase()}`;
69
+ }
70
+ return normalizedPath.startsWith("/") ? "absolute" : "relative";
71
+ };
54
72
  var ensureWithinOutDir = (outDir, filePath) => {
55
- const normalizedOutDir = joinPaths("/", outDir);
56
- const normalizedFilePath = joinPaths("/", filePath);
57
- if (normalizedFilePath !== normalizedOutDir && !normalizedFilePath.startsWith(`${normalizedOutDir}/`)) {
73
+ const outDirSegments = toSegments(joinPaths(outDir));
74
+ const filePathSegments = toSegments(joinPaths(filePath));
75
+ const hasMismatchedPathRoot = getPathRoot(outDir) !== getPathRoot(filePath);
76
+ const climbsAboveOutDir = filePathSegments[outDirSegments.length] === "..";
77
+ if (hasMismatchedPathRoot || filePathSegments.length <= outDirSegments.length || !outDirSegments.every((segment, i) => segment === filePathSegments[i]) || climbsAboveOutDir) {
58
78
  throw new Error(`Path traversal detected: "${filePath}" is outside the output directory`);
59
79
  }
60
80
  };
@@ -78,6 +78,7 @@ var applyProps = (container, attributes, oldAttributes) => {
78
78
  } else if (key === "dangerouslySetInnerHTML" && value) {
79
79
  container.innerHTML = value.__html;
80
80
  } else if (key === "ref") {
81
+ refCleanupMap.get(container)?.();
81
82
  let cleanup;
82
83
  if (typeof value === "function") {
83
84
  cleanup = value(container) || (() => value(null));
@@ -142,6 +143,7 @@ var applyProps = (container, attributes, oldAttributes) => {
142
143
  container.removeEventListener(eventSpec[0], value, eventSpec[1]);
143
144
  } else if (key === "ref") {
144
145
  refCleanupMap.get(container)?.();
146
+ refCleanupMap.delete(container);
145
147
  } else {
146
148
  try {
147
149
  container.removeAttribute(toAttributeName(container, key));
@@ -23,7 +23,7 @@ var parseVaryDirectives = (vary) => {
23
23
  };
24
24
  var createCacheKey = (key, requestUrl, request, varyHeaders) => {
25
25
  const url = new URL(cacheKeyPath, requestUrl);
26
- url.searchParams.append(cacheKeyParameter, key.split("#", 1)[0]);
26
+ url.searchParams.append(cacheKeyParameter, key);
27
27
  url.searchParams.append(cacheMethodKeyParameter, request.method);
28
28
  if (request.method === "QUERY") {
29
29
  url.searchParams.append(queryDigestKeyParameter, request.digest);
@@ -10,7 +10,7 @@ var RETAINED_304_HEADERS = [
10
10
  ];
11
11
  var stripWeak = (tag) => tag.replace(/^W\//, "");
12
12
  function etagMatches(etag2, ifNoneMatch) {
13
- return ifNoneMatch != null && ifNoneMatch.split(/,\s*/).some((t) => stripWeak(t) === stripWeak(etag2));
13
+ return ifNoneMatch != null && ifNoneMatch.split(",").some((t) => stripWeak(t.trim()) === stripWeak(etag2));
14
14
  }
15
15
  function initializeGenerator(generator) {
16
16
  if (!generator) {
package/dist/request.js CHANGED
@@ -46,13 +46,13 @@ var HonoRequest = class {
46
46
  return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
47
47
  }
48
48
  #getDecodedParam(key) {
49
- const paramKey = this.#matchResult[0][this.routeIndex][1][key];
49
+ const paramKey = this.#matchResult[0][this.routeIndex]?.[1][key];
50
50
  const param = this.#getParamValue(paramKey);
51
51
  return param && tryDecodeURIComponent(param);
52
52
  }
53
53
  #getAllDecodedParams() {
54
54
  const decoded = {};
55
- const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
55
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex]?.[1] ?? {});
56
56
  for (const key of keys) {
57
57
  const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
58
58
  if (value !== void 0) {
@@ -292,10 +292,14 @@ var cloneRawRequest = async (req) => {
292
292
  message: "Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly."
293
293
  });
294
294
  }
295
- const body = await req[cacheKey]();
295
+ let body = await req[cacheKey]();
296
296
  const headers = req.header();
297
- if (body instanceof FormData) {
297
+ if (cacheKey === "json") {
298
+ body = JSON.stringify(body);
299
+ delete headers["content-length"];
300
+ } else if (body instanceof FormData) {
298
301
  delete headers["content-type"];
302
+ delete headers["content-length"];
299
303
  }
300
304
  const requestInit = {
301
305
  body,
@@ -1,4 +1,5 @@
1
1
  // src/router/reg-exp-router/node.ts
2
+ import { createNullObject } from "../utils.js";
2
3
  var LABEL_REG_EXP_STR = "[^/]+";
3
4
  var ONLY_WILDCARD_REG_EXP_STR = ".*";
4
5
  var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
@@ -27,7 +28,7 @@ var Node = class _Node {
27
28
  // handler index of a dynamic path, or -1 for a static path terminal
28
29
  #index;
29
30
  #varIndex;
30
- #children = /* @__PURE__ */ Object.create(null);
31
+ #children = createNullObject();
31
32
  insert(tokens, index, paramMap, context, isStatic) {
32
33
  let node = this;
33
34
  for (let i = 0, len = tokens.length; i < len; i++) {
@@ -105,6 +106,9 @@ var Node = class _Node {
105
106
  }
106
107
  };
107
108
  export {
109
+ LABEL_REG_EXP_STR,
108
110
  Node,
109
- PATH_ERROR
111
+ ONLY_WILDCARD_REG_EXP_STR,
112
+ PATH_ERROR,
113
+ TAIL_WILDCARD_REG_EXP_STR
110
114
  };
@@ -5,25 +5,25 @@ import {
5
5
  UnsupportedPathError
6
6
  } from "../../router.js";
7
7
  import { checkOptionalParameter } from "../../utils/url.js";
8
+ import { createNullObject } from "../utils.js";
8
9
  import { match, emptyParam } from "./matcher.js";
9
- import { PATH_ERROR } from "./node.js";
10
+ import {
11
+ LABEL_REG_EXP_STR,
12
+ ONLY_WILDCARD_REG_EXP_STR,
13
+ PATH_ERROR,
14
+ TAIL_WILDCARD_REG_EXP_STR
15
+ } from "./node.js";
10
16
  import { Trie } from "./trie.js";
11
- var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
17
+ var wildcardRegExpCache = createNullObject();
12
18
  function buildWildcardRegExp(path) {
13
19
  return wildcardRegExpCache[path] ??= new RegExp(
14
- path === "*" ? "" : `^${path.replace(
15
- /\/\*$|([.\\+*[^\]$()])/g,
16
- (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
20
+ `^${path.replace(
21
+ /\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,
22
+ (match2, metaChar) => metaChar ? `\\${metaChar}` : match2 === "/*" ? TAIL_WILDCARD_REG_EXP_STR : match2 === "*" ? ONLY_WILDCARD_REG_EXP_STR : `/:${LABEL_REG_EXP_STR}`
17
23
  )}$`
18
24
  );
19
25
  }
20
- function clearWildcardRegExpCache() {
21
- wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
22
- }
23
26
  function findMiddleware(middleware, path) {
24
- if (!middleware) {
25
- return void 0;
26
- }
27
27
  for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
28
28
  if (buildWildcardRegExp(k).test(path)) {
29
29
  return [...middleware[k]];
@@ -37,8 +37,8 @@ var RegExpRouter = class {
37
37
  #routes;
38
38
  #tries;
39
39
  constructor() {
40
- this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
41
- this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
40
+ this.#middleware = { [METHOD_NAME_ALL]: createNullObject() };
41
+ this.#routes = { [METHOD_NAME_ALL]: createNullObject() };
42
42
  this.#tries = { [METHOD_NAME_ALL]: new Trie() };
43
43
  }
44
44
  #insertPath(method, path) {
@@ -51,117 +51,86 @@ var RegExpRouter = class {
51
51
  add(method, path, handler) {
52
52
  const middleware = this.#middleware;
53
53
  const routes = this.#routes;
54
- if (!middleware || !routes) {
54
+ if (!middleware) {
55
55
  throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
56
56
  }
57
57
  if (!middleware[method]) {
58
58
  this.#tries[method] = new Trie();
59
- [middleware, routes].forEach((handlerMap) => {
60
- handlerMap[method] = /* @__PURE__ */ Object.create(null);
61
- Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
59
+ for (const handlerMap of [middleware, routes]) {
60
+ handlerMap[method] = createNullObject();
61
+ for (const p in handlerMap[METHOD_NAME_ALL]) {
62
62
  handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
63
63
  this.#insertPath(method, p);
64
- });
65
- });
64
+ }
65
+ }
66
66
  }
67
67
  if (path === "/*") {
68
68
  path = "*";
69
69
  }
70
- const paramCount = (path.match(/\/:/g) || []).length;
70
+ const methods = method === METHOD_NAME_ALL ? Object.keys(middleware) : [method];
71
71
  if (/\*$/.test(path)) {
72
72
  const re = buildWildcardRegExp(path);
73
- Object.keys(middleware).forEach((m) => {
74
- if ((method === METHOD_NAME_ALL || method === m) && !middleware[m][path]) {
73
+ for (const m of methods) {
74
+ if (!middleware[m][path]) {
75
75
  this.#insertPath(m, path);
76
76
  middleware[m][path] = findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
77
77
  }
78
- });
79
- Object.keys(middleware).forEach((m) => {
80
- if (method === METHOD_NAME_ALL || method === m) {
81
- Object.keys(middleware[m]).forEach((p) => {
82
- re.test(p) && middleware[m][p].push([handler, paramCount]);
83
- });
84
- }
85
- });
86
- Object.keys(routes).forEach((m) => {
87
- if (method === METHOD_NAME_ALL || method === m) {
88
- Object.keys(routes[m]).forEach(
89
- (p) => re.test(p) && routes[m][p].push([handler, paramCount])
90
- );
78
+ }
79
+ for (const handlerMap of [middleware, routes]) {
80
+ for (const m of methods) {
81
+ for (const p in handlerMap[m]) {
82
+ re.test(p) && handlerMap[m][p].push([handler, path]);
83
+ }
91
84
  }
92
- });
85
+ }
93
86
  return;
94
87
  }
95
88
  const paths = checkOptionalParameter(path) || [path];
96
- for (let i = 0, len = paths.length; i < len; i++) {
97
- const path2 = paths[i];
98
- Object.keys(routes).forEach((m) => {
99
- if (method === METHOD_NAME_ALL || method === m) {
100
- if (!routes[m][path2]) {
101
- this.#insertPath(m, path2);
102
- routes[m][path2] = [
103
- ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
104
- ];
105
- }
106
- routes[m][path2].push([handler, paramCount - len + i + 1]);
89
+ for (const path2 of paths) {
90
+ for (const m of methods) {
91
+ if (!routes[m][path2]) {
92
+ this.#insertPath(m, path2);
93
+ routes[m][path2] = findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || [];
107
94
  }
108
- });
95
+ routes[m][path2].push([handler, path2]);
96
+ }
109
97
  }
110
98
  }
111
99
  match = match;
112
100
  buildAllMatchers() {
113
- const matchers = /* @__PURE__ */ Object.create(null);
114
- Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
115
- matchers[method] ||= this.#buildMatcher(method);
116
- });
101
+ const matchers = createNullObject();
102
+ for (const method of Object.keys(this.#routes)) {
103
+ matchers[method] = this.#buildMatcher(method);
104
+ }
117
105
  this.#middleware = this.#routes = this.#tries = void 0;
118
- clearWildcardRegExpCache();
106
+ wildcardRegExpCache = createNullObject();
119
107
  return matchers;
120
108
  }
121
109
  #buildMatcher(method) {
122
110
  const middleware = this.#middleware[method];
123
111
  const routes = this.#routes[method];
124
112
  const trie = this.#tries[method];
125
- const staticMap = /* @__PURE__ */ Object.create(null);
113
+ const staticMap = createNullObject();
126
114
  const handlerData = [];
127
- [middleware, routes].forEach((r) => {
115
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
116
+ for (const r of [middleware, routes]) {
128
117
  for (const path in r) {
129
118
  const handlers = r[path];
130
119
  const pathData = trie.paths[path];
131
120
  if (!pathData) {
132
- staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
133
- continue;
134
- }
135
- const paramAssoc = pathData[1];
136
- handlerData[pathData[0]] = handlers.map(([h, paramCount]) => {
137
- const paramIndexMap = /* @__PURE__ */ Object.create(null);
138
- paramCount -= 1;
139
- for (; paramCount >= 0; paramCount--) {
140
- const [key, value] = paramAssoc[paramCount];
141
- paramIndexMap[key] = value;
142
- }
143
- return [h, paramIndexMap];
144
- });
145
- }
146
- });
147
- const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
148
- for (let i = 0, len = handlerData.length; i < len; i++) {
149
- for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
150
- const map = handlerData[i][j]?.[1];
151
- if (!map) {
121
+ staticMap[path] = [handlers.map(([h]) => [h, createNullObject()]), emptyParam];
152
122
  continue;
153
123
  }
154
- const keys = Object.keys(map);
155
- for (let k = 0, len3 = keys.length; k < len3; k++) {
156
- map[keys[k]] = paramReplacementMap[map[keys[k]]];
157
- }
124
+ handlerData[pathData[0]] = handlers.map(([h, handlerPath]) => [
125
+ h,
126
+ trie.paths[handlerPath][1].reduceRight((map, [key], i) => {
127
+ map[key] = paramReplacementMap[pathData[1][i][1]];
128
+ return map;
129
+ }, createNullObject())
130
+ ]);
158
131
  }
159
132
  }
160
- const handlerMap = [];
161
- for (const i in indexReplacementMap) {
162
- handlerMap[i] = handlerData[indexReplacementMap[i]];
163
- }
164
- return [regexp, handlerMap, staticMap];
133
+ return [regexp, indexReplacementMap.map((i) => handlerData[i]), staticMap];
165
134
  }
166
135
  };
167
136
  export {
@@ -1,11 +1,12 @@
1
1
  // src/router/reg-exp-router/trie.ts
2
+ import { createNullObject } from "../utils.js";
2
3
  import { Node } from "./node.js";
3
4
  var Trie = class {
4
5
  #context = { varIndex: 0 };
5
6
  #root = new Node();
6
7
  #index = 0;
7
8
  // dynamic path -> [handler index, param assoc]; static paths are not registered
8
- paths = /* @__PURE__ */ Object.create(null);
9
+ paths = createNullObject();
9
10
  insert(path, isStatic) {
10
11
  if (isStatic) {
11
12
  this.#root.insert(path.split(""), 0, [], this.#context, true);