@gusto/baerly-storage 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -511
  3. package/dist/CHANGELOG.md +1148 -307
  4. package/dist/RECIPES.md +398 -80
  5. package/dist/THIRD-PARTY-LICENSES.txt +5 -26
  6. package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
  7. package/dist/app-config.d.ts +31 -1
  8. package/dist/app-config.js +1 -2
  9. package/dist/app-config.js.map +1 -1
  10. package/dist/auth.d.ts +33 -28
  11. package/dist/auth.js +549 -985
  12. package/dist/auth.js.map +1 -1
  13. package/dist/baerly.js +130 -138
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +97 -22
  16. package/dist/capacity-warning-header-BlVopyiI.js +16 -0
  17. package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
  18. package/dist/{client-Fe8CwB73.d.ts → client-CHQTXpef.d.ts} +121 -36
  19. package/dist/client-react.d.ts +67 -20
  20. package/dist/client-react.js +240 -54
  21. package/dist/client-react.js.map +1 -1
  22. package/dist/client.d.ts +5 -4
  23. package/dist/client.js +51 -16
  24. package/dist/client.js.map +1 -1
  25. package/dist/{cloudflare-DzKBrUlg.js → cloudflare-CKHYXccw.js} +504 -124
  26. package/dist/cloudflare-CKHYXccw.js.map +1 -0
  27. package/dist/cloudflare.d.ts +106 -71
  28. package/dist/cloudflare.js +334 -271
  29. package/dist/cloudflare.js.map +1 -1
  30. package/dist/code-resolution-CL_7L0wS.js +22 -0
  31. package/dist/code-resolution-CL_7L0wS.js.map +1 -0
  32. package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
  33. package/dist/config-DEzInG6M.js +4035 -0
  34. package/dist/config-DEzInG6M.js.map +1 -0
  35. package/dist/constants-D3GSH3tc.js +469 -0
  36. package/dist/constants-D3GSH3tc.js.map +1 -0
  37. package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
  38. package/dist/context-rlpSnHFA.js.map +1 -0
  39. package/dist/cost-B52llVDx.js +330 -0
  40. package/dist/cost-B52llVDx.js.map +1 -0
  41. package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
  42. package/dist/current-json-CC6lE4Aj.js.map +1 -0
  43. package/dist/db-plFUNTSF.d.ts +130 -0
  44. package/dist/db-read-seams-BSs0m1z1.js +3261 -0
  45. package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
  46. package/dist/{deploy-DonTr-CV.js → deploy-Obj4nE-Z.js} +12 -16
  47. package/dist/deploy-Obj4nE-Z.js.map +1 -0
  48. package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
  49. package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
  50. package/dist/dev-landing-CD-si4dW.js +50 -0
  51. package/dist/dev-landing-CD-si4dW.js.map +1 -0
  52. package/dist/dev-vite.d.ts +38 -39
  53. package/dist/dev-vite.js +67 -36
  54. package/dist/dev-vite.js.map +1 -1
  55. package/dist/dev.d.ts +3 -2
  56. package/dist/dev.js +2 -1
  57. package/dist/doctor-BA0i-YAN.js +270 -0
  58. package/dist/doctor-BA0i-YAN.js.map +1 -0
  59. package/dist/dump-D1vX8ozg.js +133 -0
  60. package/dist/dump-D1vX8ozg.js.map +1 -0
  61. package/dist/errors-7Rk1HGCE.js +160 -0
  62. package/dist/errors-7Rk1HGCE.js.map +1 -0
  63. package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
  64. package/dist/export-BVL2EvYE.js.map +1 -0
  65. package/dist/fsck-BWkPgov4.js +145 -0
  66. package/dist/fsck-BWkPgov4.js.map +1 -0
  67. package/dist/gcs-admin-Dso1HWQj.d.ts +127 -0
  68. package/dist/gcs.d.ts +30 -0
  69. package/dist/gcs.js +1 -0
  70. package/dist/goog4-signer-CeLIABoE.js +331 -0
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-DGd5tbNs.js → http-Z5rZyYMX.js} +898 -271
  73. package/dist/http-Z5rZyYMX.js.map +1 -0
  74. package/dist/http-transport-DNUM8kU-.js +1299 -0
  75. package/dist/http-transport-DNUM8kU-.js.map +1 -0
  76. package/dist/http.d.ts +366 -294
  77. package/dist/http.js +2 -2
  78. package/dist/index-JJrIu1pO.d.ts +135 -0
  79. package/dist/index-LEgHN0qJ.d.ts +50 -0
  80. package/dist/{index-CuA9Mi3K.d.ts → index-RiEYj8t0.d.ts} +291 -78
  81. package/dist/index.d.ts +27 -6
  82. package/dist/index.js +3 -5
  83. package/dist/inspect-BTsVYZKd.js +196 -0
  84. package/dist/inspect-BTsVYZKd.js.map +1 -0
  85. package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
  86. package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
  87. package/dist/ledger-Dj_bGgo0.js +192 -0
  88. package/dist/ledger-Dj_bGgo0.js.map +1 -0
  89. package/dist/legacy-names-DgZBtgOh.js +47 -0
  90. package/dist/legacy-names-DgZBtgOh.js.map +1 -0
  91. package/dist/log-C9W15Dfo.d.ts +94 -0
  92. package/dist/log-tail-DWJbneBF.js +142 -0
  93. package/dist/log-tail-DWJbneBF.js.map +1 -0
  94. package/dist/log-walk-C-vA-WGJ.js +111 -0
  95. package/dist/log-walk-C-vA-WGJ.js.map +1 -0
  96. package/dist/maintenance-Dd-Yakqj.js +1709 -0
  97. package/dist/maintenance-Dd-Yakqj.js.map +1 -0
  98. package/dist/maintenance-DevB6z4e.js +2237 -0
  99. package/dist/maintenance-DevB6z4e.js.map +1 -0
  100. package/dist/maintenance.d.ts +100 -3
  101. package/dist/maintenance.js +1 -3
  102. package/dist/node.d.ts +130 -142
  103. package/dist/node.js +4 -3
  104. package/dist/{observability-BmflLCdF.js → observability-C-ISCCLE.js} +1275 -332
  105. package/dist/observability-C-ISCCLE.js.map +1 -0
  106. package/dist/observability.d.ts +27 -3
  107. package/dist/observability.js +3 -3
  108. package/dist/path-segment-DBXG26PW.js +363 -0
  109. package/dist/path-segment-DBXG26PW.js.map +1 -0
  110. package/dist/{plan-a7PJHBCy.js → plan-BvQbaNMe.js} +19 -11
  111. package/dist/plan-BvQbaNMe.js.map +1 -0
  112. package/dist/request-CRWiTrza.js +272 -0
  113. package/dist/request-CRWiTrza.js.map +1 -0
  114. package/dist/restore-U6Im8V1V.js +1467 -0
  115. package/dist/restore-U6Im8V1V.js.map +1 -0
  116. package/dist/retry-OBtLB2GC.js +126 -0
  117. package/dist/retry-OBtLB2GC.js.map +1 -0
  118. package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
  119. package/dist/{runtime-spec-Dsw2-n8S.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DBC_wiCL.d.ts} +18 -10
  122. package/dist/s3.d.ts +20 -7
  123. package/dist/s3.js +4 -5
  124. package/dist/s3.js.map +1 -1
  125. package/dist/sha256-4FfGQNPw.js +22 -0
  126. package/dist/sha256-4FfGQNPw.js.map +1 -0
  127. package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
  128. package/dist/shared-secret-Vkur-8r0.js.map +1 -0
  129. package/dist/sigv4-sign-5IUflUD_.js +507 -0
  130. package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
  131. package/dist/snapshot-CknzkDM0.js +148 -0
  132. package/dist/snapshot-CknzkDM0.js.map +1 -0
  133. package/dist/{src-BL_JoPTn.js → src-Actga-bO.js} +1004 -378
  134. package/dist/src-Actga-bO.js.map +1 -0
  135. package/dist/src-D0MQfvOp.js +812 -0
  136. package/dist/src-D0MQfvOp.js.map +1 -0
  137. package/dist/src-Dr9uo3dc.js +501 -0
  138. package/dist/src-Dr9uo3dc.js.map +1 -0
  139. package/dist/{subcommand-DoDA-K7d.js → subcommand-BLoF66dG.js} +89 -16
  140. package/dist/subcommand-BLoF66dG.js.map +1 -0
  141. package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
  142. package/dist/time-DRxTP9iv.js.map +1 -0
  143. package/dist/types-suVbsEWS.d.ts +116 -0
  144. package/dist/{usage-DBV1eQHC.js → usage-CPzVhrQr.js} +40 -45
  145. package/dist/usage-CPzVhrQr.js.map +1 -0
  146. package/dist/uuid-BuT_c404.js +333 -0
  147. package/dist/uuid-BuT_c404.js.map +1 -0
  148. package/dist/verifier-Bmlmndzo.d.ts +95 -0
  149. package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
  150. package/dist/wire-DndvKU-K.js.map +1 -0
  151. package/package.json +96 -69
  152. package/dist/aws4fetch.esm-p7eEzLCs.js +0 -1702
  153. package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
  154. package/dist/bytes-BXdamO3L.js +0 -11
  155. package/dist/bytes-BXdamO3L.js.map +0 -1
  156. package/dist/cloudflare-DzKBrUlg.js.map +0 -1
  157. package/dist/config-1tv0-Yzm.js +0 -2693
  158. package/dist/config-1tv0-Yzm.js.map +0 -1
  159. package/dist/constants-CfeMWQWk.js +0 -222
  160. package/dist/constants-CfeMWQWk.js.map +0 -1
  161. package/dist/context-DRZ3tZ5l.js.map +0 -1
  162. package/dist/cost-DSMIVqzL.js +0 -203
  163. package/dist/cost-DSMIVqzL.js.map +0 -1
  164. package/dist/current-json-C6nhPOm1.js.map +0 -1
  165. package/dist/db-DsPkOVEH.d.ts +0 -254
  166. package/dist/deploy-DonTr-CV.js.map +0 -1
  167. package/dist/doctor-DSIyCDg_.js +0 -346
  168. package/dist/doctor-DSIyCDg_.js.map +0 -1
  169. package/dist/dump-Bh5k26VQ.js +0 -94
  170. package/dist/dump-Bh5k26VQ.js.map +0 -1
  171. package/dist/errors-Dfa3p78c.js +0 -78
  172. package/dist/errors-Dfa3p78c.js.map +0 -1
  173. package/dist/export-DtF5tDIM.js +0 -401
  174. package/dist/export-DtF5tDIM.js.map +0 -1
  175. package/dist/fsck-D_djMO5D.js +0 -279
  176. package/dist/fsck-D_djMO5D.js.map +0 -1
  177. package/dist/http-DGd5tbNs.js.map +0 -1
  178. package/dist/index-0rZcMBwy.d.ts +0 -115
  179. package/dist/index-BNRh23K9.d.ts +0 -162
  180. package/dist/index-BYk9oCNf.d.ts +0 -1112
  181. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  182. package/dist/inspect-6WZ-pC7-.js +0 -133
  183. package/dist/inspect-6WZ-pC7-.js.map +0 -1
  184. package/dist/log-tail-D98U1JBo.js +0 -522
  185. package/dist/log-tail-D98U1JBo.js.map +0 -1
  186. package/dist/maintenance-B4Dki6Ig.js +0 -2157
  187. package/dist/maintenance-B4Dki6Ig.js.map +0 -1
  188. package/dist/maintenance-B_e0T99L.d.ts +0 -537
  189. package/dist/maintenance-C7coQp4c.js +0 -1418
  190. package/dist/maintenance-C7coQp4c.js.map +0 -1
  191. package/dist/normalize-rjnZLwS4.js +0 -133
  192. package/dist/normalize-rjnZLwS4.js.map +0 -1
  193. package/dist/observability-BmflLCdF.js.map +0 -1
  194. package/dist/plan-a7PJHBCy.js.map +0 -1
  195. package/dist/query-rAtXNQQB.js +0 -1773
  196. package/dist/query-rAtXNQQB.js.map +0 -1
  197. package/dist/rebuild-index-BVzQSZlm.js +0 -81
  198. package/dist/rebuild-index-BVzQSZlm.js.map +0 -1
  199. package/dist/request-u0M51mhJ.js +0 -72
  200. package/dist/request-u0M51mhJ.js.map +0 -1
  201. package/dist/restore-R-4rbciV.js +0 -778
  202. package/dist/restore-R-4rbciV.js.map +0 -1
  203. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  204. package/dist/runtime-spec-Dsw2-n8S.js.map +0 -1
  205. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  206. package/dist/src-BL_JoPTn.js.map +0 -1
  207. package/dist/src-CYHFDrKz.js +0 -536
  208. package/dist/src-CYHFDrKz.js.map +0 -1
  209. package/dist/src-DYZ4H1aF.js +0 -392
  210. package/dist/src-DYZ4H1aF.js.map +0 -1
  211. package/dist/subcommand-DoDA-K7d.js.map +0 -1
  212. package/dist/time-DUqvFMHq.js.map +0 -1
  213. package/dist/usage-DBV1eQHC.js.map +0 -1
  214. package/dist/validate-DtljsCh1.js.map +0 -1
  215. package/dist/wire-izfGZDvr.js.map +0 -1
@@ -1,12 +1,87 @@
1
- import { d as WHERE_ORDER_JSON_RESOLUTION, f as WRITE_BODY_SHAPE_RESOLUTION, i as serializeError, l as getLogger, s as CATEGORY, u as errorEnvelope } from "./observability-BmflLCdF.js";
2
- import { r as logSeqStartOf } from "./current-json-C6nhPOm1.js";
3
- import { t as BaerlyError } from "./errors-Dfa3p78c.js";
4
- import { D as validateWire } from "./maintenance-B4Dki6Ig.js";
5
- import { n as runAllWithMeta, r as runByIdWithMeta } from "./query-rAtXNQQB.js";
6
- import { t as EMPTY_PREDICATE_WIRE } from "./wire-izfGZDvr.js";
7
- import { i as str2uintDesc } from "./time-DUqvFMHq.js";
8
- import { n as getCurrentContext } from "./context-DRZ3tZ5l.js";
9
- //#region packages/protocol/src/log.ts
1
+ import { t as BaerlyError } from "./errors-7Rk1HGCE.js";
2
+ import { t as CAPACITY_WARNING_HEADER } from "./capacity-warning-header-BlVopyiI.js";
3
+ import { t as EMPTY_PREDICATE_WIRE } from "./wire-DndvKU-K.js";
4
+ import { a as str2uintDesc, i as isUuidV7 } from "./time-DRxTP9iv.js";
5
+ import { a as probeLogChunk, c as runAllWithMeta, f as CAPACITY_WARNING_FIELD, i as getLogEntry, l as runByIdWithMeta, m as validateWire, n as collectionReadContext, r as getCurrentJson, u as runInsert } from "./db-read-seams-BSs0m1z1.js";
6
+ import { n as WHERE_ORDER_JSON_RESOLUTION, r as WRITE_BODY_SHAPE_RESOLUTION, t as CODE_RESOLUTIONS } from "./code-resolution-CL_7L0wS.js";
7
+ import { b as isCallerFacing, d as isStorageRefusal, u as forwardProbeCap, x as markCallerFacing } from "./maintenance-DevB6z4e.js";
8
+ import { f as getLogger, m as errorEnvelope, n as getCurrentContext, o as serializeError, u as CATEGORY } from "./observability-C-ISCCLE.js";
9
+ import { r as currentRequestLedger } from "./ledger-Dj_bGgo0.js";
10
+ import { d as logSeqStartOf } from "./path-segment-DBXG26PW.js";
11
+ // packages/protocol/src/cursor.ts
12
+ /**
13
+ * `/v1/since` cursor codec — the composite `<generation>.<lsn>` token a
14
+ * long-poll client acks and resumes from.
15
+ *
16
+ * Kept separate from `log.ts` for the same reason as `log-key.ts`:
17
+ * `log.ts` carries the heavier `lsn` parsing runtime, and consumers that
18
+ * only need to split a cursor shouldn't drag it into their bundle
19
+ * closure. This module imports only `BaerlyError` and the
20
+ * `NO_GENERATION` sentinel from the zero-import `constants.ts`.
21
+ *
22
+ * ## Why the cursor is not just the LSN
23
+ *
24
+ * The seq embedded in an LSN identifies a `log/<seq>` slot, and slots
25
+ * are reused. `baerly admin restore --force` truncates a collection and
26
+ * reseeds `log_seq_start` to one past the highest *surviving* log
27
+ * object, which can land BELOW the old floor (the deliberate floor
28
+ * exemption — see invariant 12 in `docs/spec/sync-protocol.md`). A
29
+ * pre-restore cursor then passes `/v1/since`'s `cursorSeq <
30
+ * log_seq_start` gate and resumes into the new generation, silently
31
+ * skipping every restored row beneath it. The stream is gapped, not
32
+ * broken, which is the worst failure mode for a sync cursor.
33
+ *
34
+ * Pairing the LSN with the generation that minted it turns that silent
35
+ * gap into a `CursorExpired` telling the client to re-bootstrap.
36
+ *
37
+ * The token is opaque on the wire: clients ack and echo it, never parse
38
+ * it. `LogEntry.lsn` is unchanged — this shape exists only at the
39
+ * `/v1/since` boundary.
40
+ */
41
+ /**
42
+ * Separator between the generation and the LSN. The LSN is
43
+ * `_`-delimited (`<base32-time>_<session>_<seq>`) and a generation is
44
+ * lowercase hex, so `.` cannot occur in either half.
45
+ */
46
+ const CURSOR_SEPARATOR = ".";
47
+ /**
48
+ * Build the wire cursor for an entry's `lsn` under a manifest's
49
+ * `generation`.
50
+ *
51
+ * A manifest predating the field emits the LSN **bare**, not
52
+ * `-.<lsn>` — {@link parseCursor} maps both to {@link NO_GENERATION},
53
+ * so the comparison is unchanged either way. Keeping it bare confines
54
+ * the wire-shape change to collections that actually carry a nonce,
55
+ * instead of changing every cursor in the bucket on upgrade.
56
+ */
57
+ const formatCursor = (generation, lsn) => generation === void 0 ? lsn : `${generation}${CURSOR_SEPARATOR}${lsn}`;
58
+ /**
59
+ * Split a wire cursor into its generation and LSN halves.
60
+ *
61
+ * A cursor with no separator is a bare LSN from a build that predates
62
+ * the composite shape; it decodes to {@link NO_GENERATION} rather than
63
+ * throwing, so an in-flight client is not forced to re-bootstrap across
64
+ * a deploy that changed nothing about its collection.
65
+ *
66
+ * Throws `SchemaError` (→ HTTP 400) on more than one separator: that is
67
+ * malformed caller input, not a shape this build ever minted, and
68
+ * guessing which half is which would be worse than rejecting.
69
+ */
70
+ const parseCursor = (cursor) => {
71
+ const parts = cursor.split(CURSOR_SEPARATOR);
72
+ if (parts.length === 1) return {
73
+ generation: "-",
74
+ lsn: cursor
75
+ };
76
+ if (parts.length !== 2) throw new BaerlyError("SchemaError", `invalid cursor shape: ${JSON.stringify(cursor)} (expected "<generation>.<lsn>")`);
77
+ return {
78
+ generation: parts[0],
79
+ lsn: parts[1]
80
+ };
81
+ };
82
+ // packages/protocol/src/log.ts
83
+ /** Canonical seq token: the fixed width `countKey` emits. */
84
+ const SEQ_TOKEN_RE = new RegExp(`^[0-9a-v]{${Math.ceil(53 / 5)}}$`);
10
85
  /**
11
86
  * Extract the `session` and `seq` embedded in an `lsn` of shape
12
87
  * `<base32-time>_<session>_<seq>`. The seq portion is decoded as a
@@ -17,24 +92,47 @@ import { n as getCurrentContext } from "./context-DRZ3tZ5l.js";
17
92
  * `LogEntry` is in scope. When iterating `LogEntry` records, read
18
93
  * `entry.session` / `entry.seq` directly instead.
19
94
  *
20
- * Throws on malformed input; callers should pass only lsns minted
21
- * by `Writer.commit` (see
95
+ * Throws `BaerlyError{InvalidResponse}` on malformed input: a wrong
96
+ * segment count, or a seq token that is not exactly the canonical
97
+ * fixed-width base-32 string (`[0-9a-v]`, `ceil(COUNT_BIT_WIDTH / 5)`
98
+ * chars) decoding to a non-negative safe integer. Callers should pass
99
+ * only lsns minted by `Writer.commit` (see
22
100
  * `packages/server/src/writer.ts`).
23
101
  */
24
102
  const lsnParts = (lsn) => {
25
103
  const parts = lsn.split("_");
26
104
  if (parts.length !== 3) throw new BaerlyError("InvalidResponse", `invalid lsn shape: ${lsn}`);
105
+ const token = parts[2];
106
+ const seq = SEQ_TOKEN_RE.test(token) ? str2uintDesc(token, 53) : NaN;
107
+ if (!Number.isSafeInteger(seq) || seq < 0) throw new BaerlyError("InvalidResponse", `invalid lsn seq: ${lsn}`);
27
108
  return {
28
109
  session: parts[1],
29
- seq: str2uintDesc(parts[2], 53)
110
+ seq
30
111
  };
31
112
  };
32
- //#endregion
33
- //#region node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/compose.js
34
- var compose = (middleware, onError, onNotFound) => {
113
+ // node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/compose.js
114
+ /**
115
+ * Compose middleware functions into a single function based on `koa-compose` package.
116
+ *
117
+ * @template E - The environment type.
118
+ *
119
+ * @param {[[Function, unknown], unknown][] | [[Function]][]} middleware - An array of middleware functions and their corresponding parameters.
120
+ * @param {ErrorHandler<E>} [onError] - An optional error handler function.
121
+ * @param {NotFoundHandler<E>} [onNotFound] - An optional not-found handler function.
122
+ *
123
+ * @returns {(context: Context, next?: Next) => Promise<Context>} - A composed middleware function.
124
+ */
125
+ const compose = (middleware, onError, onNotFound) => {
35
126
  return (context, next) => {
36
127
  let index = -1;
37
128
  return dispatch(0);
129
+ /**
130
+ * Dispatch the middleware functions.
131
+ *
132
+ * @param {number} i - The current index in the middleware array.
133
+ *
134
+ * @returns {Promise<Context>} - A promise that resolves to the context.
135
+ */
38
136
  async function dispatch(i) {
39
137
  if (i <= index) throw new Error("next() called multiple times");
40
138
  index = i;
@@ -60,60 +158,66 @@ var compose = (middleware, onError, onNotFound) => {
60
158
  }
61
159
  };
62
160
  };
63
- //#endregion
64
- //#region node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/request/constants.js
65
- var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
66
- //#endregion
67
- //#region node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/utils/body.js
68
- var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
69
- const { all = false, dot = false } = options;
70
- const contentType = (request instanceof HonoRequest ? request.raw.headers : request.headers).get("Content-Type");
71
- if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) return parseFormData(request, {
72
- all,
73
- dot
74
- });
75
- return {};
161
+ // node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/url.js
162
+ const splitPath = (path) => {
163
+ const paths = path.split("/");
164
+ if (paths[0] === "") paths.shift();
165
+ return paths;
76
166
  };
77
- async function parseFormData(request, options) {
78
- const formData = await request.formData();
79
- if (formData) return convertFormDataToBodyData(formData, options);
80
- return {};
81
- }
82
- function convertFormDataToBodyData(formData, options) {
83
- const form = /* @__PURE__ */ Object.create(null);
84
- formData.forEach((value, key) => {
85
- if (!(options.all || key.endsWith("[]"))) form[key] = value;
86
- else handleParsingAllValues(form, key, value);
167
+ const splitRoutingPath = (routePath) => {
168
+ const { groups, path } = extractGroupsFromPath(routePath);
169
+ const paths = splitPath(path);
170
+ return replaceGroupMarks(paths, groups);
171
+ };
172
+ const extractGroupsFromPath = (path) => {
173
+ const groups = [];
174
+ path = path.replace(/\{[^}]+\}/g, (match, index) => {
175
+ const mark = `@${index}`;
176
+ groups.push([mark, match]);
177
+ return mark;
87
178
  });
88
- if (options.dot) Object.entries(form).forEach(([key, value]) => {
89
- if (key.includes(".")) {
90
- handleParsingNestedValues(form, key, value);
91
- delete form[key];
179
+ return {
180
+ groups,
181
+ path
182
+ };
183
+ };
184
+ const replaceGroupMarks = (paths, groups) => {
185
+ for (let i = groups.length - 1; i >= 0; i--) {
186
+ const [mark] = groups[i];
187
+ for (let j = paths.length - 1; j >= 0; j--) if (paths[j].includes(mark)) {
188
+ paths[j] = paths[j].replace(mark, groups[i][1]);
189
+ break;
92
190
  }
93
- });
94
- return form;
95
- }
96
- var handleParsingAllValues = (form, key, value) => {
97
- if (form[key] !== void 0) if (Array.isArray(form[key])) form[key].push(value);
98
- else form[key] = [form[key], value];
99
- else if (!key.endsWith("[]")) form[key] = value;
100
- else form[key] = [value];
191
+ }
192
+ return paths;
101
193
  };
102
- var handleParsingNestedValues = (form, key, value) => {
103
- if (/(?:^|\.)__proto__\./.test(key)) return;
104
- let nestedForm = form;
105
- const keys = key.split(".");
106
- keys.forEach((key2, index) => {
107
- if (index === keys.length - 1) nestedForm[key2] = value;
108
- else {
109
- if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) nestedForm[key2] = /* @__PURE__ */ Object.create(null);
110
- nestedForm = nestedForm[key2];
194
+ const patternCache = {};
195
+ const getPattern = (label, next) => {
196
+ if (label === "*") return "*";
197
+ const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
198
+ if (match) {
199
+ const cacheKey = `${label}#${next}`;
200
+ if (!patternCache[cacheKey]) {
201
+ if (match[2]) patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [
202
+ cacheKey,
203
+ match[1],
204
+ new RegExp(`^${match[2]}(?=/${next})`)
205
+ ] : [
206
+ label,
207
+ match[1],
208
+ new RegExp(`^${match[2]}$`)
209
+ ];
210
+ else patternCache[cacheKey] = [
211
+ label,
212
+ match[1],
213
+ true
214
+ ];
111
215
  }
112
- });
216
+ return patternCache[cacheKey];
217
+ }
218
+ return null;
113
219
  };
114
- //#endregion
115
- //#region node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/utils/url.js
116
- var tryDecode = (str, decoder) => {
220
+ const tryDecode = (str, decoder) => {
117
221
  try {
118
222
  return decoder(str);
119
223
  } catch {
@@ -126,8 +230,8 @@ var tryDecode = (str, decoder) => {
126
230
  });
127
231
  }
128
232
  };
129
- var tryDecodeURI = (str) => tryDecode(str, decodeURI);
130
- var getPath = (request) => {
233
+ const decodeURIWithPreservedPercent = (value) => decodeURI(value.includes("%25") ? value.replace(/%25/g, "%2525") : value);
234
+ const getPath = (request) => {
131
235
  const url = request.url;
132
236
  const start = url.indexOf("/", url.indexOf(":") + 4);
133
237
  let i = start;
@@ -138,43 +242,66 @@ var getPath = (request) => {
138
242
  const hashIndex = url.indexOf("#", i);
139
243
  const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
140
244
  const path = url.slice(start, end);
141
- return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
245
+ const decoded = tryDecode(path, decodeURIWithPreservedPercent);
246
+ if (/%(?![0-9A-Fa-f]{2})/.test(path)) {
247
+ const rewritten = new URL("http://localhost");
248
+ rewritten.pathname = decoded.replace(/[\\\t\n\r]/g, encodeURIComponent);
249
+ if (tryDecode(rewritten.pathname, decodeURIWithPreservedPercent) !== decoded) return tryDecode(path.replace(/%(?![0-9A-Fa-f]{2})/g, "%25"), decodeURIWithPreservedPercent);
250
+ }
251
+ return decoded;
142
252
  } else if (charCode === 63 || charCode === 35) break;
143
253
  }
144
254
  return url.slice(start, i);
145
255
  };
146
- var getPathNoStrict = (request) => {
256
+ const getPathNoStrict = (request) => {
147
257
  const result = getPath(request);
148
258
  return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
149
259
  };
150
- var mergePath = (base, sub, ...rest) => {
260
+ /**
261
+ * Merge paths.
262
+ * @param {string[]} ...paths - The paths to merge.
263
+ * @returns {string} The merged path.
264
+ * @example
265
+ * mergePath('/api', '/users') // '/api/users'
266
+ * mergePath('/api/', '/users') // '/api/users'
267
+ * mergePath('/api', '/') // '/api'
268
+ * mergePath('/api/', '/') // '/api/'
269
+ */
270
+ const mergePath = (base, sub, ...rest) => {
151
271
  if (rest.length) sub = mergePath(sub, ...rest);
152
272
  return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
153
273
  };
154
- var _decodeURI = (value) => {
155
- if (!/[%+]/.test(value)) return value;
274
+ const tryDecodeURIComponent = (str) => str.indexOf("%") !== -1 ? tryDecode(str, decodeURIComponent_) : str;
275
+ const _decodeURI = (value) => {
156
276
  if (value.indexOf("+") !== -1) value = value.replace(/\+/g, " ");
157
- return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
277
+ return tryDecodeURIComponent(value);
158
278
  };
159
- var _getQueryParam = (url, key, multiple) => {
279
+ const _getQueryParam = (url, key, multiple) => {
280
+ const hashIndex = url.indexOf("#", 8);
281
+ if (hashIndex !== -1) url = url.slice(0, hashIndex);
160
282
  let encoded;
161
- if (!multiple && key && !/[%+]/.test(key)) {
162
- let keyIndex2 = url.indexOf("?", 8);
163
- if (keyIndex2 === -1) return;
164
- if (!url.startsWith(key, keyIndex2 + 1)) keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
165
- while (keyIndex2 !== -1) {
166
- const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
167
- if (trailingKeyCode === 61) {
168
- const valueIndex = keyIndex2 + key.length + 2;
169
- const endIndex = url.indexOf("&", valueIndex);
170
- return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
171
- } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) return "";
172
- keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
283
+ if (!multiple && key && !/[%+&=]/.test(key)) {
284
+ const queryIndex = url.indexOf("?", 8);
285
+ let keyIndex = queryIndex;
286
+ if (keyIndex === -1) return;
287
+ if (!url.startsWith(key, keyIndex + 1)) keyIndex = url.indexOf(`&${key}`, keyIndex + 1);
288
+ while (keyIndex !== -1) {
289
+ const trailingKeyCode = url.charCodeAt(keyIndex + key.length + 1);
290
+ if (trailingKeyCode === 61 || trailingKeyCode === 38 || isNaN(trailingKeyCode)) {
291
+ if (keyIndex > queryIndex && /(?:^|&)[^=&]*[%+]/.test(url.slice(queryIndex + 1, keyIndex))) break;
292
+ if (trailingKeyCode === 61) {
293
+ const valueIndex = keyIndex + key.length + 2;
294
+ const endIndex = url.indexOf("&", valueIndex);
295
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
296
+ }
297
+ return "";
298
+ }
299
+ keyIndex = url.indexOf(`&${key}`, keyIndex + 1);
173
300
  }
174
301
  encoded = /[%+]/.test(url);
175
302
  if (!encoded) return;
176
303
  }
177
- const results = {};
304
+ const results = Object.create(null);
178
305
  encoded ??= /[%+]/.test(url);
179
306
  let keyIndex = url.indexOf("?", 8);
180
307
  while (keyIndex !== -1) {
@@ -198,14 +325,165 @@ var _getQueryParam = (url, key, multiple) => {
198
325
  }
199
326
  return key ? results[key] : results;
200
327
  };
201
- var getQueryParam = _getQueryParam;
202
- var getQueryParams = (url, key) => {
328
+ const getQueryParam = _getQueryParam;
329
+ const getQueryParams = (url, key) => {
203
330
  return _getQueryParam(url, key, true);
204
331
  };
205
- var decodeURIComponent_ = decodeURIComponent;
206
- //#endregion
207
- //#region node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/request.js
208
- var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
332
+ const decodeURIComponent_ = decodeURIComponent;
333
+ // node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/http-exception.js
334
+ /**
335
+ * `HTTPException` must be used when a fatal error such as authentication failure occurs.
336
+ *
337
+ * @see {@link https://hono.dev/docs/api/exception}
338
+ *
339
+ * @param {StatusCode} status - status code of HTTPException
340
+ * @param {HTTPExceptionOptions} options - options of HTTPException
341
+ * @param {HTTPExceptionOptions["res"]} options.res - response of options of HTTPException
342
+ * @param {HTTPExceptionOptions["message"]} options.message - message of options of HTTPException
343
+ * @param {HTTPExceptionOptions["cause"]} options.cause - cause of options of HTTPException
344
+ *
345
+ * @example
346
+ * ```ts
347
+ * import { HTTPException } from 'hono/http-exception'
348
+ *
349
+ * // ...
350
+ *
351
+ * app.post('/auth', async (c, next) => {
352
+ * // authentication
353
+ * if (authorized === false) {
354
+ * throw new HTTPException(401, { message: 'Custom error message' })
355
+ * }
356
+ * await next()
357
+ * })
358
+ * ```
359
+ */
360
+ var HTTPException = class extends Error {
361
+ res;
362
+ status;
363
+ /**
364
+ * Creates an instance of `HTTPException`.
365
+ * @param status - HTTP status code for the exception. Defaults to 500.
366
+ * @param options - Additional options for the exception.
367
+ */
368
+ constructor(status = 500, options) {
369
+ super(options?.message, { cause: options?.cause });
370
+ this.res = options?.res;
371
+ this.status = status;
372
+ }
373
+ /**
374
+ * Returns the response object associated with the exception.
375
+ * If a response object is not provided, a new response is created with the error message and status code.
376
+ * @returns The response object.
377
+ */
378
+ getResponse() {
379
+ if (this.res) return new Response(this.res.body, {
380
+ status: this.status,
381
+ headers: this.res.headers
382
+ });
383
+ return new Response(this.message, { status: this.status });
384
+ }
385
+ };
386
+ // node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/request/constants.js
387
+ const GET_MATCH_RESULT = Symbol();
388
+ // node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/buffer.js
389
+ const bufferToFormData = (arrayBuffer, contentType) => {
390
+ return new Response(arrayBuffer, { headers: { "Content-Type": contentType.replace(/^[^;]+/, (mediaType) => mediaType.toLowerCase()) } }).formData();
391
+ };
392
+ // node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/body.js
393
+ const MAX_NESTED_OBJECTS = 1e4;
394
+ const isRawRequest = (request) => "headers" in request;
395
+ const parseBody = async (request, options = Object.create(null)) => {
396
+ const { all = false, dot = false } = options;
397
+ const mediaType = (isRawRequest(request) ? request.headers : request.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();
398
+ if (mediaType === "multipart/form-data" || mediaType === "application/x-www-form-urlencoded") return parseFormData(request, {
399
+ all,
400
+ dot
401
+ });
402
+ return {};
403
+ };
404
+ /**
405
+ * Parses form data from a request.
406
+ *
407
+ * @template T - The type of the parsed body data.
408
+ * @param {HonoRequest | Request} request - The request object containing form data.
409
+ * @param {ParseBodyOptions} options - Options for parsing the form data.
410
+ * @returns {Promise<T>} The parsed body data.
411
+ */
412
+ async function parseFormData(request, options) {
413
+ if (!isRawRequest(request) && request.bodyCache.formData) return convertFormDataToBodyData(await request.bodyCache.formData, options);
414
+ const headers = isRawRequest(request) ? request.headers : request.raw.headers;
415
+ const arrayBuffer = await request.arrayBuffer();
416
+ const formDataPromise = bufferToFormData(arrayBuffer, headers.get("Content-Type") || "");
417
+ if (!isRawRequest(request)) request.bodyCache.formData = formDataPromise;
418
+ const formData = await formDataPromise;
419
+ if (formData) return convertFormDataToBodyData(formData, options);
420
+ return {};
421
+ }
422
+ /**
423
+ * Converts form data to body data based on the provided options.
424
+ *
425
+ * @template T - The type of the parsed body data.
426
+ * @param {FormData} formData - The form data to convert.
427
+ * @param {ParseBodyOptions} options - Options for parsing the form data.
428
+ * @returns {T} The converted body data.
429
+ */
430
+ function convertFormDataToBodyData(formData, options) {
431
+ const form = Object.create(null);
432
+ const nestingState = { count: 0 };
433
+ formData.forEach((value, key) => {
434
+ if (!(options.all || key.endsWith("[]"))) form[key] = value;
435
+ else handleParsingAllValues(form, key, value);
436
+ });
437
+ if (options.dot) Object.entries(form).forEach(([key, value]) => {
438
+ if (key.includes(".")) {
439
+ handleParsingNestedValues(form, key, value, nestingState);
440
+ delete form[key];
441
+ }
442
+ });
443
+ return form;
444
+ }
445
+ /**
446
+ * Handles parsing all values for a given key, supporting multiple values as arrays.
447
+ *
448
+ * @param {BodyData} form - The form data object.
449
+ * @param {string} key - The key to parse.
450
+ * @param {FormDataEntryValue} value - The value to assign.
451
+ */
452
+ const handleParsingAllValues = (form, key, value) => {
453
+ if (form[key] !== void 0) {
454
+ if (Array.isArray(form[key])) form[key].push(value);
455
+ else form[key] = [form[key], value];
456
+ } else if (!key.endsWith("[]")) form[key] = value;
457
+ else form[key] = [value];
458
+ };
459
+ /**
460
+ * Handles parsing nested values using dot notation keys.
461
+ *
462
+ * @param {BodyData} form - The form data object.
463
+ * @param {string} key - The dot notation key.
464
+ * @param {BodyDataValue} value - The value to assign.
465
+ * @param {{ count: number }} state - The state object tracking nesting depth.
466
+ */
467
+ const handleParsingNestedValues = (form, key, value, state) => {
468
+ if (/(?:^|\.)__proto__\./.test(key)) return;
469
+ let nestedForm = form;
470
+ const keys = key.split(".", 34);
471
+ if (keys.length > 33) throwNestingLimitExceeded();
472
+ keys.forEach((key, index) => {
473
+ if (index === keys.length - 1) nestedForm[key] = value;
474
+ else {
475
+ if (!nestedForm[key] || typeof nestedForm[key] !== "object" || Array.isArray(nestedForm[key]) || nestedForm[key] instanceof File) {
476
+ if (state.count++ >= MAX_NESTED_OBJECTS) throwNestingLimitExceeded();
477
+ nestedForm[key] = Object.create(null);
478
+ }
479
+ nestedForm = nestedForm[key];
480
+ }
481
+ });
482
+ };
483
+ const throwNestingLimitExceeded = () => {
484
+ throw new Error("Nesting limit exceeded");
485
+ };
486
+ // node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/request.js
209
487
  var HonoRequest = class {
210
488
  /**
211
489
  * `.raw` can get the raw Request object.
@@ -243,22 +521,21 @@ var HonoRequest = class {
243
521
  this.raw = request;
244
522
  this.path = path;
245
523
  this.#matchResult = matchResult;
246
- this.#validatedData = {};
247
524
  }
248
525
  param(key) {
249
526
  return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
250
527
  }
251
528
  #getDecodedParam(key) {
252
- const paramKey = this.#matchResult[0][this.routeIndex][1][key];
529
+ const paramKey = this.#matchResult[0][this.routeIndex]?.[1][key];
253
530
  const param = this.#getParamValue(paramKey);
254
- return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
531
+ return param && tryDecodeURIComponent(param);
255
532
  }
256
533
  #getAllDecodedParams() {
257
534
  const decoded = {};
258
- const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
535
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex]?.[1] ?? {});
259
536
  for (const key of keys) {
260
537
  const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
261
- if (value !== void 0) decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
538
+ if (value !== void 0) decoded[key] = tryDecodeURIComponent(value);
262
539
  }
263
540
  return decoded;
264
541
  }
@@ -273,7 +550,7 @@ var HonoRequest = class {
273
550
  }
274
551
  header(name) {
275
552
  if (name) return this.raw.headers.get(name) ?? void 0;
276
- const headerData = {};
553
+ const headerData = Object.create(null);
277
554
  this.raw.headers.forEach((value, key) => {
278
555
  headerData[key] = value;
279
556
  });
@@ -286,10 +563,10 @@ var HonoRequest = class {
286
563
  const { bodyCache, raw } = this;
287
564
  const cachedBody = bodyCache[key];
288
565
  if (cachedBody) return cachedBody;
289
- const anyCachedKey = Object.keys(bodyCache)[0];
290
- if (anyCachedKey) return bodyCache[anyCachedKey].then((body) => {
566
+ for (const anyCachedKey in bodyCache) return bodyCache[anyCachedKey].then((body) => {
291
567
  if (anyCachedKey === "json") body = JSON.stringify(body);
292
- return new Response(body)[key]();
568
+ const contentType = anyCachedKey === "formData" ? void 0 : raw.headers.get("content-type");
569
+ return new Response(body, { headers: contentType ? { "Content-Type": contentType } : void 0 })[key]();
293
570
  });
294
571
  return bodyCache[key] = raw[key]();
295
572
  };
@@ -386,13 +663,13 @@ var HonoRequest = class {
386
663
  * @param data - The validated data to add.
387
664
  */
388
665
  addValidatedData(target, data) {
389
- this.#validatedData[target] = data;
666
+ (this.#validatedData ??= {})[target] = data;
390
667
  }
391
668
  valid(target) {
392
- return this.#validatedData[target];
669
+ return this.#validatedData?.[target];
393
670
  }
394
671
  /**
395
- * `.url()` can get the request url strings.
672
+ * `.url` can get the request url strings.
396
673
  *
397
674
  * @see {@link https://hono.dev/docs/api/request#url}
398
675
  *
@@ -408,7 +685,7 @@ var HonoRequest = class {
408
685
  return this.raw.url;
409
686
  }
410
687
  /**
411
- * `.method()` can get the method name of the request.
688
+ * `.method` can get the method name of the request.
412
689
  *
413
690
  * @see {@link https://hono.dev/docs/api/request#method}
414
691
  *
@@ -426,7 +703,7 @@ var HonoRequest = class {
426
703
  return this.#matchResult;
427
704
  }
428
705
  /**
429
- * `.matchedRoutes()` can return a matched route in the handler
706
+ * `.matchedRoutes` can return a matched route in the handler
430
707
  *
431
708
  * @deprecated
432
709
  *
@@ -456,7 +733,7 @@ var HonoRequest = class {
456
733
  return this.#matchResult[0].map(([[, route]]) => route);
457
734
  }
458
735
  /**
459
- * `routePath()` can retrieve the path registered within the handler
736
+ * `.routePath` can retrieve the path registered within the handler
460
737
  *
461
738
  * @deprecated
462
739
  *
@@ -475,20 +752,23 @@ var HonoRequest = class {
475
752
  return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
476
753
  }
477
754
  };
478
- //#endregion
479
- //#region node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/utils/html.js
480
- var HtmlEscapedCallbackPhase = {
755
+ // node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/html.js
756
+ /**
757
+ * @module
758
+ * HTML utility.
759
+ */
760
+ const HtmlEscapedCallbackPhase = {
481
761
  Stringify: 1,
482
762
  BeforeStream: 2,
483
763
  Stream: 3
484
764
  };
485
- var raw = (value, callbacks) => {
765
+ const raw = (value, callbacks) => {
486
766
  const escapedString = new String(value);
487
767
  escapedString.isEscaped = true;
488
768
  escapedString.callbacks = callbacks;
489
769
  return escapedString;
490
770
  };
491
- var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
771
+ const resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
492
772
  if (typeof str === "object" && !(str instanceof String)) {
493
773
  if (!(str instanceof Promise)) str = str.toString();
494
774
  if (str instanceof Promise) str = await str;
@@ -501,20 +781,19 @@ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) =>
501
781
  phase,
502
782
  buffer,
503
783
  context
504
- }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
784
+ }))).then((res) => Promise.all(res.filter(Boolean).map((str) => resolveCallback(str, phase, false, context, buffer))).then(() => buffer[0]));
505
785
  if (preserveCallbacks) return raw(await resStr, callbacks);
506
786
  else return resStr;
507
787
  };
508
- //#endregion
509
- //#region node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/context.js
510
- var TEXT_PLAIN = "text/plain; charset=UTF-8";
511
- var setDefaultContentType = (contentType, headers) => {
788
+ // node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/context.js
789
+ const TEXT_PLAIN = "text/plain; charset=UTF-8";
790
+ const setDefaultContentType = (contentType, headers) => {
512
791
  return {
513
792
  "Content-Type": contentType,
514
793
  ...headers
515
794
  };
516
795
  };
517
- var createResponseInstance = (body, init) => new Response(body, init);
796
+ const createResponseInstance = (body, init) => new Response(body, init);
518
797
  var Context = class {
519
798
  #rawRequest;
520
799
  #req;
@@ -694,12 +973,16 @@ var Context = class {
694
973
  * c.header('X-Message', 'Hello!')
695
974
  * c.header('Content-Type', 'text/plain')
696
975
  *
976
+ * // Append multiple headers using the append option (e.g. Vary)
977
+ * c.header('Vary', 'Accept-Encoding', { append: true })
978
+ * c.header('Vary', 'User-Agent', { append: true })
979
+ *
697
980
  * return c.body('Thank you for coming')
698
981
  * })
699
982
  * ```
700
983
  */
701
984
  header = (name, value, options) => {
702
- if (this.finalized) this.#res = createResponseInstance(this.#res.body, this.#res);
985
+ if (this.finalized && !this.#res.bodyUsed) this.#res = createResponseInstance(this.#res.body, this.#res);
703
986
  const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
704
987
  if (value === void 0) headers.delete(name);
705
988
  else if (options?.append) headers.append(name, value);
@@ -756,20 +1039,33 @@ var Context = class {
756
1039
  return Object.fromEntries(this.#var);
757
1040
  }
758
1041
  #newResponse(data, arg, headers) {
759
- const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
760
- if (typeof arg === "object" && "headers" in arg) {
761
- const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
762
- for (const [key, value] of argHeaders) if (key.toLowerCase() === "set-cookie") responseHeaders.append(key, value);
1042
+ let responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders;
1043
+ if (typeof arg === "object" && arg.headers) {
1044
+ responseHeaders ??= new Headers();
1045
+ for (const [key, value] of new Headers(arg.headers)) if (key === "set-cookie") responseHeaders.append(key, value);
763
1046
  else responseHeaders.set(key, value);
764
1047
  }
765
- if (headers) for (const [k, v] of Object.entries(headers)) if (typeof v === "string") responseHeaders.set(k, v);
766
- else {
767
- responseHeaders.delete(k);
768
- for (const v2 of v) responseHeaders.append(k, v2);
1048
+ if (headers) {
1049
+ if (!responseHeaders) {
1050
+ let count = 0;
1051
+ for (const k in headers) if (++count > 1 || typeof headers[k] !== "string") {
1052
+ responseHeaders = new Headers();
1053
+ break;
1054
+ }
1055
+ }
1056
+ if (responseHeaders) for (const k in headers) {
1057
+ const v = headers[k];
1058
+ if (typeof v === "string") responseHeaders.set(k, v);
1059
+ else {
1060
+ responseHeaders.delete(k);
1061
+ for (const v2 of v) responseHeaders.append(k, v2);
1062
+ }
1063
+ }
769
1064
  }
1065
+ const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
770
1066
  return createResponseInstance(data, {
771
- status: typeof arg === "number" ? arg : arg?.status ?? this.#status,
772
- headers: responseHeaders
1067
+ status,
1068
+ headers: responseHeaders ?? headers
773
1069
  });
774
1070
  }
775
1071
  newResponse = (...args) => this.#newResponse(...args);
@@ -826,7 +1122,7 @@ var Context = class {
826
1122
  return this.#newResponse(JSON.stringify(object), arg, setDefaultContentType("application/json", headers));
827
1123
  };
828
1124
  html = (html, arg, headers) => {
829
- const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
1125
+ const res = (html) => this.#newResponse(html, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
830
1126
  return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
831
1127
  };
832
1128
  /**
@@ -866,26 +1162,133 @@ var Context = class {
866
1162
  return this.#notFoundHandler(this);
867
1163
  };
868
1164
  };
869
- //#endregion
870
- //#region node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/router.js
871
- var METHODS = [
1165
+ // node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/helper/route/index.js
1166
+ /**
1167
+ * Get matched routes in the handler
1168
+ *
1169
+ * @param {Context} c - The context object
1170
+ * @returns An array of matched routes
1171
+ *
1172
+ * @example
1173
+ * ```ts
1174
+ * import { matchedRoutes } from 'hono/route'
1175
+ *
1176
+ * app.use('*', async function logger(c, next) {
1177
+ * await next()
1178
+ * matchedRoutes(c).forEach(({ handler, method, path }, i) => {
1179
+ * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
1180
+ * console.log(
1181
+ * method,
1182
+ * ' ',
1183
+ * path,
1184
+ * ' '.repeat(Math.max(10 - path.length, 0)),
1185
+ * name,
1186
+ * i === c.req.routeIndex ? '<- respond from here' : ''
1187
+ * )
1188
+ * })
1189
+ * })
1190
+ * ```
1191
+ */
1192
+ const matchedRoutes = (c) => c.req[GET_MATCH_RESULT][0].map(([[, route]]) => route);
1193
+ /**
1194
+ * Get the route path registered within the handler
1195
+ *
1196
+ * @param {Context} c - The context object
1197
+ * @param {number} index - The index of the route from which to retrieve the path, similar to Array.prototype.at(), where a negative number is the index counted from the end of the matching route. Defaults to the current route index.
1198
+ * @returns The route path registered within the handler
1199
+ *
1200
+ * @example
1201
+ * ```ts
1202
+ * import { routePath } from 'hono/route'
1203
+ *
1204
+ * app.use('*', (c, next) => {
1205
+ * console.log(routePath(c)) // '*'
1206
+ * console.log(routePath(c, -1)) // '/posts/:id'
1207
+ * return next()
1208
+ * })
1209
+ *
1210
+ * app.get('/posts/:id', (c) => {
1211
+ * return c.text(routePath(c)) // '/posts/:id'
1212
+ * })
1213
+ * ```
1214
+ */
1215
+ const routePath = (c, index) => matchedRoutes(c).at(index ?? c.req.routeIndex)?.path ?? "";
1216
+ // node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/router.js
1217
+ /**
1218
+ * Array of supported HTTP methods.
1219
+ */
1220
+ const METHODS = [
872
1221
  "get",
873
1222
  "post",
874
1223
  "put",
875
1224
  "delete",
876
1225
  "options",
877
- "patch"
1226
+ "patch",
1227
+ "query"
878
1228
  ];
1229
+ /**
1230
+ * Error class representing an unsupported path error.
1231
+ */
879
1232
  var UnsupportedPathError = class extends Error {};
880
- //#endregion
881
- //#region node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/utils/constants.js
882
- var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
883
- //#endregion
884
- //#region node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/hono-base.js
885
- var notFoundHandler = (c) => {
1233
+ // node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/constants.js
1234
+ /**
1235
+ * Constant used to mark a composed handler.
1236
+ */
1237
+ const COMPOSED_HANDLER = "__COMPOSED_HANDLER";
1238
+ // node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/mount.js
1239
+ const countTrailingSlashes = (path) => {
1240
+ let index = path.length;
1241
+ while (index > 0 && path.charCodeAt(index - 1) === 47) index--;
1242
+ return path.length - index;
1243
+ };
1244
+ const getPathPrefixLength = (c, pathPrefix, routePath) => {
1245
+ if (!/[:*]/.test(pathPrefix)) return pathPrefix.length;
1246
+ const path = c.req.path;
1247
+ const matchResult = c.req[GET_MATCH_RESULT];
1248
+ const paramNames = /* @__PURE__ */ new Set();
1249
+ let length = 0;
1250
+ for (const part of splitRoutingPath(pathPrefix)) {
1251
+ if (part[0] === ":" && part.endsWith("}?")) throw new Error(`mount(): Optional regular expression parameters are not supported in "${routePath}".`);
1252
+ const pattern = getPattern(part);
1253
+ if (pattern && pattern !== "*") {
1254
+ const name = pattern[1];
1255
+ if (paramNames.has(name)) throw new Error(`mount(): Duplicate path parameter "${name}" in "${routePath}".`);
1256
+ paramNames.add(name);
1257
+ }
1258
+ if (pattern && pattern !== "*" && pattern[2] !== true) {
1259
+ const value = matchResult.length === 2 ? matchResult[1][matchResult[0][c.req.routeIndex][1][pattern[1]]] : matchResult[0][c.req.routeIndex][1][pattern[1]];
1260
+ length += value.length + 1;
1261
+ } else if (pattern || part.endsWith("*")) {
1262
+ const end = path.indexOf("/", length + 1);
1263
+ length = end === -1 ? path.length : end;
1264
+ } else length += part.length + 1;
1265
+ }
1266
+ return length;
1267
+ };
1268
+ const createMountedRequest = (c, pathPrefix, routePath) => {
1269
+ if (/[^/]\*$/.test(routePath)) throw new Error(`mount(): Wildcard must follow "/" in "${routePath}".`);
1270
+ const prefixLength = getPathPrefixLength(c, pathPrefix, routePath);
1271
+ const path = c.req.path.slice(prefixLength) || "/";
1272
+ if (prefixLength > c.req.path.length || path[0] !== "/" || /\/(?:\.|%2e){1,2}(?:\/|$)/i.test(path)) throw new HTTPException(400, { message: "Invalid mounted path" });
1273
+ const rawUrl = c.req.raw.url;
1274
+ if (/^[^/?#]*\/\/[^/?#\\]*[?#\\]/.test(rawUrl)) throw new HTTPException(400, { message: "Invalid mounted path" });
1275
+ const rawPathEnd = rawUrl.search(/[?#]/);
1276
+ const rawTrailingSlashes = countTrailingSlashes(rawPathEnd === -1 ? rawUrl : rawUrl.slice(0, rawPathEnd));
1277
+ if (rawTrailingSlashes > 1 && countTrailingSlashes(c.req.path) === rawTrailingSlashes - 1) throw new HTTPException(400, { message: "Invalid mounted path" });
1278
+ const url = new URL(rawUrl);
1279
+ url.pathname = path.replace(/[\\\t\n\r]/g, encodeURIComponent);
1280
+ if (path.includes("%")) {}
1281
+ return new Request(url, c.req.raw);
1282
+ };
1283
+ // node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/hono-base.js
1284
+ /**
1285
+ * @module
1286
+ * This module is the base module for the Hono object.
1287
+ */
1288
+ const notFoundHandler = (c) => {
886
1289
  return c.text("404 Not Found", 404);
887
1290
  };
888
- var errorHandler = (err, c) => {
1291
+ const errorHandler = (err, c) => {
889
1292
  if ("getResponse" in err) {
890
1293
  const res = err.getResponse();
891
1294
  return c.newResponse(res.body, res);
@@ -893,13 +1296,14 @@ var errorHandler = (err, c) => {
893
1296
  console.error(err);
894
1297
  return c.text("Internal Server Error", 500);
895
1298
  };
896
- var Hono$1 = class _Hono {
1299
+ var Hono$1 = class Hono {
897
1300
  get;
898
1301
  post;
899
1302
  put;
900
1303
  delete;
901
1304
  options;
902
1305
  patch;
1306
+ query;
903
1307
  all;
904
1308
  on;
905
1309
  use;
@@ -911,10 +1315,11 @@ var Hono$1 = class _Hono {
911
1315
  constructor(options = {}) {
912
1316
  [...METHODS, "all"].forEach((method) => {
913
1317
  this[method] = (args1, ...args) => {
1318
+ const methodName = method.toUpperCase();
914
1319
  if (typeof args1 === "string") this.#path = args1;
915
- else this.#addRoute(method, this.#path, args1);
1320
+ else this.#addRoute(methodName, this.#path, args1);
916
1321
  args.forEach((handler) => {
917
- this.#addRoute(method, this.#path, handler);
1322
+ this.#addRoute(methodName, this.#path, handler);
918
1323
  });
919
1324
  return this;
920
1325
  };
@@ -922,9 +1327,10 @@ var Hono$1 = class _Hono {
922
1327
  this.on = (method, path, ...handlers) => {
923
1328
  for (const p of [path].flat()) {
924
1329
  this.#path = p;
925
- for (const m of [method].flat()) handlers.map((handler) => {
926
- this.#addRoute(m.toUpperCase(), this.#path, handler);
927
- });
1330
+ for (const m of [method].flat()) {
1331
+ const methodName = m.toUpperCase();
1332
+ for (const handler of handlers) this.#addRoute(methodName, this.#path, handler);
1333
+ }
928
1334
  }
929
1335
  return this;
930
1336
  };
@@ -944,7 +1350,7 @@ var Hono$1 = class _Hono {
944
1350
  this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
945
1351
  }
946
1352
  #clone() {
947
- const clone = new _Hono({
1353
+ const clone = new Hono({
948
1354
  router: this.router,
949
1355
  getPath: this.getPath
950
1356
  });
@@ -1046,12 +1452,16 @@ var Hono$1 = class _Hono {
1046
1452
  /**
1047
1453
  * `.mount()` allows you to mount applications built with other frameworks into your Hono application.
1048
1454
  *
1455
+ * @deprecated Use `mount()` from `hono/mount` instead. `.mount()` will be removed in v5.
1456
+ *
1049
1457
  * @see {@link https://hono.dev/docs/api/hono#mount}
1050
1458
  *
1051
1459
  * @param {string} path - base Path
1052
1460
  * @param {Function} applicationHandler - other Request Handler
1053
1461
  * @param {MountOptions} [options] - options of `.mount()`
1054
1462
  * @returns {Hono} mounted Hono instance
1463
+ * @throws {Error} If automatic request rewriting encounters duplicate path parameter names or an optional regular expression parameter.
1464
+ * @throws {HTTPException} With status 400 if automatic request rewriting cannot safely preserve the routed path.
1055
1465
  *
1056
1466
  * @example
1057
1467
  * ```ts
@@ -1078,15 +1488,17 @@ var Hono$1 = class _Hono {
1078
1488
  mount(path, applicationHandler, options) {
1079
1489
  let replaceRequest;
1080
1490
  let optionHandler;
1081
- if (options) if (typeof options === "function") optionHandler = options;
1082
- else {
1083
- optionHandler = options.optionHandler;
1084
- if (options.replaceRequest === false) replaceRequest = (request) => request;
1085
- else replaceRequest = options.replaceRequest;
1491
+ if (options) {
1492
+ if (typeof options === "function") optionHandler = options;
1493
+ else {
1494
+ optionHandler = options.optionHandler;
1495
+ if (options.replaceRequest === false) replaceRequest = (request) => request;
1496
+ else replaceRequest = options.replaceRequest;
1497
+ }
1086
1498
  }
1087
1499
  const getOptions = optionHandler ? (c) => {
1088
- const options2 = optionHandler(c);
1089
- return Array.isArray(options2) ? options2 : [options2];
1500
+ const options = optionHandler(c);
1501
+ return Array.isArray(options) ? options : [options];
1090
1502
  } : (c) => {
1091
1503
  let executionContext = void 0;
1092
1504
  try {
@@ -1094,17 +1506,12 @@ var Hono$1 = class _Hono {
1094
1506
  } catch {}
1095
1507
  return [c.env, executionContext];
1096
1508
  };
1097
- replaceRequest ||= (() => {
1098
- const mergedPath = mergePath(this._basePath, path);
1099
- const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
1100
- return (request) => {
1101
- const url = new URL(request.url);
1102
- url.pathname = this.getPath(request).slice(pathPrefixLength) || "/";
1103
- return new Request(url, request);
1104
- };
1105
- })();
1509
+ const defaultReplaceRequest = (c) => {
1510
+ const mountedRoutePath = routePath(c);
1511
+ return createMountedRequest(c, mountedRoutePath.replace(/\/?\*$/, ""), mountedRoutePath);
1512
+ };
1106
1513
  const handler = async (c, next) => {
1107
- const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
1514
+ const res = await applicationHandler(replaceRequest ? replaceRequest(c.req.raw) : defaultReplaceRequest(c), ...getOptions(c));
1108
1515
  if (res) return res;
1109
1516
  await next();
1110
1517
  };
@@ -1112,7 +1519,6 @@ var Hono$1 = class _Hono {
1112
1519
  return this;
1113
1520
  }
1114
1521
  #addRoute(method, path, handler, baseRoutePath) {
1115
- method = method.toUpperCase();
1116
1522
  path = mergePath(this._basePath, path);
1117
1523
  const r = {
1118
1524
  basePath: baseRoutePath !== void 0 ? mergePath(this._basePath, baseRoutePath) : this._basePath,
@@ -1166,8 +1572,8 @@ var Hono$1 = class _Hono {
1166
1572
  * @see {@link https://hono.dev/docs/api/hono#fetch}
1167
1573
  *
1168
1574
  * @param {Request} request - request Object of request
1169
- * @param {Env} Env - env Object
1170
- * @param {ExecutionContext} - context of execution
1575
+ * @param {Env} env - env Object
1576
+ * @param {ExecutionContext} executionCtx - context of execution
1171
1577
  * @returns {Response | Promise<Response>} response of request
1172
1578
  *
1173
1579
  */
@@ -1214,15 +1620,14 @@ var Hono$1 = class _Hono {
1214
1620
  });
1215
1621
  };
1216
1622
  };
1217
- //#endregion
1218
- //#region node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/router/pattern-router/router.js
1219
- var emptyParams = /* @__PURE__ */ Object.create(null);
1623
+ // node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/router/pattern-router/router.js
1624
+ const emptyParams = Object.create(null);
1220
1625
  var PatternRouter = class {
1221
1626
  name = "PatternRouter";
1222
1627
  #routes = [];
1223
1628
  add(method, path, handler) {
1224
- const endsWithWildcard = path.at(-1) === "*";
1225
- if (endsWithWildcard) path = path.slice(0, -2);
1629
+ const suffix = path.endsWith("/*") ? "(?:$|/)" : path.endsWith("*") ? "" : "/?$";
1630
+ path = path.replace(/\*$/, "");
1226
1631
  if (path.at(-1) === "?") {
1227
1632
  path = path.slice(0, -1);
1228
1633
  this.add(method, path.replace(/\/[^/]+$/, ""), handler);
@@ -1233,7 +1638,7 @@ var PatternRouter = class {
1233
1638
  });
1234
1639
  try {
1235
1640
  this.#routes.push([
1236
- new RegExp(`^${parts.join("")}${endsWithWildcard ? "" : "/?$"}`),
1641
+ new RegExp(`^${parts.join("")}${suffix}`),
1237
1642
  method,
1238
1643
  handler
1239
1644
  ]);
@@ -1253,8 +1658,11 @@ var PatternRouter = class {
1253
1658
  return [handlers];
1254
1659
  }
1255
1660
  };
1256
- //#endregion
1257
- //#region node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/preset/tiny.js
1661
+ // node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/preset/tiny.js
1662
+ /**
1663
+ * @module
1664
+ * The preset that uses `PatternRouter`.
1665
+ */
1258
1666
  var Hono = class extends Hono$1 {
1259
1667
  constructor(options = {}) {
1260
1668
  super(options);
@@ -1263,6 +1671,35 @@ var Hono = class extends Hono$1 {
1263
1671
  };
1264
1672
  const LSN_RE = new RegExp(`^[0-9a-v]+_[0-9a-v]+_[0-9a-v]{${Math.ceil(53 / 5)}}$`);
1265
1673
  /**
1674
+ * Generation half of a cursor: lowercase hex as minted by
1675
+ * `mintGeneration`, or the `NO_GENERATION` sentinel for a manifest that
1676
+ * predates the field.
1677
+ */
1678
+ const GENERATION_RE = /^(?:[0-9a-f]+|-)$/;
1679
+ /** `LSN_RE` admits 55-bit seq tokens; `lsnParts` rejects those outside the safe range. */
1680
+ const hasSafeSeq = (lsn) => {
1681
+ try {
1682
+ lsnParts(lsn);
1683
+ return true;
1684
+ } catch {
1685
+ return false;
1686
+ }
1687
+ };
1688
+ /**
1689
+ * Reject a malformed cursor before it reaches storage, and return its
1690
+ * decoded halves.
1691
+ *
1692
+ * Shape validation lives here rather than in the codec because the
1693
+ * codec is a protocol leaf with no opinion about which LSN dialect a
1694
+ * given build mints — `LSN_RE` is that opinion, and it is derived from
1695
+ * `COUNT_BIT_WIDTH`.
1696
+ */
1697
+ const decodeCursor = (cursor) => {
1698
+ const parts = parseCursor(cursor);
1699
+ if (!GENERATION_RE.test(parts.generation) || !LSN_RE.test(parts.lsn) || !hasSafeSeq(parts.lsn)) throw new BaerlyError("SchemaError", `cursor: invalid shape (expected a cursor returned by a prior SinceResponse); got ${JSON.stringify(cursor)}`);
1700
+ return parts;
1701
+ };
1702
+ /**
1266
1703
  * Hard cap on log entries returned in a single poll cycle. 1024 is
1267
1704
  * comfortably above the largest expected per-poll batch under the
1268
1705
  * production 1 s poll interval and bounds the worst-case memory
@@ -1291,6 +1728,12 @@ const DEFAULT_TIMEOUT_MS = 25e3;
1291
1728
  */
1292
1729
  const DEFAULT_POLL_INTERVAL_MS = 1e3;
1293
1730
  /**
1731
+ * Storage calls one poll cycle that finds nothing costs: the
1732
+ * `current.json` GET and the probe GET that finds the tail at the
1733
+ * cursor. A cycle starts only with this much room on the ledger.
1734
+ */
1735
+ const IDLE_POLL_CALLS = 2;
1736
+ /**
1294
1737
  * Long-poll wrapper around {@link listEventsSince}. Returns as soon
1295
1738
  * as the first non-empty poll lands, or when the wall-clock timeout
1296
1739
  * elapses (whichever comes first). On timeout the response is
@@ -1298,24 +1741,29 @@ const DEFAULT_POLL_INTERVAL_MS = 1e3;
1298
1741
  * because the response body carries the unchanged cursor the client
1299
1742
  * needs for the next poll cycle.
1300
1743
  *
1301
- * @throws BaerlyError{code:"SchemaError"} — invalid cursor shape, or
1302
- * the cursor references a log entry that has been folded into a
1303
- * snapshot and GC'd.
1744
+ * @throws BaerlyError{code:"SchemaError"} — invalid cursor shape.
1745
+ * @throws BaerlyError{code:"CursorExpired"} — the cursor sits below the
1746
+ * retained log, or was minted in a truncated generation.
1304
1747
  */
1305
1748
  async function longPollSince(opts) {
1306
1749
  const { db, collection, cursor, signal } = opts;
1307
1750
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1308
1751
  const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
1309
- if (cursor.length > 0 && !LSN_RE.test(cursor)) throw new BaerlyError("SchemaError", `cursor: invalid shape (expected an lsn returned by a prior SinceResponse); got ${JSON.stringify(cursor)}`);
1310
- const initial = await listEventsSince({
1752
+ if (cursor.length > 0) decodeCursor(cursor);
1753
+ const budget = pollBudget();
1754
+ if (budget.left() < IDLE_POLL_CALLS) throw new BaerlyError("MaintenancePending", `collection ${JSON.stringify(collection)}: this request has too few storage calls left to poll the change feed, so it was not polled. Retry after 1s.`, {
1755
+ resolution: "Retry after the delay in retryAfter (Retry-After header, seconds) with the same cursor: nothing was read and the cursor is still valid.",
1756
+ retryAfter: 1
1757
+ });
1758
+ const initial = await pollOnce({
1311
1759
  db,
1312
1760
  collection,
1313
1761
  cursor,
1314
1762
  signal
1315
- });
1316
- if (initial.length > 0) return {
1317
- events: initial,
1318
- next_cursor: initial[initial.length - 1].lsn
1763
+ }, budget);
1764
+ if (initial.events.length > 0) return {
1765
+ events: initial.events,
1766
+ next_cursor: nextCursor(initial)
1319
1767
  };
1320
1768
  const deadline = Date.now() + timeoutMs;
1321
1769
  return new Promise((resolve, reject) => {
@@ -1355,18 +1803,25 @@ async function longPollSince(opts) {
1355
1803
  }
1356
1804
  const tick = async () => {
1357
1805
  if (settled) return;
1806
+ if (budget.left() < IDLE_POLL_CALLS) {
1807
+ settleResolve({
1808
+ events: [],
1809
+ next_cursor: cursor
1810
+ });
1811
+ return;
1812
+ }
1358
1813
  try {
1359
- const events = await listEventsSince({
1814
+ const polled = await pollOnce({
1360
1815
  db,
1361
1816
  collection,
1362
1817
  cursor,
1363
1818
  signal
1364
- });
1819
+ }, budget);
1365
1820
  if (settled) return;
1366
- if (events.length > 0) {
1821
+ if (polled.events.length > 0) {
1367
1822
  settleResolve({
1368
- events,
1369
- next_cursor: events[events.length - 1].lsn
1823
+ events: polled.events,
1824
+ next_cursor: nextCursor(polled)
1370
1825
  });
1371
1826
  return;
1372
1827
  }
@@ -1396,43 +1851,123 @@ async function longPollSince(opts) {
1396
1851
  * return the parsed `LogEntry`s in causal order.
1397
1852
  *
1398
1853
  * On-bucket log keys are `log/<seq>.json` — the same shape
1399
- * `compactor` / `gc` / `rebuild-index` walk. Iterating
1854
+ * `compactor` / `gc` walk. Iterating
1400
1855
  * `[startSeq, endSeq)` and GET-ing each key directly avoids the
1401
1856
  * lex-`startAfter` hazard on integer filenames (`10.json` sorts
1402
1857
  * before `2.json` lex) and gives us the global causal ordering for
1403
1858
  * free — `seq` is monotonic across writer sessions.
1404
1859
  *
1405
1860
  * No `current.json` yet → `[]` (clients can poll a not-yet-existing
1406
- * collection without erroring). Cursor inside `[0, log_seq_start)` →
1407
- * `BaerlyError{code:"SchemaError"}`.
1861
+ * collection without erroring). Under a request ledger that runs out,
1862
+ * the result is a prefix of the entries past the cursor. Cursor inside `[0, log_seq_start)`, or
1863
+ * minted in a truncated generation → `BaerlyError{code:"CursorExpired"}`.
1408
1864
  */
1409
1865
  async function listEventsSince(opts) {
1866
+ return (await pollOnce(opts, pollBudget())).events;
1867
+ }
1868
+ const pollBudget = () => {
1869
+ let pool;
1870
+ return {
1871
+ left: () => forwardProbeCap(pool ?? "external").slots,
1872
+ observe: async (fn) => {
1873
+ const ledger = currentRequestLedger();
1874
+ if (ledger === void 0 || pool !== void 0) return fn();
1875
+ const before = ledger.charged;
1876
+ try {
1877
+ return await fn();
1878
+ } finally {
1879
+ const after = ledger.charged;
1880
+ if (after.external > before.external) pool = "external";
1881
+ else if (after.internal > before.internal) pool = "internal";
1882
+ }
1883
+ }
1884
+ };
1885
+ };
1886
+ /**
1887
+ * The body of {@link listEventsSince}, additionally surfacing the
1888
+ * manifest `generation` the poll read.
1889
+ *
1890
+ * `longPollSince` needs that generation to mint `next_cursor`, and
1891
+ * re-reading `current.json` to get it would add a Class A op to every
1892
+ * poll — the idle-reader cost bound this protocol is built around.
1893
+ * {@link listEventsSince} is public surface pinned by
1894
+ * `tests/integration/public-surface.test.ts`, so it keeps returning a
1895
+ * bare array and this internal variant carries the extra field.
1896
+ *
1897
+ * `generation` is `undefined` when the collection has no `current.json`
1898
+ * (no events either, so it is never consumed) or when the manifest
1899
+ * predates the field.
1900
+ *
1901
+ * Entry reads and the probe are capped by the budget's room, and a
1902
+ * refused storage call ends the cycle: the entries read so far come back
1903
+ * as a prefix, in order, which a cursor minted from the last one resumes.
1904
+ */
1905
+ async function pollOnce(opts, budget) {
1410
1906
  const { db, collection, cursor, signal } = opts;
1411
- if (cursor.length > 0 && !LSN_RE.test(cursor)) throw new BaerlyError("SchemaError", `cursor: invalid shape (expected an lsn returned by a prior SinceResponse); got ${JSON.stringify(cursor)}`);
1412
- const read = await db.getCurrentJson(collection, signalOpt(signal));
1413
- if (read === null) return [];
1414
- const logSeqStart = logSeqStartOf(read.json);
1415
- const tail = await db.probeLogTail(collection, Math.max(logSeqStart, read.json.tail_hint), signalOpt(signal));
1416
- let startSeq;
1417
- if (cursor.length === 0) startSeq = logSeqStart;
1418
- else {
1419
- const cursorSeq = lsnParts(cursor).seq;
1420
- if (cursorSeq < logSeqStart) throw new BaerlyError("SchemaError", `cursor ${JSON.stringify(cursor)} points to a log entry that has been folded into a snapshot (log_seq_start=${logSeqStart}); re-bootstrap from a snapshot read before resuming`);
1421
- startSeq = cursorSeq + 1;
1422
- }
1423
- const endSeq = Math.min(tail, startSeq + DEFAULT_MAX_EVENTS);
1907
+ const decoded = cursor.length > 0 ? decodeCursor(cursor) : void 0;
1424
1908
  const entries = [];
1425
- for (let s = startSeq; s < endSeq; s++) {
1426
- const entry = await db.getLogEntry(collection, s, signalOpt(signal));
1427
- if (entry === null) continue;
1428
- entries.push(entry);
1909
+ let generation;
1910
+ try {
1911
+ const read = await budget.observe(() => getCurrentJson(db, collection, signalOpt(signal)));
1912
+ if (read === null) return {
1913
+ events: [],
1914
+ generation: void 0
1915
+ };
1916
+ generation = read.json.generation;
1917
+ const logSeqStart = logSeqStartOf(read.json);
1918
+ const hint = Math.max(logSeqStart, read.json.tail_hint);
1919
+ let startSeq;
1920
+ if (decoded === void 0) startSeq = logSeqStart;
1921
+ else {
1922
+ const { generation: cursorGeneration, lsn } = decoded;
1923
+ if (cursorGeneration !== (read.json.generation ?? "-")) throw new BaerlyError("CursorExpired", `cursor ${JSON.stringify(cursor)} was minted in a generation that no longer exists (the collection has been truncated and restored)`, { resolution: CODE_RESOLUTIONS.CursorExpired });
1924
+ const cursorSeq = lsnParts(lsn).seq;
1925
+ if (cursorSeq < logSeqStart) throw new BaerlyError("CursorExpired", `cursor ${JSON.stringify(cursor)} is older than the oldest change this collection retains (log_seq_start=${logSeqStart}); the changes after it are no longer retained`, { resolution: CODE_RESOLUTIONS.CursorExpired });
1926
+ startSeq = cursorSeq + 1;
1927
+ }
1928
+ const endSeq = startSeq + DEFAULT_MAX_EVENTS;
1929
+ let s = startSeq;
1930
+ for (; s < Math.min(hint, endSeq); s++) {
1931
+ if (budget.left() < 1) return {
1932
+ events: entries,
1933
+ generation
1934
+ };
1935
+ const entry = await getLogEntry(db, collection, s, read.json, signalOpt(signal));
1936
+ if (entry === null) continue;
1937
+ entries.push(entry);
1938
+ }
1939
+ const cap = Math.min(endSeq - s, budget.left());
1940
+ if (cap >= 1) {
1941
+ const chunk = await probeLogChunk(db, collection, s, read.json, {
1942
+ cap,
1943
+ ...signal !== void 0 && { signal }
1944
+ });
1945
+ entries.push(...chunk.entries);
1946
+ }
1947
+ } catch (error) {
1948
+ if (isStorageRefusal(error)) return {
1949
+ events: entries,
1950
+ generation
1951
+ };
1952
+ throw error;
1429
1953
  }
1430
- return entries;
1954
+ return {
1955
+ events: entries,
1956
+ generation
1957
+ };
1431
1958
  }
1959
+ /**
1960
+ * Mint the `next_cursor` for a poll that produced events: the last
1961
+ * entry's `lsn`, paired with the generation the poll read it under.
1962
+ *
1963
+ * Only called when `events` is non-empty, which is exactly when the
1964
+ * poll saw a `current.json` — so the generation here is the manifest's,
1965
+ * not a stand-in.
1966
+ */
1967
+ const nextCursor = (polled) => formatCursor(polled.generation, polled.events[polled.events.length - 1].lsn);
1432
1968
  /** Pack an optional `signal` into the `{ signal? }` shape callers expect. */
1433
1969
  const signalOpt = (signal) => signal === void 0 ? void 0 : { signal };
1434
- //#endregion
1435
- //#region packages/server/src/http/router.ts
1970
+ // packages/server/src/http/router.ts
1436
1971
  /**
1437
1972
  * HTTP dispatcher. A small Hono `app` that implements the
1438
1973
  * five locked CRUD routes from `contract.ts`. Mounted into both
@@ -1448,10 +1983,8 @@ const signalOpt = (signal) => signal === void 0 ? void 0 : { signal };
1448
1983
  * load-balancer probe.
1449
1984
  *
1450
1985
  * `GET /v1/since` is appended to the same factory (see `./since.ts`
1451
- * for the long-poll core). The Cloudflare adapter wraps Worker-side
1452
- * GETs with `caches.default` *outside* `createRouter` so the router
1453
- * stays platform-agnostic; that wrapper EXCLUDES `/v1/since` —
1454
- * long-poll idleness is not a cache hit.
1986
+ * for the long-poll core). No adapter caches responses: every read
1987
+ * this router serves, on every host, reaches storage.
1455
1988
  */
1456
1989
  /**
1457
1990
  * Build a Hono `app` that serves the CRUD routes:
@@ -1459,30 +1992,39 @@ const signalOpt = (signal) => signal === void 0 ? void 0 : { signal };
1459
1992
  * - `GET /v1/c/:collection/:id` → read one document.
1460
1993
  * - `GET /v1/c/:collection?where=<json>&order=<json>&limit=<n>` → list rows
1461
1994
  * matching a predicate, optionally ordered and capped.
1462
- * - `POST /v1/c/:collection` → insert. Body: `{ doc }`. → `201 { _id }`.
1995
+ * - `POST /v1/c/:collection` → insert. Body: `{ doc, mintedId? }`. → `201 { _id }`.
1463
1996
  * - `PATCH /v1/c/:collection/:id` → merge-patch. Body: `{ patch }`. → `200 { modified }`.
1464
1997
  * - `PUT /v1/c/:collection/:id` → whole-doc replace. Body: `{ doc }`. → `200 { modified }`.
1465
1998
  * - `DELETE /v1/c/:collection/:id` → delete row by id. → `204`.
1466
- * - `GET /v1/count?collection=<name>&where=<json>` → scalar `{ count: N }`.
1999
+ * - `GET /v1/count?collection=<name>&where=<json>&limit=<n>` → scalar `{ count: N }`, cut by `limit`.
1467
2000
  * - `GET /v1/since?collection=<name>&cursor=<opaque>` → long-poll log.
1468
2001
  *
2002
+ * Routes are matched at `/v1/...`: strip any mount prefix from the
2003
+ * request URL before `app.fetch(req)`. Bare `createRouter` adds no
2004
+ * auth, no `/v1/healthz` or `/v1/spec`, and no canonical log line;
2005
+ * writes still run write-tick maintenance, under the default profile
2006
+ * rather than the one a stock adapter selects for its host.
2007
+ *
1469
2008
  * @example
1470
2009
  * ```ts
1471
- * import { createRouter, Db } from "@gusto/baerly-storage";
1472
- * import { MemoryStorage } from "@gusto/baerly-storage";
2010
+ * import { Db, MemoryStorage } from "@gusto/baerly-storage";
2011
+ * import { createRouter } from "@gusto/baerly-storage/http";
1473
2012
  *
2013
+ * // Tests and local tools only: every request is served as tenant "acme".
1474
2014
  * const db = Db.create({ storage: new MemoryStorage(), app: "tickets", tenant: "acme" });
1475
2015
  * const app = createRouter({ db });
1476
- * // CF Workers:
1477
- * export default { async fetch(req: Request) { return app.fetch(req); } };
2016
+ * const res = await app.fetch(new Request("http://localhost/v1/c/tickets"));
1478
2017
  * ```
2018
+ *
2019
+ * For a gated, per-request router see `dist/RECIPES.md` →
2020
+ * "Recipe — authoring a gated adapter".
1479
2021
  */
1480
2022
  function createRouter(options) {
1481
2023
  const { db, sinceTimeoutMs, sincePollIntervalMs } = options;
1482
2024
  const app = new Hono();
1483
2025
  app.get("/v1/c/:collection/:id", async (c) => {
1484
2026
  const { collection, id } = c.req.param();
1485
- const { rows, manifestPointer, fresh } = await runByIdWithMeta(db.collectionReadContext(collection), id);
2027
+ const { rows, manifestPointer, fresh } = await runByIdWithMeta(collectionReadContext(db, collection), id);
1486
2028
  const row = rows[0];
1487
2029
  if (row === void 0) throw new BaerlyError("NotFound", `No such row: ${id}`);
1488
2030
  return c.json({
@@ -1498,7 +2040,7 @@ function createRouter(options) {
1498
2040
  const wire = parseWhereParam(c);
1499
2041
  const order = parseOrder(c.req.query("order"));
1500
2042
  const limit = parseLimit(c.req.query("limit"));
1501
- const { rows, manifestPointer, fresh } = await runAllWithMeta(db.collectionReadContext(collection), {
2043
+ const { rows, manifestPointer, fresh } = await runAllWithMeta(collectionReadContext(db, collection), {
1502
2044
  wire,
1503
2045
  order,
1504
2046
  limit
@@ -1513,40 +2055,49 @@ function createRouter(options) {
1513
2055
  });
1514
2056
  app.post("/v1/c/:collection", async (c) => {
1515
2057
  const { collection } = c.req.param();
1516
- const doc = assertJsonBodyField(await readJsonBody(c, MAX_BODY_BYTES), "doc");
1517
- const { _id } = await db.collection(collection).insert(doc);
2058
+ const body = await readJsonBody(c, MAX_BODY_BYTES);
2059
+ const doc = assertJsonBodyField(body, "doc");
2060
+ const mintedId = readMintedId(body, doc);
2061
+ const { _id } = await runInsert(collectionReadContext(db, collection), doc, mintedId === void 0 ? void 0 : { mintedId });
2062
+ stampCapacityWarning(c);
1518
2063
  return c.json({ _id }, 201);
1519
2064
  });
1520
2065
  app.patch("/v1/c/:collection/:id", async (c) => {
1521
2066
  const { collection, id } = c.req.param();
1522
- const patch = assertJsonBodyField(await readJsonBody(c, MAX_BODY_BYTES), "patch");
2067
+ const body = await readJsonBody(c, MAX_BODY_BYTES);
2068
+ const patch = assertJsonBodyField(body, "patch");
1523
2069
  const { modified } = await db.collection(collection).update(id, patch);
1524
2070
  if (modified === 0) throw new BaerlyError("NotFound", `No such row: ${id}`);
2071
+ stampCapacityWarning(c);
1525
2072
  return c.json({ modified }, 200);
1526
2073
  });
1527
2074
  app.put("/v1/c/:collection/:id", async (c) => {
1528
2075
  const { collection, id } = c.req.param();
1529
- const doc = assertJsonBodyField(await readJsonBody(c, MAX_BODY_BYTES), "doc");
2076
+ const body = await readJsonBody(c, MAX_BODY_BYTES);
2077
+ const doc = assertJsonBodyField(body, "doc");
1530
2078
  await db.collection(collection).replace(id, doc);
2079
+ stampCapacityWarning(c);
1531
2080
  return c.json({ modified: 1 }, 200);
1532
2081
  });
1533
2082
  app.delete("/v1/c/:collection/:id", async (c) => {
1534
2083
  const { collection, id } = c.req.param();
1535
2084
  const { deleted } = await db.collection(collection).delete(id);
1536
2085
  if (deleted === 0) throw new BaerlyError("NotFound", `No such row: ${id}`);
1537
- return new Response(null, { status: 204 });
2086
+ stampCapacityWarning(c);
2087
+ return c.body(null, 204);
1538
2088
  });
1539
2089
  app.get("/v1/count", async (c) => {
1540
2090
  const collection = c.req.query("collection");
1541
- if (collection === void 0 || collection.length === 0) throw new BaerlyError("SchemaError", "GET /v1/count requires ?collection=<name>", void 0, void 0, void 0, "Add ?collection=<name> to the request URL.");
2091
+ if (collection === void 0 || collection.length === 0) throw new BaerlyError("SchemaError", "GET /v1/count requires ?collection=<name>", { resolution: "Add ?collection=<name> to the request URL." });
1542
2092
  const wire = parseWhereParam(c);
1543
- const { rows, manifestPointer, fresh } = await runAllWithMeta(db.collectionReadContext(collection), {
2093
+ const limit = parseLimit(c.req.query("limit"));
2094
+ const { count, manifestPointer, fresh } = await runAllWithMeta(collectionReadContext(db, collection), {
1544
2095
  wire,
1545
2096
  order: void 0,
1546
- limit: void 0
1547
- });
2097
+ limit
2098
+ }, { countOnly: true });
1548
2099
  return c.json({
1549
- data: { count: rows.length },
2100
+ data: { count },
1550
2101
  _meta: {
1551
2102
  manifest_pointer: manifestPointer,
1552
2103
  fresh
@@ -1556,10 +2107,11 @@ function createRouter(options) {
1556
2107
  app.get("/v1/since", async (c) => {
1557
2108
  const collection = c.req.query("collection");
1558
2109
  if (typeof collection !== "string" || collection.length === 0 || collection.includes("/")) throw new BaerlyError("SchemaError", "GET /v1/since requires a non-empty `collection` query parameter without `/`");
2110
+ const cursor = c.req.query("cursor") ?? "";
1559
2111
  const result = await longPollSince({
1560
2112
  db,
1561
2113
  collection,
1562
- cursor: c.req.query("cursor") ?? "",
2114
+ cursor,
1563
2115
  signal: c.req.raw.signal,
1564
2116
  timeoutMs: sinceTimeoutMs,
1565
2117
  pollIntervalMs: sincePollIntervalMs
@@ -1576,10 +2128,10 @@ function createRouter(options) {
1576
2128
  * The Node adapter (`@baerly/adapter-node`) imports this constant
1577
2129
  * and passes it to `applyBodyCap`, which wraps the request body
1578
2130
  * with a counting `TransformStream` so chunked uploads trip the cap
1579
- * mid-stream rather than materialising the full buffer. The
1580
- * router's `readJsonBody` keeps the cap as a defence-in-depth check
1581
- * (Content-Length pre-read + post-`arrayBuffer` length) for adapters
1582
- * whose platform doesn't pre-cap.
2131
+ * mid-stream and the upstream `IncomingMessage` is drained. The
2132
+ * router's `readJsonBody` enforces the same cap on every host
2133
+ * (Content-Length pre-check, then a counted streaming read), which is
2134
+ * the only cap on Workers.
1583
2135
  *
1584
2136
  * @internal — exported for tests and for the Node adapter's
1585
2137
  * `applyBodyCap` helper. Promote to
@@ -1601,10 +2153,35 @@ const MAX_BODY_BYTES = 1 << 20;
1601
2153
  */
1602
2154
  const assertJsonBodyField = (body, field) => {
1603
2155
  const value = typeof body === "object" && body !== null ? body[field] : void 0;
1604
- if (value === void 0 || typeof value !== "object" || value === null || Array.isArray(value)) throw new BaerlyError("SchemaError", `Request body must be { ${field}: object }`, void 0, void 0, void 0, WRITE_BODY_SHAPE_RESOLUTION);
2156
+ if (value === void 0 || typeof value !== "object" || value === null || Array.isArray(value)) throw new BaerlyError("SchemaError", `Request body must be { ${field}: object }`, { resolution: WRITE_BODY_SHAPE_RESOLUTION });
1605
2157
  return value;
1606
2158
  };
1607
2159
  /**
2160
+ * Read the optional `mintedId` of a `POST /v1/c/:collection` body. An SDK
2161
+ * that minted the doc's `_id` itself sends it in both `doc._id` and
2162
+ * `mintedId`; the flag lets a resend of the same insert replay as the
2163
+ * original `201 { _id }` (see `runInsert`). A server that predates the
2164
+ * field reads only `doc`, so it treats the id as caller-supplied and a
2165
+ * resend gets strict `409 AlreadyExists`, never a duplicate row.
2166
+ *
2167
+ * Validated before any I/O: `mintedId` must be a string with the
2168
+ * canonical UUIDv7 shape (`isUuidV7`, which also satisfies the `_id`
2169
+ * key-segment rule `assertDocId` applies) and must equal `doc._id`. The
2170
+ * UUIDv7 rule keeps a human-chosen id such as `"migration-x"` from
2171
+ * opting into replay. Absent → `undefined`.
2172
+ *
2173
+ * @throws BaerlyError code="SchemaError" — `mintedId` is present and
2174
+ * fails any of those checks.
2175
+ *
2176
+ * @internal
2177
+ */
2178
+ const readMintedId = (body, doc) => {
2179
+ const raw = body["mintedId"];
2180
+ if (raw === void 0) return;
2181
+ if (typeof raw !== "string" || !isUuidV7(raw) || doc["_id"] !== raw) throw new BaerlyError("SchemaError", "Request body mintedId must be a UUIDv7 string equal to doc._id", { resolution: WRITE_BODY_SHAPE_RESOLUTION });
2182
+ return raw;
2183
+ };
2184
+ /**
1608
2185
  * Parse the `?where=<urlencoded JSON>` query-string param. Absent or
1609
2186
  * empty → {@link EMPTY_PREDICATE_WIRE} (match-all). Malformed JSON →
1610
2187
  * `BaerlyError{code:"SchemaError"}` with the locked wording
@@ -1629,7 +2206,7 @@ const parseWhereParam = (c) => {
1629
2206
  try {
1630
2207
  parsed = JSON.parse(whereParam);
1631
2208
  } catch {
1632
- throw new BaerlyError("SchemaError", "Invalid JSON in ?where=", void 0, void 0, void 0, WHERE_ORDER_JSON_RESOLUTION);
2209
+ throw new BaerlyError("SchemaError", "Invalid JSON in ?where=", { resolution: WHERE_ORDER_JSON_RESOLUTION });
1633
2210
  }
1634
2211
  try {
1635
2212
  return validateWire(parsed);
@@ -1653,7 +2230,7 @@ function parseLimit(raw) {
1653
2230
  /**
1654
2231
  * Parse the `?order=<json>` query param. Mirrors the `?where=` parser
1655
2232
  * shape: undefined → no order, malformed JSON → `SchemaError`. The
1656
- * engine (`runAllWithMeta` → `sortByOrderSpec`) validates the shape
2233
+ * engine (`runAllWithMeta` → `orderRows`) validates the shape
1657
2234
  * itself, so this only handles the wire-level JSON decode.
1658
2235
  *
1659
2236
  * @internal
@@ -1664,33 +2241,41 @@ function parseOrder(raw) {
1664
2241
  try {
1665
2242
  parsed = JSON.parse(raw);
1666
2243
  } catch {
1667
- throw new BaerlyError("SchemaError", "Invalid JSON in ?order=", void 0, void 0, void 0, WHERE_ORDER_JSON_RESOLUTION);
2244
+ throw new BaerlyError("SchemaError", "Invalid JSON in ?order=", { resolution: WHERE_ORDER_JSON_RESOLUTION });
1668
2245
  }
1669
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new BaerlyError("SchemaError", "?order= must encode a JSON object", void 0, void 0, void 0, WHERE_ORDER_JSON_RESOLUTION);
2246
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new BaerlyError("SchemaError", "?order= must encode a JSON object", { resolution: WHERE_ORDER_JSON_RESOLUTION });
1670
2247
  return parsed;
1671
2248
  }
1672
2249
  const ERROR_TO_STATUS = /* @__PURE__ */ new Map([
1673
2250
  ["Unauthorized", 401],
1674
2251
  ["AccessDenied", 403],
1675
2252
  ["NotFound", 404],
1676
- ["Conflict", 409],
2253
+ ["WriteConflict", 409],
2254
+ ["AlreadyExists", 409],
2255
+ ["AmbiguousCommit", 409],
2256
+ ["CapacityExceeded", 409],
2257
+ ["MaintenancePending", 503],
2258
+ ["CursorExpired", 410],
1677
2259
  ["PayloadTooLarge", 413],
2260
+ ["UnsupportedMediaType", 415],
1678
2261
  ["SchemaError", 400],
1679
2262
  ["InvalidConfig", 400],
1680
2263
  ["UnsatisfiablePredicate", 400],
1681
2264
  ["NetworkError", 502],
1682
2265
  ["InvalidResponse", 502]
1683
2266
  ]);
1684
- const CALLER_FACING_INVALID_CONFIG_ERRORS = /* @__PURE__ */ new WeakSet();
1685
2267
  const ERROR_CODE_POLICY = {
1686
2268
  AccessDenied: {
1687
2269
  messagePolicy: "scrubbed",
1688
2270
  scrubbedMessage: "access denied"
1689
2271
  },
1690
- Conflict: {
1691
- messagePolicy: "contextual",
1692
- scrubbedMessage: "write conflict",
1693
- shouldExpose: (err) => !err.retriable
2272
+ AlreadyExists: { messagePolicy: "public" },
2273
+ CapacityExceeded: { messagePolicy: "public" },
2274
+ MaintenancePending: { messagePolicy: "public" },
2275
+ CursorExpired: { messagePolicy: "public" },
2276
+ AmbiguousCommit: {
2277
+ messagePolicy: "scrubbed",
2278
+ scrubbedMessage: "commit outcome is ambiguous; the mutation may or may not have been applied"
1694
2279
  },
1695
2280
  Internal: {
1696
2281
  messagePolicy: "scrubbed",
@@ -1699,7 +2284,7 @@ const ERROR_CODE_POLICY = {
1699
2284
  InvalidConfig: {
1700
2285
  messagePolicy: "contextual",
1701
2286
  scrubbedMessage: "invalid server configuration",
1702
- shouldExpose: (err) => CALLER_FACING_INVALID_CONFIG_ERRORS.has(err)
2287
+ shouldExpose: (err) => isCallerFacing(err)
1703
2288
  },
1704
2289
  InvalidResponse: {
1705
2290
  messagePolicy: "scrubbed",
@@ -1715,6 +2300,7 @@ const ERROR_CODE_POLICY = {
1715
2300
  },
1716
2301
  NotFound: { messagePolicy: "public" },
1717
2302
  PayloadTooLarge: { messagePolicy: "public" },
2303
+ UnsupportedMediaType: { messagePolicy: "public" },
1718
2304
  SchemaError: { messagePolicy: "public" },
1719
2305
  Unauthorized: { messagePolicy: "public" },
1720
2306
  UnexpectedWriteInQuery: {
@@ -1725,10 +2311,14 @@ const ERROR_CODE_POLICY = {
1725
2311
  UseQueryAwaitedRecorder: {
1726
2312
  messagePolicy: "scrubbed",
1727
2313
  scrubbedMessage: "internal error"
2314
+ },
2315
+ WriteConflict: {
2316
+ messagePolicy: "scrubbed",
2317
+ scrubbedMessage: "write conflict: another write changed this data first; this commit did not land"
1728
2318
  }
1729
2319
  };
1730
2320
  const markCallerFacingInvalidConfig = (err) => {
1731
- if (err instanceof BaerlyError && err.code === "InvalidConfig") CALLER_FACING_INVALID_CONFIG_ERRORS.add(err);
2321
+ if (err instanceof BaerlyError && err.code === "InvalidConfig") markCallerFacing(err);
1732
2322
  return err;
1733
2323
  };
1734
2324
  const shouldExposeErrorMessage = (err) => {
@@ -1768,12 +2358,17 @@ function mapError(err) {
1768
2358
  logScrubbedError(err, status);
1769
2359
  return {
1770
2360
  status,
1771
- envelope: errorEnvelope(wireCode, scrubbedMessageFor(wireCode), void 0, wireCode === "Conflict" ? err.resolution : void 0, wireCode === err.code ? err.retriable : void 0)
2361
+ envelope: errorEnvelope(wireCode, scrubbedMessageFor(wireCode), { _id: wireCode === err.code ? err._id : void 0 })
1772
2362
  };
1773
2363
  }
1774
2364
  return {
1775
2365
  status,
1776
- envelope: errorEnvelope(err.code, err.message, err.issues, err.resolution, err.retriable)
2366
+ envelope: errorEnvelope(err.code, err.message, {
2367
+ issues: err.issues,
2368
+ resolution: err.resolution,
2369
+ _id: err._id,
2370
+ retryAfter: err.retryAfter
2371
+ })
1777
2372
  };
1778
2373
  }
1779
2374
  getLogger(CATEGORY.http).error("unhandled_error", { error: serializeError(err) });
@@ -1782,47 +2377,79 @@ function mapError(err) {
1782
2377
  envelope: errorEnvelope("Internal", "internal error")
1783
2378
  };
1784
2379
  }
2380
+ function stampCapacityWarning(c) {
2381
+ const warning = getCurrentContext()?.fields.get(CAPACITY_WARNING_FIELD);
2382
+ if (typeof warning === "string") c.header(CAPACITY_WARNING_HEADER, warning);
2383
+ }
1785
2384
  function mapToResponse(c, err) {
1786
2385
  const { status, envelope } = mapError(err);
2386
+ const { retryAfter } = envelope.error;
2387
+ if (retryAfter !== void 0) c.header("Retry-After", String(Math.ceil(retryAfter)));
1787
2388
  return c.json(envelope, status);
1788
2389
  }
1789
2390
  /**
1790
2391
  * Read and parse the JSON request body. Returns the parsed value
1791
2392
  * (an `unknown` — caller narrows). Throws `BaerlyError`:
1792
2393
  *
1793
- * - `"PayloadTooLarge"` (→ 413) when the body exceeds `maxBytes`,
1794
- * detected via `Content-Length` pre-check, post-`arrayBuffer`
1795
- * length check, or — if the host adapter pumps the body through
1796
- * a `ReadableStream` (the Node adapter does) — a `BaerlyError`
1797
- * surfaced via `controller.error(...)` on the upstream pump.
2394
+ * - `"UnsupportedMediaType"` (→ 415), before any read, unless the
2395
+ * `Content-Type` is `application/json` or a `+json` type
2396
+ * (parameters such as `charset` allowed). Requiring it keeps every
2397
+ * write route off the CORS-simple request list, so another origin
2398
+ * cannot forge a write under ambient auth (`auth: "none"`, cookie
2399
+ * sessions).
2400
+ * - `"PayloadTooLarge"` (→ 413) when the body exceeds `maxBytes`:
2401
+ * up front from `Content-Length`, else as soon as the running size
2402
+ * of a chunked body passes the cap. The read stops there and the
2403
+ * stream is cancelled, so no host buffers more than `maxBytes`
2404
+ * (workerd has no platform cap). A `BaerlyError` surfaced by an
2405
+ * upstream pump (the Node adapter's `applyBodyCap`) is re-thrown
2406
+ * verbatim.
1798
2407
  * - `"SchemaError"` (→ 400) for empty bodies, JSON parse failures,
1799
2408
  * and any other read failure.
1800
2409
  *
1801
2410
  * Hono's `app.onError` sink routes the throw through `mapToResponse`.
1802
2411
  */
1803
2412
  async function readJsonBody(c, maxBytes) {
1804
- const lenHeader = c.req.header("content-length");
1805
- if (lenHeader !== void 0) {
1806
- const parsed = Number.parseInt(lenHeader, 10);
1807
- if (Number.isFinite(parsed) && parsed > maxBytes) throw new BaerlyError("PayloadTooLarge", `Body exceeds ${maxBytes} bytes`);
2413
+ const [typeAndSubtype = ""] = (c.req.header("content-type") ?? "").split(";");
2414
+ const mediaType = typeAndSubtype.trim().toLowerCase();
2415
+ if (mediaType !== "application/json" && !/^[a-z0-9.+-]+\/[a-z0-9.+-]+\+json$/.test(mediaType)) {
2416
+ let got = mediaType === "" ? "no Content-Type" : mediaType;
2417
+ if (got.length > 100) got = `${got.slice(0, 100)}…`;
2418
+ throw new BaerlyError("UnsupportedMediaType", `${c.req.method} bodies must be sent as application/json; got ${got}`);
1808
2419
  }
1809
- let raw;
2420
+ const tooLarge = () => new BaerlyError("PayloadTooLarge", `Body exceeds ${maxBytes} bytes`);
2421
+ const lenHeader = c.req.header("content-length");
2422
+ if (lenHeader !== void 0 && Number.parseInt(lenHeader, 10) > maxBytes) throw tooLarge();
2423
+ let raw = "";
1810
2424
  try {
1811
- const buffer = await c.req.arrayBuffer();
1812
- if (buffer.byteLength > maxBytes) throw new BaerlyError("PayloadTooLarge", `Body exceeds ${maxBytes} bytes`);
1813
- raw = new TextDecoder().decode(buffer);
2425
+ const body = c.req.raw.body;
2426
+ if (body !== null) {
2427
+ const reader = body.getReader();
2428
+ const decoder = new TextDecoder();
2429
+ let size = 0;
2430
+ for (;;) {
2431
+ const { done, value } = await reader.read();
2432
+ if (done) break;
2433
+ size += value.byteLength;
2434
+ if (size > maxBytes) {
2435
+ reader.cancel().catch(() => {});
2436
+ throw tooLarge();
2437
+ }
2438
+ raw += decoder.decode(value, { stream: true });
2439
+ }
2440
+ raw += decoder.decode();
2441
+ }
1814
2442
  } catch (error) {
1815
2443
  if (error instanceof BaerlyError) throw error;
1816
2444
  throw new BaerlyError("SchemaError", `Failed to read request body: ${error instanceof Error ? error.message : String(error)}`);
1817
2445
  }
1818
- if (raw.length === 0) throw new BaerlyError("SchemaError", "Empty request body", void 0, void 0, void 0, WRITE_BODY_SHAPE_RESOLUTION);
2446
+ if (raw.length === 0) throw new BaerlyError("SchemaError", "Empty request body", { resolution: WRITE_BODY_SHAPE_RESOLUTION });
1819
2447
  try {
1820
2448
  return JSON.parse(raw);
1821
2449
  } catch {
1822
- throw new BaerlyError("SchemaError", "Invalid JSON in request body", void 0, void 0, void 0, WRITE_BODY_SHAPE_RESOLUTION);
2450
+ throw new BaerlyError("SchemaError", "Invalid JSON in request body", { resolution: WRITE_BODY_SHAPE_RESOLUTION });
1823
2451
  }
1824
2452
  }
1825
- //#endregion
1826
2453
  export { longPollSince as a, listEventsSince as i, createRouter as n, Hono as o, mapError as r, MAX_BODY_BYTES as t };
1827
2454
 
1828
- //# sourceMappingURL=http-DGd5tbNs.js.map
2455
+ //# sourceMappingURL=http-Z5rZyYMX.js.map