hono 4.2.9 → 4.3.1

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 (72) hide show
  1. package/README.md +0 -13
  2. package/dist/adapter/deno/serve-static.js +1 -1
  3. package/dist/cjs/adapter/deno/serve-static.js +1 -1
  4. package/dist/cjs/client/client.js +2 -1
  5. package/dist/cjs/helper/cookie/index.js +2 -0
  6. package/dist/cjs/helper/factory/index.js +13 -1
  7. package/dist/cjs/jsx/base.js +26 -14
  8. package/dist/cjs/jsx/children.js +45 -0
  9. package/dist/cjs/jsx/constants.js +3 -0
  10. package/dist/cjs/jsx/dom/context.js +22 -11
  11. package/dist/cjs/jsx/dom/css.js +6 -4
  12. package/dist/cjs/jsx/dom/index.js +35 -4
  13. package/dist/cjs/jsx/dom/jsx-dev-runtime.js +20 -13
  14. package/dist/cjs/jsx/dom/render.js +110 -48
  15. package/dist/cjs/jsx/dom/utils.js +33 -0
  16. package/dist/cjs/jsx/hooks/index.js +41 -1
  17. package/dist/cjs/jsx/index.js +17 -1
  18. package/dist/cjs/jsx/jsx-dev-runtime.js +0 -1
  19. package/dist/cjs/jsx/utils.js +12 -2
  20. package/dist/cjs/middleware/bearer-auth/index.js +2 -1
  21. package/dist/cjs/middleware/secure-headers/index.js +58 -8
  22. package/dist/cjs/middleware/serve-static/index.js +5 -2
  23. package/dist/cjs/middleware/timing/index.js +3 -2
  24. package/dist/cjs/utils/mime.js +4 -2
  25. package/dist/client/client.js +2 -1
  26. package/dist/helper/cookie/index.js +2 -0
  27. package/dist/helper/factory/index.js +13 -1
  28. package/dist/jsx/base.js +27 -15
  29. package/dist/jsx/children.js +21 -0
  30. package/dist/jsx/constants.js +2 -0
  31. package/dist/jsx/dom/context.js +22 -11
  32. package/dist/jsx/dom/css.js +6 -4
  33. package/dist/jsx/dom/index.js +31 -5
  34. package/dist/jsx/dom/jsx-dev-runtime.js +20 -13
  35. package/dist/jsx/dom/render.js +109 -49
  36. package/dist/jsx/dom/utils.js +10 -0
  37. package/dist/jsx/hooks/index.js +37 -1
  38. package/dist/jsx/index.js +17 -2
  39. package/dist/jsx/jsx-dev-runtime.js +0 -1
  40. package/dist/jsx/utils.js +10 -1
  41. package/dist/middleware/bearer-auth/index.js +2 -1
  42. package/dist/middleware/secure-headers/index.js +57 -8
  43. package/dist/middleware/serve-static/index.js +5 -2
  44. package/dist/middleware/timing/index.js +3 -2
  45. package/dist/types/adapter/cloudflare-workers/serve-static.d.ts +6 -0
  46. package/dist/types/client/types.d.ts +44 -20
  47. package/dist/types/context.d.ts +6 -6
  48. package/dist/types/helper/cookie/index.d.ts +1 -1
  49. package/dist/types/helper/factory/index.d.ts +15 -1
  50. package/dist/types/helper/websocket/index.d.ts +1 -4
  51. package/dist/types/jsx/base.d.ts +10 -3
  52. package/dist/types/jsx/children.d.ts +9 -0
  53. package/dist/types/jsx/constants.d.ts +1 -0
  54. package/dist/types/jsx/dom/context.d.ts +1 -10
  55. package/dist/types/jsx/dom/index.d.ts +31 -11
  56. package/dist/types/jsx/dom/jsx-dev-runtime.d.ts +3 -13
  57. package/dist/types/jsx/dom/render.d.ts +6 -4
  58. package/dist/types/jsx/dom/utils.d.ts +1 -0
  59. package/dist/types/jsx/hooks/index.d.ts +6 -0
  60. package/dist/types/jsx/index.d.ts +18 -3
  61. package/dist/types/jsx/types.d.ts +24 -1
  62. package/dist/types/jsx/utils.d.ts +1 -0
  63. package/dist/types/middleware/bearer-auth/index.d.ts +2 -0
  64. package/dist/types/middleware/secure-headers/index.d.ts +30 -21
  65. package/dist/types/middleware/serve-static/index.d.ts +2 -2
  66. package/dist/types/middleware/timing/index.d.ts +1 -1
  67. package/dist/types/request.d.ts +3 -2
  68. package/dist/types/types.d.ts +88 -63
  69. package/dist/types/utils/mime.d.ts +2 -0
  70. package/dist/types/utils/types.d.ts +3 -0
  71. package/dist/utils/mime.js +2 -1
  72. package/package.json +9 -1
@@ -1,8 +1,11 @@
1
1
  // src/jsx/dom/render.ts
2
- import { DOM_RENDERER, DOM_ERROR_HANDLER, DOM_STASH } from "../constants.js";
2
+ import { toArray } from "../children.js";
3
+ import { DOM_RENDERER, DOM_ERROR_HANDLER, DOM_STASH, DOM_INTERNAL_TAG } from "../constants.js";
3
4
  import { globalContexts as globalJSXContexts, useContext } from "../context.js";
4
5
  import { STASH_EFFECT } from "../hooks/index.js";
6
+ import { styleObjectForEach } from "../utils.js";
5
7
  import { createContext } from "./context.js";
8
+ var HONO_PORTAL_ELEMENT = "_hp";
6
9
  var eventAliasMap = {
7
10
  Change: "Input",
8
11
  DoubleClick: "DblClick"
@@ -11,9 +14,10 @@ var nameSpaceMap = {
11
14
  svg: "http://www.w3.org/2000/svg",
12
15
  math: "http://www.w3.org/1998/Math/MathML"
13
16
  };
17
+ var skipProps = /* @__PURE__ */ new Set(["children"]);
14
18
  var buildDataStack = [];
15
19
  var nameSpaceContext = void 0;
16
- var isNodeString = (node) => Array.isArray(node);
20
+ var isNodeString = (node) => "t" in node;
17
21
  var getEventSpec = (key) => {
18
22
  const match = key.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);
19
23
  if (match) {
@@ -25,30 +29,35 @@ var getEventSpec = (key) => {
25
29
  var applyProps = (container, attributes, oldAttributes) => {
26
30
  attributes ||= {};
27
31
  for (const [key, value] of Object.entries(attributes)) {
28
- if (!oldAttributes || oldAttributes[key] !== value) {
32
+ if (!skipProps.has(key) && (!oldAttributes || oldAttributes[key] !== value)) {
29
33
  const eventSpec = getEventSpec(key);
30
34
  if (eventSpec) {
31
- if (typeof value !== "function") {
32
- throw new Error(`Event handler for "${key}" is not a function`);
33
- }
34
35
  if (oldAttributes) {
35
36
  container.removeEventListener(eventSpec[0], oldAttributes[key], eventSpec[1]);
36
37
  }
37
- container.addEventListener(eventSpec[0], value, eventSpec[1]);
38
+ if (value != null) {
39
+ if (typeof value !== "function") {
40
+ throw new Error(`Event handler for "${key}" is not a function`);
41
+ }
42
+ container.addEventListener(eventSpec[0], value, eventSpec[1]);
43
+ }
38
44
  } else if (key === "dangerouslySetInnerHTML" && value) {
39
45
  container.innerHTML = value.__html;
40
46
  } else if (key === "ref") {
41
47
  if (typeof value === "function") {
42
48
  value(container);
43
- } else if ("current" in value) {
49
+ } else if (value && "current" in value) {
44
50
  value.current = container;
45
51
  }
46
52
  } else if (key === "style") {
53
+ const style = container.style;
47
54
  if (typeof value === "string") {
48
- container.style.cssText = value;
55
+ style.cssText = value;
49
56
  } else {
50
- container.style.cssText = "";
51
- Object.assign(container.style, value);
57
+ style.cssText = "";
58
+ if (value != null) {
59
+ styleObjectForEach(value, style.setProperty.bind(style));
60
+ }
52
61
  }
53
62
  } else {
54
63
  const nodeName = container.nodeName;
@@ -85,7 +94,7 @@ var applyProps = (container, attributes, oldAttributes) => {
85
94
  }
86
95
  if (oldAttributes) {
87
96
  for (const [key, value] of Object.entries(oldAttributes)) {
88
- if (!(key in attributes)) {
97
+ if (!skipProps.has(key) && !(key in attributes)) {
89
98
  const eventSpec = getEventSpec(key);
90
99
  if (eventSpec) {
91
100
  container.removeEventListener(eventSpec[0], value, eventSpec[1]);
@@ -114,8 +123,8 @@ var invokeTag = (context, node) => {
114
123
  try {
115
124
  return [
116
125
  func.call(null, {
117
- ...node.props,
118
- children: node.children
126
+ ...func.defaultProps || {},
127
+ ...node.props
119
128
  })
120
129
  ];
121
130
  } finally {
@@ -160,21 +169,30 @@ var findInsertBefore = (node) => {
160
169
  var removeNode = (node) => {
161
170
  if (!isNodeString(node)) {
162
171
  node[DOM_STASH]?.[1][STASH_EFFECT]?.forEach((data) => data[2]?.());
172
+ if (node.e && node.props?.ref) {
173
+ if (typeof node.props.ref === "function") {
174
+ node.props.ref(null);
175
+ } else {
176
+ node.props.ref.current = null;
177
+ }
178
+ }
163
179
  node.vC?.forEach(removeNode);
164
180
  }
165
- node.e?.remove();
166
- node.tag = void 0;
181
+ if (node.tag !== HONO_PORTAL_ELEMENT) {
182
+ node.e?.remove();
183
+ }
184
+ if (typeof node.tag === "function") {
185
+ updateMap.delete(node);
186
+ fallbackUpdateFnArrayMap.delete(node);
187
+ }
167
188
  };
168
189
  var apply = (node, container) => {
169
- if (node.tag === void 0) {
170
- return;
171
- }
172
190
  node.c = container;
173
191
  applyNodeObject(node, container);
174
192
  };
175
193
  var applyNode = (node, container) => {
176
194
  if (isNodeString(node)) {
177
- container.textContent = node[0];
195
+ container.textContent = node.t;
178
196
  } else {
179
197
  applyNodeObject(node, container);
180
198
  }
@@ -201,17 +219,17 @@ var applyNodeObject = (node, container) => {
201
219
  const child = next[i];
202
220
  let el;
203
221
  if (isNodeString(child)) {
204
- if (child.e && child[1]) {
205
- child.e.textContent = child[0];
222
+ if (child.e && child.d) {
223
+ child.e.textContent = child.t;
206
224
  }
207
- child[1] = false;
208
- el = child.e ||= document.createTextNode(child[0]);
225
+ child.d = false;
226
+ el = child.e ||= document.createTextNode(child.t);
209
227
  } else {
210
228
  el = child.e ||= child.n ? document.createElementNS(child.n, child.tag) : document.createElement(child.tag);
211
229
  applyProps(el, child.props, child.pP);
212
230
  applyNode(child, el);
213
231
  }
214
- if (childNodes[offset] !== el && childNodes[offset - 1] !== child.e) {
232
+ if (childNodes[offset] !== el && childNodes[offset - 1] !== child.e && child.tag !== HONO_PORTAL_ELEMENT) {
215
233
  container.insertBefore(el, childNodes[offset] || null);
216
234
  }
217
235
  }
@@ -221,12 +239,10 @@ var applyNodeObject = (node, container) => {
221
239
  callbacks.forEach(([, , , cb]) => cb?.());
222
240
  });
223
241
  };
242
+ var fallbackUpdateFnArrayMap = /* @__PURE__ */ new WeakMap();
224
243
  var build = (context, node, topLevelErrorHandlerNode, children) => {
225
- if (node.tag === void 0) {
226
- return;
227
- }
228
244
  let errorHandler;
229
- children ||= typeof node.tag == "function" ? invokeTag(context, node) : node.children;
245
+ children ||= typeof node.tag == "function" ? invokeTag(context, node) : toArray(node.props.children);
230
246
  if (children[0]?.tag === "") {
231
247
  errorHandler = children[0][DOM_ERROR_HANDLER];
232
248
  topLevelErrorHandlerNode ||= node;
@@ -243,7 +259,7 @@ var build = (context, node, topLevelErrorHandlerNode, children) => {
243
259
  prevNode.nN = child;
244
260
  }
245
261
  prevNode = child;
246
- if (typeof child.tag === "function" && globalJSXContexts.length > 0) {
262
+ if (typeof child.tag === "function" && !child.tag[DOM_INTERNAL_TAG] && globalJSXContexts.length > 0) {
247
263
  child[DOM_STASH][2] = globalJSXContexts.map((c2) => [c2, c2.values.at(-1)]);
248
264
  }
249
265
  let oldChild;
@@ -257,9 +273,9 @@ var build = (context, node, topLevelErrorHandlerNode, children) => {
257
273
  if (!isNodeString(oldChild)) {
258
274
  vChildrenToRemove.push(oldChild);
259
275
  } else {
260
- if (oldChild[0] !== child[0]) {
261
- oldChild[0] = child[0];
262
- oldChild[1] = true;
276
+ if (oldChild.t !== child.t) {
277
+ oldChild.t = child.t;
278
+ oldChild.d = true;
263
279
  }
264
280
  child = oldChild;
265
281
  }
@@ -268,7 +284,9 @@ var build = (context, node, topLevelErrorHandlerNode, children) => {
268
284
  } else {
269
285
  oldChild.pP = oldChild.props;
270
286
  oldChild.props = child.props;
271
- oldChild.children = child.children;
287
+ if (typeof child.tag === "function") {
288
+ oldChild[DOM_STASH][2] = child[DOM_STASH][2] || [];
289
+ }
272
290
  child = oldChild;
273
291
  }
274
292
  } else if (!isNodeString(child) && nameSpaceContext) {
@@ -288,10 +306,20 @@ var build = (context, node, topLevelErrorHandlerNode, children) => {
288
306
  node.vR = vChildrenToRemove;
289
307
  } catch (e) {
290
308
  if (errorHandler) {
291
- const fallback = errorHandler(
292
- e,
293
- () => update([0, false, context[2]], topLevelErrorHandlerNode)
294
- );
309
+ const fallbackUpdateFn = () => update([0, false, context[2]], topLevelErrorHandlerNode);
310
+ const fallbackUpdateFnArray = fallbackUpdateFnArrayMap.get(topLevelErrorHandlerNode) || [];
311
+ fallbackUpdateFnArray.push(fallbackUpdateFn);
312
+ fallbackUpdateFnArrayMap.set(topLevelErrorHandlerNode, fallbackUpdateFnArray);
313
+ const fallback = errorHandler(e, () => {
314
+ const fnArray = fallbackUpdateFnArrayMap.get(topLevelErrorHandlerNode);
315
+ if (fnArray) {
316
+ const i = fnArray.indexOf(fallbackUpdateFn);
317
+ if (i !== -1) {
318
+ fnArray.splice(i, 1);
319
+ return fallbackUpdateFn();
320
+ }
321
+ }
322
+ });
295
323
  if (fallback) {
296
324
  if (context[0] === 1) {
297
325
  context[1] = true;
@@ -308,9 +336,12 @@ var buildNode = (node) => {
308
336
  if (node === void 0 || node === null || typeof node === "boolean") {
309
337
  return void 0;
310
338
  } else if (typeof node === "string" || typeof node === "number") {
311
- return [node.toString(), true];
339
+ return { t: node.toString(), d: true };
312
340
  } else {
313
341
  if (typeof node.tag === "function") {
342
+ if (node[DOM_STASH]) {
343
+ node = { ...node };
344
+ }
314
345
  ;
315
346
  node[DOM_STASH] = [0, []];
316
347
  } else {
@@ -319,13 +350,13 @@ var buildNode = (node) => {
319
350
  ;
320
351
  node.n = ns;
321
352
  nameSpaceContext ||= createContext("");
322
- node.children = [
353
+ node.props.children = [
323
354
  {
324
355
  tag: nameSpaceContext.Provider,
325
356
  props: {
326
- value: ns
327
- },
328
- children: node.children
357
+ value: ns,
358
+ children: node.props.children
359
+ }
329
360
  }
330
361
  ];
331
362
  }
@@ -352,6 +383,7 @@ var updateSync = (context, node) => {
352
383
  }
353
384
  };
354
385
  var updateMap = /* @__PURE__ */ new WeakMap();
386
+ var currentUpdateSets = [];
355
387
  var update = async (context, node) => {
356
388
  const existing = updateMap.get(node);
357
389
  if (existing) {
@@ -372,25 +404,53 @@ var update = async (context, node) => {
372
404
  }
373
405
  }
374
406
  ]);
375
- await Promise.resolve();
376
- const latest = updateMap.get(node);
377
- if (latest) {
378
- updateMap.delete(node);
379
- latest[1]();
407
+ if (currentUpdateSets.length) {
408
+ ;
409
+ currentUpdateSets.at(-1).add(node);
410
+ } else {
411
+ await Promise.resolve();
412
+ const latest = updateMap.get(node);
413
+ if (latest) {
414
+ updateMap.delete(node);
415
+ latest[1]();
416
+ }
380
417
  }
381
418
  return promise;
382
419
  };
383
420
  var render = (jsxNode, container) => {
384
- const node = buildNode({ tag: "", children: [jsxNode] });
421
+ const node = buildNode({ tag: "", props: { children: jsxNode } });
385
422
  build([], node, void 0);
386
423
  const fragment = document.createDocumentFragment();
387
424
  apply(node, fragment);
388
425
  replaceContainer(node, fragment, container);
389
426
  container.replaceChildren(fragment);
390
427
  };
428
+ var flushSync = (callback) => {
429
+ const set = /* @__PURE__ */ new Set();
430
+ currentUpdateSets.push(set);
431
+ callback();
432
+ set.forEach((node) => {
433
+ const latest = updateMap.get(node);
434
+ if (latest) {
435
+ updateMap.delete(node);
436
+ latest[1]();
437
+ }
438
+ });
439
+ currentUpdateSets.pop();
440
+ };
441
+ var createPortal = (children, container, key) => ({
442
+ tag: HONO_PORTAL_ELEMENT,
443
+ props: {
444
+ children
445
+ },
446
+ key,
447
+ e: container
448
+ });
391
449
  export {
392
450
  build,
393
451
  buildDataStack,
452
+ createPortal,
453
+ flushSync,
394
454
  render,
395
455
  update
396
456
  };
@@ -0,0 +1,10 @@
1
+ // src/jsx/dom/utils.ts
2
+ import { DOM_INTERNAL_TAG } from "../constants.js";
3
+ var setInternalTagFlag = (fn) => {
4
+ ;
5
+ fn[DOM_INTERNAL_TAG] = true;
6
+ return fn;
7
+ };
8
+ export {
9
+ setInternalTagFlag
10
+ };
@@ -114,7 +114,7 @@ var useState = (initialState) => {
114
114
  if (typeof newState === "function") {
115
115
  newState = newState(stateData[0]);
116
116
  }
117
- if (newState !== stateData[0]) {
117
+ if (!Object.is(newState, stateData[0])) {
118
118
  stateData[0] = newState;
119
119
  if (pendingStack.length) {
120
120
  const pendingType = pendingStack.at(-1);
@@ -262,8 +262,42 @@ var idCounter = 0;
262
262
  var useId = () => useMemo(() => `:r${(idCounter++).toString(32)}:`, []);
263
263
  var useDebugValue = (_value, _formatter) => {
264
264
  };
265
+ var createRef = () => {
266
+ return { current: null };
267
+ };
268
+ var forwardRef = (Component) => {
269
+ return (props) => {
270
+ const { ref, ...rest } = props;
271
+ return Component(rest, ref);
272
+ };
273
+ };
274
+ var useImperativeHandle = (ref, createHandle, deps) => {
275
+ useEffect(() => {
276
+ ref.current = createHandle();
277
+ return () => {
278
+ ref.current = null;
279
+ };
280
+ }, deps);
281
+ };
282
+ var useSyncExternalStoreGetServerSnapshotNotified = false;
283
+ var useSyncExternalStore = (subscribe, getSnapshot, getServerSnapshot) => {
284
+ const [state, setState] = useState(getSnapshot());
285
+ useEffect(
286
+ () => subscribe(() => {
287
+ setState(getSnapshot());
288
+ }),
289
+ []
290
+ );
291
+ if (getServerSnapshot && !useSyncExternalStoreGetServerSnapshotNotified) {
292
+ useSyncExternalStoreGetServerSnapshotNotified = true;
293
+ console.info("`getServerSnapshot` is not supported yet.");
294
+ }
295
+ return state;
296
+ };
265
297
  export {
266
298
  STASH_EFFECT,
299
+ createRef,
300
+ forwardRef,
267
301
  startTransition,
268
302
  startViewTransition,
269
303
  use,
@@ -272,11 +306,13 @@ export {
272
306
  useDeferredValue,
273
307
  useEffect,
274
308
  useId,
309
+ useImperativeHandle,
275
310
  useLayoutEffect,
276
311
  useMemo,
277
312
  useReducer,
278
313
  useRef,
279
314
  useState,
315
+ useSyncExternalStore,
280
316
  useTransition,
281
317
  useViewTransition
282
318
  };
package/dist/jsx/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // src/jsx/index.ts
2
2
  import { jsx, memo, Fragment, isValidElement, cloneElement } from "./base.js";
3
+ import { Children } from "./children.js";
3
4
  import { ErrorBoundary } from "./components.js";
4
5
  import { createContext, useContext } from "./context.js";
5
6
  import {
@@ -17,7 +18,11 @@ import {
17
18
  useLayoutEffect,
18
19
  useReducer,
19
20
  useId,
20
- useDebugValue
21
+ useDebugValue,
22
+ createRef,
23
+ forwardRef,
24
+ useImperativeHandle,
25
+ useSyncExternalStore
21
26
  } from "./hooks/index.js";
22
27
  import { Suspense } from "./streaming.js";
23
28
  export * from "./types.js";
@@ -45,16 +50,24 @@ var jsx_default = {
45
50
  useViewTransition,
46
51
  useMemo,
47
52
  useLayoutEffect,
48
- Suspense
53
+ createRef,
54
+ forwardRef,
55
+ useImperativeHandle,
56
+ useSyncExternalStore,
57
+ Suspense,
58
+ Children
49
59
  };
50
60
  export {
61
+ Children,
51
62
  ErrorBoundary,
52
63
  Fragment,
53
64
  Suspense,
54
65
  cloneElement,
55
66
  createContext,
56
67
  jsx as createElement,
68
+ createRef,
57
69
  jsx_default as default,
70
+ forwardRef,
58
71
  isValidElement,
59
72
  jsx,
60
73
  memo,
@@ -67,11 +80,13 @@ export {
67
80
  useDeferredValue,
68
81
  useEffect,
69
82
  useId,
83
+ useImperativeHandle,
70
84
  useLayoutEffect,
71
85
  useMemo,
72
86
  useReducer,
73
87
  useRef,
74
88
  useState,
89
+ useSyncExternalStore,
75
90
  useTransition,
76
91
  useViewTransition
77
92
  };
@@ -7,7 +7,6 @@ function jsxDEV(tag, props, key) {
7
7
  node = jsxFn(tag, props, []);
8
8
  } else {
9
9
  const children = props.children;
10
- delete props["children"];
11
10
  node = Array.isArray(children) ? jsxFn(tag, props, children) : jsxFn(tag, props, [children]);
12
11
  }
13
12
  node.key = key;
package/dist/jsx/utils.js CHANGED
@@ -5,6 +5,15 @@ var normalizeIntrinsicElementProps = (props) => {
5
5
  delete props["className"];
6
6
  }
7
7
  };
8
+ var styleObjectForEach = (style, fn) => {
9
+ for (const [k, v] of Object.entries(style)) {
10
+ fn(
11
+ k[0] === "-" ? k : k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`),
12
+ v == null ? null : typeof v === "number" ? v + "px" : v
13
+ );
14
+ }
15
+ };
8
16
  export {
9
- normalizeIntrinsicElementProps
17
+ normalizeIntrinsicElementProps,
18
+ styleObjectForEach
10
19
  };
@@ -3,6 +3,7 @@ import { HTTPException } from "../../http-exception.js";
3
3
  import { timingSafeEqual } from "../../utils/buffer.js";
4
4
  var TOKEN_STRINGS = "[A-Za-z0-9._~+/-]+=*";
5
5
  var PREFIX = "Bearer";
6
+ var HEADER = "Authorization";
6
7
  var bearerAuth = (options) => {
7
8
  if (!("token" in options || "verifyToken" in options)) {
8
9
  throw new Error('bearer auth middleware requires options for "token"');
@@ -15,7 +16,7 @@ var bearerAuth = (options) => {
15
16
  }
16
17
  const realm = options.realm?.replace(/"/g, '\\"');
17
18
  return async function bearerAuth2(c, next) {
18
- const headerToken = c.req.header("Authorization");
19
+ const headerToken = c.req.header(options.headerName || HEADER);
19
20
  if (!headerToken) {
20
21
  const res = new Response("Unauthorized", {
21
22
  status: 401,
@@ -27,11 +27,29 @@ var DEFAULT_OPTIONS = {
27
27
  xPermittedCrossDomainPolicies: true,
28
28
  xXssProtection: true
29
29
  };
30
+ var generateNonce = () => {
31
+ const buffer = new Uint8Array(16);
32
+ crypto.getRandomValues(buffer);
33
+ return Buffer.from(buffer).toString("base64");
34
+ };
35
+ var NONCE = (ctx) => {
36
+ const nonce = ctx.get("secureHeadersNonce") || (() => {
37
+ const newNonce = generateNonce();
38
+ ctx.set("secureHeadersNonce", newNonce);
39
+ return newNonce;
40
+ })();
41
+ return `'nonce-${nonce}'`;
42
+ };
30
43
  var secureHeaders = (customOptions) => {
31
44
  const options = { ...DEFAULT_OPTIONS, ...customOptions };
32
45
  const headersToSet = getFilteredHeaders(options);
46
+ const callbacks = [];
33
47
  if (options.contentSecurityPolicy) {
34
- headersToSet.push(["Content-Security-Policy", getCSPDirectives(options.contentSecurityPolicy)]);
48
+ const [callback, value] = getCSPDirectives(options.contentSecurityPolicy);
49
+ if (callback) {
50
+ callbacks.push(callback);
51
+ }
52
+ headersToSet.push(["Content-Security-Policy", value]);
35
53
  }
36
54
  if (options.reportingEndpoints) {
37
55
  headersToSet.push(["Reporting-Endpoints", getReportingEndpoints(options.reportingEndpoints)]);
@@ -40,8 +58,9 @@ var secureHeaders = (customOptions) => {
40
58
  headersToSet.push(["Report-To", getReportToOptions(options.reportTo)]);
41
59
  }
42
60
  return async function secureHeaders2(ctx, next) {
61
+ const headersToSetForReq = callbacks.length === 0 ? headersToSet : callbacks.reduce((acc, cb) => cb(ctx, acc), headersToSet);
43
62
  await next();
44
- setHeaders(ctx, headersToSet);
63
+ setHeaders(ctx, headersToSetForReq);
45
64
  ctx.res.headers.delete("X-Powered-By");
46
65
  };
47
66
  };
@@ -52,13 +71,42 @@ function getFilteredHeaders(options) {
52
71
  });
53
72
  }
54
73
  function getCSPDirectives(contentSecurityPolicy) {
55
- return Object.entries(contentSecurityPolicy || []).map(([directive, value]) => {
56
- const kebabCaseDirective = directive.replace(
57
- /[A-Z]+(?![a-z])|[A-Z]/g,
58
- (match, offset) => offset ? "-" + match.toLowerCase() : match.toLowerCase()
74
+ const callbacks = [];
75
+ const resultValues = [];
76
+ for (const [directive, value] of Object.entries(contentSecurityPolicy)) {
77
+ const valueArray = Array.isArray(value) ? value : [value];
78
+ valueArray.forEach((value2, i) => {
79
+ if (typeof value2 === "function") {
80
+ const index = i * 2 + 2 + resultValues.length;
81
+ callbacks.push((ctx, values) => {
82
+ values[index] = value2(ctx, directive);
83
+ });
84
+ }
85
+ });
86
+ resultValues.push(
87
+ directive.replace(
88
+ /[A-Z]+(?![a-z])|[A-Z]/g,
89
+ (match, offset) => offset ? "-" + match.toLowerCase() : match.toLowerCase()
90
+ ),
91
+ ...valueArray.flatMap((value2) => [" ", value2]),
92
+ "; "
59
93
  );
60
- return `${kebabCaseDirective} ${Array.isArray(value) ? value.join(" ") : value}`;
61
- }).join("; ");
94
+ }
95
+ resultValues.pop();
96
+ return callbacks.length === 0 ? [void 0, resultValues.join("")] : [
97
+ (ctx, headersToSet) => headersToSet.map((values) => {
98
+ if (values[0] === "Content-Security-Policy") {
99
+ const clone = values[1].slice();
100
+ callbacks.forEach((cb) => {
101
+ cb(ctx, clone);
102
+ });
103
+ return [values[0], clone.join("")];
104
+ } else {
105
+ return values;
106
+ }
107
+ }),
108
+ resultValues
109
+ ];
62
110
  }
63
111
  function getReportingEndpoints(reportingEndpoints = []) {
64
112
  return reportingEndpoints.map((endpoint) => `${endpoint.name}="${endpoint.url}"`).join(", ");
@@ -72,5 +120,6 @@ function setHeaders(ctx, headersToSet) {
72
120
  });
73
121
  }
74
122
  export {
123
+ NONCE,
75
124
  secureHeaders
76
125
  };
@@ -23,7 +23,7 @@ var serveStatic = (options) => {
23
23
  const getContent = options.getContent;
24
24
  const pathResolve = options.pathResolve ?? defaultPathResolve;
25
25
  path = pathResolve(path);
26
- let content = await getContent(path);
26
+ let content = await getContent(path, c);
27
27
  if (!content) {
28
28
  let pathWithOutDefaultDocument = getFilePathWithoutDefaultDocument({
29
29
  filename,
@@ -33,11 +33,14 @@ var serveStatic = (options) => {
33
33
  return await next();
34
34
  }
35
35
  pathWithOutDefaultDocument = pathResolve(pathWithOutDefaultDocument);
36
- content = await getContent(pathWithOutDefaultDocument);
36
+ content = await getContent(pathWithOutDefaultDocument, c);
37
37
  if (content) {
38
38
  path = pathWithOutDefaultDocument;
39
39
  }
40
40
  }
41
+ if (content instanceof Response) {
42
+ return c.newResponse(content.body, content);
43
+ }
41
44
  if (content) {
42
45
  let mimeType;
43
46
  if (options.mimes) {
@@ -35,10 +35,11 @@ var timing = (config) => {
35
35
  const enabled = typeof options.enabled === "function" ? options.enabled(c) : options.enabled;
36
36
  if (enabled) {
37
37
  c.res.headers.append("Server-Timing", headers.join(","));
38
- if (options.crossOrigin) {
38
+ const crossOrigin = typeof options.crossOrigin === "function" ? options.crossOrigin(c) : options.crossOrigin;
39
+ if (crossOrigin) {
39
40
  c.res.headers.append(
40
41
  "Timing-Allow-Origin",
41
- typeof options.crossOrigin === "string" ? options.crossOrigin : "*"
42
+ typeof crossOrigin === "string" ? crossOrigin : "*"
42
43
  );
43
44
  }
44
45
  }
@@ -5,4 +5,10 @@ export type ServeStaticOptions<E extends Env = Env> = BaseServeStaticOptions<E>
5
5
  namespace?: KVNamespace;
6
6
  manifest: object | string;
7
7
  };
8
+ /**
9
+ * @deprecated
10
+ * `serveStatic` in the Cloudflare Workers adapter is deprecated.
11
+ * If you want to create an application serving static assets, please consider using Cloudflare Pages.
12
+ * You can start to create the Cloudflare Pages application with the `npm create hono@latest` command.
13
+ */
8
14
  export declare const serveStatic: <E extends Env = Env>(options: ServeStaticOptions<E>) => MiddlewareHandler;