hono 4.13.1 → 4.13.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/cjs/client/client.js +3 -3
  2. package/dist/cjs/client/utils.js +1 -1
  3. package/dist/cjs/context.js +4 -0
  4. package/dist/cjs/jsx/intrinsic-element/components.js +1 -1
  5. package/dist/cjs/middleware/cors/index.js +16 -13
  6. package/dist/cjs/middleware/csrf/index.js +1 -1
  7. package/dist/cjs/middleware/etag/digest.js +47 -1
  8. package/dist/cjs/middleware/etag/index.js +2 -2
  9. package/dist/cjs/middleware/pretty-json/index.js +3 -1
  10. package/dist/cjs/middleware/secure-headers/secure-headers.js +6 -3
  11. package/dist/cjs/router/linear-router/router.js +7 -2
  12. package/dist/cjs/router/pattern-router/router.js +3 -9
  13. package/dist/cjs/router/trie-router/node.js +43 -67
  14. package/dist/cjs/router/trie-router/router.js +3 -11
  15. package/dist/cjs/utils/ipaddr.js +5 -3
  16. package/dist/cjs/utils/url.js +2 -2
  17. package/dist/client/client.js +3 -3
  18. package/dist/client/utils.js +1 -1
  19. package/dist/context.js +4 -0
  20. package/dist/jsx/intrinsic-element/components.js +1 -1
  21. package/dist/middleware/cors/index.js +16 -13
  22. package/dist/middleware/csrf/index.js +1 -1
  23. package/dist/middleware/etag/digest.js +47 -1
  24. package/dist/middleware/etag/index.js +2 -2
  25. package/dist/middleware/pretty-json/index.js +3 -1
  26. package/dist/middleware/secure-headers/secure-headers.js +6 -3
  27. package/dist/router/linear-router/router.js +7 -2
  28. package/dist/router/pattern-router/router.js +3 -9
  29. package/dist/router/trie-router/node.js +43 -67
  30. package/dist/router/trie-router/router.js +3 -11
  31. package/dist/types/context.d.ts +4 -0
  32. package/dist/types/middleware/secure-headers/permissions-policy.d.ts +3 -3
  33. package/dist/types/router/trie-router/node.d.ts +1 -2
  34. package/dist/types/router/trie-router/router.d.ts +0 -1
  35. package/dist/utils/ipaddr.js +5 -3
  36. package/dist/utils/url.js +2 -2
  37. package/package.json +1 -1
@@ -74,7 +74,7 @@ class ClientRequestImpl {
74
74
  }
75
75
  this.rBody = form;
76
76
  }
77
- if (args.json) {
77
+ if (args.json !== void 0) {
78
78
  this.rBody = JSON.stringify(args.json);
79
79
  this.cType = "application/json";
80
80
  }
@@ -90,9 +90,9 @@ class ClientRequestImpl {
90
90
  if (args?.cookie) {
91
91
  const cookies = [];
92
92
  for (const [key, value] of Object.entries(args.cookie)) {
93
- cookies.push((0, import_cookie.serialize)(key, value, { path: "/" }));
93
+ cookies.push((0, import_cookie.serialize)(key, value));
94
94
  }
95
- headerValues["Cookie"] = cookies.join(",");
95
+ headerValues["Cookie"] = cookies.join("; ");
96
96
  }
97
97
  if (this.cType) {
98
98
  headerValues["Content-Type"] = this.cType;
@@ -37,7 +37,7 @@ const mergePath = (base, path) => {
37
37
  const replaceUrlParam = (urlString, params) => {
38
38
  for (const [k, v] of Object.entries(params)) {
39
39
  const reg = new RegExp("/:" + k + "(?:{[^/]+})?\\??(?=/|$)");
40
- urlString = urlString.replace(reg, v ? `/${v}` : "");
40
+ urlString = urlString.replace(reg, () => v ? `/${v}` : "");
41
41
  }
42
42
  return urlString;
43
43
  };
@@ -224,6 +224,10 @@ class Context {
224
224
  * c.header('X-Message', 'Hello!')
225
225
  * c.header('Content-Type', 'text/plain')
226
226
  *
227
+ * // Append multiple headers using the append option (e.g. Vary)
228
+ * c.header('Vary', 'Accept-Encoding', { append: true })
229
+ * c.header('Vary', 'User-Agent', { append: true })
230
+ *
227
231
  * return c.body('Thank you for coming')
228
232
  * })
229
233
  * ```
@@ -101,7 +101,7 @@ const documentMetadataTag = (tag, children, props, sort) => {
101
101
  const string = new import_base.JSXNode(tag, restProps, (0, import_children.toArray)(children || [])).toString();
102
102
  if (string instanceof Promise) {
103
103
  return string.then(
104
- (resString) => (0, import_html.raw)(string, [
104
+ (resString) => (0, import_html.raw)(resString, [
105
105
  ...resString.callbacks || [],
106
106
  insertIntoHead(tag, resString, restProps, precedence)
107
107
  ])
@@ -28,6 +28,8 @@ const cors = (options) => {
28
28
  exposeHeaders: [],
29
29
  ...options
30
30
  };
31
+ const exposeHeadersStr = opts.exposeHeaders?.length ? opts.exposeHeaders.join(",") : void 0;
32
+ const allowHeadersStr = opts.allowHeaders?.length ? opts.allowHeaders.join(",") : void 0;
31
33
  const findAllowOrigin = ((optsOrigin) => {
32
34
  if (typeof optsOrigin === "string") {
33
35
  if (optsOrigin === "*") {
@@ -43,11 +45,12 @@ const cors = (options) => {
43
45
  })(opts.origin);
44
46
  const findAllowMethods = ((optsAllowMethods) => {
45
47
  if (typeof optsAllowMethods === "function") {
46
- return optsAllowMethods;
48
+ return async (origin, c) => (await optsAllowMethods(origin, c)).join(",");
47
49
  } else if (Array.isArray(optsAllowMethods)) {
48
- return () => optsAllowMethods;
50
+ const methodsStr = optsAllowMethods.join(",");
51
+ return () => methodsStr;
49
52
  } else {
50
- return () => [];
53
+ return () => "";
51
54
  }
52
55
  })(opts.allowMethods);
53
56
  return async function cors2(c, next) {
@@ -61,29 +64,29 @@ const cors = (options) => {
61
64
  if (opts.credentials) {
62
65
  set("Access-Control-Allow-Credentials", "true");
63
66
  }
64
- if (opts.exposeHeaders?.length) {
65
- set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
67
+ if (exposeHeadersStr) {
68
+ set("Access-Control-Expose-Headers", exposeHeadersStr);
66
69
  }
67
70
  if (c.req.method === "OPTIONS") {
68
71
  if (opts.origin !== "*") {
69
- set("Vary", "Origin");
72
+ c.res.headers.append("Vary", "Origin");
70
73
  }
71
74
  if (opts.maxAge != null) {
72
75
  set("Access-Control-Max-Age", opts.maxAge.toString());
73
76
  }
74
77
  const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
75
- if (allowMethods.length) {
76
- set("Access-Control-Allow-Methods", allowMethods.join(","));
78
+ if (allowMethods) {
79
+ set("Access-Control-Allow-Methods", allowMethods);
77
80
  }
78
- let headers = opts.allowHeaders;
79
- if (!headers?.length) {
81
+ let headersStr = allowHeadersStr;
82
+ if (!headersStr) {
80
83
  const requestHeaders = c.req.header("Access-Control-Request-Headers");
81
84
  if (requestHeaders) {
82
- headers = requestHeaders.split(",").map((h) => h.trim());
85
+ headersStr = requestHeaders.split(",").map((h) => h.trim()).join(",");
83
86
  }
84
87
  }
85
- if (headers?.length) {
86
- set("Access-Control-Allow-Headers", headers.join(","));
88
+ if (headersStr) {
89
+ set("Access-Control-Allow-Headers", headersStr);
87
90
  c.res.headers.append("Vary", "Access-Control-Request-Headers");
88
91
  }
89
92
  c.res.headers.delete("Content-Length");
@@ -23,7 +23,7 @@ module.exports = __toCommonJS(csrf_exports);
23
23
  var import_http_exception = require("../../http-exception");
24
24
  const secFetchSiteValues = ["same-origin", "same-site", "none", "cross-site"];
25
25
  const isSecFetchSite = (value) => secFetchSiteValues.includes(value);
26
- const isSafeMethodRe = /^(GET|HEAD)$/;
26
+ const isSafeMethodRe = /^(GET|HEAD|OPTIONS)$/;
27
27
  const isRequestedByFormElementRe = /^\b(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)\b/i;
28
28
  const csrf = (options) => {
29
29
  const originHandler = ((optsOrigin) => {
@@ -31,18 +31,64 @@ const mergeBuffers = (buffer1, buffer2) => {
31
31
  merged.set(buffer2, buffer1.byteLength);
32
32
  return merged;
33
33
  };
34
+ const CHUNK_SIZE = 256 * 1024;
34
35
  const generateDigest = async (stream, generator) => {
35
36
  if (!stream) {
36
37
  return null;
37
38
  }
38
39
  let result = void 0;
40
+ let chunk;
41
+ let chunkLength = 0;
42
+ const digest = async (body) => {
43
+ result = await generator(mergeBuffers(result, body));
44
+ };
39
45
  const reader = stream.getReader();
40
46
  for (; ; ) {
41
47
  const { value, done } = await reader.read();
42
48
  if (done) {
43
49
  break;
44
50
  }
45
- result = await generator(mergeBuffers(result, value));
51
+ let offset = 0;
52
+ while (offset < value.byteLength) {
53
+ const remaining = value.byteLength - offset;
54
+ if (chunkLength === 0 && remaining >= CHUNK_SIZE) {
55
+ await digest(value.subarray(offset, offset + CHUNK_SIZE));
56
+ offset += CHUNK_SIZE;
57
+ continue;
58
+ }
59
+ const requiredLength = chunkLength + remaining;
60
+ if (requiredLength < CHUNK_SIZE) {
61
+ if (!chunk) {
62
+ chunk = value.slice(offset);
63
+ } else {
64
+ if (chunk.byteLength < requiredLength) {
65
+ const nextChunk = new Uint8Array(
66
+ new ArrayBuffer(Math.min(CHUNK_SIZE, Math.max(requiredLength, chunk.byteLength * 2)))
67
+ );
68
+ nextChunk.set(chunk.subarray(0, chunkLength));
69
+ chunk = nextChunk;
70
+ }
71
+ chunk.set(value.subarray(offset), chunkLength);
72
+ }
73
+ chunkLength = requiredLength;
74
+ break;
75
+ }
76
+ const length = CHUNK_SIZE - chunkLength;
77
+ if (chunk?.byteLength !== CHUNK_SIZE) {
78
+ const nextChunk = new Uint8Array(new ArrayBuffer(CHUNK_SIZE));
79
+ if (chunk) {
80
+ nextChunk.set(chunk.subarray(0, chunkLength));
81
+ }
82
+ chunk = nextChunk;
83
+ }
84
+ chunk.set(value.subarray(offset, offset + length), chunkLength);
85
+ await digest(chunk);
86
+ chunkLength = 0;
87
+ offset += length;
88
+ }
89
+ }
90
+ if (chunk && chunkLength > 0) {
91
+ await digest(chunk.subarray(0, chunkLength));
46
92
  }
47
93
  if (!result) {
48
94
  return null;
@@ -82,11 +82,11 @@ const etag = (options) => {
82
82
  ETag: etag3
83
83
  }
84
84
  });
85
- c.res.headers.forEach((_, key) => {
85
+ for (const key of Array.from(c.res.headers.keys())) {
86
86
  if (retainedHeaders.indexOf(key.toLowerCase()) === -1) {
87
87
  c.res.headers.delete(key);
88
88
  }
89
- });
89
+ }
90
90
  } else {
91
91
  c.res.headers.set("ETag", etag3);
92
92
  }
@@ -20,12 +20,14 @@ __export(pretty_json_exports, {
20
20
  prettyJSON: () => prettyJSON
21
21
  });
22
22
  module.exports = __toCommonJS(pretty_json_exports);
23
+ const jsonContentTypeRegex = /^application\/(?:[a-z0-9._-]+\+)?json(?=$|[;\s])/i;
23
24
  const prettyJSON = (options) => {
24
25
  const targetQuery = options?.query ?? "pretty";
25
26
  return async function prettyJSON2(c, next) {
26
27
  const pretty = options?.force || c.req.query(targetQuery) || c.req.query(targetQuery) === "";
27
28
  await next();
28
- if (pretty && c.res.headers.get("Content-Type")?.startsWith("application/json")) {
29
+ const contentType = c.res.headers.get("Content-Type");
30
+ if (pretty && contentType && jsonContentTypeRegex.test(contentType)) {
29
31
  const obj = await c.res.json();
30
32
  c.res = new Response(JSON.stringify(obj, null, options?.space ?? 2), c.res);
31
33
  }
@@ -159,14 +159,17 @@ function getPermissionsPolicyDirectives(policy) {
159
159
  return Object.entries(policy).map(([directive, value]) => {
160
160
  const kebabDirective = camelToKebab(directive);
161
161
  if (typeof value === "boolean") {
162
- return `${kebabDirective}=${value ? "*" : "none"}`;
162
+ return `${kebabDirective}=${value ? "*" : "()"}`;
163
163
  }
164
164
  if (Array.isArray(value)) {
165
165
  if (value.length === 0) {
166
166
  return `${kebabDirective}=()`;
167
167
  }
168
- if (value.length === 1 && (value[0] === "*" || value[0] === "none")) {
169
- return `${kebabDirective}=${value[0]}`;
168
+ if (value.length === 1 && value[0] === "*") {
169
+ return `${kebabDirective}=*`;
170
+ }
171
+ if (value.length === 1 && value[0] === "none") {
172
+ return `${kebabDirective}=()`;
170
173
  }
171
174
  const allowlist = value.map((item) => ["self", "src"].includes(item) ? item : `"${item}"`);
172
175
  return `${kebabDirective}=(${allowlist.join(" ")})`;
@@ -50,7 +50,8 @@ class LinearRouter {
50
50
  }
51
51
  } else if (hasStar && !hasLabel) {
52
52
  const endsWithStar = routePath.charCodeAt(routePath.length - 1) === 42;
53
- const parts = (endsWithStar ? routePath.slice(0, -2) : routePath).split(splitByStarRe);
53
+ const endsWithSlashStar = routePath.endsWith("/*");
54
+ const parts = (endsWithStar ? routePath.slice(0, endsWithSlashStar ? -2 : -1) : routePath).split(splitByStarRe);
54
55
  const lastIndex = parts.length - 1;
55
56
  for (let j = 0, pos = 0, len2 = parts.length; j < len2; j++) {
56
57
  const part = parts[j];
@@ -60,7 +61,11 @@ class LinearRouter {
60
61
  }
61
62
  pos += part.length;
62
63
  if (j === lastIndex) {
63
- if (!endsWithStar && pos !== path.length && !(pos === path.length - 1 && path.charCodeAt(pos) === 47)) {
64
+ if (endsWithSlashStar) {
65
+ if (pos !== path.length && path.charCodeAt(pos) !== 47) {
66
+ continue ROUTES_LOOP;
67
+ }
68
+ } else if (!endsWithStar && pos !== path.length && !(pos === path.length - 1 && path.charCodeAt(pos) === 47)) {
64
69
  continue ROUTES_LOOP;
65
70
  }
66
71
  } else {
@@ -26,10 +26,8 @@ class PatternRouter {
26
26
  name = "PatternRouter";
27
27
  #routes = [];
28
28
  add(method, path, handler) {
29
- const endsWithWildcard = path.at(-1) === "*";
30
- if (endsWithWildcard) {
31
- path = path.slice(0, -2);
32
- }
29
+ const suffix = path.endsWith("/*") ? "(?:$|/)" : path.endsWith("*") ? "" : "/?$";
30
+ path = path.replace(/\*$/, "");
33
31
  if (path.at(-1) === "?") {
34
32
  path = path.slice(0, -1);
35
33
  this.add(method, path.replace(/\/[^/]+$/, ""), handler);
@@ -41,11 +39,7 @@ class PatternRouter {
41
39
  }
42
40
  );
43
41
  try {
44
- this.#routes.push([
45
- new RegExp(`^${parts.join("")}${endsWithWildcard ? "" : "/?$"}`),
46
- method,
47
- handler
48
- ]);
42
+ this.#routes.push([new RegExp(`^${parts.join("")}${suffix}`), method, handler]);
49
43
  } catch {
50
44
  throw new import_router.UnsupportedPathError();
51
45
  }
@@ -23,76 +23,51 @@ module.exports = __toCommonJS(node_exports);
23
23
  var import_router = require("../../router");
24
24
  var import_url = require("../../utils/url");
25
25
  const emptyParams = /* @__PURE__ */ Object.create(null);
26
- const hasChildren = (children) => {
27
- for (const _ in children) {
28
- return true;
29
- }
30
- return false;
31
- };
26
+ let order = 0;
32
27
  class Node {
33
- #methods;
34
- #children;
35
- #patterns;
36
- #order = 0;
28
+ #methods = [];
29
+ #children = /* @__PURE__ */ Object.create(null);
30
+ #patterns = [];
31
+ #pattern;
37
32
  #params = emptyParams;
38
- constructor(method, handler, children) {
39
- this.#children = children || /* @__PURE__ */ Object.create(null);
40
- this.#methods = [];
41
- if (method && handler) {
42
- const m = /* @__PURE__ */ Object.create(null);
43
- m[method] = { handler, possibleKeys: [], score: 0 };
44
- this.#methods = [m];
45
- }
46
- this.#patterns = [];
47
- }
48
33
  insert(method, path, handler) {
49
- this.#order = ++this.#order;
50
34
  let curNode = this;
51
35
  const parts = (0, import_url.splitRoutingPath)(path);
52
- const possibleKeys = [];
53
- for (let i = 0, len = parts.length; i < len; i++) {
54
- const p = parts[i];
55
- const nextP = parts[i + 1];
56
- const pattern = (0, import_url.getPattern)(p, nextP);
57
- const key = Array.isArray(pattern) ? pattern[0] : p;
58
- if (key in curNode.#children) {
59
- curNode = curNode.#children[key];
60
- if (pattern) {
61
- possibleKeys.push(pattern[1]);
62
- }
63
- continue;
36
+ const possibleKeys = /* @__PURE__ */ new Set();
37
+ let i = 0;
38
+ for (const p of parts) {
39
+ const nextP = parts[++i];
40
+ const pattern = (0, import_url.getPattern)(p, nextP) || (nextP === void 0 && p && p.indexOf("*") === p.length - 1 ? p : null);
41
+ const isParam = Array.isArray(pattern);
42
+ const key = isParam ? pattern[0] : pattern || p;
43
+ const child = curNode.#children[key] ||= new Node();
44
+ if (pattern && !child.#pattern) {
45
+ child.#pattern = pattern;
46
+ curNode.#patterns.push(child);
64
47
  }
65
- curNode.#children[key] = new Node();
66
- if (pattern) {
67
- curNode.#patterns.push(pattern);
68
- possibleKeys.push(pattern[1]);
48
+ curNode = child;
49
+ if (isParam) {
50
+ possibleKeys.add(pattern[1]);
69
51
  }
70
- curNode = curNode.#children[key];
71
52
  }
72
53
  curNode.#methods.push({
73
54
  [method]: {
74
55
  handler,
75
- possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
76
- score: this.#order
56
+ possibleKeys: [...possibleKeys],
57
+ score: ++order
77
58
  }
78
59
  });
79
- return curNode;
80
60
  }
81
61
  #pushHandlerSets(handlerSets, node, method, nodeParams, params) {
82
62
  for (let i = 0, len = node.#methods.length; i < len; i++) {
83
63
  const m = node.#methods[i];
84
64
  const handlerSet = m[method] || m[import_router.METHOD_NAME_ALL];
85
- const processedSet = {};
86
- if (handlerSet !== void 0) {
65
+ if (handlerSet) {
87
66
  handlerSet.params = /* @__PURE__ */ Object.create(null);
88
67
  handlerSets.push(handlerSet);
89
- if (nodeParams !== emptyParams || params && params !== emptyParams) {
90
- for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
91
- const key = handlerSet.possibleKeys[i2];
92
- const processed = processedSet[handlerSet.score];
93
- handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
94
- processedSet[handlerSet.score] = true;
95
- }
68
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
69
+ const key = handlerSet.possibleKeys[i2];
70
+ handlerSet.params[key] = params?.[key] && !i2 ? params[key] : nodeParams[key] ?? params?.[key];
96
71
  }
97
72
  }
98
73
  }
@@ -124,33 +99,33 @@ class Node {
124
99
  tempNodes.push(nextNode);
125
100
  }
126
101
  }
127
- for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
128
- const pattern = node.#patterns[k];
102
+ for (const child of node.#patterns) {
103
+ const pattern = child.#pattern;
129
104
  const params = node.#params === emptyParams ? {} : { ...node.#params };
130
- if (pattern === "*") {
131
- const astNode = node.#children["*"];
132
- if (astNode) {
133
- this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
134
- astNode.#params = params;
135
- tempNodes.push(astNode);
105
+ if (typeof pattern === "string") {
106
+ if (pattern === "*" || part.startsWith(pattern.slice(0, -1))) {
107
+ this.#pushHandlerSets(handlerSets, child, method, node.#params);
108
+ if (pattern === "*") {
109
+ child.#params = params;
110
+ tempNodes.push(child);
111
+ }
136
112
  }
137
113
  continue;
138
114
  }
139
- const [key, name, matcher] = pattern;
140
- if (!part && !(matcher instanceof RegExp)) {
115
+ const [, name, matcher] = pattern;
116
+ if (!part && matcher === true) {
141
117
  continue;
142
118
  }
143
- const child = node.#children[key];
144
- if (matcher instanceof RegExp) {
145
- if (partOffsets === null) {
146
- partOffsets = new Array(len);
119
+ if (matcher !== true) {
120
+ if (!partOffsets) {
121
+ partOffsets = [];
147
122
  let offset = path[0] === "/" ? 1 : 0;
148
123
  for (let p = 0; p < len; p++) {
149
124
  partOffsets[p] = offset;
150
125
  offset += parts[p].length + 1;
151
126
  }
152
127
  }
153
- const restPathString = path.substring(partOffsets[i]);
128
+ const restPathString = path.slice(partOffsets[i]);
154
129
  const m = matcher.exec(restPathString);
155
130
  if (m) {
156
131
  params[name] = m[0];
@@ -164,11 +139,12 @@ class Node {
164
139
  params
165
140
  );
166
141
  }
167
- if (hasChildren(child.#children)) {
142
+ for (const _ in child.#children) {
168
143
  child.#params = params;
169
144
  const componentCount = m[0].match(/\//g)?.length ?? 0;
170
145
  const targetCurNodes = curNodesQueue[componentCount] ||= [];
171
146
  targetCurNodes.push(child);
147
+ break;
172
148
  }
173
149
  continue;
174
150
  }
@@ -196,7 +172,7 @@ class Node {
196
172
  const shifted = curNodesQueue.shift();
197
173
  curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
198
174
  }
199
- if (handlerSets.length > 1) {
175
+ if (handlerSets[1]) {
200
176
  handlerSets.sort((a, b) => {
201
177
  return a.score - b.score;
202
178
  });
@@ -24,19 +24,11 @@ var import_url = require("../../utils/url");
24
24
  var import_node = require("./node");
25
25
  class TrieRouter {
26
26
  name = "TrieRouter";
27
- #node;
28
- constructor() {
29
- this.#node = new import_node.Node();
30
- }
27
+ #node = new import_node.Node();
31
28
  add(method, path, handler) {
32
- const results = (0, import_url.checkOptionalParameter)(path);
33
- if (results) {
34
- for (let i = 0, len = results.length; i < len; i++) {
35
- this.#node.insert(method, results[i], handler);
36
- }
37
- return;
29
+ for (const result of (0, import_url.checkOptionalParameter)(path) || [path]) {
30
+ this.#node.insert(method, result, handler);
38
31
  }
39
- this.#node.insert(method, path, handler);
40
32
  }
41
33
  match(method, path) {
42
34
  return this.#node.search(method, path);
@@ -30,12 +30,14 @@ __export(ipaddr_exports, {
30
30
  module.exports = __toCommonJS(ipaddr_exports);
31
31
  const expandIPv6 = (ipV6) => {
32
32
  const sections = ipV6.split(":");
33
- if (IPV4_REGEX.test(sections.at(-1))) {
33
+ const lastSection = sections.at(-1);
34
+ if (IPV4_REGEX.test(lastSection)) {
35
+ const octets = lastSection.split(".").map(Number);
34
36
  sections.splice(
35
37
  -1,
36
38
  1,
37
- ...convertIPv6BinaryToString(convertIPv4ToBinary(sections.at(-1))).substring(2).split(":")
38
- // => ['7f00', '0001']
39
+ (octets[0] << 8 | octets[1]).toString(16),
40
+ (octets[2] << 8 | octets[3]).toString(16)
39
41
  );
40
42
  }
41
43
  for (let i = 0; i < sections.length; i++) {
@@ -142,13 +142,13 @@ const checkOptionalParameter = (path) => {
142
142
  if (segment !== "" && !/\:/.test(segment)) {
143
143
  basePath += "/" + segment;
144
144
  } else if (/\:/.test(segment)) {
145
- if (/\?/.test(segment)) {
145
+ if (segment.charCodeAt(segment.length - 1) === 63) {
146
146
  if (results.length === 0 && basePath === "") {
147
147
  results.push("/");
148
148
  } else {
149
149
  results.push(basePath);
150
150
  }
151
- const optionalSegment = segment.replace("?", "");
151
+ const optionalSegment = segment.slice(0, -1);
152
152
  basePath += "/" + optionalSegment;
153
153
  results.push(basePath);
154
154
  } else {
@@ -60,7 +60,7 @@ var ClientRequestImpl = class {
60
60
  }
61
61
  this.rBody = form;
62
62
  }
63
- if (args.json) {
63
+ if (args.json !== void 0) {
64
64
  this.rBody = JSON.stringify(args.json);
65
65
  this.cType = "application/json";
66
66
  }
@@ -76,9 +76,9 @@ var ClientRequestImpl = class {
76
76
  if (args?.cookie) {
77
77
  const cookies = [];
78
78
  for (const [key, value] of Object.entries(args.cookie)) {
79
- cookies.push(serialize(key, value, { path: "/" }));
79
+ cookies.push(serialize(key, value));
80
80
  }
81
- headerValues["Cookie"] = cookies.join(",");
81
+ headerValues["Cookie"] = cookies.join("; ");
82
82
  }
83
83
  if (this.cType) {
84
84
  headerValues["Content-Type"] = this.cType;
@@ -9,7 +9,7 @@ var mergePath = (base, path) => {
9
9
  var replaceUrlParam = (urlString, params) => {
10
10
  for (const [k, v] of Object.entries(params)) {
11
11
  const reg = new RegExp("/:" + k + "(?:{[^/]+})?\\??(?=/|$)");
12
- urlString = urlString.replace(reg, v ? `/${v}` : "");
12
+ urlString = urlString.replace(reg, () => v ? `/${v}` : "");
13
13
  }
14
14
  return urlString;
15
15
  };
package/dist/context.js CHANGED
@@ -202,6 +202,10 @@ var Context = class {
202
202
  * c.header('X-Message', 'Hello!')
203
203
  * c.header('Content-Type', 'text/plain')
204
204
  *
205
+ * // Append multiple headers using the append option (e.g. Vary)
206
+ * c.header('Vary', 'Accept-Encoding', { append: true })
207
+ * c.header('Vary', 'User-Agent', { append: true })
208
+ *
205
209
  * return c.body('Thank you for coming')
206
210
  * })
207
211
  * ```
@@ -78,7 +78,7 @@ var documentMetadataTag = (tag, children, props, sort) => {
78
78
  const string = new JSXNode(tag, restProps, toArray(children || [])).toString();
79
79
  if (string instanceof Promise) {
80
80
  return string.then(
81
- (resString) => raw(string, [
81
+ (resString) => raw(resString, [
82
82
  ...resString.callbacks || [],
83
83
  insertIntoHead(tag, resString, restProps, precedence)
84
84
  ])
@@ -7,6 +7,8 @@ var cors = (options) => {
7
7
  exposeHeaders: [],
8
8
  ...options
9
9
  };
10
+ const exposeHeadersStr = opts.exposeHeaders?.length ? opts.exposeHeaders.join(",") : void 0;
11
+ const allowHeadersStr = opts.allowHeaders?.length ? opts.allowHeaders.join(",") : void 0;
10
12
  const findAllowOrigin = ((optsOrigin) => {
11
13
  if (typeof optsOrigin === "string") {
12
14
  if (optsOrigin === "*") {
@@ -22,11 +24,12 @@ var cors = (options) => {
22
24
  })(opts.origin);
23
25
  const findAllowMethods = ((optsAllowMethods) => {
24
26
  if (typeof optsAllowMethods === "function") {
25
- return optsAllowMethods;
27
+ return async (origin, c) => (await optsAllowMethods(origin, c)).join(",");
26
28
  } else if (Array.isArray(optsAllowMethods)) {
27
- return () => optsAllowMethods;
29
+ const methodsStr = optsAllowMethods.join(",");
30
+ return () => methodsStr;
28
31
  } else {
29
- return () => [];
32
+ return () => "";
30
33
  }
31
34
  })(opts.allowMethods);
32
35
  return async function cors2(c, next) {
@@ -40,29 +43,29 @@ var cors = (options) => {
40
43
  if (opts.credentials) {
41
44
  set("Access-Control-Allow-Credentials", "true");
42
45
  }
43
- if (opts.exposeHeaders?.length) {
44
- set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
46
+ if (exposeHeadersStr) {
47
+ set("Access-Control-Expose-Headers", exposeHeadersStr);
45
48
  }
46
49
  if (c.req.method === "OPTIONS") {
47
50
  if (opts.origin !== "*") {
48
- set("Vary", "Origin");
51
+ c.res.headers.append("Vary", "Origin");
49
52
  }
50
53
  if (opts.maxAge != null) {
51
54
  set("Access-Control-Max-Age", opts.maxAge.toString());
52
55
  }
53
56
  const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
54
- if (allowMethods.length) {
55
- set("Access-Control-Allow-Methods", allowMethods.join(","));
57
+ if (allowMethods) {
58
+ set("Access-Control-Allow-Methods", allowMethods);
56
59
  }
57
- let headers = opts.allowHeaders;
58
- if (!headers?.length) {
60
+ let headersStr = allowHeadersStr;
61
+ if (!headersStr) {
59
62
  const requestHeaders = c.req.header("Access-Control-Request-Headers");
60
63
  if (requestHeaders) {
61
- headers = requestHeaders.split(",").map((h) => h.trim());
64
+ headersStr = requestHeaders.split(",").map((h) => h.trim()).join(",");
62
65
  }
63
66
  }
64
- if (headers?.length) {
65
- set("Access-Control-Allow-Headers", headers.join(","));
67
+ if (headersStr) {
68
+ set("Access-Control-Allow-Headers", headersStr);
66
69
  c.res.headers.append("Vary", "Access-Control-Request-Headers");
67
70
  }
68
71
  c.res.headers.delete("Content-Length");
@@ -2,7 +2,7 @@
2
2
  import { HTTPException } from "../../http-exception.js";
3
3
  var secFetchSiteValues = ["same-origin", "same-site", "none", "cross-site"];
4
4
  var isSecFetchSite = (value) => secFetchSiteValues.includes(value);
5
- var isSafeMethodRe = /^(GET|HEAD)$/;
5
+ var isSafeMethodRe = /^(GET|HEAD|OPTIONS)$/;
6
6
  var isRequestedByFormElementRe = /^\b(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)\b/i;
7
7
  var csrf = (options) => {
8
8
  const originHandler = ((optsOrigin) => {
@@ -10,18 +10,64 @@ var mergeBuffers = (buffer1, buffer2) => {
10
10
  merged.set(buffer2, buffer1.byteLength);
11
11
  return merged;
12
12
  };
13
+ var CHUNK_SIZE = 256 * 1024;
13
14
  var generateDigest = async (stream, generator) => {
14
15
  if (!stream) {
15
16
  return null;
16
17
  }
17
18
  let result = void 0;
19
+ let chunk;
20
+ let chunkLength = 0;
21
+ const digest = async (body) => {
22
+ result = await generator(mergeBuffers(result, body));
23
+ };
18
24
  const reader = stream.getReader();
19
25
  for (; ; ) {
20
26
  const { value, done } = await reader.read();
21
27
  if (done) {
22
28
  break;
23
29
  }
24
- result = await generator(mergeBuffers(result, value));
30
+ let offset = 0;
31
+ while (offset < value.byteLength) {
32
+ const remaining = value.byteLength - offset;
33
+ if (chunkLength === 0 && remaining >= CHUNK_SIZE) {
34
+ await digest(value.subarray(offset, offset + CHUNK_SIZE));
35
+ offset += CHUNK_SIZE;
36
+ continue;
37
+ }
38
+ const requiredLength = chunkLength + remaining;
39
+ if (requiredLength < CHUNK_SIZE) {
40
+ if (!chunk) {
41
+ chunk = value.slice(offset);
42
+ } else {
43
+ if (chunk.byteLength < requiredLength) {
44
+ const nextChunk = new Uint8Array(
45
+ new ArrayBuffer(Math.min(CHUNK_SIZE, Math.max(requiredLength, chunk.byteLength * 2)))
46
+ );
47
+ nextChunk.set(chunk.subarray(0, chunkLength));
48
+ chunk = nextChunk;
49
+ }
50
+ chunk.set(value.subarray(offset), chunkLength);
51
+ }
52
+ chunkLength = requiredLength;
53
+ break;
54
+ }
55
+ const length = CHUNK_SIZE - chunkLength;
56
+ if (chunk?.byteLength !== CHUNK_SIZE) {
57
+ const nextChunk = new Uint8Array(new ArrayBuffer(CHUNK_SIZE));
58
+ if (chunk) {
59
+ nextChunk.set(chunk.subarray(0, chunkLength));
60
+ }
61
+ chunk = nextChunk;
62
+ }
63
+ chunk.set(value.subarray(offset, offset + length), chunkLength);
64
+ await digest(chunk);
65
+ chunkLength = 0;
66
+ offset += length;
67
+ }
68
+ }
69
+ if (chunk && chunkLength > 0) {
70
+ await digest(chunk.subarray(0, chunkLength));
25
71
  }
26
72
  if (!result) {
27
73
  return null;
@@ -60,11 +60,11 @@ var etag = (options) => {
60
60
  ETag: etag3
61
61
  }
62
62
  });
63
- c.res.headers.forEach((_, key) => {
63
+ for (const key of Array.from(c.res.headers.keys())) {
64
64
  if (retainedHeaders.indexOf(key.toLowerCase()) === -1) {
65
65
  c.res.headers.delete(key);
66
66
  }
67
- });
67
+ }
68
68
  } else {
69
69
  c.res.headers.set("ETag", etag3);
70
70
  }
@@ -1,10 +1,12 @@
1
1
  // src/middleware/pretty-json/index.ts
2
+ var jsonContentTypeRegex = /^application\/(?:[a-z0-9._-]+\+)?json(?=$|[;\s])/i;
2
3
  var prettyJSON = (options) => {
3
4
  const targetQuery = options?.query ?? "pretty";
4
5
  return async function prettyJSON2(c, next) {
5
6
  const pretty = options?.force || c.req.query(targetQuery) || c.req.query(targetQuery) === "";
6
7
  await next();
7
- if (pretty && c.res.headers.get("Content-Type")?.startsWith("application/json")) {
8
+ const contentType = c.res.headers.get("Content-Type");
9
+ if (pretty && contentType && jsonContentTypeRegex.test(contentType)) {
8
10
  const obj = await c.res.json();
9
11
  c.res = new Response(JSON.stringify(obj, null, options?.space ?? 2), c.res);
10
12
  }
@@ -137,14 +137,17 @@ function getPermissionsPolicyDirectives(policy) {
137
137
  return Object.entries(policy).map(([directive, value]) => {
138
138
  const kebabDirective = camelToKebab(directive);
139
139
  if (typeof value === "boolean") {
140
- return `${kebabDirective}=${value ? "*" : "none"}`;
140
+ return `${kebabDirective}=${value ? "*" : "()"}`;
141
141
  }
142
142
  if (Array.isArray(value)) {
143
143
  if (value.length === 0) {
144
144
  return `${kebabDirective}=()`;
145
145
  }
146
- if (value.length === 1 && (value[0] === "*" || value[0] === "none")) {
147
- return `${kebabDirective}=${value[0]}`;
146
+ if (value.length === 1 && value[0] === "*") {
147
+ return `${kebabDirective}=*`;
148
+ }
149
+ if (value.length === 1 && value[0] === "none") {
150
+ return `${kebabDirective}=()`;
148
151
  }
149
152
  const allowlist = value.map((item) => ["self", "src"].includes(item) ? item : `"${item}"`);
150
153
  return `${kebabDirective}=(${allowlist.join(" ")})`;
@@ -29,7 +29,8 @@ var LinearRouter = class {
29
29
  }
30
30
  } else if (hasStar && !hasLabel) {
31
31
  const endsWithStar = routePath.charCodeAt(routePath.length - 1) === 42;
32
- const parts = (endsWithStar ? routePath.slice(0, -2) : routePath).split(splitByStarRe);
32
+ const endsWithSlashStar = routePath.endsWith("/*");
33
+ const parts = (endsWithStar ? routePath.slice(0, endsWithSlashStar ? -2 : -1) : routePath).split(splitByStarRe);
33
34
  const lastIndex = parts.length - 1;
34
35
  for (let j = 0, pos = 0, len2 = parts.length; j < len2; j++) {
35
36
  const part = parts[j];
@@ -39,7 +40,11 @@ var LinearRouter = class {
39
40
  }
40
41
  pos += part.length;
41
42
  if (j === lastIndex) {
42
- if (!endsWithStar && pos !== path.length && !(pos === path.length - 1 && path.charCodeAt(pos) === 47)) {
43
+ if (endsWithSlashStar) {
44
+ if (pos !== path.length && path.charCodeAt(pos) !== 47) {
45
+ continue ROUTES_LOOP;
46
+ }
47
+ } else if (!endsWithStar && pos !== path.length && !(pos === path.length - 1 && path.charCodeAt(pos) === 47)) {
43
48
  continue ROUTES_LOOP;
44
49
  }
45
50
  } else {
@@ -5,10 +5,8 @@ var PatternRouter = class {
5
5
  name = "PatternRouter";
6
6
  #routes = [];
7
7
  add(method, path, handler) {
8
- const endsWithWildcard = path.at(-1) === "*";
9
- if (endsWithWildcard) {
10
- path = path.slice(0, -2);
11
- }
8
+ const suffix = path.endsWith("/*") ? "(?:$|/)" : path.endsWith("*") ? "" : "/?$";
9
+ path = path.replace(/\*$/, "");
12
10
  if (path.at(-1) === "?") {
13
11
  path = path.slice(0, -1);
14
12
  this.add(method, path.replace(/\/[^/]+$/, ""), handler);
@@ -20,11 +18,7 @@ var PatternRouter = class {
20
18
  }
21
19
  );
22
20
  try {
23
- this.#routes.push([
24
- new RegExp(`^${parts.join("")}${endsWithWildcard ? "" : "/?$"}`),
25
- method,
26
- handler
27
- ]);
21
+ this.#routes.push([new RegExp(`^${parts.join("")}${suffix}`), method, handler]);
28
22
  } catch {
29
23
  throw new UnsupportedPathError();
30
24
  }
@@ -2,76 +2,51 @@
2
2
  import { METHOD_NAME_ALL } from "../../router.js";
3
3
  import { getPattern, splitPath, splitRoutingPath } from "../../utils/url.js";
4
4
  var emptyParams = /* @__PURE__ */ Object.create(null);
5
- var hasChildren = (children) => {
6
- for (const _ in children) {
7
- return true;
8
- }
9
- return false;
10
- };
5
+ var order = 0;
11
6
  var Node = class _Node {
12
- #methods;
13
- #children;
14
- #patterns;
15
- #order = 0;
7
+ #methods = [];
8
+ #children = /* @__PURE__ */ Object.create(null);
9
+ #patterns = [];
10
+ #pattern;
16
11
  #params = emptyParams;
17
- constructor(method, handler, children) {
18
- this.#children = children || /* @__PURE__ */ Object.create(null);
19
- this.#methods = [];
20
- if (method && handler) {
21
- const m = /* @__PURE__ */ Object.create(null);
22
- m[method] = { handler, possibleKeys: [], score: 0 };
23
- this.#methods = [m];
24
- }
25
- this.#patterns = [];
26
- }
27
12
  insert(method, path, handler) {
28
- this.#order = ++this.#order;
29
13
  let curNode = this;
30
14
  const parts = splitRoutingPath(path);
31
- const possibleKeys = [];
32
- for (let i = 0, len = parts.length; i < len; i++) {
33
- const p = parts[i];
34
- const nextP = parts[i + 1];
35
- const pattern = getPattern(p, nextP);
36
- const key = Array.isArray(pattern) ? pattern[0] : p;
37
- if (key in curNode.#children) {
38
- curNode = curNode.#children[key];
39
- if (pattern) {
40
- possibleKeys.push(pattern[1]);
41
- }
42
- continue;
15
+ const possibleKeys = /* @__PURE__ */ new Set();
16
+ let i = 0;
17
+ for (const p of parts) {
18
+ const nextP = parts[++i];
19
+ const pattern = getPattern(p, nextP) || (nextP === void 0 && p && p.indexOf("*") === p.length - 1 ? p : null);
20
+ const isParam = Array.isArray(pattern);
21
+ const key = isParam ? pattern[0] : pattern || p;
22
+ const child = curNode.#children[key] ||= new _Node();
23
+ if (pattern && !child.#pattern) {
24
+ child.#pattern = pattern;
25
+ curNode.#patterns.push(child);
43
26
  }
44
- curNode.#children[key] = new _Node();
45
- if (pattern) {
46
- curNode.#patterns.push(pattern);
47
- possibleKeys.push(pattern[1]);
27
+ curNode = child;
28
+ if (isParam) {
29
+ possibleKeys.add(pattern[1]);
48
30
  }
49
- curNode = curNode.#children[key];
50
31
  }
51
32
  curNode.#methods.push({
52
33
  [method]: {
53
34
  handler,
54
- possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
55
- score: this.#order
35
+ possibleKeys: [...possibleKeys],
36
+ score: ++order
56
37
  }
57
38
  });
58
- return curNode;
59
39
  }
60
40
  #pushHandlerSets(handlerSets, node, method, nodeParams, params) {
61
41
  for (let i = 0, len = node.#methods.length; i < len; i++) {
62
42
  const m = node.#methods[i];
63
43
  const handlerSet = m[method] || m[METHOD_NAME_ALL];
64
- const processedSet = {};
65
- if (handlerSet !== void 0) {
44
+ if (handlerSet) {
66
45
  handlerSet.params = /* @__PURE__ */ Object.create(null);
67
46
  handlerSets.push(handlerSet);
68
- if (nodeParams !== emptyParams || params && params !== emptyParams) {
69
- for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
70
- const key = handlerSet.possibleKeys[i2];
71
- const processed = processedSet[handlerSet.score];
72
- handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
73
- processedSet[handlerSet.score] = true;
74
- }
47
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
48
+ const key = handlerSet.possibleKeys[i2];
49
+ handlerSet.params[key] = params?.[key] && !i2 ? params[key] : nodeParams[key] ?? params?.[key];
75
50
  }
76
51
  }
77
52
  }
@@ -103,33 +78,33 @@ var Node = class _Node {
103
78
  tempNodes.push(nextNode);
104
79
  }
105
80
  }
106
- for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
107
- const pattern = node.#patterns[k];
81
+ for (const child of node.#patterns) {
82
+ const pattern = child.#pattern;
108
83
  const params = node.#params === emptyParams ? {} : { ...node.#params };
109
- if (pattern === "*") {
110
- const astNode = node.#children["*"];
111
- if (astNode) {
112
- this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
113
- astNode.#params = params;
114
- tempNodes.push(astNode);
84
+ if (typeof pattern === "string") {
85
+ if (pattern === "*" || part.startsWith(pattern.slice(0, -1))) {
86
+ this.#pushHandlerSets(handlerSets, child, method, node.#params);
87
+ if (pattern === "*") {
88
+ child.#params = params;
89
+ tempNodes.push(child);
90
+ }
115
91
  }
116
92
  continue;
117
93
  }
118
- const [key, name, matcher] = pattern;
119
- if (!part && !(matcher instanceof RegExp)) {
94
+ const [, name, matcher] = pattern;
95
+ if (!part && matcher === true) {
120
96
  continue;
121
97
  }
122
- const child = node.#children[key];
123
- if (matcher instanceof RegExp) {
124
- if (partOffsets === null) {
125
- partOffsets = new Array(len);
98
+ if (matcher !== true) {
99
+ if (!partOffsets) {
100
+ partOffsets = [];
126
101
  let offset = path[0] === "/" ? 1 : 0;
127
102
  for (let p = 0; p < len; p++) {
128
103
  partOffsets[p] = offset;
129
104
  offset += parts[p].length + 1;
130
105
  }
131
106
  }
132
- const restPathString = path.substring(partOffsets[i]);
107
+ const restPathString = path.slice(partOffsets[i]);
133
108
  const m = matcher.exec(restPathString);
134
109
  if (m) {
135
110
  params[name] = m[0];
@@ -143,11 +118,12 @@ var Node = class _Node {
143
118
  params
144
119
  );
145
120
  }
146
- if (hasChildren(child.#children)) {
121
+ for (const _ in child.#children) {
147
122
  child.#params = params;
148
123
  const componentCount = m[0].match(/\//g)?.length ?? 0;
149
124
  const targetCurNodes = curNodesQueue[componentCount] ||= [];
150
125
  targetCurNodes.push(child);
126
+ break;
151
127
  }
152
128
  continue;
153
129
  }
@@ -175,7 +151,7 @@ var Node = class _Node {
175
151
  const shifted = curNodesQueue.shift();
176
152
  curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
177
153
  }
178
- if (handlerSets.length > 1) {
154
+ if (handlerSets[1]) {
179
155
  handlerSets.sort((a, b) => {
180
156
  return a.score - b.score;
181
157
  });
@@ -3,19 +3,11 @@ import { checkOptionalParameter } from "../../utils/url.js";
3
3
  import { Node } from "./node.js";
4
4
  var TrieRouter = class {
5
5
  name = "TrieRouter";
6
- #node;
7
- constructor() {
8
- this.#node = new Node();
9
- }
6
+ #node = new Node();
10
7
  add(method, path, handler) {
11
- const results = checkOptionalParameter(path);
12
- if (results) {
13
- for (let i = 0, len = results.length; i < len; i++) {
14
- this.#node.insert(method, results[i], handler);
15
- }
16
- return;
8
+ for (const result of checkOptionalParameter(path) || [path]) {
9
+ this.#node.insert(method, result, handler);
17
10
  }
18
- this.#node.insert(method, path, handler);
19
11
  }
20
12
  match(method, path) {
21
13
  return this.#node.search(method, path);
@@ -323,6 +323,10 @@ export declare class Context<E extends Env = any, P extends string = any, I exte
323
323
  * c.header('X-Message', 'Hello!')
324
324
  * c.header('Content-Type', 'text/plain')
325
325
  *
326
+ * // Append multiple headers using the append option (e.g. Vary)
327
+ * c.header('Vary', 'Accept-Encoding', { append: true })
328
+ * c.header('Vary', 'User-Agent', { append: true })
329
+ *
326
330
  * return c.body('Thank you for coming')
327
331
  * })
328
332
  * ```
@@ -2,13 +2,13 @@ export type PermissionsPolicyDirective = StandardizedFeatures | ProposedFeatures
2
2
  /**
3
3
  * These features have been declared in a published version of the respective specification.
4
4
  */
5
- type StandardizedFeatures = 'accelerometer' | 'ambientLightSensor' | 'attributionReporting' | 'autoplay' | 'battery' | 'bluetooth' | 'camera' | 'chUa' | 'chUaArch' | 'chUaBitness' | 'chUaFullVersion' | 'chUaFullVersionList' | 'chUaMobile' | 'chUaModel' | 'chUaPlatform' | 'chUaPlatformVersion' | 'chUaWow64' | 'computePressure' | 'crossOriginIsolated' | 'directSockets' | 'displayCapture' | 'encryptedMedia' | 'executionWhileNotRendered' | 'executionWhileOutOfViewport' | 'fullscreen' | 'geolocation' | 'gyroscope' | 'hid' | 'identityCredentialsGet' | 'idleDetection' | 'keyboardMap' | 'magnetometer' | 'microphone' | 'midi' | 'navigationOverride' | 'payment' | 'pictureInPicture' | 'publickeyCredentialsGet' | 'screenWakeLock' | 'serial' | 'storageAccess' | 'syncXhr' | 'usb' | 'webShare' | 'windowManagement' | 'xrSpatialTracking';
5
+ type StandardizedFeatures = 'accelerometer' | 'ambientLightSensor' | 'attributionReporting' | 'autoplay' | 'battery' | 'bluetooth' | 'camera' | 'chUa' | 'chUaArch' | 'chUaBitness' | 'chUaFullVersion' | 'chUaFullVersionList' | 'chUaHighEntropyValues' | 'chUaMobile' | 'chUaModel' | 'chUaPlatform' | 'chUaPlatformVersion' | 'chUaWow64' | 'computePressure' | 'crossOriginIsolated' | 'directSockets' | 'displayCapture' | 'encryptedMedia' | 'executionWhileNotRendered' | 'executionWhileOutOfViewport' | 'fullscreen' | 'geolocation' | 'gyroscope' | 'hid' | 'identityCredentialsGet' | 'idleDetection' | 'keyboardMap' | 'magnetometer' | 'mediasession' | 'microphone' | 'midi' | 'navigationOverride' | 'otpCredentials' | 'payment' | 'pictureInPicture' | 'publickeyCredentialsGet' | 'screenWakeLock' | 'serial' | 'storageAccess' | 'syncXhr' | 'tools' | 'usb' | 'webShare' | 'windowManagement' | 'xrSpatialTracking';
6
6
  /**
7
7
  * These features have been proposed, but the definitions have not yet been integrated into their respective specs.
8
8
  */
9
- type ProposedFeatures = 'clipboardRead' | 'clipboardWrite' | 'gamepad' | 'sharedAutofill' | 'speakerSelection';
9
+ type ProposedFeatures = 'autofill' | 'clipboardRead' | 'clipboardWrite' | 'deferredFetch' | 'gamepad' | 'languageDetector' | 'languageModel' | 'manualText' | 'rewriter' | 'sharedAutofill' | 'speakerSelection' | 'summarizer' | 'translator' | 'writer';
10
10
  /**
11
11
  * These features generally have an explainer only, but may be available for experimentation by web developers.
12
12
  */
13
- type ExperimentalFeatures = 'allScreensCapture' | 'browsingTopics' | 'capturedSurfaceControl' | 'conversionMeasurement' | 'digitalCredentialsGet' | 'focusWithoutUserActivation' | 'joinAdInterestGroup' | 'localFonts' | 'runAdAuction' | 'smartCard' | 'syncScript' | 'trustTokenRedemption' | 'unload' | 'verticalScroll';
13
+ type ExperimentalFeatures = 'allScreensCapture' | 'browsingTopics' | 'capturedSurfaceControl' | 'conversionMeasurement' | 'digitalCredentialsCreate' | 'digitalCredentialsGet' | 'focusWithoutUserActivation' | 'joinAdInterestGroup' | 'localFonts' | 'monetization' | 'runAdAuction' | 'smartCard' | 'syncScript' | 'trustTokenRedemption' | 'unload' | 'verticalScroll';
14
14
  export {};
@@ -1,7 +1,6 @@
1
1
  import type { Params } from '../../router';
2
2
  export declare class Node<T> {
3
3
 
4
- constructor(method?: string, handler?: T, children?: Record<string, Node<T>>);
5
- insert(method: string, path: string, handler: T): Node<T>;
4
+ insert(method: string, path: string, handler: T): void;
6
5
  search(method: string, path: string): [[T, Params][]];
7
6
  }
@@ -2,7 +2,6 @@ import type { Result, Router } from '../../router';
2
2
  export declare class TrieRouter<T> implements Router<T> {
3
3
 
4
4
  name: string;
5
- constructor();
6
5
  add(method: string, path: string, handler: T): void;
7
6
  match(method: string, path: string): Result<T>;
8
7
  }
@@ -1,12 +1,14 @@
1
1
  // src/utils/ipaddr.ts
2
2
  var expandIPv6 = (ipV6) => {
3
3
  const sections = ipV6.split(":");
4
- if (IPV4_REGEX.test(sections.at(-1))) {
4
+ const lastSection = sections.at(-1);
5
+ if (IPV4_REGEX.test(lastSection)) {
6
+ const octets = lastSection.split(".").map(Number);
5
7
  sections.splice(
6
8
  -1,
7
9
  1,
8
- ...convertIPv6BinaryToString(convertIPv4ToBinary(sections.at(-1))).substring(2).split(":")
9
- // => ['7f00', '0001']
10
+ (octets[0] << 8 | octets[1]).toString(16),
11
+ (octets[2] << 8 | octets[3]).toString(16)
10
12
  );
11
13
  }
12
14
  for (let i = 0; i < sections.length; i++) {
package/dist/utils/url.js CHANGED
@@ -108,13 +108,13 @@ var checkOptionalParameter = (path) => {
108
108
  if (segment !== "" && !/\:/.test(segment)) {
109
109
  basePath += "/" + segment;
110
110
  } else if (/\:/.test(segment)) {
111
- if (/\?/.test(segment)) {
111
+ if (segment.charCodeAt(segment.length - 1) === 63) {
112
112
  if (results.length === 0 && basePath === "") {
113
113
  results.push("/");
114
114
  } else {
115
115
  results.push(basePath);
116
116
  }
117
- const optionalSegment = segment.replace("?", "");
117
+ const optionalSegment = segment.slice(0, -1);
118
118
  basePath += "/" + optionalSegment;
119
119
  results.push(basePath);
120
120
  } else {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hono",
3
- "version": "4.13.1",
3
+ "version": "4.13.3",
4
4
  "description": "Web framework built on Web Standards",
5
5
  "main": "dist/cjs/index.js",
6
6
  "type": "module",