@backblaze-labs/b2-sdk 0.1.0 → 0.3.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 (885) hide show
  1. package/CHANGELOG.md +151 -5
  2. package/README.md +163 -34
  3. package/dist/_virtual/_b2-sdk-version-json.cjs +4 -0
  4. package/dist/_virtual/_b2-sdk-version-json.js +4 -0
  5. package/dist/auth/account-info.d.cts +32 -0
  6. package/dist/auth/account-info.d.cts.map +1 -1
  7. package/dist/auth/account-info.d.ts +32 -0
  8. package/dist/auth/account-info.d.ts.map +1 -1
  9. package/dist/auth/file.cjs +408 -207
  10. package/dist/auth/file.cjs.map +1 -1
  11. package/dist/auth/file.d.cts +77 -3
  12. package/dist/auth/file.d.cts.map +1 -1
  13. package/dist/auth/file.d.ts +77 -3
  14. package/dist/auth/file.d.ts.map +1 -1
  15. package/dist/auth/file.js +407 -207
  16. package/dist/auth/file.js.map +1 -1
  17. package/dist/auth/in-memory.cjs +212 -183
  18. package/dist/auth/in-memory.cjs.map +1 -1
  19. package/dist/auth/in-memory.d.cts +8 -0
  20. package/dist/auth/in-memory.d.cts.map +1 -1
  21. package/dist/auth/in-memory.d.ts +8 -0
  22. package/dist/auth/in-memory.d.ts.map +1 -1
  23. package/dist/auth/in-memory.js +211 -182
  24. package/dist/auth/in-memory.js.map +1 -1
  25. package/dist/auth/index.cjs +7 -9
  26. package/dist/auth/index.d.cts +3 -2
  27. package/dist/auth/index.d.cts.map +1 -1
  28. package/dist/auth/index.d.ts +3 -2
  29. package/dist/auth/index.d.ts.map +1 -1
  30. package/dist/auth/index.js +2 -8
  31. package/dist/auth/realms.cjs +80 -7
  32. package/dist/auth/realms.cjs.map +1 -1
  33. package/dist/auth/realms.d.cts +27 -4
  34. package/dist/auth/realms.d.cts.map +1 -1
  35. package/dist/auth/realms.d.ts +27 -4
  36. package/dist/auth/realms.d.ts.map +1 -1
  37. package/dist/auth/realms.js +80 -9
  38. package/dist/auth/realms.js.map +1 -1
  39. package/dist/auth/upload-url-pool.cjs +55 -51
  40. package/dist/auth/upload-url-pool.cjs.map +1 -1
  41. package/dist/auth/upload-url-pool.js +55 -51
  42. package/dist/auth/upload-url-pool.js.map +1 -1
  43. package/dist/backup/client.cjs +206 -0
  44. package/dist/backup/client.cjs.map +1 -0
  45. package/dist/backup/client.d.cts +238 -0
  46. package/dist/backup/client.d.cts.map +1 -0
  47. package/dist/backup/client.d.ts +238 -0
  48. package/dist/backup/client.d.ts.map +1 -0
  49. package/dist/backup/client.js +206 -0
  50. package/dist/backup/client.js.map +1 -0
  51. package/dist/backup/index.cjs +15 -0
  52. package/dist/backup/index.d.cts +22 -0
  53. package/dist/backup/index.d.cts.map +1 -0
  54. package/dist/backup/index.d.ts +22 -0
  55. package/dist/backup/index.d.ts.map +1 -0
  56. package/dist/backup/index.js +7 -0
  57. package/dist/backup/raw.cjs +146 -0
  58. package/dist/backup/raw.cjs.map +1 -0
  59. package/dist/backup/raw.d.cts +122 -0
  60. package/dist/backup/raw.d.cts.map +1 -0
  61. package/dist/backup/raw.d.ts +122 -0
  62. package/dist/backup/raw.d.ts.map +1 -0
  63. package/dist/backup/raw.js +146 -0
  64. package/dist/backup/raw.js.map +1 -0
  65. package/dist/bucket.cjs +786 -787
  66. package/dist/bucket.cjs.map +1 -1
  67. package/dist/bucket.d.cts +35 -47
  68. package/dist/bucket.d.cts.map +1 -1
  69. package/dist/bucket.d.ts +35 -47
  70. package/dist/bucket.d.ts.map +1 -1
  71. package/dist/bucket.js +781 -782
  72. package/dist/bucket.js.map +1 -1
  73. package/dist/client.cjs +246 -228
  74. package/dist/client.cjs.map +1 -1
  75. package/dist/client.d.cts +25 -17
  76. package/dist/client.d.cts.map +1 -1
  77. package/dist/client.d.ts +25 -17
  78. package/dist/client.d.ts.map +1 -1
  79. package/dist/client.js +243 -225
  80. package/dist/client.js.map +1 -1
  81. package/dist/copy/large.cjs +116 -71
  82. package/dist/copy/large.cjs.map +1 -1
  83. package/dist/copy/large.d.cts +6 -0
  84. package/dist/copy/large.d.cts.map +1 -1
  85. package/dist/copy/large.d.ts +6 -0
  86. package/dist/copy/large.d.ts.map +1 -1
  87. package/dist/copy/large.js +114 -69
  88. package/dist/copy/large.js.map +1 -1
  89. package/dist/download/checksum.cjs +93 -0
  90. package/dist/download/checksum.cjs.map +1 -0
  91. package/dist/download/checksum.d.cts +40 -0
  92. package/dist/download/checksum.d.cts.map +1 -0
  93. package/dist/download/checksum.d.ts +40 -0
  94. package/dist/download/checksum.d.ts.map +1 -0
  95. package/dist/download/checksum.js +91 -0
  96. package/dist/download/checksum.js.map +1 -0
  97. package/dist/download/parallel.cjs +251 -118
  98. package/dist/download/parallel.cjs.map +1 -1
  99. package/dist/download/parallel.d.cts +13 -2
  100. package/dist/download/parallel.d.cts.map +1 -1
  101. package/dist/download/parallel.d.ts +13 -2
  102. package/dist/download/parallel.d.ts.map +1 -1
  103. package/dist/download/parallel.js +249 -116
  104. package/dist/download/parallel.js.map +1 -1
  105. package/dist/download/single.cjs +323 -97
  106. package/dist/download/single.cjs.map +1 -1
  107. package/dist/download/single.d.cts +6 -1
  108. package/dist/download/single.d.cts.map +1 -1
  109. package/dist/download/single.d.ts +6 -1
  110. package/dist/download/single.d.ts.map +1 -1
  111. package/dist/download/single.js +322 -99
  112. package/dist/download/single.js.map +1 -1
  113. package/dist/errors/index.cjs +869 -243
  114. package/dist/errors/index.cjs.map +1 -1
  115. package/dist/errors/index.d.cts +404 -82
  116. package/dist/errors/index.d.cts.map +1 -1
  117. package/dist/errors/index.d.ts +404 -82
  118. package/dist/errors/index.d.ts.map +1 -1
  119. package/dist/errors/index.js +835 -261
  120. package/dist/errors/index.js.map +1 -1
  121. package/dist/http/retry.cjs +45 -28
  122. package/dist/http/retry.cjs.map +1 -1
  123. package/dist/http/retry.d.cts +15 -2
  124. package/dist/http/retry.d.cts.map +1 -1
  125. package/dist/http/retry.d.ts +15 -2
  126. package/dist/http/retry.d.ts.map +1 -1
  127. package/dist/http/retry.js +46 -31
  128. package/dist/http/retry.js.map +1 -1
  129. package/dist/http/transport.cjs +476 -140
  130. package/dist/http/transport.cjs.map +1 -1
  131. package/dist/http/transport.d.cts +46 -5
  132. package/dist/http/transport.d.cts.map +1 -1
  133. package/dist/http/transport.d.ts +46 -5
  134. package/dist/http/transport.d.ts.map +1 -1
  135. package/dist/http/transport.js +474 -140
  136. package/dist/http/transport.js.map +1 -1
  137. package/dist/http/url-guard.cjs +154 -89
  138. package/dist/http/url-guard.cjs.map +1 -1
  139. package/dist/http/url-guard.d.cts +25 -3
  140. package/dist/http/url-guard.d.cts.map +1 -1
  141. package/dist/http/url-guard.d.ts +25 -3
  142. package/dist/http/url-guard.d.ts.map +1 -1
  143. package/dist/http/url-guard.js +152 -90
  144. package/dist/http/url-guard.js.map +1 -1
  145. package/dist/http/user-agent.cjs +84 -44
  146. package/dist/http/user-agent.cjs.map +1 -1
  147. package/dist/http/user-agent.js +84 -46
  148. package/dist/http/user-agent.js.map +1 -1
  149. package/dist/index.cjs +124 -77
  150. package/dist/index.d.cts +29 -21
  151. package/dist/index.d.cts.map +1 -1
  152. package/dist/index.d.ts +29 -21
  153. package/dist/index.d.ts.map +1 -1
  154. package/dist/index.js +18 -72
  155. package/dist/internal/b2-naming.cjs +66 -0
  156. package/dist/internal/b2-naming.cjs.map +1 -0
  157. package/dist/internal/b2-naming.d.cts +43 -0
  158. package/dist/internal/b2-naming.d.cts.map +1 -0
  159. package/dist/internal/b2-naming.d.ts +43 -0
  160. package/dist/internal/b2-naming.d.ts.map +1 -0
  161. package/dist/internal/b2-naming.js +60 -0
  162. package/dist/internal/b2-naming.js.map +1 -0
  163. package/dist/internal/upload-retry-options.cjs +21 -0
  164. package/dist/internal/upload-retry-options.cjs.map +1 -0
  165. package/dist/internal/upload-retry-options.d.cts +12 -0
  166. package/dist/internal/upload-retry-options.d.cts.map +1 -0
  167. package/dist/internal/upload-retry-options.d.ts +12 -0
  168. package/dist/internal/upload-retry-options.d.ts.map +1 -0
  169. package/dist/internal/upload-retry-options.js +21 -0
  170. package/dist/internal/upload-retry-options.js.map +1 -0
  171. package/dist/internal/url-redaction.cjs +31 -0
  172. package/dist/internal/url-redaction.cjs.map +1 -0
  173. package/dist/internal/url-redaction.d.cts +17 -0
  174. package/dist/internal/url-redaction.d.cts.map +1 -0
  175. package/dist/internal/url-redaction.d.ts +17 -0
  176. package/dist/internal/url-redaction.d.ts.map +1 -0
  177. package/dist/internal/url-redaction.js +31 -0
  178. package/dist/internal/url-redaction.js.map +1 -0
  179. package/dist/notifications/index.cjs +4 -6
  180. package/dist/notifications/index.d.cts +1 -1
  181. package/dist/notifications/index.d.cts.map +1 -1
  182. package/dist/notifications/index.d.ts +1 -1
  183. package/dist/notifications/index.d.ts.map +1 -1
  184. package/dist/notifications/index.js +1 -6
  185. package/dist/notifications/webhook.cjs +195 -85
  186. package/dist/notifications/webhook.cjs.map +1 -1
  187. package/dist/notifications/webhook.d.cts.map +1 -1
  188. package/dist/notifications/webhook.d.ts.map +1 -1
  189. package/dist/notifications/webhook.js +195 -87
  190. package/dist/notifications/webhook.js.map +1 -1
  191. package/dist/object.cjs +253 -210
  192. package/dist/object.cjs.map +1 -1
  193. package/dist/object.d.cts +13 -57
  194. package/dist/object.d.cts.map +1 -1
  195. package/dist/object.d.ts +13 -57
  196. package/dist/object.d.ts.map +1 -1
  197. package/dist/object.js +249 -206
  198. package/dist/object.js.map +1 -1
  199. package/dist/partner/account-info.d.cts +43 -0
  200. package/dist/partner/account-info.d.cts.map +1 -0
  201. package/dist/partner/account-info.d.ts +43 -0
  202. package/dist/partner/account-info.d.ts.map +1 -0
  203. package/dist/partner/auth-clone.cjs +64 -0
  204. package/dist/partner/auth-clone.cjs.map +1 -0
  205. package/dist/partner/auth-clone.d.cts +27 -0
  206. package/dist/partner/auth-clone.d.cts.map +1 -0
  207. package/dist/partner/auth-clone.d.ts +27 -0
  208. package/dist/partner/auth-clone.d.ts.map +1 -0
  209. package/dist/partner/auth-clone.js +63 -0
  210. package/dist/partner/auth-clone.js.map +1 -0
  211. package/dist/partner/auth-core.cjs +175 -0
  212. package/dist/partner/auth-core.cjs.map +1 -0
  213. package/dist/partner/auth-core.d.cts +111 -0
  214. package/dist/partner/auth-core.d.cts.map +1 -0
  215. package/dist/partner/auth-core.d.ts +111 -0
  216. package/dist/partner/auth-core.d.ts.map +1 -0
  217. package/dist/partner/auth-core.js +175 -0
  218. package/dist/partner/auth-core.js.map +1 -0
  219. package/dist/partner/auth-shape.cjs +36 -0
  220. package/dist/partner/auth-shape.cjs.map +1 -0
  221. package/dist/partner/auth-shape.d.cts +12 -0
  222. package/dist/partner/auth-shape.d.cts.map +1 -0
  223. package/dist/partner/auth-shape.d.ts +12 -0
  224. package/dist/partner/auth-shape.d.ts.map +1 -0
  225. package/dist/partner/auth-shape.js +36 -0
  226. package/dist/partner/auth-shape.js.map +1 -0
  227. package/dist/partner/client.cjs +255 -0
  228. package/dist/partner/client.cjs.map +1 -0
  229. package/dist/partner/client.d.cts +335 -0
  230. package/dist/partner/client.d.cts.map +1 -0
  231. package/dist/partner/client.d.ts +335 -0
  232. package/dist/partner/client.d.ts.map +1 -0
  233. package/dist/partner/client.js +255 -0
  234. package/dist/partner/client.js.map +1 -0
  235. package/dist/partner/endpoint-url.cjs +108 -0
  236. package/dist/partner/endpoint-url.cjs.map +1 -0
  237. package/dist/partner/endpoint-url.d.cts +72 -0
  238. package/dist/partner/endpoint-url.d.cts.map +1 -0
  239. package/dist/partner/endpoint-url.d.ts +72 -0
  240. package/dist/partner/endpoint-url.d.ts.map +1 -0
  241. package/dist/partner/endpoint-url.js +105 -0
  242. package/dist/partner/endpoint-url.js.map +1 -0
  243. package/dist/partner/in-memory.cjs +135 -0
  244. package/dist/partner/in-memory.cjs.map +1 -0
  245. package/dist/partner/in-memory.d.cts +99 -0
  246. package/dist/partner/in-memory.d.cts.map +1 -0
  247. package/dist/partner/in-memory.d.ts +99 -0
  248. package/dist/partner/in-memory.d.ts.map +1 -0
  249. package/dist/partner/in-memory.js +135 -0
  250. package/dist/partner/in-memory.js.map +1 -0
  251. package/dist/partner/index.cjs +18 -0
  252. package/dist/partner/index.d.cts +23 -0
  253. package/dist/partner/index.d.cts.map +1 -0
  254. package/dist/partner/index.d.ts +23 -0
  255. package/dist/partner/index.d.ts.map +1 -0
  256. package/dist/partner/index.js +7 -0
  257. package/dist/partner/raw.cjs +392 -0
  258. package/dist/partner/raw.cjs.map +1 -0
  259. package/dist/partner/raw.d.cts +223 -0
  260. package/dist/partner/raw.d.cts.map +1 -0
  261. package/dist/partner/raw.d.ts +223 -0
  262. package/dist/partner/raw.d.ts.map +1 -0
  263. package/dist/partner/raw.js +390 -0
  264. package/dist/partner/raw.js.map +1 -0
  265. package/dist/partner/redaction-placeholders.cjs +10 -0
  266. package/dist/partner/redaction-placeholders.cjs.map +1 -0
  267. package/dist/partner/redaction-placeholders.d.cts +5 -0
  268. package/dist/partner/redaction-placeholders.d.cts.map +1 -0
  269. package/dist/partner/redaction-placeholders.d.ts +5 -0
  270. package/dist/partner/redaction-placeholders.d.ts.map +1 -0
  271. package/dist/partner/redaction-placeholders.js +9 -0
  272. package/dist/partner/redaction-placeholders.js.map +1 -0
  273. package/dist/partner/redaction.cjs +267 -0
  274. package/dist/partner/redaction.cjs.map +1 -0
  275. package/dist/partner/redaction.d.cts +124 -0
  276. package/dist/partner/redaction.d.cts.map +1 -0
  277. package/dist/partner/redaction.d.ts +124 -0
  278. package/dist/partner/redaction.d.ts.map +1 -0
  279. package/dist/partner/redaction.js +257 -0
  280. package/dist/partner/redaction.js.map +1 -0
  281. package/dist/raw/encoding.cjs +74 -35
  282. package/dist/raw/encoding.cjs.map +1 -1
  283. package/dist/raw/encoding.js +74 -38
  284. package/dist/raw/encoding.js.map +1 -1
  285. package/dist/raw/index.cjs +740 -587
  286. package/dist/raw/index.cjs.map +1 -1
  287. package/dist/raw/index.d.cts +126 -19
  288. package/dist/raw/index.d.cts.map +1 -1
  289. package/dist/raw/index.d.ts +126 -19
  290. package/dist/raw/index.d.ts.map +1 -1
  291. package/dist/raw/index.js +736 -589
  292. package/dist/raw/index.js.map +1 -1
  293. package/dist/raw/url.cjs +111 -0
  294. package/dist/raw/url.cjs.map +1 -0
  295. package/dist/raw/url.d.cts +41 -0
  296. package/dist/raw/url.d.cts.map +1 -0
  297. package/dist/raw/url.d.ts +41 -0
  298. package/dist/raw/url.d.ts.map +1 -0
  299. package/dist/raw/url.js +110 -0
  300. package/dist/raw/url.js.map +1 -0
  301. package/dist/s3/index.cjs +355 -18
  302. package/dist/s3/index.cjs.map +1 -1
  303. package/dist/s3/index.d.cts +233 -5
  304. package/dist/s3/index.d.cts.map +1 -1
  305. package/dist/s3/index.d.ts +233 -5
  306. package/dist/s3/index.d.ts.map +1 -1
  307. package/dist/s3/index.js +351 -22
  308. package/dist/s3/index.js.map +1 -1
  309. package/dist/s3/sigv4.cjs +154 -0
  310. package/dist/s3/sigv4.cjs.map +1 -0
  311. package/dist/s3/sigv4.d.cts +43 -0
  312. package/dist/s3/sigv4.d.cts.map +1 -0
  313. package/dist/s3/sigv4.d.ts +43 -0
  314. package/dist/s3/sigv4.d.ts.map +1 -0
  315. package/dist/s3/sigv4.js +153 -0
  316. package/dist/s3/sigv4.js.map +1 -0
  317. package/dist/s3/validation.cjs +69 -0
  318. package/dist/s3/validation.cjs.map +1 -0
  319. package/dist/s3/validation.d.cts +43 -0
  320. package/dist/s3/validation.d.cts.map +1 -0
  321. package/dist/s3/validation.d.ts +43 -0
  322. package/dist/s3/validation.d.ts.map +1 -0
  323. package/dist/s3/validation.js +66 -0
  324. package/dist/s3/validation.js.map +1 -0
  325. package/dist/simulator/capabilities.cjs +63 -48
  326. package/dist/simulator/capabilities.cjs.map +1 -1
  327. package/dist/simulator/capabilities.js +63 -49
  328. package/dist/simulator/capabilities.js.map +1 -1
  329. package/dist/simulator/index.cjs +3114 -1547
  330. package/dist/simulator/index.cjs.map +1 -1
  331. package/dist/simulator/index.d.cts +186 -20
  332. package/dist/simulator/index.d.cts.map +1 -1
  333. package/dist/simulator/index.d.ts +186 -20
  334. package/dist/simulator/index.d.ts.map +1 -1
  335. package/dist/simulator/index.js +3098 -1545
  336. package/dist/simulator/index.js.map +1 -1
  337. package/dist/simulator/partner.cjs +719 -0
  338. package/dist/simulator/partner.cjs.map +1 -0
  339. package/dist/simulator/partner.d.cts +183 -0
  340. package/dist/simulator/partner.d.cts.map +1 -0
  341. package/dist/simulator/partner.d.ts +183 -0
  342. package/dist/simulator/partner.d.ts.map +1 -0
  343. package/dist/simulator/partner.js +718 -0
  344. package/dist/simulator/partner.js.map +1 -0
  345. package/dist/simulator/validation.cjs +772 -157
  346. package/dist/simulator/validation.cjs.map +1 -1
  347. package/dist/simulator/validation.d.cts +120 -21
  348. package/dist/simulator/validation.d.cts.map +1 -1
  349. package/dist/simulator/validation.d.ts +120 -21
  350. package/dist/simulator/validation.d.ts.map +1 -1
  351. package/dist/simulator/validation.js +755 -167
  352. package/dist/simulator/validation.js.map +1 -1
  353. package/dist/streams/collect.cjs +74 -24
  354. package/dist/streams/collect.cjs.map +1 -1
  355. package/dist/streams/collect.d.cts +14 -1
  356. package/dist/streams/collect.d.cts.map +1 -1
  357. package/dist/streams/collect.d.ts +14 -1
  358. package/dist/streams/collect.d.ts.map +1 -1
  359. package/dist/streams/collect.js +74 -25
  360. package/dist/streams/collect.js.map +1 -1
  361. package/dist/streams/file-source.cjs +287 -0
  362. package/dist/streams/file-source.cjs.map +1 -0
  363. package/dist/streams/file-source.d.cts +96 -0
  364. package/dist/streams/file-source.d.cts.map +1 -0
  365. package/dist/streams/file-source.d.ts +96 -0
  366. package/dist/streams/file-source.d.ts.map +1 -0
  367. package/dist/streams/file-source.js +286 -0
  368. package/dist/streams/file-source.js.map +1 -0
  369. package/dist/streams/hash.cjs +207 -115
  370. package/dist/streams/hash.cjs.map +1 -1
  371. package/dist/streams/hash.d.cts +5 -4
  372. package/dist/streams/hash.d.cts.map +1 -1
  373. package/dist/streams/hash.d.ts +5 -4
  374. package/dist/streams/hash.d.ts.map +1 -1
  375. package/dist/streams/hash.js +208 -95
  376. package/dist/streams/hash.js.map +1 -1
  377. package/dist/streams/index.cjs +12 -12
  378. package/dist/streams/index.d.cts +3 -3
  379. package/dist/streams/index.d.cts.map +1 -1
  380. package/dist/streams/index.d.ts +3 -3
  381. package/dist/streams/index.d.ts.map +1 -1
  382. package/dist/streams/index.js +3 -11
  383. package/dist/streams/progress.cjs +60 -46
  384. package/dist/streams/progress.cjs.map +1 -1
  385. package/dist/streams/progress.js +60 -46
  386. package/dist/streams/progress.js.map +1 -1
  387. package/dist/streams/source.cjs +317 -146
  388. package/dist/streams/source.cjs.map +1 -1
  389. package/dist/streams/source.d.cts +56 -18
  390. package/dist/streams/source.d.cts.map +1 -1
  391. package/dist/streams/source.d.ts +56 -18
  392. package/dist/streams/source.d.ts.map +1 -1
  393. package/dist/streams/source.js +313 -149
  394. package/dist/streams/source.js.map +1 -1
  395. package/dist/sync/actions/index.cjs +236 -184
  396. package/dist/sync/actions/index.cjs.map +1 -1
  397. package/dist/sync/actions/index.d.cts +29 -21
  398. package/dist/sync/actions/index.d.cts.map +1 -1
  399. package/dist/sync/actions/index.d.ts +29 -21
  400. package/dist/sync/actions/index.d.ts.map +1 -1
  401. package/dist/sync/actions/index.js +236 -190
  402. package/dist/sync/actions/index.js.map +1 -1
  403. package/dist/sync/b2-sha1-reader.cjs +152 -0
  404. package/dist/sync/b2-sha1-reader.cjs.map +1 -0
  405. package/dist/sync/b2-sha1-reader.d.cts +58 -0
  406. package/dist/sync/b2-sha1-reader.d.cts.map +1 -0
  407. package/dist/sync/b2-sha1-reader.d.ts +58 -0
  408. package/dist/sync/b2-sha1-reader.d.ts.map +1 -0
  409. package/dist/sync/b2-sha1-reader.js +149 -0
  410. package/dist/sync/b2-sha1-reader.js.map +1 -0
  411. package/dist/sync/download-staging.cjs +266 -0
  412. package/dist/sync/download-staging.cjs.map +1 -0
  413. package/dist/sync/download-staging.d.cts +55 -0
  414. package/dist/sync/download-staging.d.cts.map +1 -0
  415. package/dist/sync/download-staging.d.ts +55 -0
  416. package/dist/sync/download-staging.d.ts.map +1 -0
  417. package/dist/sync/download-staging.js +260 -0
  418. package/dist/sync/download-staging.js.map +1 -0
  419. package/dist/sync/filesystem-errors.cjs +32 -0
  420. package/dist/sync/filesystem-errors.cjs.map +1 -0
  421. package/dist/sync/filesystem-errors.d.cts +8 -0
  422. package/dist/sync/filesystem-errors.d.cts.map +1 -0
  423. package/dist/sync/filesystem-errors.d.ts +8 -0
  424. package/dist/sync/filesystem-errors.d.ts.map +1 -0
  425. package/dist/sync/filesystem-errors.js +32 -0
  426. package/dist/sync/filesystem-errors.js.map +1 -0
  427. package/dist/sync/filters.cjs +217 -0
  428. package/dist/sync/filters.cjs.map +1 -0
  429. package/dist/sync/filters.d.cts +51 -0
  430. package/dist/sync/filters.d.cts.map +1 -0
  431. package/dist/sync/filters.d.ts +51 -0
  432. package/dist/sync/filters.d.ts.map +1 -0
  433. package/dist/sync/filters.js +213 -0
  434. package/dist/sync/filters.js.map +1 -0
  435. package/dist/sync/index.cjs +39 -22
  436. package/dist/sync/index.d.cts +14 -9
  437. package/dist/sync/index.d.cts.map +1 -1
  438. package/dist/sync/index.d.ts +14 -9
  439. package/dist/sync/index.d.ts.map +1 -1
  440. package/dist/sync/index.js +9 -20
  441. package/dist/sync/local-file-identity.cjs +61 -0
  442. package/dist/sync/local-file-identity.cjs.map +1 -0
  443. package/dist/sync/local-file-identity.d.cts +37 -0
  444. package/dist/sync/local-file-identity.d.cts.map +1 -0
  445. package/dist/sync/local-file-identity.d.ts +37 -0
  446. package/dist/sync/local-file-identity.d.ts.map +1 -0
  447. package/dist/sync/local-file-identity.js +60 -0
  448. package/dist/sync/local-file-identity.js.map +1 -0
  449. package/dist/sync/local-file-io.cjs +369 -0
  450. package/dist/sync/local-file-io.cjs.map +1 -0
  451. package/dist/sync/local-file-io.d.cts +76 -0
  452. package/dist/sync/local-file-io.d.cts.map +1 -0
  453. package/dist/sync/local-file-io.d.ts +76 -0
  454. package/dist/sync/local-file-io.d.ts.map +1 -0
  455. package/dist/sync/local-file-io.js +365 -0
  456. package/dist/sync/local-file-io.js.map +1 -0
  457. package/dist/sync/local-filesystem-root.cjs +27 -0
  458. package/dist/sync/local-filesystem-root.cjs.map +1 -0
  459. package/dist/sync/local-filesystem-root.d.cts +18 -0
  460. package/dist/sync/local-filesystem-root.d.cts.map +1 -0
  461. package/dist/sync/local-filesystem-root.d.ts +18 -0
  462. package/dist/sync/local-filesystem-root.d.ts.map +1 -0
  463. package/dist/sync/local-filesystem-root.js +26 -0
  464. package/dist/sync/local-filesystem-root.js.map +1 -0
  465. package/dist/sync/local-sha1.cjs +110 -0
  466. package/dist/sync/local-sha1.cjs.map +1 -0
  467. package/dist/sync/local-sha1.d.cts +31 -0
  468. package/dist/sync/local-sha1.d.cts.map +1 -0
  469. package/dist/sync/local-sha1.d.ts +31 -0
  470. package/dist/sync/local-sha1.d.ts.map +1 -0
  471. package/dist/sync/local-sha1.js +109 -0
  472. package/dist/sync/local-sha1.js.map +1 -0
  473. package/dist/sync/pairing.cjs +118 -29
  474. package/dist/sync/pairing.cjs.map +1 -1
  475. package/dist/sync/pairing.d.cts +7 -2
  476. package/dist/sync/pairing.d.cts.map +1 -1
  477. package/dist/sync/pairing.d.ts +7 -2
  478. package/dist/sync/pairing.d.ts.map +1 -1
  479. package/dist/sync/pairing.js +120 -31
  480. package/dist/sync/pairing.js.map +1 -1
  481. package/dist/sync/path-order.cjs +30 -0
  482. package/dist/sync/path-order.cjs.map +1 -0
  483. package/dist/sync/path-order.d.cts +28 -0
  484. package/dist/sync/path-order.d.cts.map +1 -0
  485. package/dist/sync/path-order.d.ts +28 -0
  486. package/dist/sync/path-order.d.ts.map +1 -0
  487. package/dist/sync/path-order.js +29 -0
  488. package/dist/sync/path-order.js.map +1 -0
  489. package/dist/sync/path-safety.cjs +111 -0
  490. package/dist/sync/path-safety.cjs.map +1 -0
  491. package/dist/sync/path-safety.d.cts +78 -0
  492. package/dist/sync/path-safety.d.cts.map +1 -0
  493. package/dist/sync/path-safety.d.ts +78 -0
  494. package/dist/sync/path-safety.d.ts.map +1 -0
  495. package/dist/sync/path-safety.js +105 -0
  496. package/dist/sync/path-safety.js.map +1 -0
  497. package/dist/sync/paths.d.cts +19 -0
  498. package/dist/sync/paths.d.cts.map +1 -0
  499. package/dist/sync/paths.d.ts +19 -0
  500. package/dist/sync/paths.d.ts.map +1 -0
  501. package/dist/sync/policies/compare.cjs +391 -11
  502. package/dist/sync/policies/compare.cjs.map +1 -1
  503. package/dist/sync/policies/compare.d.cts +100 -2
  504. package/dist/sync/policies/compare.d.cts.map +1 -1
  505. package/dist/sync/policies/compare.d.ts +100 -2
  506. package/dist/sync/policies/compare.d.ts.map +1 -1
  507. package/dist/sync/policies/compare.js +389 -13
  508. package/dist/sync/policies/compare.js.map +1 -1
  509. package/dist/sync/policies/index.cjs +70 -65
  510. package/dist/sync/policies/index.cjs.map +1 -1
  511. package/dist/sync/policies/index.d.cts +35 -6
  512. package/dist/sync/policies/index.d.cts.map +1 -1
  513. package/dist/sync/policies/index.d.ts +35 -6
  514. package/dist/sync/policies/index.d.ts.map +1 -1
  515. package/dist/sync/policies/index.js +70 -65
  516. package/dist/sync/policies/index.js.map +1 -1
  517. package/dist/sync/prefix.cjs +96 -0
  518. package/dist/sync/prefix.cjs.map +1 -0
  519. package/dist/sync/prefix.d.cts +55 -0
  520. package/dist/sync/prefix.d.cts.map +1 -0
  521. package/dist/sync/prefix.d.ts +55 -0
  522. package/dist/sync/prefix.d.ts.map +1 -0
  523. package/dist/sync/prefix.js +92 -0
  524. package/dist/sync/prefix.js.map +1 -0
  525. package/dist/sync/regexp-safety.cjs +192 -0
  526. package/dist/sync/regexp-safety.cjs.map +1 -0
  527. package/dist/sync/regexp-safety.d.cts +29 -0
  528. package/dist/sync/regexp-safety.d.cts.map +1 -0
  529. package/dist/sync/regexp-safety.d.ts +29 -0
  530. package/dist/sync/regexp-safety.d.ts.map +1 -0
  531. package/dist/sync/regexp-safety.js +190 -0
  532. package/dist/sync/regexp-safety.js.map +1 -0
  533. package/dist/sync/scan-events.cjs +33 -0
  534. package/dist/sync/scan-events.cjs.map +1 -0
  535. package/dist/sync/scan-events.d.cts +17 -0
  536. package/dist/sync/scan-events.d.cts.map +1 -0
  537. package/dist/sync/scan-events.d.ts +17 -0
  538. package/dist/sync/scan-events.d.ts.map +1 -0
  539. package/dist/sync/scan-events.js +32 -0
  540. package/dist/sync/scan-events.js.map +1 -0
  541. package/dist/sync/scan-limit.cjs +33 -0
  542. package/dist/sync/scan-limit.cjs.map +1 -0
  543. package/dist/sync/scan-limit.d.cts +21 -0
  544. package/dist/sync/scan-limit.d.cts.map +1 -0
  545. package/dist/sync/scan-limit.d.ts +21 -0
  546. package/dist/sync/scan-limit.d.ts.map +1 -0
  547. package/dist/sync/scan-limit.js +31 -0
  548. package/dist/sync/scan-limit.js.map +1 -0
  549. package/dist/sync/scanners/b2.cjs +239 -55
  550. package/dist/sync/scanners/b2.cjs.map +1 -1
  551. package/dist/sync/scanners/b2.d.cts +26 -7
  552. package/dist/sync/scanners/b2.d.cts.map +1 -1
  553. package/dist/sync/scanners/b2.d.ts +26 -7
  554. package/dist/sync/scanners/b2.d.ts.map +1 -1
  555. package/dist/sync/scanners/b2.js +239 -55
  556. package/dist/sync/scanners/b2.js.map +1 -1
  557. package/dist/sync/scanners/local.cjs +215 -56
  558. package/dist/sync/scanners/local.cjs.map +1 -1
  559. package/dist/sync/scanners/local.d.cts +22 -7
  560. package/dist/sync/scanners/local.d.cts.map +1 -1
  561. package/dist/sync/scanners/local.d.ts +22 -7
  562. package/dist/sync/scanners/local.d.ts.map +1 -1
  563. package/dist/sync/scanners/local.js +216 -57
  564. package/dist/sync/scanners/local.js.map +1 -1
  565. package/dist/sync/sha1-metadata.cjs +94 -0
  566. package/dist/sync/sha1-metadata.cjs.map +1 -0
  567. package/dist/sync/sha1-metadata.d.cts +82 -0
  568. package/dist/sync/sha1-metadata.d.cts.map +1 -0
  569. package/dist/sync/sha1-metadata.d.ts +82 -0
  570. package/dist/sync/sha1-metadata.d.ts.map +1 -0
  571. package/dist/sync/sha1-metadata.js +89 -0
  572. package/dist/sync/sha1-metadata.js.map +1 -0
  573. package/dist/sync/sha1-options.cjs +23 -0
  574. package/dist/sync/sha1-options.cjs.map +1 -0
  575. package/dist/sync/sha1-options.d.cts +14 -0
  576. package/dist/sync/sha1-options.d.cts.map +1 -0
  577. package/dist/sync/sha1-options.d.ts +14 -0
  578. package/dist/sync/sha1-options.d.ts.map +1 -0
  579. package/dist/sync/sha1-options.js +21 -0
  580. package/dist/sync/sha1-options.js.map +1 -0
  581. package/dist/sync/synchronizer.cjs +783 -197
  582. package/dist/sync/synchronizer.cjs.map +1 -1
  583. package/dist/sync/synchronizer.d.cts +47 -1
  584. package/dist/sync/synchronizer.d.cts.map +1 -1
  585. package/dist/sync/synchronizer.d.ts +47 -1
  586. package/dist/sync/synchronizer.d.ts.map +1 -1
  587. package/dist/sync/synchronizer.js +780 -173
  588. package/dist/sync/synchronizer.js.map +1 -1
  589. package/dist/sync/types.d.cts +208 -16
  590. package/dist/sync/types.d.cts.map +1 -1
  591. package/dist/sync/types.d.ts +208 -16
  592. package/dist/sync/types.d.ts.map +1 -1
  593. package/dist/types/auth.cjs +80 -56
  594. package/dist/types/auth.cjs.map +1 -1
  595. package/dist/types/auth.d.cts +71 -9
  596. package/dist/types/auth.d.cts.map +1 -1
  597. package/dist/types/auth.d.ts +71 -9
  598. package/dist/types/auth.d.ts.map +1 -1
  599. package/dist/types/auth.js +81 -57
  600. package/dist/types/auth.js.map +1 -1
  601. package/dist/types/backup.d.cts +80 -0
  602. package/dist/types/backup.d.cts.map +1 -0
  603. package/dist/types/backup.d.ts +80 -0
  604. package/dist/types/backup.d.ts.map +1 -0
  605. package/dist/types/bucket.cjs +74 -38
  606. package/dist/types/bucket.cjs.map +1 -1
  607. package/dist/types/bucket.d.cts +4 -2
  608. package/dist/types/bucket.d.cts.map +1 -1
  609. package/dist/types/bucket.d.ts +4 -2
  610. package/dist/types/bucket.d.ts.map +1 -1
  611. package/dist/types/bucket.js +75 -41
  612. package/dist/types/bucket.js.map +1 -1
  613. package/dist/types/download.cjs +62 -0
  614. package/dist/types/download.cjs.map +1 -0
  615. package/dist/types/download.d.cts +98 -0
  616. package/dist/types/download.d.cts.map +1 -1
  617. package/dist/types/download.d.ts +98 -0
  618. package/dist/types/download.d.ts.map +1 -1
  619. package/dist/types/download.js +61 -0
  620. package/dist/types/download.js.map +1 -0
  621. package/dist/types/encryption.cjs +194 -328
  622. package/dist/types/encryption.cjs.map +1 -1
  623. package/dist/types/encryption.d.cts +48 -0
  624. package/dist/types/encryption.d.cts.map +1 -1
  625. package/dist/types/encryption.d.ts +48 -0
  626. package/dist/types/encryption.d.ts.map +1 -1
  627. package/dist/types/encryption.js +192 -311
  628. package/dist/types/encryption.js.map +1 -1
  629. package/dist/types/errors.cjs +56 -0
  630. package/dist/types/errors.cjs.map +1 -0
  631. package/dist/types/errors.d.cts +13 -4
  632. package/dist/types/errors.d.cts.map +1 -1
  633. package/dist/types/errors.d.ts +13 -4
  634. package/dist/types/errors.d.ts.map +1 -1
  635. package/dist/types/errors.js +56 -0
  636. package/dist/types/errors.js.map +1 -0
  637. package/dist/types/file.cjs +36 -19
  638. package/dist/types/file.cjs.map +1 -1
  639. package/dist/types/file.d.cts +17 -4
  640. package/dist/types/file.d.cts.map +1 -1
  641. package/dist/types/file.d.ts +17 -4
  642. package/dist/types/file.d.ts.map +1 -1
  643. package/dist/types/file.js +37 -21
  644. package/dist/types/file.js.map +1 -1
  645. package/dist/types/ids.cjs +83 -9
  646. package/dist/types/ids.cjs.map +1 -1
  647. package/dist/types/ids.d.cts +32 -0
  648. package/dist/types/ids.d.cts.map +1 -1
  649. package/dist/types/ids.d.ts +32 -0
  650. package/dist/types/ids.d.ts.map +1 -1
  651. package/dist/types/ids.js +82 -16
  652. package/dist/types/ids.js.map +1 -1
  653. package/dist/types/index.d.cts +18 -13
  654. package/dist/types/index.d.cts.map +1 -1
  655. package/dist/types/index.d.ts +18 -13
  656. package/dist/types/index.d.ts.map +1 -1
  657. package/dist/types/key.d.cts +44 -8
  658. package/dist/types/key.d.cts.map +1 -1
  659. package/dist/types/key.d.ts +44 -8
  660. package/dist/types/key.d.ts.map +1 -1
  661. package/dist/types/lock.cjs +33 -13
  662. package/dist/types/lock.cjs.map +1 -1
  663. package/dist/types/lock.d.cts +14 -0
  664. package/dist/types/lock.d.cts.map +1 -1
  665. package/dist/types/lock.d.ts +14 -0
  666. package/dist/types/lock.d.ts.map +1 -1
  667. package/dist/types/lock.js +34 -15
  668. package/dist/types/lock.js.map +1 -1
  669. package/dist/types/notifications.cjs +44 -22
  670. package/dist/types/notifications.cjs.map +1 -1
  671. package/dist/types/notifications.d.cts +5 -3
  672. package/dist/types/notifications.d.cts.map +1 -1
  673. package/dist/types/notifications.d.ts +5 -3
  674. package/dist/types/notifications.d.ts.map +1 -1
  675. package/dist/types/notifications.js +45 -23
  676. package/dist/types/notifications.js.map +1 -1
  677. package/dist/types/partner.cjs +32 -0
  678. package/dist/types/partner.cjs.map +1 -0
  679. package/dist/types/partner.d.cts +394 -0
  680. package/dist/types/partner.d.cts.map +1 -0
  681. package/dist/types/partner.d.ts +394 -0
  682. package/dist/types/partner.d.ts.map +1 -0
  683. package/dist/types/partner.js +29 -0
  684. package/dist/types/partner.js.map +1 -0
  685. package/dist/types/upload.d.cts +53 -6
  686. package/dist/types/upload.d.cts.map +1 -1
  687. package/dist/types/upload.d.ts +53 -6
  688. package/dist/types/upload.d.ts.map +1 -1
  689. package/dist/upload/abort-scope.cjs +46 -0
  690. package/dist/upload/abort-scope.cjs.map +1 -0
  691. package/dist/upload/abort-scope.d.cts +26 -0
  692. package/dist/upload/abort-scope.d.cts.map +1 -0
  693. package/dist/upload/abort-scope.d.ts +26 -0
  694. package/dist/upload/abort-scope.d.ts.map +1 -0
  695. package/dist/upload/abort-scope.js +45 -0
  696. package/dist/upload/abort-scope.js.map +1 -0
  697. package/dist/upload/cancel.cjs +183 -8
  698. package/dist/upload/cancel.cjs.map +1 -1
  699. package/dist/upload/cancel.d.cts +110 -2
  700. package/dist/upload/cancel.d.cts.map +1 -1
  701. package/dist/upload/cancel.d.ts +110 -2
  702. package/dist/upload/cancel.d.ts.map +1 -1
  703. package/dist/upload/cancel.js +178 -9
  704. package/dist/upload/cancel.js.map +1 -1
  705. package/dist/upload/concurrency.cjs +79 -52
  706. package/dist/upload/concurrency.cjs.map +1 -1
  707. package/dist/upload/concurrency.js +79 -53
  708. package/dist/upload/concurrency.js.map +1 -1
  709. package/dist/upload/finish.cjs +54 -0
  710. package/dist/upload/finish.cjs.map +1 -0
  711. package/dist/upload/finish.d.cts +26 -0
  712. package/dist/upload/finish.d.cts.map +1 -0
  713. package/dist/upload/finish.d.ts +26 -0
  714. package/dist/upload/finish.d.ts.map +1 -0
  715. package/dist/upload/finish.js +54 -0
  716. package/dist/upload/finish.js.map +1 -0
  717. package/dist/upload/large.cjs +305 -218
  718. package/dist/upload/large.cjs.map +1 -1
  719. package/dist/upload/large.d.cts +90 -9
  720. package/dist/upload/large.d.cts.map +1 -1
  721. package/dist/upload/large.d.ts +90 -9
  722. package/dist/upload/large.d.ts.map +1 -1
  723. package/dist/upload/large.js +305 -218
  724. package/dist/upload/large.js.map +1 -1
  725. package/dist/upload/options.cjs +28 -0
  726. package/dist/upload/options.cjs.map +1 -0
  727. package/dist/upload/options.d.cts +116 -0
  728. package/dist/upload/options.d.cts.map +1 -0
  729. package/dist/upload/options.d.ts +116 -0
  730. package/dist/upload/options.d.ts.map +1 -0
  731. package/dist/upload/options.js +27 -0
  732. package/dist/upload/options.js.map +1 -0
  733. package/dist/upload/resume.cjs +334 -33
  734. package/dist/upload/resume.cjs.map +1 -1
  735. package/dist/upload/resume.d.cts +84 -12
  736. package/dist/upload/resume.d.cts.map +1 -1
  737. package/dist/upload/resume.d.ts +84 -12
  738. package/dist/upload/resume.d.ts.map +1 -1
  739. package/dist/upload/resume.js +331 -33
  740. package/dist/upload/resume.js.map +1 -1
  741. package/dist/upload/retry.cjs +191 -0
  742. package/dist/upload/retry.cjs.map +1 -0
  743. package/dist/upload/retry.d.cts +127 -0
  744. package/dist/upload/retry.d.cts.map +1 -0
  745. package/dist/upload/retry.d.ts +127 -0
  746. package/dist/upload/retry.d.ts.map +1 -0
  747. package/dist/upload/retry.js +187 -0
  748. package/dist/upload/retry.js.map +1 -0
  749. package/dist/upload/single.cjs +69 -44
  750. package/dist/upload/single.cjs.map +1 -1
  751. package/dist/upload/single.d.cts +8 -1
  752. package/dist/upload/single.d.cts.map +1 -1
  753. package/dist/upload/single.d.ts +8 -1
  754. package/dist/upload/single.d.ts.map +1 -1
  755. package/dist/upload/single.js +69 -44
  756. package/dist/upload/single.js.map +1 -1
  757. package/dist/upload/stream.cjs +319 -193
  758. package/dist/upload/stream.cjs.map +1 -1
  759. package/dist/upload/stream.d.cts +9 -1
  760. package/dist/upload/stream.d.cts.map +1 -1
  761. package/dist/upload/stream.d.ts +9 -1
  762. package/dist/upload/stream.d.ts.map +1 -1
  763. package/dist/upload/stream.js +318 -192
  764. package/dist/upload/stream.js.map +1 -1
  765. package/dist/util/abort.cjs +114 -0
  766. package/dist/util/abort.cjs.map +1 -0
  767. package/dist/util/abort.d.cts +65 -0
  768. package/dist/util/abort.d.cts.map +1 -0
  769. package/dist/util/abort.d.ts +65 -0
  770. package/dist/util/abort.d.ts.map +1 -0
  771. package/dist/util/abort.js +109 -0
  772. package/dist/util/abort.js.map +1 -0
  773. package/dist/util/best-effort.cjs +42 -8
  774. package/dist/util/best-effort.cjs.map +1 -1
  775. package/dist/util/best-effort.d.cts +2 -1
  776. package/dist/util/best-effort.d.cts.map +1 -1
  777. package/dist/util/best-effort.d.ts +2 -1
  778. package/dist/util/best-effort.d.ts.map +1 -1
  779. package/dist/util/best-effort.js +43 -9
  780. package/dist/util/best-effort.js.map +1 -1
  781. package/dist/util/bytes.cjs +23 -0
  782. package/dist/util/bytes.cjs.map +1 -0
  783. package/dist/util/bytes.d.cts +15 -0
  784. package/dist/util/bytes.d.cts.map +1 -0
  785. package/dist/util/bytes.d.ts +15 -0
  786. package/dist/util/bytes.d.ts.map +1 -0
  787. package/dist/util/bytes.js +23 -0
  788. package/dist/util/bytes.js.map +1 -0
  789. package/dist/util/crypto.cjs +68 -0
  790. package/dist/util/crypto.cjs.map +1 -0
  791. package/dist/util/crypto.d.cts +26 -0
  792. package/dist/util/crypto.d.cts.map +1 -0
  793. package/dist/util/crypto.d.ts +26 -0
  794. package/dist/util/crypto.d.ts.map +1 -0
  795. package/dist/util/crypto.js +66 -0
  796. package/dist/util/crypto.js.map +1 -0
  797. package/dist/util/defaults.cjs +28 -9
  798. package/dist/util/defaults.cjs.map +1 -1
  799. package/dist/util/defaults.d.cts +2 -0
  800. package/dist/util/defaults.d.cts.map +1 -1
  801. package/dist/util/defaults.d.ts +2 -0
  802. package/dist/util/defaults.d.ts.map +1 -1
  803. package/dist/util/defaults.js +28 -11
  804. package/dist/util/defaults.js.map +1 -1
  805. package/dist/util/error-reason.cjs +41 -0
  806. package/dist/util/error-reason.cjs.map +1 -0
  807. package/dist/util/error-reason.d.cts +9 -0
  808. package/dist/util/error-reason.d.cts.map +1 -0
  809. package/dist/util/error-reason.d.ts +9 -0
  810. package/dist/util/error-reason.d.ts.map +1 -0
  811. package/dist/util/error-reason.js +41 -0
  812. package/dist/util/error-reason.js.map +1 -0
  813. package/dist/util/http.cjs +23 -0
  814. package/dist/util/http.cjs.map +1 -0
  815. package/dist/util/http.d.cts +13 -0
  816. package/dist/util/http.d.cts.map +1 -0
  817. package/dist/util/http.d.ts +13 -0
  818. package/dist/util/http.d.ts.map +1 -0
  819. package/dist/util/http.js +23 -0
  820. package/dist/util/http.js.map +1 -0
  821. package/dist/util/md5.cjs +211 -0
  822. package/dist/util/md5.cjs.map +1 -0
  823. package/dist/util/md5.d.cts +43 -0
  824. package/dist/util/md5.d.cts.map +1 -0
  825. package/dist/util/md5.d.ts +43 -0
  826. package/dist/util/md5.d.ts.map +1 -0
  827. package/dist/util/md5.js +209 -0
  828. package/dist/util/md5.js.map +1 -0
  829. package/dist/util/normalize.cjs +66 -7
  830. package/dist/util/normalize.cjs.map +1 -1
  831. package/dist/util/normalize.d.cts +7 -7
  832. package/dist/util/normalize.d.cts.map +1 -1
  833. package/dist/util/normalize.d.ts +7 -7
  834. package/dist/util/normalize.d.ts.map +1 -1
  835. package/dist/util/normalize.js +67 -10
  836. package/dist/util/normalize.js.map +1 -1
  837. package/dist/util/paginator.cjs +69 -14
  838. package/dist/util/paginator.cjs.map +1 -1
  839. package/dist/util/paginator.d.cts +3 -1
  840. package/dist/util/paginator.d.cts.map +1 -1
  841. package/dist/util/paginator.d.ts +3 -1
  842. package/dist/util/paginator.d.ts.map +1 -1
  843. package/dist/util/paginator.js +70 -16
  844. package/dist/util/paginator.js.map +1 -1
  845. package/dist/util/plan-ranges.cjs +47 -22
  846. package/dist/util/plan-ranges.cjs.map +1 -1
  847. package/dist/util/plan-ranges.js +48 -24
  848. package/dist/util/plan-ranges.js.map +1 -1
  849. package/dist/util/sha1.cjs +27 -0
  850. package/dist/util/sha1.cjs.map +1 -0
  851. package/dist/util/sha1.d.cts +17 -0
  852. package/dist/util/sha1.d.cts.map +1 -0
  853. package/dist/util/sha1.d.ts +17 -0
  854. package/dist/util/sha1.d.ts.map +1 -0
  855. package/dist/util/sha1.js +26 -0
  856. package/dist/util/sha1.js.map +1 -0
  857. package/dist/util/text-codec.cjs +29 -5
  858. package/dist/util/text-codec.cjs.map +1 -1
  859. package/dist/util/text-codec.js +30 -7
  860. package/dist/util/text-codec.js.map +1 -1
  861. package/dist/util/to-error.cjs +18 -4
  862. package/dist/util/to-error.cjs.map +1 -1
  863. package/dist/util/to-error.js +19 -5
  864. package/dist/util/to-error.js.map +1 -1
  865. package/dist/version.cjs +17 -5
  866. package/dist/version.cjs.map +1 -1
  867. package/dist/version.d.cts +3 -3
  868. package/dist/version.d.ts +3 -3
  869. package/dist/version.js +19 -6
  870. package/dist/version.js.map +1 -1
  871. package/package.json +45 -20
  872. package/dist/auth/index.cjs.map +0 -1
  873. package/dist/auth/index.js.map +0 -1
  874. package/dist/index.cjs.map +0 -1
  875. package/dist/index.js.map +0 -1
  876. package/dist/notifications/index.cjs.map +0 -1
  877. package/dist/notifications/index.js.map +0 -1
  878. package/dist/package.json.cjs +0 -9
  879. package/dist/package.json.cjs.map +0 -1
  880. package/dist/package.json.js +0 -9
  881. package/dist/package.json.js.map +0 -1
  882. package/dist/streams/index.cjs.map +0 -1
  883. package/dist/streams/index.js.map +0 -1
  884. package/dist/sync/index.cjs.map +0 -1
  885. package/dist/sync/index.js.map +0 -1
@@ -1,1559 +1,3126 @@
1
- "use strict";
2
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const hash = require("../streams/hash.cjs");
4
- const auth = require("../types/auth.cjs");
5
- const bucket = require("../types/bucket.cjs");
6
- const encryption = require("../types/encryption.cjs");
7
- const file = require("../types/file.cjs");
8
- const ids = require("../types/ids.cjs");
9
- const textCodec = require("../util/text-codec.cjs");
10
- const toError = require("../util/to-error.cjs");
11
- const capabilities = require("./capabilities.cjs");
12
- const validation = require("./validation.cjs");
2
+ const require_file = require("../types/file.cjs");
3
+ const require_ids = require("../types/ids.cjs");
4
+ const require_text_codec = require("../util/text-codec.cjs");
5
+ const require_encoding = require("../raw/encoding.cjs");
6
+ const require_download = require("../types/download.cjs");
7
+ const require_md5 = require("../util/md5.cjs");
8
+ const require_encryption = require("../types/encryption.cjs");
9
+ const require_lock = require("../types/lock.cjs");
10
+ const require_crypto = require("../util/crypto.cjs");
11
+ const require_hash = require("../streams/hash.cjs");
12
+ const require_bucket = require("../types/bucket.cjs");
13
+ const require_to_error = require("../util/to-error.cjs");
14
+ const require_url = require("../raw/url.cjs");
15
+ const require_auth = require("../types/auth.cjs");
16
+ const require_partner = require("./partner.cjs");
17
+ const require_capabilities = require("./capabilities.cjs");
18
+ const require_b2_naming = require("../internal/b2-naming.cjs");
19
+ const require_validation = require("./validation.cjs");
20
+ //#region src/simulator/index.ts
21
+ var UPLOAD_TOKEN_SIGNING_KEY = [
22
+ "b2 sdk typescript",
23
+ "simulator upload authorization",
24
+ "v1"
25
+ ].join(":");
26
+ var SIMULATOR_MASTER_APPLICATION_KEY_ID = "master-key-id";
27
+ var SIMULATOR_MASTER_APPLICATION_KEY = "master-key";
28
+ var SIMULATOR_TEST_APPLICATION_KEY_ID = "test-key-id";
29
+ var SIMULATOR_TEST_APPLICATION_KEY = "test-key";
30
+ var SIMULATOR_APPLICATION_KEY_ID_PREFIX = "sim_key_";
31
+ var SIMULATOR_MASTER_CAPABILITIES = [
32
+ require_auth.Capability.ListBuckets,
33
+ require_auth.Capability.ListAllBucketNames,
34
+ require_auth.Capability.ReadBuckets,
35
+ require_auth.Capability.WriteBuckets,
36
+ require_auth.Capability.DeleteBuckets,
37
+ require_auth.Capability.ReadBucketEncryption,
38
+ require_auth.Capability.WriteBucketEncryption,
39
+ require_auth.Capability.ReadBucketReplications,
40
+ require_auth.Capability.WriteBucketReplications,
41
+ require_auth.Capability.ReadBucketNotifications,
42
+ require_auth.Capability.WriteBucketNotifications,
43
+ require_auth.Capability.ReadBucketLogging,
44
+ require_auth.Capability.WriteBucketLogging,
45
+ require_auth.Capability.ReadBucketLifecycleRules,
46
+ require_auth.Capability.WriteBucketLifecycleRules,
47
+ require_auth.Capability.ListFiles,
48
+ require_auth.Capability.ReadFiles,
49
+ require_auth.Capability.WriteFiles,
50
+ require_auth.Capability.DeleteFiles,
51
+ require_auth.Capability.ListKeys,
52
+ require_auth.Capability.WriteKeys,
53
+ require_auth.Capability.DeleteKeys,
54
+ require_auth.Capability.ShareFiles
55
+ ];
56
+ function apiPathParts(path) {
57
+ const segments = path.split("/").filter((segment) => segment.length > 0);
58
+ const candidate = segments.at(-2);
59
+ return {
60
+ endpoint: segments.at(-1) ?? "",
61
+ version: candidate !== void 0 && require_url.isB2ApiVersion(candidate) ? candidate : "v3"
62
+ };
63
+ }
64
+ function parseBasicAuthorizationHeader(authzHeader) {
65
+ if (!authzHeader?.startsWith("Basic ")) return null;
66
+ const decoded = (() => {
67
+ try {
68
+ return atob(authzHeader.slice(6));
69
+ } catch {
70
+ return null;
71
+ }
72
+ })();
73
+ if (decoded === null) return null;
74
+ const idx = decoded.indexOf(":");
75
+ if (idx <= 0 || idx === decoded.length - 1) return null;
76
+ return {
77
+ applicationKeyId: decoded.slice(0, idx),
78
+ applicationKey: decoded.slice(idx + 1)
79
+ };
80
+ }
81
+ var B2_MIN_PART_NUMBER = 1;
82
+ var B2_MAX_PART_NUMBER = 1e4;
83
+ function base64UrlEncode(bytes) {
84
+ let binary = "";
85
+ for (const byte of bytes) binary += String.fromCharCode(byte);
86
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
87
+ }
88
+ function base64UrlDecode(encoded) {
89
+ const base64 = encoded.replaceAll("-", "+").replaceAll("_", "/");
90
+ const padding = (4 - base64.length % 4) % 4;
91
+ try {
92
+ const binary = atob(base64.padEnd(base64.length + padding, "="));
93
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+ function timingSafeStringEqual(left, right) {
99
+ const max = Math.max(left.length, right.length);
100
+ let mismatch = left.length === right.length ? 0 : 1;
101
+ for (let i = 0; i < max; i++) mismatch |= (left.charCodeAt(i) || 0) ^ (right.charCodeAt(i) || 0);
102
+ return mismatch === 0;
103
+ }
104
+ var MS_PER_DAY = 864e5;
105
+ var MAX_JS_DATE_MS = 864e13;
106
+ function isValidRetentionTimestamp(timestamp, now = Date.now()) {
107
+ return Number.isFinite(timestamp) && timestamp <= MAX_JS_DATE_MS && timestamp > now;
108
+ }
109
+ /**
110
+ * Parse an RFC 7233 `Range` header value into inclusive start/end byte
111
+ * offsets clamped to the file size. Supports closed (`bytes=0-999`),
112
+ * open-ended (`bytes=1000-`), and suffix (`bytes=-500`) forms.
113
+ *
114
+ * @param header - The raw header value (e.g. `'bytes=0-999'`).
115
+ * @param totalSize - The full file size in bytes (for clamping + suffix).
116
+ *
117
+ * @returns A {@link RangeParseResult} tagged with how the simulator
118
+ * should respond: serve the range, send 416, or ignore the header.
119
+ *
120
+ * @see https://www.rfc-editor.org/rfc/rfc7233#section-2.1
121
+ */
13
122
  function parseRangeHeader(header, totalSize) {
14
- const m = header.match(/^bytes=(\d*)-(\d*)$/);
15
- if (!m) return { kind: "malformed" };
16
- const [, startStr, endStr] = m;
17
- const hasStart = startStr !== "";
18
- const hasEnd = endStr !== "";
19
- if (!hasStart && !hasEnd) return { kind: "malformed" };
20
- if (totalSize === 0) return { kind: "unsatisfiable" };
21
- let start;
22
- let end;
23
- if (!hasStart) {
24
- const suffixLen = Number.parseInt(endStr ?? "0", 10);
25
- if (!Number.isFinite(suffixLen) || suffixLen <= 0) return { kind: "malformed" };
26
- start = Math.max(0, totalSize - suffixLen);
27
- end = totalSize - 1;
28
- } else if (!hasEnd) {
29
- start = Number.parseInt(startStr ?? "0", 10);
30
- end = totalSize - 1;
31
- } else {
32
- start = Number.parseInt(startStr ?? "0", 10);
33
- end = Number.parseInt(endStr ?? "0", 10);
34
- }
35
- if (!Number.isFinite(start) || !Number.isFinite(end) || start < 0 || start > end) {
36
- return { kind: "malformed" };
37
- }
38
- if (start >= totalSize) return { kind: "unsatisfiable" };
39
- end = Math.min(end, totalSize - 1);
40
- return { kind: "ok", start, end };
123
+ const m = header.match(/^bytes=(\d*)-(\d*)$/);
124
+ if (!m) return { kind: "malformed" };
125
+ const [, startStr, endStr] = m;
126
+ const hasStart = startStr !== "";
127
+ const hasEnd = endStr !== "";
128
+ if (!hasStart && !hasEnd) return { kind: "malformed" };
129
+ if (totalSize === 0) return { kind: "unsatisfiable" };
130
+ let start;
131
+ let end;
132
+ if (!hasStart) {
133
+ const suffixLen = Number.parseInt(endStr ?? "0", 10);
134
+ if (!Number.isFinite(suffixLen) || suffixLen <= 0) return { kind: "malformed" };
135
+ start = Math.max(0, totalSize - suffixLen);
136
+ end = totalSize - 1;
137
+ } else if (!hasEnd) {
138
+ start = Number.parseInt(startStr ?? "0", 10);
139
+ end = totalSize - 1;
140
+ } else {
141
+ start = Number.parseInt(startStr ?? "0", 10);
142
+ end = Number.parseInt(endStr ?? "0", 10);
143
+ }
144
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start < 0 || start > end) return { kind: "malformed" };
145
+ if (start >= totalSize) return { kind: "unsatisfiable" };
146
+ end = Math.min(end, totalSize - 1);
147
+ return {
148
+ kind: "ok",
149
+ start,
150
+ end
151
+ };
41
152
  }
153
+ /**
154
+ * Parse `X-Bz-Info-*` headers (lowercased Map keys) into a plain
155
+ * fileInfo record. Mirrors the SDK's `parseFileInfoHeaders` in
156
+ * `raw/encoding.ts` but operates on a `Record<string, string>` rather
157
+ * than a `Headers` object so the simulator can reuse the same
158
+ * extraction logic without converting back to `Headers`.
159
+ *
160
+ * @param headers - Lowercased header map.
161
+ *
162
+ * @returns Plain `Record<string, string>` of `fileInfo` keys/values.
163
+ */
42
164
  function parseFileInfoHeaders(headers) {
43
- const info = {};
44
- const prefix = "x-bz-info-";
45
- for (const [key, value] of Object.entries(headers)) {
46
- if (!key.startsWith(prefix)) continue;
47
- const fileInfoKey = decodeURIComponent(key.slice(prefix.length));
48
- info[fileInfoKey] = decodeURIComponent(value);
49
- }
50
- return info;
165
+ const info = {};
166
+ const prefix = "x-bz-info-";
167
+ for (const [key, value] of Object.entries(headers)) {
168
+ if (!key.startsWith(prefix)) continue;
169
+ const fileInfoKey = decodeURIComponent(key.slice(10));
170
+ info[fileInfoKey] = decodeURIComponent(value);
171
+ }
172
+ return info;
173
+ }
174
+ function decodeHeaderValue(value) {
175
+ try {
176
+ return decodeURIComponent(value);
177
+ } catch {
178
+ return value;
179
+ }
180
+ }
181
+ /**
182
+ * Compares B2 file names with deterministic JS string order, not locale collation.
183
+ *
184
+ * @param a - First file name.
185
+ * @param b - Second file name.
186
+ *
187
+ * @returns `-1` when `a` sorts first, `1` when `b` sorts first, otherwise `0`.
188
+ */
189
+ function compareB2FileNames(a, b) {
190
+ if (a < b) return -1;
191
+ if (a > b) return 1;
192
+ return 0;
193
+ }
194
+ var DOWNLOAD_AUTH_TOKEN_BYTES = 32;
195
+ var DOWNLOAD_AUTH_TOKEN_PREFIX = "sim_dl_auth_";
196
+ var DOWNLOAD_AUTH_PURGE_BATCH_SIZE = 128;
197
+ var DOWNLOAD_RESPONSE_OVERRIDE_PARAMS = [
198
+ "b2ContentDisposition",
199
+ "b2ContentLanguage",
200
+ "b2ContentEncoding",
201
+ "b2ContentType",
202
+ "b2CacheControl",
203
+ "b2Expires"
204
+ ];
205
+ var DOWNLOAD_RESPONSE_OVERRIDE_HEADERS = {
206
+ b2ContentDisposition: require_download.DownloadHeaderName.ContentDisposition,
207
+ b2ContentLanguage: require_download.DownloadHeaderName.ContentLanguage,
208
+ b2ContentEncoding: require_download.DownloadHeaderName.ContentEncoding,
209
+ b2ContentType: require_download.DownloadHeaderName.ContentType,
210
+ b2CacheControl: require_download.DownloadHeaderName.CacheControl,
211
+ b2Expires: require_download.DownloadHeaderName.Expires
212
+ };
213
+ function randomDownloadAuthorizationToken() {
214
+ const crypto = globalThis.crypto;
215
+ if (typeof crypto?.getRandomValues !== "function") throw new Error("Download authorization tokens require globalThis.crypto.getRandomValues");
216
+ const bytes = new Uint8Array(DOWNLOAD_AUTH_TOKEN_BYTES);
217
+ crypto.getRandomValues(bytes);
218
+ return `${DOWNLOAD_AUTH_TOKEN_PREFIX}${require_crypto.hexEncode(bytes)}`;
219
+ }
220
+ function pickDownloadResponseOverrides(req) {
221
+ const overrides = {};
222
+ for (const param of DOWNLOAD_RESPONSE_OVERRIDE_PARAMS) {
223
+ const value = req[param];
224
+ if (typeof value === "string") overrides[param] = value;
225
+ }
226
+ return overrides;
227
+ }
228
+ function validateDownloadResponseOverrides(req) {
229
+ for (const param of DOWNLOAD_RESPONSE_OVERRIDE_PARAMS) {
230
+ const value = req[param];
231
+ if (value === void 0 || typeof value === "string") continue;
232
+ return {
233
+ code: "bad_request",
234
+ message: `${param} must be a string`
235
+ };
236
+ }
237
+ return null;
238
+ }
239
+ function normalizeKeyBucketIds(req) {
240
+ return req.bucketIds === void 0 || req.bucketIds === null ? null : Object.freeze([...req.bucketIds]);
241
+ }
242
+ function singleBucketId(bucketIds) {
243
+ return bucketIds?.length === 1 ? bucketIds[0] ?? null : null;
244
+ }
245
+ function cloneBucketIds(bucketIds) {
246
+ return bucketIds === null ? null : [...bucketIds];
247
+ }
248
+ function cloneCapabilities(capabilities) {
249
+ return [...capabilities];
250
+ }
251
+ function isImplicitStorageMasterCredential(credentials) {
252
+ return credentials.applicationKeyId === SIMULATOR_MASTER_APPLICATION_KEY_ID && credentials.applicationKey === SIMULATOR_MASTER_APPLICATION_KEY || credentials.applicationKeyId === SIMULATOR_TEST_APPLICATION_KEY_ID && credentials.applicationKey === SIMULATOR_TEST_APPLICATION_KEY;
253
+ }
254
+ function isImplicitPartnerMasterCredential(credentials) {
255
+ return credentials.applicationKeyId === SIMULATOR_MASTER_APPLICATION_KEY_ID && credentials.applicationKey === SIMULATOR_MASTER_APPLICATION_KEY;
256
+ }
257
+ function isSimulatorApplicationKeyId(applicationKeyId) {
258
+ return applicationKeyId.startsWith(SIMULATOR_APPLICATION_KEY_ID_PREFIX);
259
+ }
260
+ function hasOwnField(body, field) {
261
+ return typeof body === "object" && body !== null && Object.hasOwn(body, field);
262
+ }
263
+ function requestStringField(body, field) {
264
+ if (typeof body !== "object" || body === null) return void 0;
265
+ const value = body[field];
266
+ return typeof value === "string" ? value : void 0;
267
+ }
268
+ function requestRecord(body) {
269
+ return typeof body === "object" && body !== null && !Array.isArray(body) ? body : null;
270
+ }
271
+ function replicationDestinationBucketIds(body) {
272
+ const rules = requestRecord(requestRecord(requestRecord(body)?.["replicationConfiguration"])?.["asReplicationSource"])?.["replicationRules"];
273
+ if (!Array.isArray(rules)) return [];
274
+ const bucketIds = [];
275
+ for (const rule of rules) {
276
+ const destinationBucketId = requestRecord(rule)?.["destinationBucketId"];
277
+ if (typeof destinationBucketId === "string") bucketIds.push(destinationBucketId);
278
+ }
279
+ return [...new Set(bucketIds)];
280
+ }
281
+ function normalizeReplicationConfiguration(config) {
282
+ return {
283
+ asReplicationSource: config.asReplicationSource ?? null,
284
+ asReplicationDestination: config.asReplicationDestination ?? null
285
+ };
286
+ }
287
+ function validateBucketConfigurationFields(fields, options) {
288
+ if (fields.bucketInfo !== void 0) {
289
+ const infoError = require_validation.validateBucketInfo(fields.bucketInfo);
290
+ if (infoError) return infoError;
291
+ }
292
+ if (fields.corsRules !== void 0) {
293
+ const corsError = require_validation.validateCorsRules(fields.corsRules);
294
+ if (corsError) return corsError;
295
+ }
296
+ if (fields.lifecycleRules !== void 0) {
297
+ const lifecycleError = require_validation.validateLifecycleRules(fields.lifecycleRules);
298
+ if (lifecycleError) return lifecycleError;
299
+ }
300
+ if (fields.replicationConfiguration !== void 0) {
301
+ const replicationError = require_validation.validateReplicationConfiguration(fields.replicationConfiguration);
302
+ if (replicationError) return replicationError;
303
+ }
304
+ if (fields.defaultRetention !== void 0) {
305
+ const retentionError = require_validation.validateDefaultRetention(fields.defaultRetention);
306
+ if (retentionError) return retentionError;
307
+ if (requestRecord(fields.defaultRetention)?.["mode"] !== require_bucket.BucketRetentionMode.None && !options.objectLockEnabled) return {
308
+ code: "file_lock_not_enabled",
309
+ message: "Bucket must have Object Lock enabled to set defaultRetention"
310
+ };
311
+ }
312
+ return null;
313
+ }
314
+ function nextObjectLockEnabled(current, requested) {
315
+ if (requested === void 0) return current;
316
+ if (typeof requested !== "boolean") return {
317
+ code: "bad_request",
318
+ message: "fileLockEnabled must be a boolean"
319
+ };
320
+ if (current && requested === false) return {
321
+ code: "file_lock_conflict",
322
+ message: "Object Lock cannot be disabled"
323
+ };
324
+ return current || requested;
325
+ }
326
+ function requestHeaderValue(headers, name) {
327
+ const exact = headers[name];
328
+ if (exact !== void 0) return exact;
329
+ const lowerName = name.toLowerCase();
330
+ for (const [key, value] of Object.entries(headers)) if (key.toLowerCase() === lowerName) return value;
331
+ }
332
+ function parseContentLengthHeader(headers) {
333
+ const header = requestHeaderValue(headers, "content-length");
334
+ if (header === void 0) return { kind: "absent" };
335
+ if (!/^\d+$/.test(header)) return {
336
+ kind: "error",
337
+ message: `Content-Length must be a byte count: ${header}`
338
+ };
339
+ const expectedLength = Number(header);
340
+ if (!Number.isSafeInteger(expectedLength)) return {
341
+ kind: "error",
342
+ message: `Content-Length is too large: ${header}`
343
+ };
344
+ return {
345
+ kind: "ok",
346
+ expectedLength
347
+ };
348
+ }
349
+ function contentLengthMismatchMessage(expectedLength, actualLength) {
350
+ return `Content-Length ${expectedLength} does not match request body length ${actualLength}`;
51
351
  }
52
- class B2Simulator {
53
- buckets = /* @__PURE__ */ new Map();
54
- accountId = "sim_account_0001";
55
- largeFiles = /* @__PURE__ */ new Map();
56
- keys = /* @__PURE__ */ new Map();
57
- notificationRules = /* @__PURE__ */ new Map();
58
- minimumPartSize;
59
- recommendedPartSize;
60
- faults = [];
61
- nextFaultId = 1;
62
- onWebhookDeliver;
63
- onReplicate;
64
- onHookError;
65
- strictAuth;
66
- authTokenTtlMs;
67
- /**
68
- * Issued auth tokens with their associated grant scope + expiry. In
69
- * permissive mode (`strictAuth: false`) this is still populated by
70
- * `authorize` but never consulted on subsequent requests. In strict
71
- * mode each request looks up its `Authorization` header here.
72
- */
73
- issuedTokens = /* @__PURE__ */ new Map();
74
- /**
75
- * Virtual-clock offset applied to `Date.now()` for expiry checks.
76
- * Defaults to 0. Tests advance via {@link advanceTime} to fast-forward
77
- * past auth-token expiry without sleeping.
78
- */
79
- clockOffsetMs = 0;
80
- /**
81
- * Per-instance monotonic counter used to mint realistic-looking
82
- * IDs (`b2_bucket_<24-hex>`, `4_z<24-hex>`, etc.) and auth tokens.
83
- * Module-global previously, which leaked state across `B2Simulator`
84
- * instances in the same Vitest worker — concurrent tests could see
85
- * colliding tokens. Per-instance ensures determinism within a single
86
- * simulator's lifetime.
87
- */
88
- nextId = 1;
89
- /**
90
- * Last-issued upload timestamp. The simulator enforces strict
91
- * monotonicity so version ordering is deterministic for tests; if
92
- * two writes hit the same `Date.now()` millisecond, the second
93
- * receives `lastTimestamp + 1`.
94
- */
95
- lastTimestamp = 0;
96
- /**
97
- * Outstanding fire-and-forget hook invocations. Tracked so tests
98
- * (and future {@link flushHooks} callers) can wait for every
99
- * dispatched `onWebhookDeliver` / `onReplicate` callback to settle
100
- * before asserting against observable side effects. The microtask
101
- * dance in fidelity tests was previously brittle: positive cases
102
- * flushed twice, negative cases flushed once, and any addition to
103
- * the hook dispatch chain quietly broke the negative path.
104
- */
105
- pendingHooks = /* @__PURE__ */ new Set();
106
- /**
107
- * Constructs a new in-memory B2 simulator.
108
- * @param options - Optional simulator overrides. See {@link B2SimulatorOptions}.
109
- */
110
- constructor(options = {}) {
111
- this.minimumPartSize = options.minimumPartSize ?? 5e6;
112
- this.recommendedPartSize = options.recommendedPartSize ?? 1e8;
113
- if (options.onWebhookDeliver !== void 0) this.onWebhookDeliver = options.onWebhookDeliver;
114
- if (options.onReplicate !== void 0) this.onReplicate = options.onReplicate;
115
- if (options.onHookError !== void 0) this.onHookError = options.onHookError;
116
- this.strictAuth = options.strictAuth ?? false;
117
- this.authTokenTtlMs = options.authTokenTtlMs ?? 24 * 60 * 60 * 1e3;
118
- }
119
- /**
120
- * Advance the simulator's virtual clock by `ms` milliseconds. Used in
121
- * conjunction with `strictAuth: true` + a finite `authTokenTtlMs` to
122
- * force token expiry without `setTimeout`-based delays.
123
- *
124
- * @param ms - Milliseconds to advance. Negative values rewind (rarely useful).
125
- */
126
- advanceTime(ms) {
127
- this.clockOffsetMs += ms;
128
- }
129
- /**
130
- * Current simulator time. Equal to `Date.now() + clockOffsetMs`.
131
- *
132
- * @returns Unix milliseconds.
133
- */
134
- now() {
135
- return Date.now() + this.clockOffsetMs;
136
- }
137
- /**
138
- * Generate a deterministic-but-realistic-looking B2 identifier of the
139
- * shape `<prefix>_<24-hex-counter>`, which approximates the visual
140
- * width of real B2 wire IDs. The counter is monotonic per instance
141
- * so test fixtures are deterministic across runs of the same
142
- * simulator.
143
- *
144
- * @param prefix - B2-style prefix (`'b2_bucket'`, `'4_z'`, etc.).
145
- *
146
- * @returns A simulator-issued identifier that looks like a B2 wire ID.
147
- */
148
- genId(prefix) {
149
- const n = this.nextId++;
150
- return `${prefix}_${n.toString(16).padStart(24, "0")}`;
151
- }
152
- /**
153
- * Return a strictly-increasing upload timestamp, even when multiple
154
- * writes land in the same `Date.now()` millisecond. Tests rely on
155
- * `uploadTimestamp` ordering to discriminate file versions; ties from
156
- * coarse system-clock resolution would otherwise make version
157
- * selection nondeterministic.
158
- *
159
- * @returns Unix milliseconds.
160
- */
161
- monotonicTimestamp() {
162
- const now = Date.now();
163
- if (now <= this.lastTimestamp) {
164
- this.lastTimestamp += 1;
165
- } else {
166
- this.lastTimestamp = now;
167
- }
168
- return this.lastTimestamp;
169
- }
170
- /**
171
- * Wait for every fire-and-forget hook (`onWebhookDeliver`,
172
- * `onReplicate`) currently in flight to settle. Use in tests after
173
- * an upload/copy/finish-large-file call to deterministically observe
174
- * hook side effects without microtask-flush guesswork.
175
- *
176
- * @returns A promise that resolves once every pending hook callback
177
- * has either resolved or rejected.
178
- */
179
- async flushHooks() {
180
- while (this.pendingHooks.size > 0) {
181
- const snapshot = [...this.pendingHooks];
182
- await Promise.allSettled(snapshot);
183
- }
184
- }
185
- /**
186
- * Authorize a request against the strict-auth bookkeeping. Returns
187
- * a `SimulatorJsonResponse` error on failure or `null` on success.
188
- * Only consulted when `strictAuth: true`.
189
- *
190
- * @param authToken - The `Authorization` header value from the request.
191
- * @param endpoint - B2 endpoint name being invoked.
192
- * @param bucketId - Optional bucket ID the request operates on, for scope check.
193
- * @param fileName - Optional file name the request operates on, for prefix check.
194
- *
195
- * @returns `null` when the request is authorized, otherwise a 401/403 response.
196
- */
197
- authorizeRequest(authToken, endpoint, bucketId, fileName) {
198
- const required = capabilities.missingCapabilitiesFor(endpoint, []);
199
- const noCheckNeeded = required.length === 0 && endpoint === "b2_authorize_account";
200
- if (noCheckNeeded) return null;
201
- if (authToken === void 0 || authToken === "") {
202
- return this.error(401, "bad_auth_token", "missing Authorization header");
203
- }
204
- const token = this.issuedTokens.get(authToken);
205
- if (!token) {
206
- return this.error(401, "bad_auth_token", "unknown auth token");
207
- }
208
- if (this.now() > token.expiresAt) {
209
- return this.error(401, "expired_auth_token", "auth token has expired; reauthorize");
210
- }
211
- const missing = capabilities.missingCapabilitiesFor(endpoint, token.capabilities);
212
- if (missing.length > 0) {
213
- return this.error(
214
- 403,
215
- "unauthorized",
216
- `application key lacks required capabilities: ${missing.join(", ")}`
217
- );
218
- }
219
- if (token.bucketId !== null && bucketId !== void 0 && bucketId !== token.bucketId) {
220
- return this.error(
221
- 403,
222
- "unauthorized",
223
- `application key is scoped to bucket ${token.bucketId}; cannot access ${bucketId}`
224
- );
225
- }
226
- if (token.namePrefix !== null && fileName !== void 0 && !fileName.startsWith(token.namePrefix)) {
227
- return this.error(
228
- 403,
229
- "unauthorized",
230
- `application key is scoped to prefix "${token.namePrefix}"; "${fileName}" is outside scope`
231
- );
232
- }
233
- return null;
234
- }
235
- /**
236
- * Look up the application key matching the `Authorization` header on
237
- * an `authorize_account` request. The header is in the form
238
- * `Basic base64(applicationKeyId:applicationKey)`.
239
- *
240
- * Returns `null` for the implicit master credential (anything that
241
- * does not match a key minted via `b2_create_key`); in that case
242
- * `authorize` grants the full master capability set.
243
- *
244
- * @param authzHeader - Raw HTTP `Authorization` header value.
245
- *
246
- * @returns The matching key's grant scope, or `null` for the master.
247
- */
248
- findKeyForAuthHeader(authzHeader) {
249
- if (!authzHeader || !authzHeader.startsWith("Basic ")) return null;
250
- const decoded = (() => {
251
- try {
252
- return atob(authzHeader.slice(6));
253
- } catch {
254
- return null;
255
- }
256
- })();
257
- if (decoded === null) return null;
258
- const idx = decoded.indexOf(":");
259
- if (idx === -1) return null;
260
- const applicationKeyId = decoded.slice(0, idx);
261
- const applicationKey = decoded.slice(idx + 1);
262
- const stored = this.keys.get(applicationKeyId);
263
- if (!stored || stored.applicationKey !== applicationKey) return null;
264
- return {
265
- capabilities: stored.capabilities,
266
- bucketId: stored.bucketId,
267
- namePrefix: stored.namePrefix,
268
- applicationKeyId
269
- };
270
- }
271
- /**
272
- * Creates an {@link HttpTransport} that routes requests to this simulator.
273
- * @returns A transport instance backed by this in-memory simulator.
274
- */
275
- transport() {
276
- return new SimulatorTransport(this);
277
- }
278
- /**
279
- * Register a synthetic failure to inject on requests whose URL contains
280
- * `spec.on`. Use this to exercise retry / backoff / error-handling
281
- * paths in tests without hand-rolling a wrapping `HttpTransport`. The
282
- * fault is consumed in registration order on each matched request;
283
- * once its `count` budget is exhausted it auto-retires.
284
- *
285
- * Faults are checked BEFORE the simulator's real handlers run, so a
286
- * matched request never touches in-memory state — failed uploads
287
- * don't create partial parts, failed deletes don't remove anything.
288
- *
289
- * @param spec - The failure to inject. See {@link FaultSpec}.
290
- *
291
- * @returns A handle whose `clear()` method removes this specific
292
- * fault registration (other faults remain in effect).
293
- *
294
- * @example
295
- * ```ts
296
- * // Fail the next 2 b2_upload_part calls with 503, then succeed.
297
- * sim.injectFailure({ on: 'b2_upload_part', status: 503, count: 2 })
298
- *
299
- * // Fail every b2_authorize_account with 401 + Retry-After: 5.
300
- * const handle = sim.injectFailure({
301
- * on: 'b2_authorize_account',
302
- * status: 401,
303
- * code: 'expired_auth_token',
304
- * retryAfter: 5,
305
- * })
306
- * // ... later
307
- * handle.clear()
308
- * ```
309
- */
310
- injectFailure(spec) {
311
- const id = this.nextFaultId++;
312
- const fault = {
313
- id,
314
- spec,
315
- remainingSkip: spec.skip ?? 0,
316
- remainingCount: spec.count ?? Number.POSITIVE_INFINITY
317
- };
318
- this.faults.push(fault);
319
- return {
320
- clear: () => {
321
- const idx = this.faults.findIndex((f) => f.id === id);
322
- if (idx !== -1) this.faults.splice(idx, 1);
323
- }
324
- };
325
- }
326
- /**
327
- * Remove every registered fault. Equivalent to calling `.clear()` on
328
- * every handle returned by {@link injectFailure}, plus a defensive
329
- * reset for tests that re-use a simulator across cases.
330
- */
331
- clearFaults() {
332
- this.faults.length = 0;
333
- }
334
- /**
335
- * Internal: checks the registered faults for a match on the given URL
336
- * and consumes one if it should fire. Called from
337
- * {@link SimulatorTransport.send} before any real handler runs.
338
- *
339
- * @param url - The request URL to match against each fault's `on`
340
- * substring.
341
- *
342
- * @returns The fault to apply, or `null` if no fault should fire.
343
- *
344
- * @internal
345
- */
346
- consumeMatchingFault(url) {
347
- for (let i = 0; i < this.faults.length; i++) {
348
- const fault = this.faults[i];
349
- if (!url.includes(fault.spec.on)) continue;
350
- if (fault.remainingSkip > 0) {
351
- fault.remainingSkip -= 1;
352
- continue;
353
- }
354
- if (fault.remainingCount <= 0) continue;
355
- fault.remainingCount -= 1;
356
- if (fault.remainingCount <= 0) {
357
- this.faults.splice(i, 1);
358
- }
359
- return fault.spec;
360
- }
361
- return null;
362
- }
363
- /**
364
- * Dispatches a JSON API request to the appropriate handler.
365
- * @param _method - The HTTP method (unused).
366
- * @param path - The request URL path containing the B2 endpoint name.
367
- * @param headers - The HTTP request headers; consulted by the
368
- * strict-auth gate to look up the issued auth token.
369
- * @param body - The parsed JSON request body.
370
- *
371
- * @returns An object with HTTP status and JSON response body.
372
- */
373
- async handleRequest(_method, path, headers, body) {
374
- const endpoint = path.split("/").pop() ?? "";
375
- if (this.strictAuth) {
376
- const authError = this.authorizeRequest(headers["authorization"], endpoint);
377
- if (authError !== null) return authError;
378
- }
379
- switch (endpoint) {
380
- case "b2_authorize_account":
381
- return this.authorize(headers["authorization"]);
382
- case "b2_create_bucket":
383
- return this.createBucket(
384
- body
385
- );
386
- case "b2_list_buckets":
387
- return this.listBuckets();
388
- case "b2_delete_bucket":
389
- return this.deleteBucket(body);
390
- case "b2_update_bucket":
391
- return this.updateBucket(body);
392
- case "b2_get_upload_url":
393
- return this.getUploadUrl(body);
394
- case "b2_list_file_names":
395
- return this.listFileNames(
396
- body
397
- );
398
- case "b2_list_file_versions":
399
- return this.listFileVersions(
400
- body
401
- );
402
- case "b2_get_file_info":
403
- return this.getFileInfo(body);
404
- case "b2_hide_file":
405
- return this.hideFile(body);
406
- case "b2_delete_file_version":
407
- return this.deleteFileVersion(
408
- body
409
- );
410
- case "b2_copy_file":
411
- return this.copyFile(
412
- body
413
- );
414
- case "b2_start_large_file":
415
- return this.startLargeFile(
416
- body
417
- );
418
- case "b2_get_upload_part_url":
419
- return this.getUploadPartUrl(body);
420
- case "b2_finish_large_file":
421
- return this.finishLargeFile(body);
422
- case "b2_cancel_large_file":
423
- return this.cancelLargeFile(body);
424
- case "b2_list_unfinished_large_files":
425
- return this.listUnfinishedLargeFiles(
426
- body
427
- );
428
- case "b2_list_parts":
429
- return this.listParts(
430
- body
431
- );
432
- case "b2_copy_part":
433
- return await this.copyPart(
434
- body
435
- );
436
- case "b2_get_download_authorization":
437
- return this.getDownloadAuthorization(
438
- body
439
- );
440
- case "b2_create_key":
441
- return this.createKey(
442
- body
443
- );
444
- case "b2_list_keys":
445
- return this.listKeys(
446
- body
447
- );
448
- case "b2_delete_key":
449
- return this.deleteKey(body);
450
- case "b2_update_file_retention":
451
- return this.updateFileRetention(
452
- body
453
- );
454
- case "b2_update_file_legal_hold":
455
- return this.updateFileLegalHold(
456
- body
457
- );
458
- case "b2_get_bucket_notification_rules":
459
- return this.getBucketNotificationRules(body);
460
- case "b2_set_bucket_notification_rules":
461
- return this.setBucketNotificationRules(
462
- body
463
- );
464
- default:
465
- return {
466
- status: 400,
467
- body: { status: 400, code: "bad_request", message: `Unknown endpoint: ${endpoint}` }
468
- };
469
- }
470
- }
471
- /**
472
- * Handles file and part upload requests (`b2_upload_file`, `b2_upload_part`).
473
- * Dispatches to the appropriate internal handler based on the URL.
474
- * @param url - The upload endpoint URL used to determine the upload type.
475
- * @param headers - The HTTP headers containing file metadata and authorization.
476
- * @param data - The raw file or part content as bytes.
477
- *
478
- * @returns An object with HTTP status and JSON response body.
479
- */
480
- handleUpload(url, headers, data) {
481
- const isPart = url.includes("b2_upload_part");
482
- if (this.strictAuth) {
483
- const endpoint = isPart ? "b2_upload_part" : "b2_upload_file";
484
- const authError = this.authorizeRequest(headers["authorization"], endpoint);
485
- if (authError !== null) return authError;
486
- }
487
- if (isPart) {
488
- return this.handleUploadPart(url, headers, data);
489
- }
490
- return this.handleUploadFile(url, headers, data);
491
- }
492
- /**
493
- * Handles file download requests (`b2_download_file_by_id`, `/file/` by name).
494
- * Returns the file data along with B2 response headers.
495
- * @param path - The request URL path identifying the file to download.
496
- * @param headers - The HTTP request headers for range or authorization.
497
- * @param method - The HTTP method; `'HEAD'` suppresses the response body.
498
- *
499
- * @returns The download response containing file data and B2 headers.
500
- */
501
- handleDownload(path, headers, method = "GET") {
502
- if (path.includes("b2_download_file_by_id")) {
503
- if (this.strictAuth) {
504
- const authError = this.authorizeRequest(headers["authorization"], "b2_download_file_by_id");
505
- if (authError !== null) return this.errorAsDownload(authError);
506
- }
507
- const url = new URL(`http://localhost${path}`);
508
- const fileId = url.searchParams.get("fileId") ?? "";
509
- return this.finalizeDownload(this.downloadById(fileId, headers["range"]), url, method);
510
- }
511
- const fileMatch = path.match(/^([^?]+)/)?.[1]?.match(/\/file\/([^/]+)\/(.+)/);
512
- if (fileMatch) {
513
- const bucketName = decodeURIComponent(fileMatch[1] ?? "");
514
- const fileName = decodeURIComponent(fileMatch[2] ?? "");
515
- if (this.strictAuth) {
516
- const authError = this.authorizeRequest(
517
- headers["authorization"],
518
- "b2_download_file_by_name",
519
- void 0,
520
- fileName
521
- );
522
- if (authError !== null) return this.errorAsDownload(authError);
523
- }
524
- const url = new URL(`http://localhost${path}`);
525
- return this.finalizeDownload(
526
- this.downloadByName(bucketName, fileName, headers["range"]),
527
- url,
528
- method
529
- );
530
- }
531
- return { status: 404, headers: {}, data: null };
532
- }
533
- /**
534
- * Convert a synthetic JSON error body into a `SimulatorDownloadResponse`
535
- * shape so the strict-auth gate on download paths can surface 401/403s
536
- * through the same transport plumbing as a regular failed download.
537
- *
538
- * @param json - The JSON error from {@link authorizeRequest}.
539
- *
540
- * @returns A download-shaped response with the error body bytes inline.
541
- */
542
- errorAsDownload(json) {
543
- return {
544
- status: json.status,
545
- headers: { "Content-Type": "application/json" },
546
- data: textCodec.utf8Encoder.encode(JSON.stringify(json.body))
547
- };
548
- }
549
- /**
550
- * Applies HEAD-method body suppression and `b2Content*` response-header
551
- * overrides parsed from the download URL's query string. Mirrors what the
552
- * real B2 service does: any `b2Content*` query parameter is echoed back as
553
- * the corresponding response header.
554
- *
555
- * @param response - The download response produced by {@link downloadById} or {@link downloadByName}.
556
- * @param url - The parsed download URL (used to read `b2Content*` query params).
557
- * @param method - The HTTP method of the originating request.
558
- *
559
- * @returns The response with overrides applied.
560
- */
561
- finalizeDownload(response, url, method) {
562
- const overrideMap = {
563
- b2ContentDisposition: "Content-Disposition",
564
- b2ContentLanguage: "Content-Language",
565
- b2ContentEncoding: "Content-Encoding",
566
- b2ContentType: "Content-Type",
567
- b2CacheControl: "Cache-Control",
568
- b2Expires: "Expires"
569
- };
570
- const newHeaders = { ...response.headers };
571
- for (const [param, header] of Object.entries(overrideMap)) {
572
- const value = url.searchParams.get(param);
573
- if (value !== null) newHeaders[header] = value;
574
- }
575
- const data = method === "HEAD" ? null : response.data;
576
- return { status: response.status, headers: newHeaders, data };
577
- }
578
- handleUploadFile(url, headers, data) {
579
- const bucketId = new URL(url).searchParams.get("bucketId");
580
- if (!bucketId) return this.error(400, "bad_request", "Missing bucketId");
581
- const bucket2 = this.buckets.get(bucketId);
582
- if (!bucket2) return this.error(400, "bad_bucket_id", "Bucket not found");
583
- const fileName = decodeURIComponent(headers["x-bz-file-name"] ?? "");
584
- const contentType = headers["content-type"] ?? "application/octet-stream";
585
- const sha1 = headers["x-bz-content-sha1"] ?? "none";
586
- const fileNameError = validation.validateFileName(fileName);
587
- if (fileNameError) return this.error(400, fileNameError.code, fileNameError.message);
588
- const fileInfo = parseFileInfoHeaders(headers);
589
- const fileInfoError = validation.validateFileInfo(fileInfo);
590
- if (fileInfoError) return this.error(400, fileInfoError.code, fileInfoError.message);
591
- const fileVersion = this.makeFileVersion({
592
- bucketId,
593
- fileName,
594
- contentType,
595
- contentLength: data.byteLength,
596
- contentSha1: sha1,
597
- action: file.FileAction.Upload
598
- });
599
- const stored = { fileVersion, data };
600
- const existing = bucket2.files.get(fileName);
601
- if (existing) {
602
- existing.push(stored);
603
- } else {
604
- bucket2.files.set(fileName, [stored]);
605
- }
606
- this.firePostUploadHooks(fileVersion, bucketId, "b2:ObjectCreated:Upload");
607
- return { status: 200, body: fileVersion };
608
- }
609
- handleUploadPart(url, headers, data) {
610
- const fileId = new URL(url).searchParams.get("fileId");
611
- if (!fileId) return this.error(400, "bad_request", "Missing fileId");
612
- const large = this.largeFiles.get(fileId);
613
- if (!large) return this.error(400, "bad_request", "Large file not found");
614
- const partNumber = Number.parseInt(headers["x-bz-part-number"] ?? "0", 10);
615
- const sha1 = headers["x-bz-content-sha1"] ?? "none";
616
- large.parts.set(partNumber, { data, sha1 });
617
- return {
618
- status: 200,
619
- body: {
620
- fileId: large.fileId,
621
- partNumber,
622
- contentLength: data.byteLength,
623
- contentSha1: sha1,
624
- serverSideEncryption: { mode: encryption.EncryptionMode.None },
625
- uploadTimestamp: Date.now()
626
- }
627
- };
628
- }
629
- downloadById(fileId, range) {
630
- const found = this.findFile(fileId);
631
- if (found === null) return { status: 404, headers: {}, data: null };
632
- return this.serveFile(found.stored, range);
633
- }
634
- downloadByName(bucketName, fileName, range) {
635
- for (const bucket2 of this.buckets.values()) {
636
- if (bucket2.info.bucketName !== bucketName) continue;
637
- const versions = bucket2.files.get(fileName);
638
- if (!versions || versions.length === 0) break;
639
- const latest = versions[versions.length - 1];
640
- if (!latest || latest.fileVersion.action === file.FileAction.Hide) {
641
- return { status: 404, headers: {}, data: null };
642
- }
643
- return this.serveFile(latest, range);
644
- }
645
- return { status: 404, headers: {}, data: null };
646
- }
647
- serveFile(stored, range) {
648
- const fullData = stored.data;
649
- let data = fullData;
650
- let status = 200;
651
- let contentRange = null;
652
- if (range) {
653
- const parsed = parseRangeHeader(range, fullData.byteLength);
654
- if (parsed.kind === "ok") {
655
- data = fullData.subarray(parsed.start, parsed.end + 1);
656
- status = 206;
657
- contentRange = `bytes ${parsed.start}-${parsed.end}/${fullData.byteLength}`;
658
- } else if (parsed.kind === "unsatisfiable") {
659
- return {
660
- status: 416,
661
- headers: {
662
- "Content-Type": stored.fileVersion.contentType,
663
- "Content-Range": `bytes */${fullData.byteLength}`
664
- },
665
- data: new Uint8Array(0)
666
- };
667
- }
668
- }
669
- const fv = stored.fileVersion;
670
- const headers = {
671
- "Content-Type": fv.contentType,
672
- "Content-Length": String(data.byteLength),
673
- "X-Bz-File-Id": fv.fileId,
674
- "X-Bz-File-Name": encodeURIComponent(fv.fileName),
675
- "X-Bz-Content-Sha1": fv.contentSha1 ?? "none",
676
- "X-Bz-Upload-Timestamp": String(fv.uploadTimestamp),
677
- "X-Bz-Info-src_last_modified_millis": String(fv.uploadTimestamp)
678
- };
679
- if (contentRange !== null) {
680
- headers["Content-Range"] = contentRange;
681
- }
682
- return { status, headers, data };
683
- }
684
- // --- API handlers ---
685
- authorize(authzHeader) {
686
- const capabilities2 = [
687
- auth.Capability.ListBuckets,
688
- auth.Capability.ReadBuckets,
689
- auth.Capability.WriteBuckets,
690
- auth.Capability.DeleteBuckets,
691
- auth.Capability.ListFiles,
692
- auth.Capability.ReadFiles,
693
- auth.Capability.WriteFiles,
694
- auth.Capability.DeleteFiles,
695
- auth.Capability.ListKeys,
696
- auth.Capability.WriteKeys,
697
- auth.Capability.DeleteKeys,
698
- auth.Capability.ShareFiles,
699
- auth.Capability.ReadBucketNotifications,
700
- auth.Capability.WriteBucketNotifications
701
- ];
702
- const keyForAuth = this.findKeyForAuthHeader(authzHeader);
703
- const tokenStr = `sim_auth_token_${this.nextId++}`;
704
- this.issuedTokens.set(tokenStr, {
705
- capabilities: keyForAuth?.capabilities ?? capabilities2,
706
- bucketId: keyForAuth?.bucketId ?? null,
707
- namePrefix: keyForAuth?.namePrefix ?? null,
708
- expiresAt: this.now() + this.authTokenTtlMs,
709
- applicationKeyId: keyForAuth?.applicationKeyId ?? null
710
- });
711
- return {
712
- status: 200,
713
- body: {
714
- accountId: ids.accountId(this.accountId),
715
- // `AuthToken` has no public factory by design — auth tokens are
716
- // minted by B2, not constructed by user code. The simulator is
717
- // the only legitimate place that needs to forge one.
718
- authorizationToken: tokenStr,
719
- apiInfo: {
720
- storageApi: {
721
- absoluteMinimumPartSize: this.minimumPartSize,
722
- apiUrl: "http://localhost:0",
723
- bucketId: keyForAuth?.bucketId ?? null,
724
- bucketName: null,
725
- downloadUrl: "http://localhost:0",
726
- infoType: "storageApi",
727
- namePrefix: keyForAuth?.namePrefix ?? null,
728
- recommendedPartSize: this.recommendedPartSize,
729
- s3ApiUrl: "http://localhost:0",
730
- allowed: {
731
- capabilities: keyForAuth?.capabilities ?? capabilities2,
732
- bucketId: keyForAuth?.bucketId ?? null,
733
- bucketName: null,
734
- namePrefix: keyForAuth?.namePrefix ?? null
735
- }
736
- }
737
- },
738
- applicationKeyExpirationTimestamp: null
739
- }
740
- };
741
- }
742
- createBucket(req) {
743
- const nameError = validation.validateBucketName(req.bucketName);
744
- if (nameError) return this.error(400, nameError.code, nameError.message);
745
- if (req.bucketInfo !== void 0) {
746
- const infoError = validation.validateBucketInfo(req.bucketInfo);
747
- if (infoError) return this.error(400, infoError.code, infoError.message);
748
- }
749
- for (const b of this.buckets.values()) {
750
- if (b.info.bucketName === req.bucketName) {
751
- return this.error(400, "duplicate_bucket_name", "Bucket name already in use");
752
- }
753
- }
754
- const bid = ids.bucketId(this.genId("b2_bucket"));
755
- const defaultRetention = req.defaultRetention ?? {
756
- mode: bucket.BucketRetentionMode.None,
757
- period: null
758
- };
759
- const info = {
760
- accountId: ids.accountId(req.accountId),
761
- bucketId: bid,
762
- bucketName: req.bucketName,
763
- bucketType: req.bucketType,
764
- bucketInfo: req.bucketInfo ?? {},
765
- corsRules: req.corsRules ?? [],
766
- defaultServerSideEncryption: req.defaultServerSideEncryption ?? { mode: encryption.EncryptionMode.None },
767
- fileLockConfiguration: {
768
- isClientAuthorizedToRead: true,
769
- value: {
770
- isFileLockEnabled: req.fileLockEnabled ?? false,
771
- defaultRetention
772
- }
773
- },
774
- lifecycleRules: req.lifecycleRules ?? [],
775
- options: [],
776
- revision: 1,
777
- defaultRetention,
778
- replicationConfiguration: req.replicationConfiguration ?? {
779
- asReplicationSource: null,
780
- asReplicationDestination: null
781
- }
782
- };
783
- this.buckets.set(bid, { info, files: /* @__PURE__ */ new Map() });
784
- return { status: 200, body: info };
785
- }
786
- listBuckets() {
787
- const buckets = [...this.buckets.values()].map((b) => b.info);
788
- return { status: 200, body: { buckets } };
789
- }
790
- deleteBucket(req) {
791
- const bucket2 = this.buckets.get(req.bucketId);
792
- if (!bucket2) return this.error(400, "bad_bucket_id", "Bucket not found");
793
- this.buckets.delete(req.bucketId);
794
- return { status: 200, body: bucket2.info };
795
- }
796
- updateBucket(req) {
797
- const bucket2 = this.buckets.get(req["bucketId"]);
798
- if (!bucket2) return this.error(400, "bad_bucket_id", "Bucket not found");
799
- if (req["bucketInfo"] !== void 0) {
800
- const infoError = validation.validateBucketInfo(req["bucketInfo"]);
801
- if (infoError) return this.error(400, infoError.code, infoError.message);
802
- }
803
- const updated = {
804
- ...bucket2.info,
805
- ...req["bucketType"] !== void 0 ? { bucketType: req["bucketType"] } : {},
806
- ...req["bucketInfo"] !== void 0 ? { bucketInfo: req["bucketInfo"] } : {},
807
- ...req["lifecycleRules"] !== void 0 ? { lifecycleRules: req["lifecycleRules"] } : {},
808
- ...req["corsRules"] !== void 0 ? { corsRules: req["corsRules"] } : {},
809
- ...req["replicationConfiguration"] !== void 0 ? {
810
- replicationConfiguration: req["replicationConfiguration"]
811
- } : {},
812
- ...req["defaultRetention"] !== void 0 ? {
813
- defaultRetention: req["defaultRetention"],
814
- fileLockConfiguration: {
815
- isClientAuthorizedToRead: true,
816
- value: {
817
- isFileLockEnabled: bucket2.info.fileLockConfiguration.value?.isFileLockEnabled ?? false,
818
- defaultRetention: req["defaultRetention"]
819
- }
820
- }
821
- } : {},
822
- ...req["defaultServerSideEncryption"] !== void 0 ? {
823
- defaultServerSideEncryption: req["defaultServerSideEncryption"]
824
- } : {},
825
- revision: bucket2.info.revision + 1
826
- };
827
- this.buckets.set(req["bucketId"], { info: updated, files: bucket2.files });
828
- return { status: 200, body: updated };
829
- }
830
- getUploadUrl(req) {
831
- if (!this.buckets.has(req.bucketId)) return this.error(400, "bad_bucket_id", "Bucket not found");
832
- return {
833
- status: 200,
834
- body: {
835
- bucketId: req.bucketId,
836
- uploadUrl: `http://localhost:0/b2api/v3/b2_upload_file?bucketId=${req.bucketId}`,
837
- authorizationToken: "sim_upload_token"
838
- }
839
- };
840
- }
841
- listFileNames(req) {
842
- const bucket2 = this.buckets.get(req.bucketId);
843
- if (!bucket2) return this.error(400, "bad_bucket_id", "Bucket not found");
844
- const countError = validation.validateMaxCount(req.maxFileCount, "b2_list_file_names");
845
- if (countError) return this.error(400, countError.code, countError.message);
846
- const max = req.maxFileCount ?? 1e3;
847
- const prefix = req.prefix ?? "";
848
- let allFiles = [...bucket2.files.entries()].filter(([name]) => name.startsWith(prefix)).map(([_, versions]) => versions[versions.length - 1]).filter((v) => v !== void 0).map((v) => v.fileVersion).sort((a, b) => a.fileName.localeCompare(b.fileName));
849
- if (req.startFileName) {
850
- const start = req.startFileName;
851
- allFiles = allFiles.filter((f) => f.fileName >= start);
852
- }
853
- const files = allFiles.slice(0, max);
854
- const nextFileName = allFiles.length > max ? allFiles[max]?.fileName ?? null : null;
855
- return { status: 200, body: { files, nextFileName } };
856
- }
857
- listFileVersions(req) {
858
- const bucket2 = this.buckets.get(req.bucketId);
859
- if (!bucket2) return this.error(400, "bad_bucket_id", "Bucket not found");
860
- const countError = validation.validateMaxCount(req.maxFileCount, "b2_list_file_versions");
861
- if (countError) return this.error(400, countError.code, countError.message);
862
- const max = req.maxFileCount ?? 1e3;
863
- const prefix = req.prefix ?? "";
864
- const allVersions = [...bucket2.files.entries()].filter(([name]) => name.startsWith(prefix)).flatMap(([_, versions]) => versions.map((v) => v.fileVersion)).sort((a, b) => {
865
- const nameCmp = a.fileName.localeCompare(b.fileName);
866
- if (nameCmp !== 0) return nameCmp;
867
- return b.uploadTimestamp - a.uploadTimestamp;
868
- });
869
- let startIdx = 0;
870
- if (req.startFileName !== void 0) {
871
- const startName = req.startFileName;
872
- const startId = req.startFileId;
873
- const nameIdx = allVersions.findIndex((f) => f.fileName >= startName);
874
- if (nameIdx === -1) {
875
- startIdx = allVersions.length;
876
- } else if (startId !== void 0) {
877
- const exactIdx = allVersions.findIndex((f, i) => i >= nameIdx && f.fileId === startId);
878
- startIdx = exactIdx !== -1 ? exactIdx : nameIdx;
879
- } else {
880
- startIdx = nameIdx;
881
- }
882
- }
883
- const sliced = allVersions.slice(startIdx, startIdx + max);
884
- const hasMore = startIdx + max < allVersions.length;
885
- const nextFileName = hasMore ? allVersions[startIdx + max]?.fileName ?? null : null;
886
- const nextFileId = hasMore ? allVersions[startIdx + max]?.fileId ?? null : null;
887
- return { status: 200, body: { files: sliced, nextFileName, nextFileId } };
888
- }
889
- getFileInfo(req) {
890
- const found = this.findFile(req.fileId);
891
- if (found === null) return this.error(404, "file_not_present", "File not found");
892
- return { status: 200, body: found.stored.fileVersion };
893
- }
894
- hideFile(req) {
895
- const bucket2 = this.buckets.get(req.bucketId);
896
- if (!bucket2) return this.error(400, "bad_bucket_id", "Bucket not found");
897
- const nameError = validation.validateFileName(req.fileName);
898
- if (nameError) return this.error(400, nameError.code, nameError.message);
899
- const fileVersion = this.makeFileVersion({
900
- bucketId: req.bucketId,
901
- fileName: req.fileName,
902
- contentType: "application/octet-stream",
903
- contentLength: 0,
904
- contentSha1: "none",
905
- action: file.FileAction.Hide
906
- });
907
- const existing = bucket2.files.get(req.fileName);
908
- const stored = { fileVersion, data: new Uint8Array(0) };
909
- if (existing) {
910
- existing.push(stored);
911
- } else {
912
- bucket2.files.set(req.fileName, [stored]);
913
- }
914
- return { status: 200, body: fileVersion };
915
- }
916
- deleteFileVersion(req) {
917
- const found = this.findFile(req.fileId);
918
- if (found === null || found.stored.fileVersion.fileName !== req.fileName) {
919
- return this.error(400, "file_not_present", "File version not found");
920
- }
921
- const fv = found.stored.fileVersion;
922
- const retention = fv.fileRetention?.value;
923
- const legalHold = fv.legalHold?.value;
924
- const now = Date.now();
925
- if (legalHold === "on") {
926
- return this.error(
927
- 400,
928
- "file_lock_legal_hold_protected",
929
- "File is on legal hold and cannot be deleted"
930
- );
931
- }
932
- if (retention?.mode === "compliance" && retention.retainUntilTimestamp !== null && retention.retainUntilTimestamp > now) {
933
- return this.error(
934
- 400,
935
- "file_lock_compliance_protected",
936
- `File is under compliance-mode retention and cannot be deleted until ${new Date(retention.retainUntilTimestamp).toISOString()}`
937
- );
938
- }
939
- if (retention?.mode === "governance" && retention.retainUntilTimestamp !== null && retention.retainUntilTimestamp > now && req.bypassGovernance !== true) {
940
- return this.error(
941
- 400,
942
- "file_lock_governance_protected",
943
- "File is under governance-mode retention; pass bypassGovernance: true to delete"
944
- );
945
- }
946
- found.versions.splice(found.index, 1);
947
- if (found.versions.length === 0) found.bucket.files.delete(req.fileName);
948
- return { status: 200, body: { fileId: req.fileId, fileName: req.fileName } };
949
- }
950
- copyFile(req) {
951
- const nameError = validation.validateFileName(req.fileName);
952
- if (nameError) return this.error(400, nameError.code, nameError.message);
953
- const found = this.findFile(req.sourceFileId);
954
- if (found === null) return this.error(404, "file_not_present", "Source file not found");
955
- const sourceStored = found.stored;
956
- const destBucketId = req.destinationBucketId ?? found.bucketId;
957
- const destBucket = this.buckets.get(destBucketId);
958
- if (!destBucket) return this.error(400, "bad_bucket_id", "Destination bucket not found");
959
- const fileVersion = this.makeFileVersion({
960
- bucketId: destBucketId,
961
- fileName: req.fileName,
962
- contentType: sourceStored.fileVersion.contentType,
963
- contentLength: sourceStored.data.byteLength,
964
- contentSha1: sourceStored.fileVersion.contentSha1 ?? "none",
965
- action: file.FileAction.Copy
966
- });
967
- const copied = { fileVersion, data: new Uint8Array(sourceStored.data) };
968
- const existing = destBucket.files.get(req.fileName);
969
- if (existing) {
970
- existing.push(copied);
971
- } else {
972
- destBucket.files.set(req.fileName, [copied]);
973
- }
974
- this.firePostUploadHooks(fileVersion, destBucketId, "b2:ObjectCreated:Copy");
975
- return { status: 200, body: fileVersion };
976
- }
977
- startLargeFile(req) {
978
- if (!this.buckets.has(req.bucketId)) return this.error(400, "bad_bucket_id", "Bucket not found");
979
- const nameError = validation.validateFileName(req.fileName);
980
- if (nameError) return this.error(400, nameError.code, nameError.message);
981
- if (req.fileInfo !== void 0) {
982
- const infoError = validation.validateFileInfo(req.fileInfo);
983
- if (infoError) return this.error(400, infoError.code, infoError.message);
984
- }
985
- const fid = this.genId("4_z");
986
- const large = {
987
- fileId: fid,
988
- bucketId: req.bucketId,
989
- fileName: req.fileName,
990
- contentType: req.contentType,
991
- fileInfo: req.fileInfo ?? {},
992
- parts: /* @__PURE__ */ new Map()
993
- };
994
- this.largeFiles.set(fid, large);
995
- return {
996
- status: 200,
997
- body: {
998
- fileId: fid,
999
- fileName: req.fileName,
1000
- accountId: this.accountId,
1001
- bucketId: req.bucketId,
1002
- contentType: req.contentType,
1003
- fileInfo: large.fileInfo
1004
- }
1005
- };
1006
- }
1007
- getUploadPartUrl(req) {
1008
- if (!this.largeFiles.has(req.fileId))
1009
- return this.error(400, "bad_request", "Large file not found");
1010
- return {
1011
- status: 200,
1012
- body: {
1013
- fileId: req.fileId,
1014
- uploadUrl: `http://localhost:0/b2api/v3/b2_upload_part?fileId=${req.fileId}`,
1015
- authorizationToken: "sim_part_token"
1016
- }
1017
- };
1018
- }
1019
- finishLargeFile(req) {
1020
- const large = this.largeFiles.get(req.fileId);
1021
- if (!large) return this.error(400, "bad_request", "Large file not found");
1022
- const bucket2 = this.buckets.get(large.bucketId);
1023
- if (!bucket2) return this.error(400, "bad_bucket_id", "Bucket not found");
1024
- const sortedParts = [...large.parts.entries()].sort((a, b) => a[0] - b[0]);
1025
- if (sortedParts.length > 1e4) {
1026
- return this.error(
1027
- 400,
1028
- "bad_request",
1029
- `multipart upload has ${sortedParts.length} parts; B2 caps at 10000`
1030
- );
1031
- }
1032
- for (const [partNumber] of sortedParts) {
1033
- if (!Number.isInteger(partNumber) || partNumber < 1 || partNumber > 1e4) {
1034
- return this.error(
1035
- 400,
1036
- "bad_request",
1037
- `partNumber ${partNumber} is outside the [1, 10000] range B2 accepts`
1038
- );
1039
- }
1040
- }
1041
- if (req.partSha1Array.length !== sortedParts.length) {
1042
- return this.error(
1043
- 400,
1044
- "bad_request",
1045
- `partSha1Array has ${req.partSha1Array.length} entries but ${sortedParts.length} parts were uploaded`
1046
- );
1047
- }
1048
- for (let i = 0; i < sortedParts.length - 1; i++) {
1049
- const [partNumber, part] = sortedParts[i];
1050
- if (part.data.byteLength < this.minimumPartSize) {
1051
- return this.error(
1052
- 400,
1053
- "bad_request",
1054
- `part ${partNumber} (${part.data.byteLength} bytes) is smaller than the minimum part size of ${this.minimumPartSize}`
1055
- );
1056
- }
1057
- }
1058
- let totalSize = 0;
1059
- for (const [_, part] of sortedParts) totalSize += part.data.byteLength;
1060
- const combined = new Uint8Array(totalSize);
1061
- let offset = 0;
1062
- for (const [_, part] of sortedParts) {
1063
- combined.set(part.data, offset);
1064
- offset += part.data.byteLength;
1065
- }
1066
- const fileVersion = this.makeFileVersion({
1067
- bucketId: large.bucketId,
1068
- fileName: large.fileName,
1069
- contentType: large.contentType,
1070
- contentLength: totalSize,
1071
- contentSha1: "none",
1072
- action: file.FileAction.Upload
1073
- });
1074
- const stored = { fileVersion, data: combined };
1075
- const existing = bucket2.files.get(large.fileName);
1076
- if (existing) {
1077
- existing.push(stored);
1078
- } else {
1079
- bucket2.files.set(large.fileName, [stored]);
1080
- }
1081
- this.largeFiles.delete(req.fileId);
1082
- this.firePostUploadHooks(fileVersion, large.bucketId, "b2:ObjectCreated:Upload");
1083
- return { status: 200, body: fileVersion };
1084
- }
1085
- cancelLargeFile(req) {
1086
- const large = this.largeFiles.get(req.fileId);
1087
- if (!large) return this.error(400, "bad_request", "Large file not found");
1088
- this.largeFiles.delete(req.fileId);
1089
- return {
1090
- status: 200,
1091
- body: {
1092
- fileId: large.fileId,
1093
- accountId: this.accountId,
1094
- bucketId: large.bucketId,
1095
- fileName: large.fileName
1096
- }
1097
- };
1098
- }
1099
- listUnfinishedLargeFiles(req) {
1100
- const countError = validation.validateMaxCount(req.maxFileCount, "b2_list_unfinished_large_files");
1101
- if (countError) return this.error(400, countError.code, countError.message);
1102
- const prefix = req.namePrefix ?? "";
1103
- const max = req.maxFileCount ?? 100;
1104
- const candidates = [...this.largeFiles.values()].filter((f) => f.bucketId === req.bucketId).filter((f) => f.fileName.startsWith(prefix)).sort((a, b) => a.fileName.localeCompare(b.fileName));
1105
- let startIndex = 0;
1106
- if (req.startFileId !== void 0) {
1107
- const found = candidates.findIndex((f) => f.fileId === req.startFileId);
1108
- startIndex = found >= 0 ? found : 0;
1109
- }
1110
- const slice = candidates.slice(startIndex, startIndex + max);
1111
- const files = slice.map((f) => ({
1112
- fileId: f.fileId,
1113
- fileName: f.fileName,
1114
- accountId: this.accountId,
1115
- bucketId: f.bucketId,
1116
- contentType: f.contentType,
1117
- fileInfo: f.fileInfo
1118
- }));
1119
- const hasMore = startIndex + max < candidates.length;
1120
- const nextFileId = hasMore ? candidates[startIndex + max]?.fileId ?? null : null;
1121
- return { status: 200, body: { files, nextFileId } };
1122
- }
1123
- listParts(req) {
1124
- const large = this.largeFiles.get(req.fileId);
1125
- if (!large) return this.error(400, "bad_request", "Large file not found");
1126
- const countError = validation.validateMaxCount(req.maxPartCount, "b2_list_parts");
1127
- if (countError) return this.error(400, countError.code, countError.message);
1128
- const start = req.startPartNumber ?? 1;
1129
- const max = req.maxPartCount ?? 1e3;
1130
- const allParts = [...large.parts.entries()].filter(([n]) => n >= start).sort((a, b) => a[0] - b[0]).map(([partNumber, part]) => ({
1131
- fileId: req.fileId,
1132
- partNumber,
1133
- contentLength: part.data.byteLength,
1134
- contentSha1: part.sha1,
1135
- uploadTimestamp: Date.now()
1136
- }));
1137
- const parts = allParts.slice(0, max);
1138
- const nextPartNumber = allParts.length > max ? allParts[max]?.partNumber ?? null : null;
1139
- return { status: 200, body: { parts, nextPartNumber } };
1140
- }
1141
- async copyPart(req) {
1142
- const large = this.largeFiles.get(req.largeFileId);
1143
- if (!large) return this.error(400, "bad_request", "Large file not found");
1144
- const found = this.findFile(req.sourceFileId);
1145
- if (found === null) return this.error(404, "file_not_present", "Source file not found");
1146
- const sourceStored = found.stored;
1147
- let partData = sourceStored.data;
1148
- if (req.range) {
1149
- const match = req.range.match(/bytes=(\d+)-(\d+)?/);
1150
- if (match) {
1151
- const rs = Number.parseInt(match[1] ?? "0", 10);
1152
- const re = match[2] !== void 0 ? Number.parseInt(match[2], 10) : sourceStored.data.byteLength - 1;
1153
- partData = sourceStored.data.slice(rs, re + 1);
1154
- }
1155
- }
1156
- const sha1 = await hash.sha1Hex(partData);
1157
- large.parts.set(req.partNumber, { data: new Uint8Array(partData), sha1 });
1158
- return {
1159
- status: 200,
1160
- body: {
1161
- fileId: req.largeFileId,
1162
- partNumber: req.partNumber,
1163
- contentLength: partData.byteLength,
1164
- contentSha1: sha1
1165
- }
1166
- };
1167
- }
1168
- getDownloadAuthorization(req) {
1169
- if (!this.buckets.has(req.bucketId)) return this.error(400, "bad_bucket_id", "Bucket not found");
1170
- return {
1171
- status: 200,
1172
- body: {
1173
- bucketId: req.bucketId,
1174
- fileNamePrefix: req.fileNamePrefix,
1175
- authorizationToken: `sim_dl_auth_${this.genId("tok")}`
1176
- }
1177
- };
1178
- }
1179
- // --- Keys ---
1180
- createKey(req) {
1181
- const kid = this.genId("sim_key");
1182
- const appKey = this.genId("sim_secret");
1183
- const expiration = req.validDurationInSeconds !== void 0 ? Date.now() + req.validDurationInSeconds * 1e3 : null;
1184
- const stored = {
1185
- applicationKeyId: kid,
1186
- keyName: req.keyName,
1187
- capabilities: req.capabilities,
1188
- accountId: req.accountId,
1189
- applicationKey: appKey,
1190
- bucketId: req.bucketId ?? null,
1191
- namePrefix: req.namePrefix ?? null,
1192
- expirationTimestamp: expiration
1193
- };
1194
- this.keys.set(kid, stored);
1195
- return {
1196
- status: 200,
1197
- body: {
1198
- keyName: stored.keyName,
1199
- applicationKeyId: stored.applicationKeyId,
1200
- applicationKey: stored.applicationKey,
1201
- capabilities: stored.capabilities,
1202
- accountId: stored.accountId,
1203
- expirationTimestamp: stored.expirationTimestamp,
1204
- bucketId: stored.bucketId,
1205
- namePrefix: stored.namePrefix,
1206
- options: []
1207
- }
1208
- };
1209
- }
1210
- listKeys(req) {
1211
- const countError = validation.validateMaxCount(req.maxKeyCount, "b2_list_keys");
1212
- if (countError) return this.error(400, countError.code, countError.message);
1213
- const max = req.maxKeyCount ?? 1e3;
1214
- let allKeys = [...this.keys.values()].sort(
1215
- (a, b) => a.applicationKeyId.localeCompare(b.applicationKeyId)
1216
- );
1217
- if (req.startApplicationKeyId) {
1218
- const start = req.startApplicationKeyId;
1219
- allKeys = allKeys.filter((k) => k.applicationKeyId >= start);
1220
- }
1221
- const keys = allKeys.slice(0, max).map((k) => ({
1222
- keyName: k.keyName,
1223
- applicationKeyId: k.applicationKeyId,
1224
- capabilities: k.capabilities,
1225
- accountId: k.accountId,
1226
- expirationTimestamp: k.expirationTimestamp,
1227
- bucketId: k.bucketId,
1228
- namePrefix: k.namePrefix,
1229
- options: []
1230
- }));
1231
- const nextId = allKeys.length > max ? allKeys[max]?.applicationKeyId ?? null : null;
1232
- return { status: 200, body: { keys, nextApplicationKeyId: nextId } };
1233
- }
1234
- deleteKey(req) {
1235
- const key = this.keys.get(req.applicationKeyId);
1236
- if (!key) return this.error(400, "bad_request", "Key not found");
1237
- this.keys.delete(req.applicationKeyId);
1238
- for (const [token, scope] of this.issuedTokens.entries()) {
1239
- if (scope.applicationKeyId === req.applicationKeyId) {
1240
- this.issuedTokens.delete(token);
1241
- }
1242
- }
1243
- return {
1244
- status: 200,
1245
- body: {
1246
- keyName: key.keyName,
1247
- applicationKeyId: key.applicationKeyId,
1248
- capabilities: key.capabilities,
1249
- accountId: key.accountId,
1250
- expirationTimestamp: key.expirationTimestamp,
1251
- bucketId: key.bucketId,
1252
- namePrefix: key.namePrefix,
1253
- options: []
1254
- }
1255
- };
1256
- }
1257
- // --- File lock ---
1258
- updateFileRetention(req) {
1259
- const found = this.findFile(req.fileId);
1260
- if (found === null || found.stored.fileVersion.fileName !== req.fileName) {
1261
- return this.error(404, "file_not_present", "File not found");
1262
- }
1263
- found.versions[found.index] = {
1264
- fileVersion: {
1265
- ...found.stored.fileVersion,
1266
- fileRetention: { isClientAuthorizedToRead: true, value: req.fileRetention }
1267
- },
1268
- data: found.stored.data
1269
- };
1270
- return {
1271
- status: 200,
1272
- body: {
1273
- fileName: req.fileName,
1274
- fileId: req.fileId,
1275
- fileRetention: req.fileRetention
1276
- }
1277
- };
1278
- }
1279
- updateFileLegalHold(req) {
1280
- const found = this.findFile(req.fileId);
1281
- if (found === null || found.stored.fileVersion.fileName !== req.fileName) {
1282
- return this.error(404, "file_not_present", "File not found");
1283
- }
1284
- found.versions[found.index] = {
1285
- fileVersion: {
1286
- ...found.stored.fileVersion,
1287
- legalHold: {
1288
- isClientAuthorizedToRead: true,
1289
- value: req.legalHold
1290
- }
1291
- },
1292
- data: found.stored.data
1293
- };
1294
- return {
1295
- status: 200,
1296
- body: {
1297
- fileName: req.fileName,
1298
- fileId: req.fileId,
1299
- legalHold: req.legalHold
1300
- }
1301
- };
1302
- }
1303
- // --- Notifications ---
1304
- getBucketNotificationRules(req) {
1305
- if (!this.buckets.has(req.bucketId)) return this.error(400, "bad_bucket_id", "Bucket not found");
1306
- const rules = this.notificationRules.get(req.bucketId) ?? [];
1307
- return { status: 200, body: { bucketId: req.bucketId, eventNotificationRules: rules } };
1308
- }
1309
- setBucketNotificationRules(req) {
1310
- if (!this.buckets.has(req.bucketId)) return this.error(400, "bad_bucket_id", "Bucket not found");
1311
- this.notificationRules.set(req.bucketId, req.eventNotificationRules);
1312
- return {
1313
- status: 200,
1314
- body: { bucketId: req.bucketId, eventNotificationRules: req.eventNotificationRules }
1315
- };
1316
- }
1317
- // --- Helpers ---
1318
- /**
1319
- * Locates a stored file version by its `fileId`, scanning every bucket.
1320
- *
1321
- * Returns enough context to support read-only inspection (`stored`,
1322
- * `bucketId`) AND in-place mutation (`versions`, `index`) so callers
1323
- * that need to splice the version out can do so without re-scanning.
1324
- *
1325
- * Real B2 fileIds embed the bucketId, so production lookups are O(1);
1326
- * the simulator's flat ID generator (`this.genId('4_z')`) doesn't, so this
1327
- * is O(buckets × files × versions). Acceptable for tests.
1328
- *
1329
- * @param fileId - The file version ID to locate.
1330
- *
1331
- * @returns The location of the matching version, or `null` if not found.
1332
- */
1333
- findFile(fileId) {
1334
- for (const [bid, bucket2] of this.buckets.entries()) {
1335
- for (const versions of bucket2.files.values()) {
1336
- const idx = versions.findIndex((v) => v.fileVersion.fileId === fileId);
1337
- if (idx !== -1) {
1338
- const stored = versions[idx];
1339
- return { stored, bucketId: bid, bucket: bucket2, versions, index: idx };
1340
- }
1341
- }
1342
- }
1343
- return null;
1344
- }
1345
- makeFileVersion(params) {
1346
- return {
1347
- accountId: ids.accountId(this.accountId),
1348
- action: params.action,
1349
- bucketId: ids.bucketId(params.bucketId),
1350
- contentLength: params.contentLength,
1351
- contentMd5: null,
1352
- contentSha1: params.contentSha1,
1353
- contentType: params.contentType,
1354
- fileId: ids.fileId(this.genId("4_z")),
1355
- fileInfo: {},
1356
- fileName: params.fileName,
1357
- fileRetention: { isClientAuthorizedToRead: true, value: null },
1358
- legalHold: { isClientAuthorizedToRead: true, value: null },
1359
- replicationStatus: null,
1360
- serverSideEncryption: { mode: encryption.EncryptionMode.None },
1361
- uploadTimestamp: this.monotonicTimestamp()
1362
- };
1363
- }
1364
- error(status, code, message) {
1365
- return { status, body: { status, code, message } };
1366
- }
1367
- /**
1368
- * Fire the pluggable post-upload hooks for a file that just landed in
1369
- * a bucket: matching event-notification rules → `onWebhookDeliver`,
1370
- * configured replication source rules → `onReplicate`. Errors thrown
1371
- * from user-supplied hooks are swallowed so a buggy listener never
1372
- * masks an otherwise-successful API response.
1373
- *
1374
- * Fired-and-forgotten (no await) by the handler so the synthetic
1375
- * response is returned to the caller as fast as production B2 would
1376
- * acknowledge the write.
1377
- *
1378
- * @param fileVersion - The freshly-stored file metadata.
1379
- * @param bucketId - The bucket the upload landed in.
1380
- * @param eventType - The B2 event-type tag (e.g. `'b2:ObjectCreated:Upload'`)
1381
- * used to match against `EventNotificationRule.eventTypes` globs.
1382
- */
1383
- firePostUploadHooks(fileVersion, bucketId, eventType) {
1384
- const bucket2 = this.buckets.get(bucketId);
1385
- if (!bucket2) return;
1386
- if (this.onWebhookDeliver !== void 0) {
1387
- const rules = this.notificationRules.get(bucketId) ?? [];
1388
- for (const rule of rules) {
1389
- if (!rule.isEnabled) continue;
1390
- const matches = rule.eventTypes.some((pattern) => eventTypeMatches(pattern, eventType));
1391
- if (!matches) continue;
1392
- const hook = this.onWebhookDeliver;
1393
- this.dispatchHook("webhook", () => hook({ rule, fileVersion, bucketId }));
1394
- }
1395
- }
1396
- if (this.onReplicate !== void 0) {
1397
- const replConfig = bucket2.info.replicationConfiguration;
1398
- const sourceRules = replConfig.asReplicationSource?.replicationRules ?? [];
1399
- for (const rule of sourceRules) {
1400
- if (!rule.isEnabled) continue;
1401
- if (rule.fileNamePrefix && !fileVersion.fileName.startsWith(rule.fileNamePrefix)) continue;
1402
- const hook = this.onReplicate;
1403
- this.dispatchHook(
1404
- "replication",
1405
- () => hook({
1406
- sourceFileVersion: fileVersion,
1407
- sourceBucketId: bucketId,
1408
- destinationBucketId: rule.destinationBucketId
1409
- })
1410
- );
1411
- }
1412
- }
1413
- }
1414
- /**
1415
- * Schedule a user-supplied hook callback. Errors are routed to
1416
- * `onHookError` if configured, swallowed otherwise. The returned
1417
- * promise is tracked in {@link pendingHooks} so `flushHooks()` can
1418
- * wait for every dispatched hook to settle.
1419
- *
1420
- * @param kind - Which hook this is (`'webhook'` or `'replication'`).
1421
- * @param fn - Thunk that performs the hook invocation.
1422
- */
1423
- dispatchHook(kind, fn) {
1424
- const task = Promise.resolve().then(() => fn()).catch((err) => {
1425
- if (this.onHookError !== void 0) {
1426
- this.onHookError({ kind, error: toError.toError(err) });
1427
- }
1428
- }).finally(() => {
1429
- this.pendingHooks.delete(task);
1430
- });
1431
- this.pendingHooks.add(task);
1432
- }
352
+ function fileNames(...names) {
353
+ const present = names.filter((name) => name !== void 0);
354
+ return present.length > 0 ? present : void 0;
1433
355
  }
1434
- const eventTypeRegexCache = /* @__PURE__ */ new Map();
356
+ function queryParamsBody(params) {
357
+ const body = Object.create(null);
358
+ let hasParams = false;
359
+ for (const [key, value] of params) {
360
+ if (body[key] !== void 0) continue;
361
+ body[key] = value;
362
+ hasParams = true;
363
+ }
364
+ return hasParams ? body : null;
365
+ }
366
+ var JSON_GET_ENDPOINTS = /* @__PURE__ */ new Set([
367
+ "b2_authorize_account",
368
+ "b2_list_groups",
369
+ "b2_list_group_members",
370
+ "bz_list_computers"
371
+ ]);
372
+ var JSON_POST_ENDPOINTS = /* @__PURE__ */ new Set([
373
+ "b2_create_group_member",
374
+ "b2_eject_group_member",
375
+ "b2_reserve_trial_create_account",
376
+ "bz_delete_computer",
377
+ "b2_create_bucket",
378
+ "b2_list_buckets",
379
+ "b2_delete_bucket",
380
+ "b2_update_bucket",
381
+ "b2_get_upload_url",
382
+ "b2_list_file_names",
383
+ "b2_list_file_versions",
384
+ "b2_get_file_info",
385
+ "b2_hide_file",
386
+ "b2_delete_file_version",
387
+ "b2_copy_file",
388
+ "b2_start_large_file",
389
+ "b2_get_upload_part_url",
390
+ "b2_finish_large_file",
391
+ "b2_cancel_large_file",
392
+ "b2_list_unfinished_large_files",
393
+ "b2_list_parts",
394
+ "b2_copy_part",
395
+ "b2_get_download_authorization",
396
+ "b2_create_key",
397
+ "b2_list_keys",
398
+ "b2_delete_key",
399
+ "b2_update_file_retention",
400
+ "b2_update_file_legal_hold",
401
+ "b2_get_bucket_notification_rules",
402
+ "b2_set_bucket_notification_rules"
403
+ ]);
404
+ function jsonEndpointAllowsMethod(method, endpoint) {
405
+ const normalizedMethod = method.toUpperCase();
406
+ if (JSON_GET_ENDPOINTS.has(endpoint)) return normalizedMethod === "GET";
407
+ if (JSON_POST_ENDPOINTS.has(endpoint)) return normalizedMethod === "POST";
408
+ return true;
409
+ }
410
+ function notificationRulePrefixes(body) {
411
+ if (typeof body !== "object" || body === null) return void 0;
412
+ const rules = body["eventNotificationRules"];
413
+ if (!Array.isArray(rules)) return void 0;
414
+ return rules.map((rule) => {
415
+ if (typeof rule !== "object" || rule === null) return "";
416
+ const objectNamePrefix = rule["objectNamePrefix"];
417
+ return typeof objectNamePrefix === "string" ? objectNamePrefix : "";
418
+ });
419
+ }
420
+ function storedNotificationRulePrefixes(rules) {
421
+ return (rules ?? []).map((rule) => typeof rule.objectNamePrefix === "string" ? rule.objectNamePrefix : "");
422
+ }
423
+ function hasKeyManagementCapability(capabilities) {
424
+ return capabilities.some((capability) => capability === require_auth.Capability.ListKeys || capability === require_auth.Capability.WriteKeys || capability === require_auth.Capability.DeleteKeys);
425
+ }
426
+ function missingStoredKeyCapabilities(key, required) {
427
+ const capabilities = new Set(key.capabilities);
428
+ return required.filter((capability) => !capabilities.has(capability));
429
+ }
430
+ function storedKeyAllowsBucket(key, bucketId) {
431
+ return key.bucketIds === null || key.bucketIds.includes(bucketId);
432
+ }
433
+ function publicServerSideEncryption(encryption) {
434
+ if (encryption.mode === require_encryption.EncryptionMode.SseC) return {
435
+ mode: encryption.mode,
436
+ algorithm: encryption.algorithm
437
+ };
438
+ if (encryption.mode === require_encryption.EncryptionMode.None) return {
439
+ mode: null,
440
+ algorithm: null
441
+ };
442
+ return encryption;
443
+ }
444
+ function customerKeyDigest(customerKey) {
445
+ let first = 2166136261;
446
+ let second = 668265261;
447
+ for (const byte of customerKey) {
448
+ first = Math.imul(first ^ byte, 16777619) >>> 0;
449
+ second = Math.imul(second ^ byte, 2246822507) >>> 0;
450
+ }
451
+ return `${first.toString(16).padStart(8, "0")}${second.toString(16).padStart(8, "0")}`;
452
+ }
453
+ var BASE64_ALPHABET = /^[A-Za-z0-9+/]+$/;
454
+ function normalizeSizedBase64(value, decodedByteLength) {
455
+ const paddedLength = Math.ceil(decodedByteLength / 3) * 4;
456
+ const noPaddingLength = Math.ceil(decodedByteLength * 8 / 6);
457
+ const padding = "=".repeat(paddedLength - noPaddingLength);
458
+ if (value.length === noPaddingLength && BASE64_ALPHABET.test(value)) return value.padEnd(paddedLength, "=");
459
+ if (value.length === paddedLength && value.endsWith(padding) && BASE64_ALPHABET.test(value.slice(0, noPaddingLength))) return value;
460
+ return null;
461
+ }
462
+ function base64ToBytes(value, decodedByteLength) {
463
+ const normalized = normalizeSizedBase64(value, decodedByteLength);
464
+ if (normalized === null) return null;
465
+ try {
466
+ const decoded = atob(normalized);
467
+ if (decoded.length !== decodedByteLength) return null;
468
+ const bytes = new Uint8Array(decoded.length);
469
+ for (let i = 0; i < decoded.length; i++) bytes[i] = decoded.charCodeAt(i);
470
+ return bytes;
471
+ } catch {
472
+ return null;
473
+ }
474
+ }
475
+ function encryptionValidationError(message) {
476
+ return {
477
+ status: 400,
478
+ body: {
479
+ status: 400,
480
+ code: "bad_request",
481
+ message
482
+ }
483
+ };
484
+ }
485
+ function sameStoredServerSideEncryption(a, b) {
486
+ if (a.mode !== b.mode) return false;
487
+ if (a.mode === require_encryption.EncryptionMode.None) return true;
488
+ if (a.mode === require_encryption.EncryptionMode.SseB2 && b.mode === require_encryption.EncryptionMode.SseB2) return a.algorithm === b.algorithm;
489
+ if (a.mode === require_encryption.EncryptionMode.SseC && b.mode === require_encryption.EncryptionMode.SseC) return a.algorithm === b.algorithm && a.customerKeyDigest === b.customerKeyDigest && a.customerKeyMd5 === b.customerKeyMd5;
490
+ return false;
491
+ }
492
+ function hasCustomerEncryptionFields(encryption) {
493
+ return encryption["customerKey"] !== void 0 || encryption["customerKeyMd5"] !== void 0 || encryption["customerAlgorithm"] !== void 0;
494
+ }
495
+ function hasCustomerEncryptionHeaders(headers) {
496
+ return headers["x-bz-server-side-encryption-customer-algorithm"] !== void 0 || headers["x-bz-server-side-encryption-customer-key"] !== void 0 || headers["x-bz-server-side-encryption-customer-key-md5"] !== void 0;
497
+ }
498
+ async function storedServerSideEncryption(encryption) {
499
+ const runtimeEncryption = encryption;
500
+ if (encryption.mode === require_encryption.EncryptionMode.SseC) {
501
+ if (runtimeEncryption["algorithm"] === void 0) return encryptionValidationError("SSE-C customer algorithm is required");
502
+ if (encryption.algorithm !== require_encryption.EncryptionAlgorithm.Aes256) return encryptionValidationError("SSE-C customer algorithm must be AES256");
503
+ const customerKey = encryption.customerKey;
504
+ const customerKeyMd5 = encryption.customerKeyMd5;
505
+ if (typeof customerKey !== "string" || customerKey === "") return encryptionValidationError("SSE-C customer key is required");
506
+ if (typeof customerKeyMd5 !== "string" || customerKeyMd5 === "") return encryptionValidationError("SSE-C customer key MD5 is required");
507
+ const customerKeyBytes = base64ToBytes(customerKey, 32);
508
+ if (customerKeyBytes === null) return encryptionValidationError("SSE-C customer key must be a base64-encoded 256-bit key");
509
+ const normalizedCustomerKeyMd5 = normalizeSizedBase64(customerKeyMd5, 16);
510
+ if (normalizedCustomerKeyMd5 === null) return encryptionValidationError("SSE-C customer key MD5 must be a base64-encoded 128-bit digest");
511
+ if (await require_md5.md5Base64(customerKeyBytes) !== normalizedCustomerKeyMd5) return encryptionValidationError("SSE-C customer key MD5 does not match the key");
512
+ return {
513
+ mode: encryption.mode,
514
+ algorithm: encryption.algorithm,
515
+ customerKeyDigest: customerKeyDigest(customerKeyBytes),
516
+ customerKeyMd5: normalizedCustomerKeyMd5
517
+ };
518
+ }
519
+ if (encryption.mode === require_encryption.EncryptionMode.SseB2) {
520
+ if (hasCustomerEncryptionFields(runtimeEncryption)) return encryptionValidationError("SSE-B2 settings must not include SSE-C customer keys");
521
+ if (encryption.algorithm !== require_encryption.EncryptionAlgorithm.Aes256) return encryptionValidationError("SSE-B2 algorithm must be AES256");
522
+ return {
523
+ mode: encryption.mode,
524
+ algorithm: encryption.algorithm
525
+ };
526
+ }
527
+ if (encryption.mode === require_encryption.EncryptionMode.None) {
528
+ if (hasCustomerEncryptionFields(runtimeEncryption)) return encryptionValidationError("No-encryption settings must not include SSE-C customer keys");
529
+ return { mode: require_encryption.EncryptionMode.None };
530
+ }
531
+ return encryptionValidationError(`Unsupported server-side encryption mode: ${String(runtimeEncryption["mode"])}`);
532
+ }
533
+ async function uploadServerSideEncryption(headers, fallback) {
534
+ const customerAlgorithm = headers["x-bz-server-side-encryption-customer-algorithm"];
535
+ const customerKey = headers["x-bz-server-side-encryption-customer-key"];
536
+ const customerKeyMd5 = headers["x-bz-server-side-encryption-customer-key-md5"];
537
+ const managedEncryption = headers["x-bz-server-side-encryption"];
538
+ if (hasCustomerEncryptionHeaders(headers)) {
539
+ if (managedEncryption !== void 0) return encryptionValidationError("SSE-B2 settings must not include SSE-C customer keys");
540
+ if (customerAlgorithm === void 0) return encryptionValidationError("SSE-C customer algorithm is required");
541
+ if (customerAlgorithm !== require_encryption.EncryptionAlgorithm.Aes256) return encryptionValidationError("SSE-C customer algorithm must be AES256");
542
+ if (!customerKey || !customerKeyMd5) return encryptionValidationError("SSE-C customer key and MD5 are required");
543
+ return await storedServerSideEncryption({
544
+ mode: require_encryption.EncryptionMode.SseC,
545
+ algorithm: require_encryption.EncryptionAlgorithm.Aes256,
546
+ customerKey,
547
+ customerKeyMd5
548
+ });
549
+ }
550
+ if (managedEncryption !== void 0) {
551
+ if (managedEncryption !== require_encryption.EncryptionAlgorithm.Aes256) return encryptionValidationError("SSE-B2 algorithm must be AES256");
552
+ return {
553
+ mode: require_encryption.EncryptionMode.SseB2,
554
+ algorithm: require_encryption.EncryptionAlgorithm.Aes256
555
+ };
556
+ }
557
+ return await storedServerSideEncryption(fallback);
558
+ }
559
+ function defaultFileRetention(policy, uploadTimestamp) {
560
+ if (policy.mode === require_bucket.BucketRetentionMode.None || policy.period === null) return null;
561
+ const retainUntilTimestamp = uploadTimestamp + (policy.period.unit === "days" ? policy.period.duration : policy.period.duration * 365) * MS_PER_DAY;
562
+ if (!isValidRetentionTimestamp(retainUntilTimestamp, uploadTimestamp)) return null;
563
+ return {
564
+ mode: policy.mode,
565
+ retainUntilTimestamp
566
+ };
567
+ }
568
+ function isRetentionMode(value) {
569
+ return value === require_lock.RetentionMode.Compliance || value === require_lock.RetentionMode.Governance;
570
+ }
571
+ function parseFileRetentionValue(value, now) {
572
+ if (typeof value !== "object" || value === null) return null;
573
+ const candidate = value;
574
+ const mode = candidate["mode"];
575
+ const retainUntilTimestamp = candidate["retainUntilTimestamp"];
576
+ if (mode === null && retainUntilTimestamp === null) return {
577
+ mode,
578
+ retainUntilTimestamp
579
+ };
580
+ if (isRetentionMode(mode) && typeof retainUntilTimestamp === "number") {
581
+ if (!isValidRetentionTimestamp(retainUntilTimestamp, now)) return null;
582
+ return {
583
+ mode,
584
+ retainUntilTimestamp
585
+ };
586
+ }
587
+ return null;
588
+ }
589
+ function isRetentionWeakened(current, next) {
590
+ if (current === null || current === void 0) return false;
591
+ if (current.mode === null) return false;
592
+ if (next.mode === null) return true;
593
+ if (current.mode === require_lock.RetentionMode.Compliance && next.mode !== require_lock.RetentionMode.Compliance) return true;
594
+ if (current.retainUntilTimestamp === null) return next.mode !== current.mode;
595
+ if (next.retainUntilTimestamp === null) return true;
596
+ return next.retainUntilTimestamp < current.retainUntilTimestamp;
597
+ }
598
+ function requiresGovernanceBypass(current, next) {
599
+ if (current?.mode !== require_lock.RetentionMode.Governance) return false;
600
+ if (next.mode === require_lock.RetentionMode.Compliance) return true;
601
+ return isRetentionWeakened(current, next);
602
+ }
603
+ /**
604
+ * In-memory B2 simulator for testing. Implements the B2 native API at the
605
+ * request/response level without any network I/O. Supports 25+ operations
606
+ * including buckets, files, large files, keys, and notifications.
607
+ *
608
+ * @example
609
+ * ```ts
610
+ * const sim = new B2Simulator()
611
+ * const client = new B2Client({
612
+ * applicationKeyId: 'test-key-id',
613
+ * applicationKey: 'test-key',
614
+ * transport: sim.transport(),
615
+ * })
616
+ * await client.authorize()
617
+ * ```
618
+ *
619
+ * `test-key-id:test-key` is the documented implicit full-access
620
+ * storage credential. `master-key-id:master-key` is also accepted for
621
+ * tests that share storage and Partner simulator credentials. In the
622
+ * default permissive mode, other well-formed Basic credentials whose
623
+ * applicationKeyId was not minted by `b2_create_key` receive the same
624
+ * implicit master grant for backward compatibility. A simulator-created
625
+ * key always authorizes with its own capabilities, bucket restrictions,
626
+ * name prefix, and expiration.
627
+ */
628
+ var B2Simulator = class {
629
+ buckets = /* @__PURE__ */ new Map();
630
+ accountId = "sim_account_0001";
631
+ largeFiles = /* @__PURE__ */ new Map();
632
+ keys = /* @__PURE__ */ new Map();
633
+ notificationRules = /* @__PURE__ */ new Map();
634
+ minimumPartSize;
635
+ recommendedPartSize;
636
+ faults = [];
637
+ nextFaultId = 1;
638
+ onWebhookDeliver;
639
+ onReplicate;
640
+ onHookError;
641
+ strictAuth;
642
+ authTokenTtlMs;
643
+ customUploadTimestampsEnabled;
644
+ partner;
645
+ /**
646
+ * Issued auth tokens with their associated grant scope + expiry. In
647
+ * permissive mode (`strictAuth: false`) this is still populated by
648
+ * `authorize` but never consulted on subsequent requests. In strict
649
+ * mode each request looks up its `Authorization` header here.
650
+ */
651
+ issuedTokens = /* @__PURE__ */ new Map();
652
+ /**
653
+ * Mutable upload-token overrides for tokens minted by `b2_get_upload_url`
654
+ * and `b2_get_upload_part_url`. The token string is self-describing
655
+ * and signed so another simulator instance can validate issued-token
656
+ * state, while this map records local invalidation / forced-expiry
657
+ * state for tests.
658
+ */
659
+ uploadTokens = /* @__PURE__ */ new Map();
660
+ downloadAuthorizationTokens = /* @__PURE__ */ new Map();
661
+ downloadAuthorizationExpiryHeap = [];
662
+ /**
663
+ * Virtual-clock offset applied to `Date.now()` for expiry checks.
664
+ * Defaults to 0. Tests advance via {@link advanceTime} to fast-forward
665
+ * past auth-token expiry without sleeping.
666
+ */
667
+ clockOffsetMs = 0;
668
+ /**
669
+ * Per-instance monotonic counter used to mint realistic-looking
670
+ * IDs (`b2_bucket_<24-hex>`, `4_z<24-hex>`, etc.) and auth tokens.
671
+ * Module-global previously, which leaked state across `B2Simulator`
672
+ * instances in the same Vitest worker — concurrent tests could see
673
+ * colliding tokens. Per-instance ensures determinism within a single
674
+ * simulator's lifetime.
675
+ */
676
+ nextId = 1;
677
+ /**
678
+ * Last-issued upload timestamp. The simulator enforces strict
679
+ * monotonicity so version ordering is deterministic for tests; if
680
+ * two writes hit the same `Date.now()` millisecond, the second
681
+ * receives `lastTimestamp + 1`.
682
+ */
683
+ lastTimestamp = 0;
684
+ /**
685
+ * Outstanding fire-and-forget hook invocations. Tracked so tests
686
+ * (and future {@link flushHooks} callers) can wait for every
687
+ * dispatched `onWebhookDeliver` / `onReplicate` callback to settle
688
+ * before asserting against observable side effects. The microtask
689
+ * dance in fidelity tests was previously brittle: positive cases
690
+ * flushed twice, negative cases flushed once, and any addition to
691
+ * the hook dispatch chain quietly broke the negative path.
692
+ */
693
+ pendingHooks = /* @__PURE__ */ new Set();
694
+ /**
695
+ * Constructs a new in-memory B2 simulator.
696
+ * @param options - Optional simulator overrides. See {@link B2SimulatorOptions}.
697
+ */
698
+ constructor(options = {}) {
699
+ this.minimumPartSize = options.minimumPartSize ?? 5e6;
700
+ this.recommendedPartSize = options.recommendedPartSize ?? 1e8;
701
+ if (options.onWebhookDeliver !== void 0) this.onWebhookDeliver = options.onWebhookDeliver;
702
+ if (options.onReplicate !== void 0) this.onReplicate = options.onReplicate;
703
+ if (options.onHookError !== void 0) this.onHookError = options.onHookError;
704
+ this.strictAuth = options.strictAuth ?? false;
705
+ this.customUploadTimestampsEnabled = options.customUploadTimestampsEnabled ?? false;
706
+ this.authTokenTtlMs = options.authTokenTtlMs ?? 864e5;
707
+ this.partner = new require_partner.PartnerSimulator({
708
+ accountId: this.accountId,
709
+ authTokenTtlMs: this.authTokenTtlMs,
710
+ minimumPartSize: this.minimumPartSize,
711
+ recommendedPartSize: this.recommendedPartSize,
712
+ canAuthorize: (authzHeader) => this.canAuthorizePartner(authzHeader),
713
+ createBucket: (req) => this.createBucket(req),
714
+ error: (status, code, message) => this.error(status, code, message),
715
+ genId: (prefix) => this.genId(prefix),
716
+ monotonicTimestamp: () => this.monotonicTimestamp(),
717
+ now: () => this.now(),
718
+ storeKey: (key) => {
719
+ this.keys.set(key.applicationKeyId, key);
720
+ }
721
+ }, options);
722
+ }
723
+ /**
724
+ * Advance the simulator's virtual clock by `ms` milliseconds. Used in
725
+ * conjunction with `strictAuth: true` + a finite `authTokenTtlMs` to
726
+ * force token expiry without `setTimeout`-based delays.
727
+ *
728
+ * @param ms - Milliseconds to advance. Negative values rewind (rarely useful).
729
+ */
730
+ advanceTime(ms) {
731
+ this.clockOffsetMs += ms;
732
+ }
733
+ /**
734
+ * Expire an upload authorization token previously returned by
735
+ * `b2_get_upload_url` or `b2_get_upload_part_url`. Tests can use this
736
+ * to simulate a stale upload URL and verify retry paths that fetch a
737
+ * fresh URL/token pair.
738
+ *
739
+ * @param authorizationToken - The upload authorization token to expire.
740
+ *
741
+ * @returns `true` when the token existed and was expired, otherwise `false`.
742
+ */
743
+ expireUploadToken(authorizationToken) {
744
+ const now = this.now();
745
+ const token = this.uploadTokens.get(authorizationToken);
746
+ if (token === void 0 || now >= token.cleanupAt) return false;
747
+ token.expiresAt = now - 1;
748
+ this.uploadTokens.set(authorizationToken, token);
749
+ return true;
750
+ }
751
+ /**
752
+ * Invalidate an upload authorization token previously returned by
753
+ * `b2_get_upload_url` or `b2_get_upload_part_url`.
754
+ *
755
+ * @param authorizationToken - The upload authorization token to invalidate.
756
+ *
757
+ * @returns `true` when the token existed and was invalidated, otherwise `false`.
758
+ */
759
+ invalidateUploadToken(authorizationToken) {
760
+ const now = this.now();
761
+ const token = this.uploadTokens.get(authorizationToken);
762
+ if (token === void 0 || now >= token.cleanupAt) {
763
+ this.pruneExpiredUploadTokens(now);
764
+ return false;
765
+ }
766
+ token.invalidated = true;
767
+ this.uploadTokens.set(authorizationToken, token);
768
+ this.pruneExpiredUploadTokens();
769
+ return true;
770
+ }
771
+ /**
772
+ * Current simulator time. Equal to `Date.now() + clockOffsetMs`.
773
+ *
774
+ * @returns Unix milliseconds.
775
+ */
776
+ now() {
777
+ return Date.now() + this.clockOffsetMs;
778
+ }
779
+ isStoredKeyExpired(key) {
780
+ return key.expirationTimestamp !== null && key.expirationTimestamp <= this.now();
781
+ }
782
+ pruneExpiredUploadTokens(now = this.now()) {
783
+ for (const [authorizationToken, token] of this.uploadTokens.entries()) if (now >= token.cleanupAt) this.uploadTokens.delete(authorizationToken);
784
+ }
785
+ async uploadTokenState(authorizationToken) {
786
+ const stored = this.uploadTokens.get(authorizationToken);
787
+ if (stored !== void 0) return stored;
788
+ return await this.decodeUploadAuthorizationToken(authorizationToken);
789
+ }
790
+ async encodeUploadAuthorizationToken(token) {
791
+ const payload = {
792
+ v: 1,
793
+ kind: token.kind,
794
+ fileName: token.fileName,
795
+ uploadUrl: token.uploadUrl,
796
+ namePrefix: token.namePrefix,
797
+ applicationKeyId: token.applicationKeyId,
798
+ expiresAt: token.expiresAt
799
+ };
800
+ const encoded = base64UrlEncode(require_text_codec.utf8Encoder.encode(JSON.stringify(payload)));
801
+ const signature = await this.signUploadTokenPayload(encoded);
802
+ return `${token.kind === "file" ? "sim_upload_auth" : "sim_part_auth"}_${encoded}.${signature}`;
803
+ }
804
+ async decodeUploadAuthorizationToken(authorizationToken) {
805
+ const expectedKind = authorizationToken.startsWith("sim_upload_auth_") ? "file" : authorizationToken.startsWith("sim_part_auth_") ? "part" : null;
806
+ if (expectedKind === null) return null;
807
+ const tokenParts = authorizationToken.slice(expectedKind === "file" ? 16 : 14).split(".");
808
+ if (tokenParts.length !== 2) return null;
809
+ const [payloadBytes, signature] = tokenParts;
810
+ if (!timingSafeStringEqual(signature, await this.signUploadTokenPayload(payloadBytes))) return null;
811
+ let parsed;
812
+ try {
813
+ const bytes = base64UrlDecode(payloadBytes);
814
+ if (bytes === null) return null;
815
+ parsed = JSON.parse(require_text_codec.utf8Decoder.decode(bytes));
816
+ } catch {
817
+ return null;
818
+ }
819
+ if (typeof parsed !== "object" || parsed === null) return null;
820
+ const payload = parsed;
821
+ if (payload["v"] !== 1 || payload["kind"] !== expectedKind || typeof payload["uploadUrl"] !== "string" || typeof payload["expiresAt"] !== "number" || !Number.isFinite(payload["expiresAt"]) || !(payload["namePrefix"] === null || typeof payload["namePrefix"] === "string") || !(payload["applicationKeyId"] === null || typeof payload["applicationKeyId"] === "string")) return null;
822
+ let fileName;
823
+ if (expectedKind === "part") {
824
+ if (typeof payload["fileName"] !== "string") return null;
825
+ fileName = payload["fileName"];
826
+ } else {
827
+ if (payload["fileName"] !== null) return null;
828
+ fileName = null;
829
+ }
830
+ return {
831
+ kind: expectedKind,
832
+ fileName,
833
+ uploadUrl: payload["uploadUrl"],
834
+ namePrefix: payload["namePrefix"],
835
+ applicationKeyId: payload["applicationKeyId"],
836
+ expiresAt: payload["expiresAt"],
837
+ cleanupAt: payload["expiresAt"],
838
+ invalidated: false
839
+ };
840
+ }
841
+ async signUploadTokenPayload(encodedPayload) {
842
+ return base64UrlEncode(await require_crypto.hmacSha256(UPLOAD_TOKEN_SIGNING_KEY, encodedPayload));
843
+ }
844
+ /**
845
+ * Generate a deterministic-but-realistic-looking B2 identifier of the
846
+ * shape `<prefix>_<24-hex-counter>`, which approximates the visual
847
+ * width of real B2 wire IDs. The counter is monotonic per instance
848
+ * so test fixtures are deterministic across runs of the same
849
+ * simulator.
850
+ *
851
+ * @param prefix - B2-style prefix (`'b2_bucket'`, `'4_z'`, etc.).
852
+ *
853
+ * @returns A simulator-issued identifier that looks like a B2 wire ID.
854
+ */
855
+ genId(prefix) {
856
+ return `${prefix}_${(this.nextId++).toString(16).padStart(24, "0")}`;
857
+ }
858
+ /**
859
+ * Return a strictly-increasing upload timestamp, even when multiple
860
+ * writes land in the same `Date.now()` millisecond. Tests rely on
861
+ * `uploadTimestamp` ordering to discriminate file versions; ties from
862
+ * coarse system-clock resolution would otherwise make version
863
+ * selection nondeterministic.
864
+ *
865
+ * @returns Unix milliseconds.
866
+ */
867
+ monotonicTimestamp() {
868
+ const now = Date.now();
869
+ if (now <= this.lastTimestamp) this.lastTimestamp += 1;
870
+ else this.lastTimestamp = now;
871
+ return this.lastTimestamp;
872
+ }
873
+ /**
874
+ * Wait for every fire-and-forget hook (`onWebhookDeliver`,
875
+ * `onReplicate`) currently in flight to settle. Use in tests after
876
+ * an upload/copy/finish-large-file call to deterministically observe
877
+ * hook side effects without microtask-flush guesswork.
878
+ *
879
+ * @returns A promise that resolves once every pending hook callback
880
+ * has either resolved or rejected.
881
+ */
882
+ async flushHooks() {
883
+ while (this.pendingHooks.size > 0) {
884
+ const snapshot = [...this.pendingHooks];
885
+ await Promise.allSettled(snapshot);
886
+ }
887
+ }
888
+ /**
889
+ * Authorize a request against the strict-auth bookkeeping. Returns
890
+ * a `SimulatorJsonResponse` error on failure or `null` on success.
891
+ * Only consulted when `strictAuth: true`.
892
+ *
893
+ * @param authToken - The `Authorization` header value from the request.
894
+ * @param endpoint - B2 endpoint name being invoked.
895
+ * @param scope - Optional effective bucket and file-name scope derived from the request.
896
+ *
897
+ * @returns `null` when the request is authorized, otherwise a 401/403 response.
898
+ */
899
+ authorizeRequest(authToken, endpoint, scope) {
900
+ if (require_capabilities.missingCapabilitiesFor(endpoint, []).length === 0 && endpoint === "b2_authorize_account") return null;
901
+ if (authToken === void 0 || authToken === "") return this.error(401, "bad_auth_token", "missing Authorization header");
902
+ const token = this.issuedTokens.get(authToken);
903
+ if (!token) return this.error(401, "bad_auth_token", "unknown auth token");
904
+ if (this.now() > token.expiresAt) return this.error(401, "expired_auth_token", "auth token has expired; reauthorize");
905
+ if (token.applicationKeyId !== null) {
906
+ const key = this.keys.get(token.applicationKeyId);
907
+ if (key === void 0) return this.error(401, "bad_auth_token", "application key has been deleted; reauthorize");
908
+ if (this.isStoredKeyExpired(key)) return this.error(401, "expired_auth_token", "application key has expired; reauthorize");
909
+ }
910
+ const missing = require_capabilities.missingCapabilitiesFor(endpoint, token.capabilities);
911
+ if (missing.length > 0) return this.error(403, "unauthorized", `application key lacks required capabilities: ${missing.join(", ")}`);
912
+ return this.authorizeScopeGrant(scope, {
913
+ bucketIds: token.bucketIds,
914
+ namePrefix: token.namePrefix,
915
+ bucketScopeRequiredMessage: () => `application key is scoped to buckets ${token.bucketIds?.join(", ")}; bucket scope is required`,
916
+ bucketMismatchMessage: (bucketId) => `application key is scoped to buckets ${token.bucketIds?.join(", ")}; cannot access ${bucketId}`,
917
+ prefixMismatchMessage: (fileName) => `application key is scoped to prefix "${token.namePrefix}"; "${fileName}" is outside scope`
918
+ });
919
+ }
920
+ authorizeScopeGrant(scope, grant) {
921
+ if (grant.bucketIds !== null) {
922
+ if (scope?.requiresAccountLevelBucketAccess === true) return this.error(403, "unauthorized", grant.bucketScopeRequiredMessage());
923
+ if ((scope?.bucketIds.length ?? 0) === 0 && scope?.requiresBucketScope === true) return this.error(403, "unauthorized", grant.bucketScopeRequiredMessage());
924
+ for (const bucketId of scope?.bucketIds ?? []) {
925
+ if (grant.bucketIds.includes(bucketId)) continue;
926
+ return this.error(403, "unauthorized", grant.bucketMismatchMessage(bucketId));
927
+ }
928
+ }
929
+ if (grant.namePrefix !== null) for (const fileName of scope?.fileNames ?? []) {
930
+ if (fileName.startsWith(grant.namePrefix)) continue;
931
+ return this.error(403, "unauthorized", grant.prefixMismatchMessage(fileName));
932
+ }
933
+ return null;
934
+ }
935
+ authorizeDownloadRequest(authToken, endpoint, scope, url) {
936
+ if (authToken === void 0 || authToken === "") return this.error(401, "bad_auth_token", "missing authorization token");
937
+ const downloadAuth = this.downloadAuthorizationTokens.get(authToken);
938
+ if (downloadAuth === void 0) {
939
+ this.purgeExpiredDownloadAuthorizationTokens();
940
+ return this.authorizeRequest(authToken, endpoint, scope);
941
+ }
942
+ if (this.isExpiredDownloadAuthorizationToken(downloadAuth)) {
943
+ this.downloadAuthorizationTokens.delete(authToken);
944
+ this.purgeExpiredDownloadAuthorizationTokens();
945
+ return this.error(401, "expired_auth_token", "download authorization token has expired");
946
+ }
947
+ if (endpoint === "b2_download_file_by_id") return this.error(403, "unauthorized", "download authorization tokens cannot be used with b2_download_file_by_id");
948
+ const overrideError = this.authorizeDownloadResponseOverrides(downloadAuth, url);
949
+ if (overrideError !== null) return overrideError;
950
+ return this.authorizeScopeGrant(scope, {
951
+ bucketIds: [downloadAuth.bucketId],
952
+ namePrefix: downloadAuth.fileNamePrefix,
953
+ bucketScopeRequiredMessage: () => `download authorization is scoped to bucket ${downloadAuth.bucketId}; bucket scope is required`,
954
+ bucketMismatchMessage: (bucketId) => `download authorization is scoped to bucket ${downloadAuth.bucketId}; cannot access ${bucketId}`,
955
+ prefixMismatchMessage: (fileName) => `download authorization is scoped to prefix "${downloadAuth.fileNamePrefix}"; "${fileName}" is outside scope`
956
+ });
957
+ }
958
+ isExpiredDownloadAuthorizationToken(token, now = this.now()) {
959
+ return now >= token.expiresAt;
960
+ }
961
+ purgeExpiredDownloadAuthorizationTokens() {
962
+ const now = this.now();
963
+ for (let i = 0; i < DOWNLOAD_AUTH_PURGE_BATCH_SIZE; i++) {
964
+ const next = this.downloadAuthorizationExpiryHeap[0];
965
+ if (next === void 0 || next.expiresAt > now) return;
966
+ this.popDownloadAuthorizationExpiry();
967
+ if (this.downloadAuthorizationTokens.get(next.token)?.expiresAt === next.expiresAt) this.downloadAuthorizationTokens.delete(next.token);
968
+ }
969
+ }
970
+ pushDownloadAuthorizationExpiry(entry) {
971
+ const heap = this.downloadAuthorizationExpiryHeap;
972
+ heap.push(entry);
973
+ let idx = heap.length - 1;
974
+ while (idx > 0) {
975
+ const parentIdx = Math.floor((idx - 1) / 2);
976
+ const parent = heap[parentIdx];
977
+ if (parent.expiresAt <= entry.expiresAt) break;
978
+ heap[idx] = parent;
979
+ idx = parentIdx;
980
+ }
981
+ heap[idx] = entry;
982
+ }
983
+ popDownloadAuthorizationExpiry() {
984
+ const heap = this.downloadAuthorizationExpiryHeap;
985
+ const root = heap[0];
986
+ const last = heap.pop();
987
+ if (root === void 0 || last === void 0 || heap.length === 0) return root;
988
+ let idx = 0;
989
+ while (true) {
990
+ const leftIdx = idx * 2 + 1;
991
+ const rightIdx = leftIdx + 1;
992
+ const left = heap[leftIdx];
993
+ const right = heap[rightIdx];
994
+ if (left === void 0) break;
995
+ const childIdx = right !== void 0 && right.expiresAt < left.expiresAt ? rightIdx : leftIdx;
996
+ const child = heap[childIdx];
997
+ if (child.expiresAt >= last.expiresAt) break;
998
+ heap[idx] = child;
999
+ idx = childIdx;
1000
+ }
1001
+ heap[idx] = last;
1002
+ return root;
1003
+ }
1004
+ authorizeDownloadResponseOverrides(downloadAuth, url) {
1005
+ for (const param of DOWNLOAD_RESPONSE_OVERRIDE_PARAMS) {
1006
+ const expected = downloadAuth.responseHeaderOverrides[param];
1007
+ if (expected === void 0) continue;
1008
+ const actual = url.searchParams.get(param);
1009
+ if (actual === expected) continue;
1010
+ const expectedText = JSON.stringify(expected);
1011
+ const actualText = actual === null ? "absent" : JSON.stringify(actual);
1012
+ return this.error(403, "unauthorized", `download authorization requires ${param}=${expectedText}; got ${actualText}`);
1013
+ }
1014
+ return null;
1015
+ }
1016
+ downloadAuthorizationFromRequest(headers, url, options = {}) {
1017
+ const headerToken = requestHeaderValue(headers, "authorization");
1018
+ if (headerToken !== void 0) return headerToken;
1019
+ if (options.allowQueryAuthorization !== true) return void 0;
1020
+ const queryToken = url.searchParams.get("Authorization") ?? url.searchParams.get("authorization");
1021
+ return queryToken?.startsWith(DOWNLOAD_AUTH_TOKEN_PREFIX) ? queryToken : void 0;
1022
+ }
1023
+ requestHasCapability(authToken, capability) {
1024
+ if (!this.strictAuth) return true;
1025
+ if (authToken === void 0) return false;
1026
+ return this.issuedTokens.get(authToken)?.capabilities.includes(capability) === true;
1027
+ }
1028
+ requireFileLockEnabled(bucket) {
1029
+ if (bucket.info.fileLockConfiguration.value?.isFileLockEnabled === true) return null;
1030
+ return this.error(400, "file_lock_not_enabled", "Bucket does not have file lock enabled");
1031
+ }
1032
+ requireGovernanceBypass(req, authToken, message) {
1033
+ if (req.bypassGovernance !== true) return this.error(400, "file_lock_governance_protected", message);
1034
+ if (!this.requestHasCapability(authToken, require_auth.Capability.BypassGovernance)) return this.error(403, "unauthorized", `application key lacks required capabilities: ${require_auth.Capability.BypassGovernance}`);
1035
+ return null;
1036
+ }
1037
+ validateReplicationApplicationKey(applicationKeyId, requiredCapabilities, options) {
1038
+ const key = this.keys.get(applicationKeyId);
1039
+ if (key === void 0) return this.invalidReplicationApplicationKey(options.role);
1040
+ if (missingStoredKeyCapabilities(key, requiredCapabilities).length > 0) return this.invalidReplicationApplicationKey(options.role);
1041
+ if (options.bucketId !== void 0 && !storedKeyAllowsBucket(key, options.bucketId)) return this.invalidReplicationApplicationKey(options.role);
1042
+ return null;
1043
+ }
1044
+ invalidReplicationApplicationKey(role) {
1045
+ return this.error(400, "bad_request", `${role} application key is invalid or not authorized for this replication configuration`);
1046
+ }
1047
+ invalidReplicationDestinationBucket() {
1048
+ return this.error(400, "bad_request", "replication destination bucket is invalid or not configured for this source application key");
1049
+ }
1050
+ validateReplicationDestinationBuckets(sourceApplicationKeyId, rules) {
1051
+ for (const rule of rules) {
1052
+ const destinationBucketId = requestRecord(rule)?.["destinationBucketId"];
1053
+ if (typeof destinationBucketId !== "string") continue;
1054
+ const destinationApplicationKeyId = this.buckets.get(destinationBucketId)?.info.replicationConfiguration.asReplicationDestination?.sourceToDestinationKeyMapping[sourceApplicationKeyId];
1055
+ if (destinationApplicationKeyId === void 0) return this.invalidReplicationDestinationBucket();
1056
+ const destinationKeyError = this.validateReplicationApplicationKey(destinationApplicationKeyId, [require_auth.Capability.WriteFiles], {
1057
+ bucketId: destinationBucketId,
1058
+ role: "replication destination"
1059
+ });
1060
+ if (destinationKeyError !== null) return destinationKeyError;
1061
+ }
1062
+ return null;
1063
+ }
1064
+ validateReplicationApplicationKeys(config, bucketId) {
1065
+ if (!this.strictAuth || config === void 0) return null;
1066
+ const replicationConfiguration = requestRecord(config);
1067
+ const source = requestRecord(replicationConfiguration?.["asReplicationSource"]);
1068
+ if (source !== null) {
1069
+ const sourceApplicationKeyId = source["sourceApplicationKeyId"];
1070
+ if (typeof sourceApplicationKeyId === "string") {
1071
+ const sourceKeyError = this.validateReplicationApplicationKey(sourceApplicationKeyId, [require_auth.Capability.ReadFiles, require_auth.Capability.ListFiles], {
1072
+ bucketId,
1073
+ role: "replication source"
1074
+ });
1075
+ if (sourceKeyError !== null) return sourceKeyError;
1076
+ }
1077
+ const rules = source["replicationRules"];
1078
+ if (typeof sourceApplicationKeyId === "string" && Array.isArray(rules)) {
1079
+ const destinationError = this.validateReplicationDestinationBuckets(sourceApplicationKeyId, rules);
1080
+ if (destinationError !== null) return destinationError;
1081
+ }
1082
+ }
1083
+ const mapping = requestRecord(requestRecord(replicationConfiguration?.["asReplicationDestination"])?.["sourceToDestinationKeyMapping"]);
1084
+ if (mapping !== null) for (const [sourceApplicationKeyId, destinationApplicationKeyId] of Object.entries(mapping)) {
1085
+ const sourceKeyError = this.validateReplicationApplicationKey(sourceApplicationKeyId, [require_auth.Capability.ReadFiles, require_auth.Capability.ListFiles], { role: "replication source" });
1086
+ if (sourceKeyError !== null) return sourceKeyError;
1087
+ if (typeof destinationApplicationKeyId === "string") {
1088
+ const destinationKeyError = this.validateReplicationApplicationKey(destinationApplicationKeyId, [require_auth.Capability.WriteFiles], {
1089
+ bucketId,
1090
+ role: "replication destination"
1091
+ });
1092
+ if (destinationKeyError !== null) return destinationKeyError;
1093
+ }
1094
+ }
1095
+ return null;
1096
+ }
1097
+ requestScope(endpoint, body) {
1098
+ const directBucketId = requestStringField(body, "bucketId");
1099
+ const directFileName = requestStringField(body, "fileName");
1100
+ switch (endpoint) {
1101
+ case "b2_create_bucket": return this.createBucketScope(body);
1102
+ case "b2_list_buckets": return this.listBucketsScope(body, directBucketId);
1103
+ case "b2_list_file_names":
1104
+ case "b2_list_file_versions": return {
1105
+ bucketIds: directBucketId === void 0 ? [] : [directBucketId],
1106
+ fileNames: [requestStringField(body, "prefix") ?? ""],
1107
+ requiresBucketScope: true
1108
+ };
1109
+ case "b2_get_file_info": return this.fileIdScope(requestStringField(body, "fileId")) ?? {
1110
+ bucketIds: [],
1111
+ requiresBucketScope: true
1112
+ };
1113
+ case "b2_delete_file_version":
1114
+ case "b2_update_file_retention":
1115
+ case "b2_update_file_legal_hold": return this.fileVersionScope(body, directFileName);
1116
+ case "b2_get_upload_part_url":
1117
+ case "b2_finish_large_file":
1118
+ case "b2_cancel_large_file":
1119
+ case "b2_list_parts": return this.largeFileScope(requestStringField(body, "fileId")) ?? {
1120
+ bucketIds: [],
1121
+ requiresBucketScope: true
1122
+ };
1123
+ case "b2_copy_file": return this.copyFileScope(body, directFileName);
1124
+ case "b2_copy_part": return this.copyPartScope(body);
1125
+ case "b2_list_unfinished_large_files": return {
1126
+ bucketIds: directBucketId === void 0 ? [] : [directBucketId],
1127
+ fileNames: [requestStringField(body, "namePrefix") ?? ""],
1128
+ requiresBucketScope: true
1129
+ };
1130
+ case "b2_get_download_authorization": return {
1131
+ bucketIds: directBucketId === void 0 ? [] : [directBucketId],
1132
+ fileNames: [requestStringField(body, "fileNamePrefix") ?? ""],
1133
+ requiresBucketScope: true
1134
+ };
1135
+ case "b2_get_bucket_notification_rules": return this.notificationRulesScope(body, directBucketId, false);
1136
+ case "b2_set_bucket_notification_rules": return this.notificationRulesScope(body, directBucketId, true);
1137
+ case "b2_update_bucket": return this.updateBucketScope(body, directBucketId);
1138
+ default: return this.defaultRequestScope(directBucketId, directFileName);
1139
+ }
1140
+ }
1141
+ createBucketScope(body) {
1142
+ return {
1143
+ bucketIds: replicationDestinationBucketIds(body),
1144
+ requiresBucketScope: true,
1145
+ requiresAccountLevelBucketAccess: true
1146
+ };
1147
+ }
1148
+ updateBucketScope(body, directBucketId) {
1149
+ return {
1150
+ bucketIds: [...directBucketId === void 0 ? [] : [directBucketId], ...replicationDestinationBucketIds(body)],
1151
+ requiresBucketScope: true
1152
+ };
1153
+ }
1154
+ listBucketsScope(body, directBucketId) {
1155
+ if (directBucketId !== void 0) return {
1156
+ bucketIds: [directBucketId],
1157
+ requiresBucketScope: true
1158
+ };
1159
+ const bucketName = requestStringField(body, "bucketName");
1160
+ if (bucketName !== void 0) {
1161
+ const bucket = [...this.buckets.values()].find((b) => b.info.bucketName === bucketName);
1162
+ return {
1163
+ bucketIds: bucket === void 0 ? [] : [bucket.info.bucketId],
1164
+ requiresBucketScope: true
1165
+ };
1166
+ }
1167
+ return {
1168
+ bucketIds: [],
1169
+ requiresBucketScope: true
1170
+ };
1171
+ }
1172
+ fileVersionScope(body, directFileName) {
1173
+ const fileScope = this.fileIdScope(requestStringField(body, "fileId"));
1174
+ if (fileScope !== void 0) return fileScope;
1175
+ return {
1176
+ bucketIds: [],
1177
+ ...directFileName !== void 0 ? { fileNames: [directFileName] } : {},
1178
+ requiresBucketScope: true
1179
+ };
1180
+ }
1181
+ copyFileScope(body, directFileName) {
1182
+ const sourceScope = this.fileIdScope(requestStringField(body, "sourceFileId"));
1183
+ const destinationBucketId = requestStringField(body, "destinationBucketId");
1184
+ const bucketIds = [...sourceScope?.bucketIds ?? [], ...destinationBucketId !== void 0 ? [destinationBucketId] : []];
1185
+ const scopedFileNames = fileNames(...sourceScope?.fileNames ?? [], directFileName);
1186
+ return {
1187
+ bucketIds,
1188
+ ...scopedFileNames !== void 0 ? { fileNames: scopedFileNames } : {},
1189
+ requiresBucketScope: true
1190
+ };
1191
+ }
1192
+ copyPartScope(body) {
1193
+ const sourceScope = this.fileIdScope(requestStringField(body, "sourceFileId"));
1194
+ const largeScope = this.largeFileScope(requestStringField(body, "largeFileId"));
1195
+ const scopedFileNames = fileNames(...sourceScope?.fileNames ?? [], ...largeScope?.fileNames ?? []);
1196
+ return {
1197
+ bucketIds: [...sourceScope?.bucketIds ?? [], ...largeScope?.bucketIds ?? []],
1198
+ ...scopedFileNames !== void 0 ? { fileNames: scopedFileNames } : {},
1199
+ requiresBucketScope: true
1200
+ };
1201
+ }
1202
+ notificationRulesScope(body, directBucketId, includeRequestRules) {
1203
+ const existingPrefixes = directBucketId === void 0 ? [] : storedNotificationRulePrefixes(this.notificationRules.get(directBucketId));
1204
+ const requestPrefixes = includeRequestRules ? notificationRulePrefixes(body) ?? [] : [];
1205
+ const prefixes = [...existingPrefixes, ...requestPrefixes];
1206
+ return {
1207
+ bucketIds: directBucketId === void 0 ? [] : [directBucketId],
1208
+ ...prefixes.length > 0 ? { fileNames: prefixes } : {},
1209
+ requiresBucketScope: true
1210
+ };
1211
+ }
1212
+ defaultRequestScope(directBucketId, directFileName) {
1213
+ if (directBucketId !== void 0) return {
1214
+ bucketIds: [directBucketId],
1215
+ ...directFileName !== void 0 ? { fileNames: [directFileName] } : {},
1216
+ requiresBucketScope: true
1217
+ };
1218
+ return directFileName !== void 0 ? {
1219
+ bucketIds: [],
1220
+ fileNames: [directFileName],
1221
+ requiresBucketScope: false
1222
+ } : void 0;
1223
+ }
1224
+ fileIdScope(fileId) {
1225
+ if (fileId === void 0) return void 0;
1226
+ const found = this.findFile(fileId);
1227
+ if (found === null) return void 0;
1228
+ return {
1229
+ bucketIds: [found.bucketId],
1230
+ fileNames: [found.stored.fileVersion.fileName],
1231
+ requiresBucketScope: true
1232
+ };
1233
+ }
1234
+ largeFileScope(fileId) {
1235
+ if (fileId === void 0) return void 0;
1236
+ const large = this.largeFiles.get(fileId);
1237
+ if (large === void 0) return void 0;
1238
+ return {
1239
+ bucketIds: [large.bucketId],
1240
+ fileNames: [large.fileName],
1241
+ requiresBucketScope: true
1242
+ };
1243
+ }
1244
+ async issueUploadAuthorization(options) {
1245
+ const now = this.now();
1246
+ this.pruneExpiredUploadTokens(now);
1247
+ const endpoint = options.kind === "file" ? "b2_upload_file" : "b2_upload_part";
1248
+ const idParam = options.kind === "file" ? "bucketId" : "fileId";
1249
+ const scopedId = options.kind === "file" ? options.bucketId : options.fileId;
1250
+ const uploadId = this.genId(options.kind === "file" ? "upload_file" : "upload_part");
1251
+ const uploadUrl = new URL(require_url.b2Url("http://localhost:0", {
1252
+ version: "v3",
1253
+ endpoint
1254
+ }));
1255
+ uploadUrl.searchParams.set(idParam, scopedId);
1256
+ uploadUrl.searchParams.set("uploadId", uploadId);
1257
+ const sourceToken = options.sourceAuthToken === void 0 ? void 0 : this.issuedTokens.get(options.sourceAuthToken);
1258
+ const token = {
1259
+ kind: options.kind,
1260
+ fileName: options.kind === "part" ? options.fileName : null,
1261
+ uploadUrl: uploadUrl.toString(),
1262
+ namePrefix: this.strictAuth ? sourceToken?.namePrefix ?? null : null,
1263
+ applicationKeyId: sourceToken?.applicationKeyId ?? null,
1264
+ expiresAt: now + this.authTokenTtlMs,
1265
+ cleanupAt: now + this.authTokenTtlMs,
1266
+ invalidated: false
1267
+ };
1268
+ const authorizationToken = await this.encodeUploadAuthorizationToken(token);
1269
+ this.uploadTokens.set(authorizationToken, token);
1270
+ return {
1271
+ uploadUrl: uploadUrl.toString(),
1272
+ authorizationToken
1273
+ };
1274
+ }
1275
+ async validateUploadAuthorization(kind, uploadUrl, authToken, fileName) {
1276
+ if (authToken === void 0 || authToken === "") return this.error(401, "bad_auth_token", "missing upload Authorization header");
1277
+ const token = await this.uploadTokenState(authToken);
1278
+ if (token === null) {
1279
+ this.pruneExpiredUploadTokens();
1280
+ return this.error(401, "bad_auth_token", "unknown upload authorization token");
1281
+ }
1282
+ const now = this.now();
1283
+ if (now >= token.expiresAt) {
1284
+ if (now >= token.cleanupAt) this.uploadTokens.delete(authToken);
1285
+ else this.uploadTokens.set(authToken, token);
1286
+ this.pruneExpiredUploadTokens(now);
1287
+ return this.error(401, "expired_auth_token", "upload authorization token has expired; get a new upload URL");
1288
+ }
1289
+ if (token.invalidated) {
1290
+ this.uploadTokens.set(authToken, token);
1291
+ this.pruneExpiredUploadTokens(now);
1292
+ return this.error(401, "bad_auth_token", "upload authorization token has been invalidated");
1293
+ }
1294
+ if (token.kind !== kind) {
1295
+ this.pruneExpiredUploadTokens(now);
1296
+ return this.error(401, "bad_auth_token", "upload authorization token type mismatch");
1297
+ }
1298
+ this.pruneExpiredUploadTokens(now);
1299
+ if (!this.uploadUrlMatches(token, uploadUrl)) return this.error(401, "bad_auth_token", "upload authorization token is not valid for this upload URL");
1300
+ const scopedName = kind === "file" ? fileName : token.fileName ?? void 0;
1301
+ if (token.namePrefix !== null && scopedName !== void 0) {
1302
+ if (!scopedName.startsWith(token.namePrefix)) return this.error(403, "unauthorized", `application key is scoped to prefix "${token.namePrefix}"; "${scopedName}" is outside scope`);
1303
+ }
1304
+ return null;
1305
+ }
1306
+ uploadUrlMatches(token, uploadUrl) {
1307
+ let expected;
1308
+ let actual;
1309
+ try {
1310
+ expected = new URL(token.uploadUrl);
1311
+ actual = new URL(uploadUrl);
1312
+ } catch {
1313
+ return false;
1314
+ }
1315
+ if (actual.origin !== expected.origin || actual.pathname !== expected.pathname) return false;
1316
+ const scopeParam = token.kind === "file" ? "bucketId" : "fileId";
1317
+ return actual.searchParams.get(scopeParam) === expected.searchParams.get(scopeParam) && actual.searchParams.get("uploadId") === expected.searchParams.get("uploadId");
1318
+ }
1319
+ allowedBuckets(bucketIds) {
1320
+ if (bucketIds === void 0 || bucketIds === null) return null;
1321
+ return bucketIds.map((id) => ({
1322
+ id: require_ids.bucketId(id),
1323
+ name: this.buckets.get(id)?.info.bucketName ?? null
1324
+ }));
1325
+ }
1326
+ /**
1327
+ * Resolve the application key matching the `Authorization` header on
1328
+ * an `authorize_account` request. The header is in the form
1329
+ * `Basic base64(applicationKeyId:applicationKey)`.
1330
+ *
1331
+ * The simulator has two implicit full-access storage credentials:
1332
+ * the documented `test-key-id:test-key` pair used by SDK tests and
1333
+ * `master-key-id:master-key`. In default permissive mode, any other
1334
+ * well-formed Basic credential whose applicationKeyId is not a stored
1335
+ * key also receives that implicit master grant for backward
1336
+ * compatibility. A credential whose applicationKeyId matches a stored
1337
+ * key must use the stored secret and must not be expired.
1338
+ *
1339
+ * @param authzHeader - Raw HTTP `Authorization` header value.
1340
+ *
1341
+ * @returns The authorizing key's grant scope or the rejection reason.
1342
+ */
1343
+ findAuthorizationGrant(authzHeader) {
1344
+ const credentials = parseBasicAuthorizationHeader(authzHeader);
1345
+ if (credentials === null) return { kind: "invalid" };
1346
+ const stored = this.keys.get(credentials.applicationKeyId);
1347
+ if (stored !== void 0) {
1348
+ if (!timingSafeStringEqual(stored.applicationKey, credentials.applicationKey)) return { kind: "invalid" };
1349
+ if (this.isStoredKeyExpired(stored)) return { kind: "expired" };
1350
+ return {
1351
+ kind: "ok",
1352
+ grant: {
1353
+ capabilities: stored.capabilities,
1354
+ bucketIds: stored.bucketIds,
1355
+ namePrefix: stored.namePrefix,
1356
+ applicationKeyId: credentials.applicationKeyId,
1357
+ accountId: stored.accountId,
1358
+ expirationTimestamp: stored.expirationTimestamp
1359
+ }
1360
+ };
1361
+ }
1362
+ if (isSimulatorApplicationKeyId(credentials.applicationKeyId)) return { kind: "invalid" };
1363
+ if (isImplicitStorageMasterCredential(credentials) || !this.strictAuth) return {
1364
+ kind: "ok",
1365
+ grant: {
1366
+ capabilities: SIMULATOR_MASTER_CAPABILITIES,
1367
+ bucketIds: null,
1368
+ namePrefix: null,
1369
+ applicationKeyId: null,
1370
+ accountId: this.accountId,
1371
+ expirationTimestamp: null
1372
+ }
1373
+ };
1374
+ return { kind: "invalid" };
1375
+ }
1376
+ canAuthorizePartner(authzHeader) {
1377
+ const credentials = parseBasicAuthorizationHeader(authzHeader);
1378
+ if (credentials === null) return false;
1379
+ if (isImplicitPartnerMasterCredential(credentials)) return true;
1380
+ const stored = this.keys.get(credentials.applicationKeyId);
1381
+ return stored !== void 0 && stored.accountId === this.accountId && !this.isStoredKeyExpired(stored) && timingSafeStringEqual(stored.applicationKey, credentials.applicationKey);
1382
+ }
1383
+ /**
1384
+ * Creates an {@link HttpTransport} that routes requests to this simulator.
1385
+ * @returns A transport instance backed by this in-memory simulator.
1386
+ */
1387
+ transport() {
1388
+ return new SimulatorTransport(this);
1389
+ }
1390
+ /**
1391
+ * Register a synthetic failure to inject on requests whose URL contains
1392
+ * `spec.on`. Use this to exercise retry / backoff / error-handling
1393
+ * paths in tests without hand-rolling a wrapping `HttpTransport`. The
1394
+ * fault is consumed in registration order on each matched request;
1395
+ * once its `count` budget is exhausted it auto-retires.
1396
+ *
1397
+ * Faults are checked BEFORE the simulator's real handlers run, so a
1398
+ * matched request never touches in-memory state — failed uploads
1399
+ * don't create partial parts, failed deletes don't remove anything.
1400
+ *
1401
+ * @param spec - The failure to inject. See {@link FaultSpec}.
1402
+ *
1403
+ * @returns A handle whose `clear()` method removes this specific
1404
+ * fault registration (other faults remain in effect).
1405
+ *
1406
+ * @example
1407
+ * ```ts
1408
+ * // Fail the next 2 b2_upload_part calls with 503, then succeed.
1409
+ * sim.injectFailure({ on: 'b2_upload_part', status: 503, count: 2 })
1410
+ *
1411
+ * // Fail every b2_authorize_account with 401 + Retry-After: 5.
1412
+ * const handle = sim.injectFailure({
1413
+ * on: 'b2_authorize_account',
1414
+ * status: 401,
1415
+ * code: 'expired_auth_token',
1416
+ * retryAfter: 5,
1417
+ * })
1418
+ * // ... later
1419
+ * handle.clear()
1420
+ * ```
1421
+ */
1422
+ injectFailure(spec) {
1423
+ const id = this.nextFaultId++;
1424
+ const fault = {
1425
+ id,
1426
+ spec,
1427
+ remainingSkip: spec.skip ?? 0,
1428
+ remainingCount: spec.count ?? Number.POSITIVE_INFINITY
1429
+ };
1430
+ this.faults.push(fault);
1431
+ return { clear: () => {
1432
+ const idx = this.faults.findIndex((f) => f.id === id);
1433
+ if (idx !== -1) this.faults.splice(idx, 1);
1434
+ } };
1435
+ }
1436
+ /**
1437
+ * Remove every registered fault. Equivalent to calling `.clear()` on
1438
+ * every handle returned by {@link injectFailure}, plus a defensive
1439
+ * reset for tests that re-use a simulator across cases.
1440
+ */
1441
+ clearFaults() {
1442
+ this.faults.length = 0;
1443
+ }
1444
+ /**
1445
+ * Internal: checks the registered faults for a match on the given URL
1446
+ * and consumes one if it should fire. Called from
1447
+ * {@link SimulatorTransport.send} before any real handler runs.
1448
+ *
1449
+ * @param url - The request URL to match against each fault's `on`
1450
+ * substring.
1451
+ *
1452
+ * @returns The fault to apply, or `null` if no fault should fire.
1453
+ *
1454
+ * @internal
1455
+ */
1456
+ consumeMatchingFault(url) {
1457
+ for (let i = 0; i < this.faults.length; i++) {
1458
+ const fault = this.faults[i];
1459
+ if (!url.includes(fault.spec.on)) continue;
1460
+ if (fault.remainingSkip > 0) {
1461
+ fault.remainingSkip -= 1;
1462
+ continue;
1463
+ }
1464
+ if (fault.remainingCount <= 0) continue;
1465
+ fault.remainingCount -= 1;
1466
+ if (fault.remainingCount <= 0) this.faults.splice(i, 1);
1467
+ return fault.spec;
1468
+ }
1469
+ return null;
1470
+ }
1471
+ /**
1472
+ * Dispatches a JSON API request to the appropriate handler.
1473
+ * @param method - The HTTP method.
1474
+ * @param origin - The request URL origin used for simulator-issued endpoints.
1475
+ * @param path - The request URL path containing the B2 endpoint name.
1476
+ * @param headers - The HTTP request headers; consulted by the
1477
+ * strict-auth gate to look up the issued auth token.
1478
+ * @param body - The parsed JSON request body.
1479
+ *
1480
+ * @returns An object with HTTP status and JSON response body.
1481
+ */
1482
+ async handleRequest(method, origin, path, headers, body) {
1483
+ const { endpoint, version } = apiPathParts(path);
1484
+ if (!jsonEndpointAllowsMethod(method, endpoint)) return this.error(405, "method_not_allowed", `${endpoint} does not support ${method.toUpperCase()}`);
1485
+ if (this.strictAuth && !this.partner.isEndpoint(endpoint)) {
1486
+ const authError = this.authorizeRequest(headers["authorization"], endpoint, this.requestScope(endpoint, body));
1487
+ if (authError !== null) return authError;
1488
+ }
1489
+ switch (endpoint) {
1490
+ case "b2_authorize_account":
1491
+ if (version === "v3" && this.partner.isAuthorizeEnabled()) return this.partner.authorize(headers["authorization"], origin);
1492
+ return this.authorize(headers["authorization"], origin);
1493
+ case "b2_create_group_member": return this.partner.createGroupMember(body, headers["authorization"]);
1494
+ case "b2_eject_group_member": return this.partner.ejectGroupMember(body, headers["authorization"]);
1495
+ case "b2_list_groups": return this.partner.listGroups(body, headers["authorization"]);
1496
+ case "b2_list_group_members": return this.partner.listGroupMembers(body, headers["authorization"]);
1497
+ case "b2_reserve_trial_create_account": return this.partner.reserveTrialCreateAccount(body, headers["authorization"]);
1498
+ case "bz_list_computers": return this.partner.listComputers(body, headers["authorization"]);
1499
+ case "bz_delete_computer": return this.partner.deleteComputer(body, headers["authorization"]);
1500
+ case "b2_create_bucket": return this.createBucket(body);
1501
+ case "b2_list_buckets": return this.listBuckets(body);
1502
+ case "b2_delete_bucket": return this.deleteBucket(body);
1503
+ case "b2_update_bucket": return this.updateBucket(body);
1504
+ case "b2_get_upload_url": return await this.getUploadUrl(body, headers["authorization"]);
1505
+ case "b2_list_file_names": return this.listFileNames(body);
1506
+ case "b2_list_file_versions": return this.listFileVersions(body);
1507
+ case "b2_get_file_info": return this.getFileInfo(body);
1508
+ case "b2_hide_file": return this.hideFile(body);
1509
+ case "b2_delete_file_version": return this.deleteFileVersion(body, headers["authorization"]);
1510
+ case "b2_copy_file": return await this.copyFile(body);
1511
+ case "b2_start_large_file": return await this.startLargeFile(body);
1512
+ case "b2_get_upload_part_url": return await this.getUploadPartUrl(body, headers["authorization"]);
1513
+ case "b2_finish_large_file": return this.finishLargeFile(body);
1514
+ case "b2_cancel_large_file": return this.cancelLargeFile(body);
1515
+ case "b2_list_unfinished_large_files": return this.listUnfinishedLargeFiles(body);
1516
+ case "b2_list_parts": return this.listParts(body);
1517
+ case "b2_copy_part": return await this.copyPart(body);
1518
+ case "b2_get_download_authorization": return this.getDownloadAuthorization(body);
1519
+ case "b2_create_key": return this.createKey(body, version, headers["authorization"]);
1520
+ case "b2_list_keys": return this.listKeys(body);
1521
+ case "b2_delete_key": return this.deleteKey(body);
1522
+ case "b2_update_file_retention": return this.updateFileRetention(body, headers["authorization"]);
1523
+ case "b2_update_file_legal_hold": return this.updateFileLegalHold(body);
1524
+ case "b2_get_bucket_notification_rules": return this.getBucketNotificationRules(body);
1525
+ case "b2_set_bucket_notification_rules": return this.setBucketNotificationRules(body);
1526
+ default: return {
1527
+ status: 400,
1528
+ body: {
1529
+ status: 400,
1530
+ code: "bad_request",
1531
+ message: `Unknown endpoint: ${endpoint}`
1532
+ }
1533
+ };
1534
+ }
1535
+ }
1536
+ /**
1537
+ * Handles file and part upload requests (`b2_upload_file`, `b2_upload_part`).
1538
+ * Dispatches to the appropriate internal handler based on the URL.
1539
+ * @param url - The upload endpoint URL used to determine the upload type.
1540
+ * @param headers - The HTTP headers containing file metadata and authorization.
1541
+ * @param data - The raw file or part content as bytes.
1542
+ *
1543
+ * @returns A promise resolving to an object with HTTP status and JSON response body.
1544
+ */
1545
+ async handleUpload(url, headers, data) {
1546
+ const endpoint = new URL(url).pathname.split("/").pop() ?? "";
1547
+ const kind = endpoint === "b2_upload_file" ? "file" : endpoint === "b2_upload_part" ? "part" : null;
1548
+ if (kind === null) return this.error(400, "bad_request", `Unknown upload endpoint: ${endpoint}`);
1549
+ const fileName = kind === "part" || headers["x-bz-file-name"] === void 0 ? void 0 : decodeHeaderValue(headers["x-bz-file-name"]);
1550
+ const authError = await this.validateUploadAuthorization(kind, url, headers["authorization"], fileName);
1551
+ if (authError !== null) return authError;
1552
+ const contentLengthError = this.validateContentLength(headers, data.byteLength);
1553
+ if (contentLengthError !== null) return contentLengthError;
1554
+ if (kind === "part") return await this.handleUploadPart(url, headers, data);
1555
+ return await this.handleUploadFile(url, headers, data);
1556
+ }
1557
+ validateContentLength(headers, actualLength) {
1558
+ const parsed = parseContentLengthHeader(headers);
1559
+ if (parsed.kind === "absent") return null;
1560
+ if (parsed.kind === "error") return this.error(400, "bad_request", parsed.message);
1561
+ if (parsed.expectedLength !== actualLength) return this.error(400, "bad_request", contentLengthMismatchMessage(parsed.expectedLength, actualLength));
1562
+ return null;
1563
+ }
1564
+ parseCustomUploadTimestamp(value) {
1565
+ if (value === void 0 || value === null) return { timestamp: null };
1566
+ if (!this.customUploadTimestampsEnabled) return this.error(400, "custom_timestamp_not_allowed", "Custom upload timestamps are not enabled for this account.");
1567
+ const timestamp = typeof value === "string" && /^\d+$/.test(value) ? Number(value) : NaN;
1568
+ if (!Number.isSafeInteger(timestamp) || timestamp < 0 || timestamp > this.now()) return this.error(400, "custom_timestamp_invalid", "The request has an invalid custom upload timestamp.");
1569
+ return { timestamp };
1570
+ }
1571
+ /**
1572
+ * Handles file download requests (`b2_download_file_by_id`, `/file/` by name).
1573
+ * Returns the file data along with B2 response headers.
1574
+ * @param path - The request URL path identifying the file to download.
1575
+ * @param headers - The HTTP request headers for range or authorization.
1576
+ * @param method - The HTTP method; `'HEAD'` suppresses the response body.
1577
+ *
1578
+ * @returns The download response containing file data and B2 headers.
1579
+ */
1580
+ handleDownload(path, headers, method = "GET") {
1581
+ if (path.includes("b2_download_file_by_id")) {
1582
+ const url = new URL(`http://localhost${path}`);
1583
+ if (this.strictAuth) {
1584
+ const authError = this.authorizeDownloadRequest(this.downloadAuthorizationFromRequest(headers, url, { allowQueryAuthorization: false }), "b2_download_file_by_id", this.fileIdScope(url.searchParams.get("fileId") ?? void 0) ?? {
1585
+ bucketIds: [],
1586
+ requiresBucketScope: true
1587
+ }, url);
1588
+ if (authError !== null) return this.errorAsDownload(authError);
1589
+ }
1590
+ const fileId = url.searchParams.get("fileId") ?? "";
1591
+ return this.finalizeDownload(this.downloadById(fileId, headers, requestHeaderValue(headers, "range")), url, method);
1592
+ }
1593
+ const fileMatch = path.match(/^([^?]+)/)?.[1]?.match(/\/file\/([^/]+)\/(.+)/);
1594
+ if (fileMatch) {
1595
+ const bucketName = decodeURIComponent(fileMatch[1] ?? "");
1596
+ const fileName = decodeURIComponent(fileMatch[2] ?? "");
1597
+ const url = new URL(`http://localhost${path}`);
1598
+ if (this.strictAuth) {
1599
+ const bucket = [...this.buckets.values()].find((b) => b.info.bucketName === bucketName);
1600
+ const authError = this.authorizeDownloadRequest(this.downloadAuthorizationFromRequest(headers, url, { allowQueryAuthorization: true }), "b2_download_file_by_name", {
1601
+ bucketIds: bucket === void 0 ? [] : [bucket.info.bucketId],
1602
+ fileNames: [fileName],
1603
+ requiresBucketScope: true
1604
+ }, url);
1605
+ if (authError !== null) return this.errorAsDownload(authError);
1606
+ }
1607
+ return this.finalizeDownload(this.downloadByName(bucketName, fileName, headers, requestHeaderValue(headers, "range")), url, method);
1608
+ }
1609
+ return {
1610
+ status: 404,
1611
+ headers: {},
1612
+ data: null
1613
+ };
1614
+ }
1615
+ /**
1616
+ * Convert a synthetic JSON error body into a `SimulatorDownloadResponse`
1617
+ * shape so the strict-auth gate on download paths can surface 401/403s
1618
+ * through the same transport plumbing as a regular failed download.
1619
+ *
1620
+ * @param json - The JSON error from {@link authorizeRequest}.
1621
+ *
1622
+ * @returns A download-shaped response with the error body bytes inline.
1623
+ */
1624
+ errorAsDownload(json) {
1625
+ return {
1626
+ status: json.status,
1627
+ headers: { "Content-Type": "application/json" },
1628
+ data: require_text_codec.utf8Encoder.encode(JSON.stringify(json.body))
1629
+ };
1630
+ }
1631
+ /**
1632
+ * Applies HEAD-method body suppression and `b2Content*` response-header
1633
+ * overrides parsed from the download URL's query string. Mirrors what the
1634
+ * real B2 service does: any `b2Content*` query parameter is echoed back as
1635
+ * the corresponding response header.
1636
+ *
1637
+ * @param response - The download response produced by {@link downloadById} or {@link downloadByName}.
1638
+ * @param url - The parsed download URL (used to read `b2Content*` query params).
1639
+ * @param method - The HTTP method of the originating request.
1640
+ *
1641
+ * @returns The response with overrides applied.
1642
+ */
1643
+ finalizeDownload(response, url, method) {
1644
+ const newHeaders = { ...response.headers };
1645
+ for (const [param, header] of Object.entries(DOWNLOAD_RESPONSE_OVERRIDE_HEADERS)) {
1646
+ const value = url.searchParams.get(param);
1647
+ if (value !== null) newHeaders[header] = value;
1648
+ }
1649
+ const data = method === "HEAD" ? null : response.data;
1650
+ return {
1651
+ status: response.status,
1652
+ headers: newHeaders,
1653
+ data
1654
+ };
1655
+ }
1656
+ async handleUploadFile(url, headers, data) {
1657
+ const bucketId = new URL(url).searchParams.get("bucketId");
1658
+ if (!bucketId) return this.error(400, "bad_request", "Missing bucketId");
1659
+ const bucket = this.buckets.get(bucketId);
1660
+ if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
1661
+ const fileName = decodeHeaderValue(headers["x-bz-file-name"] ?? "");
1662
+ const contentType = headers["content-type"] ?? "application/octet-stream";
1663
+ const fileNameError = require_validation.validateFileName(fileName);
1664
+ if (fileNameError) return this.error(400, fileNameError.code, fileNameError.message);
1665
+ const fileInfo = parseFileInfoHeaders(headers);
1666
+ const fileInfoError = require_validation.validateFileInfo(fileInfo);
1667
+ if (fileInfoError) return this.error(400, fileInfoError.code, fileInfoError.message);
1668
+ const resolved = await this.resolveUploadSha1(headers["x-bz-content-sha1"], data);
1669
+ if ("status" in resolved) return resolved;
1670
+ const { sha1: contentSha1, data: storedData } = resolved;
1671
+ const serverSideEncryption = await uploadServerSideEncryption(headers, bucket.info.defaultServerSideEncryption);
1672
+ if ("status" in serverSideEncryption) return serverSideEncryption;
1673
+ const customUploadTimestamp = this.parseCustomUploadTimestamp(requestHeaderValue(headers, "x-bz-custom-upload-timestamp"));
1674
+ if ("status" in customUploadTimestamp) return customUploadTimestamp;
1675
+ const fileVersion = this.makeFileVersion({
1676
+ bucketId,
1677
+ fileName,
1678
+ contentType,
1679
+ contentLength: storedData.byteLength,
1680
+ contentSha1,
1681
+ fileInfo,
1682
+ action: require_file.FileAction.Upload,
1683
+ serverSideEncryption,
1684
+ ...this.newReplicationStatusField(bucketId, fileName),
1685
+ ...customUploadTimestamp.timestamp !== null ? { uploadTimestamp: customUploadTimestamp.timestamp } : {}
1686
+ });
1687
+ const stored = {
1688
+ fileVersion,
1689
+ data: storedData,
1690
+ serverSideEncryption
1691
+ };
1692
+ const existing = bucket.files.get(fileName);
1693
+ if (existing) existing.push(stored);
1694
+ else bucket.files.set(fileName, [stored]);
1695
+ this.firePostUploadHooks(fileVersion, bucketId, "b2:ObjectCreated:Upload");
1696
+ return {
1697
+ status: 200,
1698
+ body: fileVersion
1699
+ };
1700
+ }
1701
+ /**
1702
+ * Resolve the `X-Bz-Content-Sha1` header into the SHA-1 to store, verifying
1703
+ * it against the uploaded bytes where B2 would. Returns the SHA-1 string to
1704
+ * persist, or a `400 bad_request` response when a verifiable hash does not
1705
+ * match the data received.
1706
+ *
1707
+ * @param header - The raw `X-Bz-Content-Sha1` header value, if any.
1708
+ * @param data - The uploaded bytes.
1709
+ *
1710
+ * @returns The SHA-1 string to store, or an error response on mismatch.
1711
+ */
1712
+ async resolveUploadSha1(header, data) {
1713
+ const value = header ?? "none";
1714
+ if (value === "none" || value === "do_not_verify") return {
1715
+ sha1: "none",
1716
+ data
1717
+ };
1718
+ if (value.startsWith("unverified:")) return {
1719
+ sha1: value.slice(11).toLowerCase(),
1720
+ data
1721
+ };
1722
+ if (value === "hex_digits_at_end") {
1723
+ if (data.byteLength < 40) return this.error(400, "bad_request", "Sha1 did not match data received");
1724
+ const body = data.subarray(0, data.byteLength - 40);
1725
+ const trailer = require_text_codec.utf8Decoder.decode(data.subarray(data.byteLength - 40)).toLowerCase();
1726
+ const actual = await require_hash.sha1Hex(body);
1727
+ if (actual !== trailer) return this.error(400, "bad_request", "Sha1 did not match data received");
1728
+ return {
1729
+ sha1: actual,
1730
+ data: body
1731
+ };
1732
+ }
1733
+ const expected = value.toLowerCase();
1734
+ if (await require_hash.sha1Hex(data) !== expected) return this.error(400, "bad_request", "Sha1 did not match data received");
1735
+ return {
1736
+ sha1: expected,
1737
+ data
1738
+ };
1739
+ }
1740
+ async validateUploadPartEncryption(large, headers) {
1741
+ if (large.serverSideEncryption.mode !== require_encryption.EncryptionMode.SseC) {
1742
+ if (!hasCustomerEncryptionHeaders(headers)) return null;
1743
+ return this.error(400, "bad_request", "SSE-C upload part headers require an SSE-C large file");
1744
+ }
1745
+ const supplied = await storedServerSideEncryption({
1746
+ mode: require_encryption.EncryptionMode.SseC,
1747
+ algorithm: headers["x-bz-server-side-encryption-customer-algorithm"],
1748
+ customerKey: headers["x-bz-server-side-encryption-customer-key"],
1749
+ customerKeyMd5: headers["x-bz-server-side-encryption-customer-key-md5"]
1750
+ });
1751
+ if ("status" in supplied) return supplied;
1752
+ if (!sameStoredServerSideEncryption(large.serverSideEncryption, supplied)) return this.error(400, "bad_request", "SSE-C upload parts require matching customer encryption headers");
1753
+ return null;
1754
+ }
1755
+ async handleUploadPart(url, headers, data) {
1756
+ const fileId = new URL(url).searchParams.get("fileId");
1757
+ if (!fileId) return this.error(400, "bad_request", "Missing fileId");
1758
+ const large = this.largeFiles.get(fileId);
1759
+ if (!large) return this.error(400, "bad_request", "Large file not found");
1760
+ const partNumber = this.parsePartNumberHeader(requestHeaderValue(headers, "x-bz-part-number"));
1761
+ if (typeof partNumber !== "number") return partNumber;
1762
+ const encryptionError = await this.validateUploadPartEncryption(large, headers);
1763
+ if (encryptionError !== null) return encryptionError;
1764
+ const resolved = await this.resolveUploadSha1(headers["x-bz-content-sha1"], data);
1765
+ if ("status" in resolved) return resolved;
1766
+ const { sha1, data: partData } = resolved;
1767
+ const uploadTimestamp = this.monotonicTimestamp();
1768
+ large.parts.set(partNumber, {
1769
+ data: partData,
1770
+ sha1,
1771
+ contentMd5: null,
1772
+ uploadTimestamp
1773
+ });
1774
+ return {
1775
+ status: 200,
1776
+ body: {
1777
+ fileId: large.fileId,
1778
+ partNumber,
1779
+ contentLength: partData.byteLength,
1780
+ contentSha1: sha1,
1781
+ contentMd5: null,
1782
+ serverSideEncryption: publicServerSideEncryption(large.serverSideEncryption),
1783
+ uploadTimestamp
1784
+ }
1785
+ };
1786
+ }
1787
+ parsePartNumberHeader(header) {
1788
+ if (header === void 0) return this.error(400, "bad_request", "X-Bz-Part-Number header is required");
1789
+ if (!/^\d+$/.test(header)) return this.error(400, "bad_request", `X-Bz-Part-Number must be an integer between ${B2_MIN_PART_NUMBER} and ${B2_MAX_PART_NUMBER}; received ${header}`);
1790
+ const partNumber = Number(header);
1791
+ return this.validatePartNumber(partNumber) ?? partNumber;
1792
+ }
1793
+ validatePartNumber(partNumber) {
1794
+ if (Number.isInteger(partNumber) && partNumber >= B2_MIN_PART_NUMBER && partNumber <= B2_MAX_PART_NUMBER) return null;
1795
+ return this.error(400, "bad_request", `partNumber must be an integer between ${B2_MIN_PART_NUMBER} and ${B2_MAX_PART_NUMBER}; received ${String(partNumber)}`);
1796
+ }
1797
+ downloadById(fileId, headers, range) {
1798
+ const found = this.findFile(fileId);
1799
+ if (found === null) return {
1800
+ status: 404,
1801
+ headers: {},
1802
+ data: null
1803
+ };
1804
+ return this.serveFile(found.stored, headers, range);
1805
+ }
1806
+ downloadByName(bucketName, fileName, headers, range) {
1807
+ for (const bucket of this.buckets.values()) {
1808
+ if (bucket.info.bucketName !== bucketName) continue;
1809
+ const versions = bucket.files.get(fileName);
1810
+ if (!versions || versions.length === 0) break;
1811
+ const latest = versions[versions.length - 1];
1812
+ if (!latest || latest.fileVersion.action === require_file.FileAction.Hide) return {
1813
+ status: 404,
1814
+ headers: {},
1815
+ data: null
1816
+ };
1817
+ return this.serveFile(latest, headers, range);
1818
+ }
1819
+ return {
1820
+ status: 404,
1821
+ headers: {},
1822
+ data: null
1823
+ };
1824
+ }
1825
+ validateDownloadEncryption(stored, headers) {
1826
+ const encryption = stored.serverSideEncryption;
1827
+ if (encryption.mode !== require_encryption.EncryptionMode.SseC) return null;
1828
+ const algorithm = headers["x-bz-server-side-encryption-customer-algorithm"];
1829
+ const customerKey = headers["x-bz-server-side-encryption-customer-key"];
1830
+ const customerKeyMd5 = headers["x-bz-server-side-encryption-customer-key-md5"];
1831
+ const customerKeyBytes = customerKey === void 0 ? null : base64ToBytes(customerKey, 32);
1832
+ const normalizedCustomerKeyMd5 = customerKeyMd5 === void 0 ? null : normalizeSizedBase64(customerKeyMd5, 16);
1833
+ if (algorithm !== encryption.algorithm || customerKeyBytes === null || normalizedCustomerKeyMd5 === null || require_md5.md5Base64Sync(customerKeyBytes) !== normalizedCustomerKeyMd5) return this.errorAsDownload(this.error(400, "bad_request", "SSE-C downloads require matching customer encryption headers"));
1834
+ if (normalizedCustomerKeyMd5 !== encryption.customerKeyMd5 || customerKeyDigest(customerKeyBytes) !== encryption.customerKeyDigest) return this.errorAsDownload(this.error(403, "access_denied", "SSE-C customer encryption key does not match the stored file"));
1835
+ return null;
1836
+ }
1837
+ async validateSourceServerSideEncryption(stored, encryption) {
1838
+ const expected = stored.serverSideEncryption;
1839
+ if (expected.mode !== require_encryption.EncryptionMode.SseC) return null;
1840
+ if (encryption?.mode !== require_encryption.EncryptionMode.SseC) return this.error(400, "bad_request", "SSE-C source copies require customer encryption");
1841
+ const supplied = await storedServerSideEncryption(encryption);
1842
+ if ("status" in supplied) return supplied;
1843
+ if (!sameStoredServerSideEncryption(expected, supplied)) return this.error(400, "bad_request", "SSE-C source customer encryption does not match");
1844
+ return null;
1845
+ }
1846
+ async resolveCopyDestinationEncryption(destinationBucket, requested) {
1847
+ if (requested !== void 0) return await storedServerSideEncryption(requested);
1848
+ return await storedServerSideEncryption(destinationBucket.info.defaultServerSideEncryption);
1849
+ }
1850
+ async validateCopyPartDestinationEncryption(large, encryption) {
1851
+ if (encryption === void 0) return large.serverSideEncryption.mode === require_encryption.EncryptionMode.SseC ? this.error(400, "bad_request", "SSE-C destination copies require customer encryption") : null;
1852
+ const supplied = await storedServerSideEncryption(encryption);
1853
+ if ("status" in supplied) return supplied;
1854
+ if (!sameStoredServerSideEncryption(large.serverSideEncryption, supplied)) return this.error(400, "bad_request", "Destination server-side encryption does not match");
1855
+ return null;
1856
+ }
1857
+ serveFile(stored, requestHeaders, range) {
1858
+ const encryptionError = this.validateDownloadEncryption(stored, requestHeaders);
1859
+ if (encryptionError !== null) return encryptionError;
1860
+ const fullData = stored.data;
1861
+ let data = fullData;
1862
+ let status = 200;
1863
+ let contentRange = null;
1864
+ if (range) {
1865
+ const parsed = parseRangeHeader(range, fullData.byteLength);
1866
+ if (parsed.kind === "ok") {
1867
+ data = fullData.subarray(parsed.start, parsed.end + 1);
1868
+ status = 206;
1869
+ contentRange = `bytes ${parsed.start}-${parsed.end}/${fullData.byteLength}`;
1870
+ } else if (parsed.kind === "unsatisfiable") return {
1871
+ status: 416,
1872
+ headers: {
1873
+ "Content-Type": stored.fileVersion.contentType,
1874
+ "Content-Range": `bytes */${fullData.byteLength}`
1875
+ },
1876
+ data: /* @__PURE__ */ new Uint8Array(0)
1877
+ };
1878
+ }
1879
+ const fv = stored.fileVersion;
1880
+ const headers = {
1881
+ "Content-Type": fv.contentType,
1882
+ "Content-Length": String(data.byteLength),
1883
+ "X-Bz-File-Id": fv.fileId,
1884
+ "X-Bz-File-Name": require_encoding.encodeFileName(fv.fileName),
1885
+ "X-Bz-Content-Sha1": fv.contentSha1 ?? "none",
1886
+ "X-Bz-Upload-Timestamp": String(fv.uploadTimestamp)
1887
+ };
1888
+ for (const [key, value] of Object.entries(fv.fileInfo)) headers[`X-Bz-Info-${require_encoding.encodeFileName(key)}`] = require_encoding.encodeFileName(value);
1889
+ if (!("src_last_modified_millis" in fv.fileInfo)) headers["X-Bz-Info-src_last_modified_millis"] = String(fv.uploadTimestamp);
1890
+ const unauthorizedToRead = [];
1891
+ this.addDownloadEncryptionHeaders(headers, stored.serverSideEncryption, requestHeaders, unauthorizedToRead);
1892
+ this.addDownloadObjectLockHeaders(headers, fv, requestHeaders, unauthorizedToRead);
1893
+ if (unauthorizedToRead.length > 0) headers[require_download.DownloadHeaderName.ClientUnauthorizedToRead] = unauthorizedToRead.join(",");
1894
+ if (contentRange !== null) headers["Content-Range"] = contentRange;
1895
+ return {
1896
+ status,
1897
+ headers,
1898
+ data
1899
+ };
1900
+ }
1901
+ addDownloadEncryptionHeaders(headers, encryption, requestHeaders, unauthorizedToRead) {
1902
+ if (encryption.mode === require_encryption.EncryptionMode.None) return;
1903
+ if (!this.requestHasCapability(requestHeaderValue(requestHeaders, "authorization"), require_auth.Capability.ReadBucketEncryption)) {
1904
+ if (encryption.mode === require_encryption.EncryptionMode.SseB2) unauthorizedToRead.push(require_download.DownloadClientUnauthorizedToReadMarker.ServerSideEncryption);
1905
+ else unauthorizedToRead.push(require_download.DownloadClientUnauthorizedToReadMarker.ServerSideEncryptionCustomerAlgorithm, require_download.DownloadClientUnauthorizedToReadMarker.ServerSideEncryptionCustomerKeyMd5);
1906
+ return;
1907
+ }
1908
+ if (encryption.mode === require_encryption.EncryptionMode.SseB2) {
1909
+ headers[require_download.DownloadHeaderName.ServerSideEncryption] = encryption.algorithm;
1910
+ return;
1911
+ }
1912
+ headers[require_download.DownloadHeaderName.ServerSideEncryptionCustomerAlgorithm] = encryption.algorithm;
1913
+ headers[require_download.DownloadHeaderName.ServerSideEncryptionCustomerKeyMd5] = encryption.customerKeyMd5;
1914
+ }
1915
+ addDownloadObjectLockHeaders(headers, fileVersion, requestHeaders, unauthorizedToRead) {
1916
+ const authToken = requestHeaderValue(requestHeaders, "authorization");
1917
+ const retention = fileVersion.fileRetention.value;
1918
+ if (retention !== null && retention.mode !== null && retention.retainUntilTimestamp !== null) {
1919
+ if (this.requestHasCapability(authToken, require_auth.Capability.ReadFileRetentions)) {
1920
+ headers[require_download.DownloadHeaderName.FileRetentionMode] = retention.mode;
1921
+ headers[require_download.DownloadHeaderName.FileRetentionRetainUntilTimestamp] = String(retention.retainUntilTimestamp);
1922
+ } else unauthorizedToRead.push(require_download.DownloadClientUnauthorizedToReadMarker.FileRetentionMode, require_download.DownloadClientUnauthorizedToReadMarker.FileRetentionRetainUntilTimestamp);
1923
+ }
1924
+ const legalHold = fileVersion.legalHold.value;
1925
+ if (legalHold === null) return;
1926
+ if (this.requestHasCapability(authToken, require_auth.Capability.ReadFileLegalHolds)) {
1927
+ headers[require_download.DownloadHeaderName.FileLegalHold] = legalHold;
1928
+ return;
1929
+ }
1930
+ unauthorizedToRead.push(require_download.DownloadClientUnauthorizedToReadMarker.FileLegalHold);
1931
+ }
1932
+ authorize(authzHeader, origin = "http://localhost:0") {
1933
+ const resolution = this.findAuthorizationGrant(authzHeader);
1934
+ if (resolution.kind === "invalid") return this.error(401, "unauthorized", "application key is not valid");
1935
+ if (resolution.kind === "expired") return this.error(401, "unauthorized", "application key is expired");
1936
+ const { grant } = resolution;
1937
+ const allowedBuckets = this.allowedBuckets(grant.bucketIds);
1938
+ const legacyBucketId = singleBucketId(grant.bucketIds);
1939
+ const legacyBucketName = legacyBucketId === null ? null : this.buckets.get(legacyBucketId)?.info.bucketName ?? null;
1940
+ const tokenStr = `sim_auth_token_${this.nextId++}`;
1941
+ this.issuedTokens.set(tokenStr, {
1942
+ accountId: grant.accountId,
1943
+ capabilities: grant.capabilities,
1944
+ bucketIds: grant.bucketIds,
1945
+ namePrefix: grant.namePrefix,
1946
+ expiresAt: this.now() + this.authTokenTtlMs,
1947
+ applicationKeyId: grant.applicationKeyId
1948
+ });
1949
+ return {
1950
+ status: 200,
1951
+ body: {
1952
+ accountId: require_ids.accountId(grant.accountId),
1953
+ authorizationToken: tokenStr,
1954
+ apiInfo: { storageApi: {
1955
+ absoluteMinimumPartSize: this.minimumPartSize,
1956
+ apiUrl: origin,
1957
+ bucketId: legacyBucketId === null ? null : require_ids.bucketId(legacyBucketId),
1958
+ bucketName: legacyBucketName,
1959
+ downloadUrl: origin,
1960
+ infoType: "storageApi",
1961
+ namePrefix: grant.namePrefix,
1962
+ recommendedPartSize: this.recommendedPartSize,
1963
+ s3ApiUrl: origin,
1964
+ allowed: {
1965
+ capabilities: cloneCapabilities(grant.capabilities),
1966
+ buckets: allowedBuckets,
1967
+ bucketId: legacyBucketId === null ? null : require_ids.bucketId(legacyBucketId),
1968
+ bucketName: legacyBucketName,
1969
+ namePrefix: grant.namePrefix
1970
+ }
1971
+ } },
1972
+ applicationKeyExpirationTimestamp: grant.expirationTimestamp
1973
+ }
1974
+ };
1975
+ }
1976
+ createBucket(req) {
1977
+ const nameError = require_validation.validateBucketName(req.bucketName);
1978
+ if (nameError) return this.error(400, nameError.code, nameError.message);
1979
+ const objectLockEnabled = nextObjectLockEnabled(false, req.fileLockEnabled);
1980
+ if (typeof objectLockEnabled !== "boolean") return this.error(400, objectLockEnabled.code, objectLockEnabled.message);
1981
+ const configError = validateBucketConfigurationFields(req, { objectLockEnabled });
1982
+ if (configError) return this.error(400, configError.code, configError.message);
1983
+ const replicationKeyError = this.validateReplicationApplicationKeys(req.replicationConfiguration, void 0);
1984
+ if (replicationKeyError !== null) return replicationKeyError;
1985
+ for (const b of this.buckets.values()) if (b.info.bucketName === req.bucketName) return this.error(400, "duplicate_bucket_name", "Bucket name already in use");
1986
+ const bid = require_ids.bucketId(this.genId("b2_bucket"));
1987
+ const defaultRetention = req.defaultRetention ?? {
1988
+ mode: require_bucket.BucketRetentionMode.None,
1989
+ period: null
1990
+ };
1991
+ const info = {
1992
+ accountId: require_ids.accountId(req.accountId),
1993
+ bucketId: bid,
1994
+ bucketName: req.bucketName,
1995
+ bucketType: req.bucketType,
1996
+ bucketInfo: req.bucketInfo ?? {},
1997
+ corsRules: req.corsRules ?? [],
1998
+ defaultServerSideEncryption: req.defaultServerSideEncryption ?? { mode: require_encryption.EncryptionMode.None },
1999
+ fileLockConfiguration: {
2000
+ isClientAuthorizedToRead: true,
2001
+ value: {
2002
+ isFileLockEnabled: objectLockEnabled,
2003
+ defaultRetention
2004
+ }
2005
+ },
2006
+ lifecycleRules: req.lifecycleRules ?? [],
2007
+ options: [],
2008
+ revision: 1,
2009
+ defaultRetention,
2010
+ replicationConfiguration: req.replicationConfiguration === void 0 ? {
2011
+ asReplicationSource: null,
2012
+ asReplicationDestination: null
2013
+ } : normalizeReplicationConfiguration(req.replicationConfiguration)
2014
+ };
2015
+ this.buckets.set(bid, {
2016
+ info,
2017
+ files: /* @__PURE__ */ new Map()
2018
+ });
2019
+ return {
2020
+ status: 200,
2021
+ body: info
2022
+ };
2023
+ }
2024
+ listBuckets(req) {
2025
+ const bucketTypesError = require_validation.validateBucketTypes(req.bucketTypes);
2026
+ if (bucketTypesError) return this.error(400, bucketTypesError.code, bucketTypesError.message);
2027
+ return {
2028
+ status: 200,
2029
+ body: { buckets: [...this.buckets.values()].map((b) => b.info).filter((bucket) => req.bucketId === void 0 || bucket.bucketId === req.bucketId).filter((bucket) => req.bucketName === void 0 || bucket.bucketName === req.bucketName).filter((bucket) => req.bucketTypes === void 0 || req.bucketTypes.includes(bucket.bucketType)) }
2030
+ };
2031
+ }
2032
+ deleteBucket(req) {
2033
+ const bucket = this.buckets.get(req.bucketId);
2034
+ if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
2035
+ if (this.bucketHasContents(bucket)) return this.error(400, "cannot_delete_non_empty_bucket", "Bucket is not empty and cannot be deleted");
2036
+ this.buckets.delete(req.bucketId);
2037
+ return {
2038
+ status: 200,
2039
+ body: bucket.info
2040
+ };
2041
+ }
2042
+ bucketHasContents(bucket) {
2043
+ for (const versions of bucket.files.values()) if (versions.length > 0) return true;
2044
+ for (const large of this.largeFiles.values()) if (large.bucketId === bucket.info.bucketId) return true;
2045
+ return false;
2046
+ }
2047
+ updateBucket(req) {
2048
+ const bucket = this.buckets.get(req["bucketId"]);
2049
+ if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
2050
+ const revisionGuard = req["ifRevisionIs"];
2051
+ if (revisionGuard !== void 0) {
2052
+ if (typeof revisionGuard !== "number" || !Number.isInteger(revisionGuard)) return this.error(400, "bad_request", "ifRevisionIs must be an integer");
2053
+ if (revisionGuard !== bucket.info.revision) return this.error(409, "conflict", "ifRevisionIs test failed");
2054
+ }
2055
+ const objectLockEnabled = nextObjectLockEnabled(bucket.info.fileLockConfiguration.value?.isFileLockEnabled ?? false, req["fileLockEnabled"]);
2056
+ if (typeof objectLockEnabled !== "boolean") return this.error(400, objectLockEnabled.code, objectLockEnabled.message);
2057
+ const configError = validateBucketConfigurationFields({
2058
+ bucketInfo: req["bucketInfo"],
2059
+ corsRules: req["corsRules"],
2060
+ defaultRetention: req["defaultRetention"],
2061
+ lifecycleRules: req["lifecycleRules"],
2062
+ replicationConfiguration: req["replicationConfiguration"]
2063
+ }, { objectLockEnabled });
2064
+ if (configError) return this.error(400, configError.code, configError.message);
2065
+ const replicationKeyError = this.validateReplicationApplicationKeys(req["replicationConfiguration"], req["bucketId"]);
2066
+ if (replicationKeyError !== null) return replicationKeyError;
2067
+ const updated = {
2068
+ ...bucket.info,
2069
+ ...req["bucketType"] !== void 0 ? { bucketType: req["bucketType"] } : {},
2070
+ ...req["bucketInfo"] !== void 0 ? { bucketInfo: req["bucketInfo"] } : {},
2071
+ ...req["lifecycleRules"] !== void 0 ? { lifecycleRules: req["lifecycleRules"] } : {},
2072
+ ...req["corsRules"] !== void 0 ? { corsRules: req["corsRules"] } : {},
2073
+ ...req["replicationConfiguration"] !== void 0 ? { replicationConfiguration: normalizeReplicationConfiguration(req["replicationConfiguration"]) } : {},
2074
+ ...req["defaultRetention"] !== void 0 ? {
2075
+ defaultRetention: req["defaultRetention"],
2076
+ fileLockConfiguration: {
2077
+ isClientAuthorizedToRead: true,
2078
+ value: {
2079
+ isFileLockEnabled: objectLockEnabled,
2080
+ defaultRetention: req["defaultRetention"]
2081
+ }
2082
+ }
2083
+ } : {},
2084
+ ...req["fileLockEnabled"] !== void 0 && req["defaultRetention"] === void 0 ? { fileLockConfiguration: {
2085
+ isClientAuthorizedToRead: true,
2086
+ value: {
2087
+ isFileLockEnabled: objectLockEnabled,
2088
+ defaultRetention: bucket.info.defaultRetention
2089
+ }
2090
+ } } : {},
2091
+ ...req["defaultServerSideEncryption"] !== void 0 ? { defaultServerSideEncryption: req["defaultServerSideEncryption"] } : {},
2092
+ revision: bucket.info.revision + 1
2093
+ };
2094
+ this.buckets.set(req["bucketId"], {
2095
+ info: updated,
2096
+ files: bucket.files
2097
+ });
2098
+ return {
2099
+ status: 200,
2100
+ body: updated
2101
+ };
2102
+ }
2103
+ async getUploadUrl(req, authToken) {
2104
+ if (!this.buckets.get(req.bucketId)) return this.error(400, "bad_bucket_id", "Bucket not found");
2105
+ const uploadAuth = await this.issueUploadAuthorization({
2106
+ kind: "file",
2107
+ sourceAuthToken: authToken,
2108
+ bucketId: req.bucketId
2109
+ });
2110
+ return {
2111
+ status: 200,
2112
+ body: {
2113
+ bucketId: req.bucketId,
2114
+ uploadUrl: uploadAuth.uploadUrl,
2115
+ authorizationToken: uploadAuth.authorizationToken
2116
+ }
2117
+ };
2118
+ }
2119
+ listFileNames(req) {
2120
+ const bucket = this.buckets.get(req.bucketId);
2121
+ if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
2122
+ const countError = require_validation.validateMaxCount(req.maxFileCount, "b2_list_file_names");
2123
+ if (countError) return this.error(400, countError.code, countError.message);
2124
+ const max = req.maxFileCount ?? 1e3;
2125
+ const prefix = req.prefix ?? "";
2126
+ let allFiles = [...bucket.files.entries()].filter(([name]) => name.startsWith(prefix)).map(([_, versions]) => versions[versions.length - 1]).filter((v) => v !== void 0).map((v) => v.fileVersion).sort((a, b) => compareB2FileNames(a.fileName, b.fileName));
2127
+ if (req.startFileName) {
2128
+ const start = req.startFileName;
2129
+ allFiles = allFiles.filter((f) => f.fileName >= start);
2130
+ }
2131
+ return {
2132
+ status: 200,
2133
+ body: {
2134
+ files: allFiles.slice(0, max),
2135
+ nextFileName: allFiles.length > max ? allFiles[max]?.fileName ?? null : null
2136
+ }
2137
+ };
2138
+ }
2139
+ listFileVersions(req) {
2140
+ const bucket = this.buckets.get(req.bucketId);
2141
+ if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
2142
+ const countError = require_validation.validateMaxCount(req.maxFileCount, "b2_list_file_versions");
2143
+ if (countError) return this.error(400, countError.code, countError.message);
2144
+ const max = req.maxFileCount ?? 1e3;
2145
+ const prefix = req.prefix ?? "";
2146
+ const allVersions = [...bucket.files.entries()].filter(([name]) => name.startsWith(prefix)).flatMap(([_, versions]) => versions.map((v) => v.fileVersion)).sort((a, b) => {
2147
+ const nameCmp = compareB2FileNames(a.fileName, b.fileName);
2148
+ if (nameCmp !== 0) return nameCmp;
2149
+ return b.uploadTimestamp - a.uploadTimestamp;
2150
+ });
2151
+ let startIdx = 0;
2152
+ if (req.startFileName !== void 0) {
2153
+ const startName = req.startFileName;
2154
+ const startId = req.startFileId;
2155
+ const nameIdx = allVersions.findIndex((f) => f.fileName >= startName);
2156
+ if (nameIdx === -1) startIdx = allVersions.length;
2157
+ else if (startId !== void 0) {
2158
+ const exactIdx = allVersions.findIndex((f, i) => i >= nameIdx && f.fileId === startId);
2159
+ startIdx = exactIdx !== -1 ? exactIdx : nameIdx;
2160
+ } else startIdx = nameIdx;
2161
+ }
2162
+ const sliced = allVersions.slice(startIdx, startIdx + max);
2163
+ const hasMore = startIdx + max < allVersions.length;
2164
+ return {
2165
+ status: 200,
2166
+ body: {
2167
+ files: sliced,
2168
+ nextFileName: hasMore ? allVersions[startIdx + max]?.fileName ?? null : null,
2169
+ nextFileId: hasMore ? allVersions[startIdx + max]?.fileId ?? null : null
2170
+ }
2171
+ };
2172
+ }
2173
+ getFileInfo(req) {
2174
+ const found = this.findFile(req.fileId);
2175
+ if (found === null) return this.error(404, "file_not_present", "File not found");
2176
+ return {
2177
+ status: 200,
2178
+ body: found.stored.fileVersion
2179
+ };
2180
+ }
2181
+ hideFile(req) {
2182
+ const bucket = this.buckets.get(req.bucketId);
2183
+ if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
2184
+ const nameError = require_validation.validateFileName(req.fileName);
2185
+ if (nameError) return this.error(400, nameError.code, nameError.message);
2186
+ const fileVersion = this.makeFileVersion({
2187
+ bucketId: req.bucketId,
2188
+ fileName: req.fileName,
2189
+ contentType: "application/octet-stream",
2190
+ contentLength: 0,
2191
+ contentSha1: "none",
2192
+ action: require_file.FileAction.Hide
2193
+ });
2194
+ const existing = bucket.files.get(req.fileName);
2195
+ const stored = {
2196
+ fileVersion,
2197
+ data: /* @__PURE__ */ new Uint8Array(0),
2198
+ serverSideEncryption: { mode: require_encryption.EncryptionMode.None }
2199
+ };
2200
+ if (existing) existing.push(stored);
2201
+ else bucket.files.set(req.fileName, [stored]);
2202
+ return {
2203
+ status: 200,
2204
+ body: fileVersion
2205
+ };
2206
+ }
2207
+ deleteFileVersion(req, authToken) {
2208
+ const found = this.findFile(req.fileId);
2209
+ if (found === null || found.stored.fileVersion.fileName !== req.fileName) return this.error(400, "file_not_present", "File version not found");
2210
+ const fv = found.stored.fileVersion;
2211
+ const retention = fv.fileRetention?.value;
2212
+ const legalHold = fv.legalHold?.value;
2213
+ const now = Date.now();
2214
+ if (legalHold === require_lock.LegalHoldValue.On) return this.error(400, "file_lock_legal_hold_protected", "File is on legal hold and cannot be deleted");
2215
+ if (retention?.mode === require_lock.RetentionMode.Compliance && retention.retainUntilTimestamp !== null && retention.retainUntilTimestamp > now) return this.error(400, "file_lock_compliance_protected", `File is under compliance-mode retention and cannot be deleted until ${new Date(retention.retainUntilTimestamp).toISOString()}`);
2216
+ if (retention?.mode === require_lock.RetentionMode.Governance && retention.retainUntilTimestamp !== null && retention.retainUntilTimestamp > now) {
2217
+ const bypassError = this.requireGovernanceBypass(req, authToken, "File is under governance-mode retention; pass bypassGovernance: true to delete");
2218
+ if (bypassError !== null) return bypassError;
2219
+ }
2220
+ found.versions.splice(found.index, 1);
2221
+ if (found.versions.length === 0) found.bucket.files.delete(req.fileName);
2222
+ return {
2223
+ status: 200,
2224
+ body: {
2225
+ fileId: req.fileId,
2226
+ fileName: req.fileName
2227
+ }
2228
+ };
2229
+ }
2230
+ async copyFile(req) {
2231
+ const nameError = require_validation.validateFileName(req.fileName);
2232
+ if (nameError) return this.error(400, nameError.code, nameError.message);
2233
+ const found = this.findFile(req.sourceFileId);
2234
+ if (found === null) return this.error(404, "file_not_present", "Source file not found");
2235
+ const sourceStored = found.stored;
2236
+ const destBucketId = req.destinationBucketId ?? found.bucketId;
2237
+ const destBucket = this.buckets.get(destBucketId);
2238
+ if (!destBucket) return this.error(400, "bad_bucket_id", "Destination bucket not found");
2239
+ const sourceEncryptionError = await this.validateSourceServerSideEncryption(sourceStored, req.sourceServerSideEncryption);
2240
+ if (sourceEncryptionError !== null) return sourceEncryptionError;
2241
+ const destinationEncryption = await this.resolveCopyDestinationEncryption(destBucket, req.destinationServerSideEncryption);
2242
+ if ("status" in destinationEncryption) return destinationEncryption;
2243
+ let data = sourceStored.data;
2244
+ let contentSha1 = sourceStored.fileVersion.contentSha1 ?? "none";
2245
+ if (req.range !== void 0) {
2246
+ const parsed = parseRangeHeader(req.range, sourceStored.data.byteLength);
2247
+ if (parsed.kind === "malformed") return this.error(400, "bad_request", `Malformed copy range: ${req.range}`);
2248
+ if (parsed.kind === "unsatisfiable") return this.error(416, "range_not_satisfiable", `Unsatisfiable copy range: ${req.range}`);
2249
+ data = sourceStored.data.subarray(parsed.start, parsed.end + 1);
2250
+ contentSha1 = await require_hash.sha1Hex(data);
2251
+ }
2252
+ const directive = req.metadataDirective;
2253
+ if (directive !== void 0 && directive !== "COPY" && directive !== "REPLACE") return this.error(400, "bad_request", `Invalid metadataDirective: ${directive}`);
2254
+ let contentType;
2255
+ let fileInfo;
2256
+ if (directive === "REPLACE") {
2257
+ if (req.contentType === void 0) return this.error(400, "bad_request", "contentType is required when metadataDirective is REPLACE");
2258
+ const replaceFileInfo = req.fileInfo ?? {};
2259
+ const fileInfoError = require_validation.validateFileInfo(replaceFileInfo);
2260
+ if (fileInfoError) return this.error(400, fileInfoError.code, fileInfoError.message);
2261
+ contentType = req.contentType;
2262
+ fileInfo = replaceFileInfo;
2263
+ } else {
2264
+ if (req.contentType !== void 0 || req.fileInfo !== void 0) return this.error(400, "bad_request", "contentType and fileInfo may only be set when metadataDirective is REPLACE");
2265
+ contentType = sourceStored.fileVersion.contentType;
2266
+ fileInfo = sourceStored.fileVersion.fileInfo;
2267
+ }
2268
+ const fileVersion = this.makeFileVersion({
2269
+ bucketId: destBucketId,
2270
+ fileName: req.fileName,
2271
+ contentType,
2272
+ contentLength: data.byteLength,
2273
+ contentSha1,
2274
+ fileInfo,
2275
+ action: require_file.FileAction.Copy,
2276
+ serverSideEncryption: destinationEncryption,
2277
+ ...this.newReplicationStatusField(destBucketId, req.fileName)
2278
+ });
2279
+ const copied = {
2280
+ fileVersion,
2281
+ data: new Uint8Array(data),
2282
+ serverSideEncryption: destinationEncryption
2283
+ };
2284
+ const existing = destBucket.files.get(req.fileName);
2285
+ if (existing) existing.push(copied);
2286
+ else destBucket.files.set(req.fileName, [copied]);
2287
+ this.firePostUploadHooks(fileVersion, destBucketId, "b2:ObjectCreated:Copy");
2288
+ return {
2289
+ status: 200,
2290
+ body: fileVersion
2291
+ };
2292
+ }
2293
+ async startLargeFile(req) {
2294
+ const bucket = this.buckets.get(req.bucketId);
2295
+ if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
2296
+ const nameError = require_validation.validateFileName(req.fileName);
2297
+ if (nameError) return this.error(400, nameError.code, nameError.message);
2298
+ if (req.fileInfo !== void 0) {
2299
+ const infoError = require_validation.validateFileInfo(req.fileInfo);
2300
+ if (infoError) return this.error(400, infoError.code, infoError.message);
2301
+ }
2302
+ const customUploadTimestamp = this.parseCustomUploadTimestamp(req.customUploadTimestamp);
2303
+ if ("status" in customUploadTimestamp) return customUploadTimestamp;
2304
+ const fid = this.genId("4_z");
2305
+ const uploadTimestamp = customUploadTimestamp.timestamp ?? this.monotonicTimestamp();
2306
+ const serverSideEncryption = await storedServerSideEncryption(req.serverSideEncryption ?? bucket.info.defaultServerSideEncryption);
2307
+ if ("status" in serverSideEncryption) return serverSideEncryption;
2308
+ const replicationStatus = this.replicationStatusForNewFile(req.bucketId, req.fileName);
2309
+ const large = {
2310
+ fileId: fid,
2311
+ bucketId: req.bucketId,
2312
+ fileName: req.fileName,
2313
+ contentType: req.contentType,
2314
+ fileInfo: req.fileInfo ?? {},
2315
+ fileRetention: req.fileRetention ?? defaultFileRetention(bucket.info.defaultRetention, uploadTimestamp),
2316
+ legalHold: req.legalHold ?? null,
2317
+ ...this.replicationStatusMetadataFor(replicationStatus),
2318
+ serverSideEncryption,
2319
+ uploadTimestamp,
2320
+ parts: /* @__PURE__ */ new Map()
2321
+ };
2322
+ this.largeFiles.set(fid, large);
2323
+ return {
2324
+ status: 200,
2325
+ body: {
2326
+ fileId: fid,
2327
+ fileName: req.fileName,
2328
+ accountId: this.accountId,
2329
+ bucketId: req.bucketId,
2330
+ contentType: req.contentType,
2331
+ fileInfo: large.fileInfo,
2332
+ action: require_file.FileAction.Start,
2333
+ contentLength: 0,
2334
+ contentSha1: "none",
2335
+ contentMd5: null,
2336
+ fileRetention: {
2337
+ isClientAuthorizedToRead: true,
2338
+ value: large.fileRetention
2339
+ },
2340
+ legalHold: {
2341
+ isClientAuthorizedToRead: true,
2342
+ value: large.legalHold
2343
+ },
2344
+ ...this.replicationStatusMetadataFor(large.replicationStatus),
2345
+ serverSideEncryption: publicServerSideEncryption(large.serverSideEncryption),
2346
+ uploadTimestamp: large.uploadTimestamp
2347
+ }
2348
+ };
2349
+ }
2350
+ async getUploadPartUrl(req, authToken) {
2351
+ const large = this.largeFiles.get(req.fileId);
2352
+ if (large === void 0) return this.error(400, "bad_request", "Large file not found");
2353
+ const uploadAuth = await this.issueUploadAuthorization({
2354
+ kind: "part",
2355
+ sourceAuthToken: authToken,
2356
+ fileId: req.fileId,
2357
+ fileName: large.fileName
2358
+ });
2359
+ return {
2360
+ status: 200,
2361
+ body: {
2362
+ fileId: req.fileId,
2363
+ uploadUrl: uploadAuth.uploadUrl,
2364
+ authorizationToken: uploadAuth.authorizationToken
2365
+ }
2366
+ };
2367
+ }
2368
+ finishLargeFile(req) {
2369
+ const large = this.largeFiles.get(req.fileId);
2370
+ if (!large) return this.error(400, "bad_request", "Large file not found");
2371
+ const bucket = this.buckets.get(large.bucketId);
2372
+ if (!bucket) return this.error(400, "bad_bucket_id", "Bucket not found");
2373
+ const sortedParts = [...large.parts.entries()].sort((a, b) => a[0] - b[0]);
2374
+ if (sortedParts.length > B2_MAX_PART_NUMBER) return this.error(400, "bad_request", `multipart upload has ${sortedParts.length} parts; B2 caps at ${B2_MAX_PART_NUMBER}`);
2375
+ for (const [partNumber] of sortedParts) if (!Number.isInteger(partNumber) || partNumber < B2_MIN_PART_NUMBER || partNumber > B2_MAX_PART_NUMBER) return this.error(400, "bad_request", `partNumber ${partNumber} is outside the [${B2_MIN_PART_NUMBER}, ${B2_MAX_PART_NUMBER}] range B2 accepts`);
2376
+ if (req.partSha1Array.length !== sortedParts.length) return this.error(400, "bad_request", `partSha1Array has ${req.partSha1Array.length} entries but ${sortedParts.length} parts were uploaded`);
2377
+ for (const [i, [partNumber, part]] of sortedParts.entries()) if (req.partSha1Array[i]?.toLowerCase() !== part.sha1) return this.error(400, "bad_request", `part ${partNumber} SHA-1 does not match the uploaded part`);
2378
+ for (const [partNumber, part] of sortedParts.slice(0, -1)) if (part.data.byteLength < this.minimumPartSize) return this.error(400, "bad_request", `part ${partNumber} (${part.data.byteLength} bytes) is smaller than the minimum part size of ${this.minimumPartSize}`);
2379
+ let totalSize = 0;
2380
+ for (const [_, part] of sortedParts) totalSize += part.data.byteLength;
2381
+ const combined = new Uint8Array(totalSize);
2382
+ let offset = 0;
2383
+ for (const [_, part] of sortedParts) {
2384
+ combined.set(part.data, offset);
2385
+ offset += part.data.byteLength;
2386
+ }
2387
+ const fileVersion = this.makeFileVersion({
2388
+ bucketId: large.bucketId,
2389
+ fileName: large.fileName,
2390
+ contentType: large.contentType,
2391
+ contentLength: totalSize,
2392
+ contentSha1: "none",
2393
+ fileInfo: large.fileInfo,
2394
+ action: require_file.FileAction.Upload,
2395
+ fileRetention: large.fileRetention,
2396
+ legalHold: large.legalHold,
2397
+ serverSideEncryption: large.serverSideEncryption,
2398
+ uploadTimestamp: large.uploadTimestamp,
2399
+ ...this.replicationStatusMetadataFor(large.replicationStatus)
2400
+ });
2401
+ const stored = {
2402
+ fileVersion,
2403
+ data: combined,
2404
+ serverSideEncryption: large.serverSideEncryption
2405
+ };
2406
+ const existing = bucket.files.get(large.fileName);
2407
+ if (existing) existing.push(stored);
2408
+ else bucket.files.set(large.fileName, [stored]);
2409
+ this.largeFiles.delete(req.fileId);
2410
+ this.firePostUploadHooks(fileVersion, large.bucketId, "b2:ObjectCreated:Upload");
2411
+ return {
2412
+ status: 200,
2413
+ body: fileVersion
2414
+ };
2415
+ }
2416
+ cancelLargeFile(req) {
2417
+ const large = this.largeFiles.get(req.fileId);
2418
+ if (!large) return this.error(400, "bad_request", "Large file not found");
2419
+ this.largeFiles.delete(req.fileId);
2420
+ return {
2421
+ status: 200,
2422
+ body: {
2423
+ fileId: large.fileId,
2424
+ accountId: this.accountId,
2425
+ bucketId: large.bucketId,
2426
+ fileName: large.fileName
2427
+ }
2428
+ };
2429
+ }
2430
+ listUnfinishedLargeFiles(req) {
2431
+ const countError = require_validation.validateMaxCount(req.maxFileCount, "b2_list_unfinished_large_files");
2432
+ if (countError) return this.error(400, countError.code, countError.message);
2433
+ const prefix = req.namePrefix ?? "";
2434
+ const max = req.maxFileCount ?? 100;
2435
+ const candidates = [...this.largeFiles.values()].filter((f) => f.bucketId === req.bucketId).filter((f) => f.fileName.startsWith(prefix)).sort((a, b) => compareB2FileNames(a.fileName, b.fileName));
2436
+ let startIndex = 0;
2437
+ if (req.startFileId !== void 0) {
2438
+ const found = candidates.findIndex((f) => f.fileId === req.startFileId);
2439
+ startIndex = found >= 0 ? found : 0;
2440
+ }
2441
+ return {
2442
+ status: 200,
2443
+ body: {
2444
+ files: candidates.slice(startIndex, startIndex + max).map((f) => ({
2445
+ fileId: f.fileId,
2446
+ fileName: f.fileName,
2447
+ accountId: this.accountId,
2448
+ bucketId: f.bucketId,
2449
+ contentType: f.contentType,
2450
+ action: require_file.FileAction.Start,
2451
+ contentLength: 0,
2452
+ contentSha1: "none",
2453
+ contentMd5: null,
2454
+ fileInfo: f.fileInfo,
2455
+ fileRetention: {
2456
+ isClientAuthorizedToRead: true,
2457
+ value: f.fileRetention
2458
+ },
2459
+ legalHold: {
2460
+ isClientAuthorizedToRead: true,
2461
+ value: f.legalHold
2462
+ },
2463
+ ...this.replicationStatusMetadataFor(f.replicationStatus),
2464
+ serverSideEncryption: publicServerSideEncryption(f.serverSideEncryption),
2465
+ uploadTimestamp: f.uploadTimestamp
2466
+ })),
2467
+ nextFileId: startIndex + max < candidates.length ? candidates[startIndex + max]?.fileId ?? null : null
2468
+ }
2469
+ };
2470
+ }
2471
+ listParts(req) {
2472
+ const large = this.largeFiles.get(req.fileId);
2473
+ if (!large) return this.error(400, "bad_request", "Large file not found");
2474
+ const countError = require_validation.validateMaxCount(req.maxPartCount, "b2_list_parts");
2475
+ if (countError) return this.error(400, countError.code, countError.message);
2476
+ const start = req.startPartNumber ?? 1;
2477
+ const max = req.maxPartCount ?? 1e3;
2478
+ const allParts = [...large.parts.entries()].filter(([n]) => n >= start).sort((a, b) => a[0] - b[0]).map(([partNumber, part]) => ({
2479
+ fileId: req.fileId,
2480
+ partNumber,
2481
+ contentLength: part.data.byteLength,
2482
+ contentSha1: part.sha1,
2483
+ contentMd5: part.contentMd5,
2484
+ serverSideEncryption: publicServerSideEncryption(large.serverSideEncryption),
2485
+ uploadTimestamp: part.uploadTimestamp
2486
+ }));
2487
+ return {
2488
+ status: 200,
2489
+ body: {
2490
+ parts: allParts.slice(0, max),
2491
+ nextPartNumber: allParts.length > max ? allParts[max]?.partNumber ?? null : null
2492
+ }
2493
+ };
2494
+ }
2495
+ async copyPart(req) {
2496
+ const large = this.largeFiles.get(req.largeFileId);
2497
+ if (!large) return this.error(400, "bad_request", "Large file not found");
2498
+ const partNumberError = this.validatePartNumber(req.partNumber);
2499
+ if (partNumberError !== null) return partNumberError;
2500
+ const found = this.findFile(req.sourceFileId);
2501
+ if (found === null) return this.error(404, "file_not_present", "Source file not found");
2502
+ const sourceStored = found.stored;
2503
+ const sourceEncryptionError = await this.validateSourceServerSideEncryption(sourceStored, req.sourceServerSideEncryption);
2504
+ if (sourceEncryptionError !== null) return sourceEncryptionError;
2505
+ const destinationEncryptionError = await this.validateCopyPartDestinationEncryption(large, req.destinationServerSideEncryption);
2506
+ if (destinationEncryptionError !== null) return destinationEncryptionError;
2507
+ let partData = sourceStored.data;
2508
+ if (req.range !== void 0) {
2509
+ const parsed = parseRangeHeader(req.range, sourceStored.data.byteLength);
2510
+ if (parsed.kind === "malformed") return this.error(400, "bad_request", `Malformed copy range: ${req.range}`);
2511
+ if (parsed.kind === "unsatisfiable") return this.error(416, "range_not_satisfiable", `Unsatisfiable copy range: ${req.range}`);
2512
+ partData = sourceStored.data.subarray(parsed.start, parsed.end + 1);
2513
+ }
2514
+ const sha1 = await require_hash.sha1Hex(partData);
2515
+ const uploadTimestamp = this.monotonicTimestamp();
2516
+ large.parts.set(req.partNumber, {
2517
+ data: new Uint8Array(partData),
2518
+ sha1,
2519
+ contentMd5: null,
2520
+ uploadTimestamp
2521
+ });
2522
+ return {
2523
+ status: 200,
2524
+ body: {
2525
+ fileId: req.largeFileId,
2526
+ partNumber: req.partNumber,
2527
+ contentLength: partData.byteLength,
2528
+ contentSha1: sha1,
2529
+ contentMd5: null,
2530
+ serverSideEncryption: publicServerSideEncryption(large.serverSideEncryption),
2531
+ uploadTimestamp
2532
+ }
2533
+ };
2534
+ }
2535
+ getDownloadAuthorization(req) {
2536
+ this.purgeExpiredDownloadAuthorizationTokens();
2537
+ if (!this.buckets.has(req.bucketId)) return this.error(400, "bad_bucket_id", "Bucket not found");
2538
+ const prefixError = require_validation.validateDownloadAuthorizationPrefix(req.fileNamePrefix);
2539
+ if (prefixError) return this.error(400, prefixError.code, prefixError.message);
2540
+ const durationError = require_validation.validateDownloadAuthorizationDuration(req.validDurationInSeconds);
2541
+ if (durationError) return this.error(400, durationError.code, durationError.message);
2542
+ const overrideError = validateDownloadResponseOverrides(req);
2543
+ if (overrideError) return this.error(400, overrideError.code, overrideError.message);
2544
+ let authorizationToken = randomDownloadAuthorizationToken();
2545
+ while (this.downloadAuthorizationTokens.has(authorizationToken)) authorizationToken = randomDownloadAuthorizationToken();
2546
+ const expiresAt = this.now() + req.validDurationInSeconds * 1e3;
2547
+ this.downloadAuthorizationTokens.set(authorizationToken, {
2548
+ bucketId: req.bucketId,
2549
+ fileNamePrefix: req.fileNamePrefix,
2550
+ expiresAt,
2551
+ responseHeaderOverrides: pickDownloadResponseOverrides(req)
2552
+ });
2553
+ this.pushDownloadAuthorizationExpiry({
2554
+ token: authorizationToken,
2555
+ expiresAt
2556
+ });
2557
+ return {
2558
+ status: 200,
2559
+ body: {
2560
+ bucketId: req.bucketId,
2561
+ fileNamePrefix: req.fileNamePrefix,
2562
+ authorizationToken
2563
+ }
2564
+ };
2565
+ }
2566
+ createKeyCapabilitiesOutsideGrant(authToken, requested) {
2567
+ const creator = authToken === void 0 ? void 0 : this.issuedTokens.get(authToken);
2568
+ if (creator === void 0) return this.strictAuth ? requested : [];
2569
+ if (creator.applicationKeyId === null) return [];
2570
+ const granted = new Set(creator.capabilities);
2571
+ return requested.filter((capability) => !granted.has(capability));
2572
+ }
2573
+ createKeyCreatorAccountId(authToken) {
2574
+ return (authToken === void 0 ? void 0 : this.issuedTokens.get(authToken))?.accountId ?? this.accountId;
2575
+ }
2576
+ createKey(req, version, authToken) {
2577
+ if (version === "v4" && hasOwnField(req, "bucketId")) return this.error(400, "bad_request", "bucketId is not accepted by v4 b2_create_key; use bucketIds");
2578
+ if (version !== "v4" && req.bucketId !== void 0 && req.bucketIds !== void 0) return this.error(400, "bad_request", "b2_create_key accepts either bucketIds or bucketId");
2579
+ const bucketIds = version !== "v4" && req.bucketId !== void 0 ? Object.freeze([req.bucketId]) : normalizeKeyBucketIds(req);
2580
+ const namePrefix = req.namePrefix === void 0 || req.namePrefix === "" ? null : req.namePrefix;
2581
+ const creatorAccountId = this.createKeyCreatorAccountId(authToken);
2582
+ if (req.accountId !== creatorAccountId) return this.error(400, "bad_request", "accountId must match authorized account");
2583
+ const keyNameError = require_validation.validateCreateKeyName(req.keyName);
2584
+ if (keyNameError) return this.error(400, keyNameError.code, keyNameError.message);
2585
+ const keyName = req.keyName;
2586
+ const capabilitiesError = require_validation.validateCreateKeyCapabilities(req.capabilities);
2587
+ if (capabilitiesError) return this.error(400, capabilitiesError.code, capabilitiesError.message);
2588
+ const capabilities = require_validation.normalizeCreateKeyCapabilities(req.capabilities);
2589
+ const unauthorizedCapabilities = this.createKeyCapabilitiesOutsideGrant(authToken, capabilities);
2590
+ if (unauthorizedCapabilities.length > 0) return this.error(400, "bad_request", `requested capabilities exceed creator grant: ${unauthorizedCapabilities.join(", ")}`);
2591
+ if (hasKeyManagementCapability(capabilities) && (bucketIds !== null || namePrefix !== null)) return this.error(400, "bad_request", "key-management capabilities are account-level and cannot be bucket or name-prefix scoped");
2592
+ const kid = this.genId("sim_key");
2593
+ const stored = {
2594
+ applicationKeyId: kid,
2595
+ keyName,
2596
+ capabilities,
2597
+ accountId: creatorAccountId,
2598
+ applicationKey: this.genId("sim_secret"),
2599
+ bucketIds,
2600
+ namePrefix,
2601
+ expirationTimestamp: req.validDurationInSeconds !== void 0 ? this.now() + req.validDurationInSeconds * 1e3 : null
2602
+ };
2603
+ this.keys.set(kid, stored);
2604
+ return {
2605
+ status: 200,
2606
+ body: {
2607
+ keyName: stored.keyName,
2608
+ applicationKeyId: stored.applicationKeyId,
2609
+ applicationKey: stored.applicationKey,
2610
+ capabilities: cloneCapabilities(stored.capabilities),
2611
+ accountId: stored.accountId,
2612
+ expirationTimestamp: stored.expirationTimestamp,
2613
+ bucketIds: cloneBucketIds(stored.bucketIds),
2614
+ bucketId: singleBucketId(stored.bucketIds),
2615
+ namePrefix: stored.namePrefix,
2616
+ options: []
2617
+ }
2618
+ };
2619
+ }
2620
+ listKeys(req) {
2621
+ const countError = require_validation.validateMaxCount(req.maxKeyCount, "b2_list_keys");
2622
+ if (countError) return this.error(400, countError.code, countError.message);
2623
+ const max = req.maxKeyCount ?? 1e3;
2624
+ let allKeys = [...this.keys.values()].sort((a, b) => a.applicationKeyId.localeCompare(b.applicationKeyId));
2625
+ if (req.startApplicationKeyId) {
2626
+ const start = req.startApplicationKeyId;
2627
+ allKeys = allKeys.filter((k) => k.applicationKeyId >= start);
2628
+ }
2629
+ return {
2630
+ status: 200,
2631
+ body: {
2632
+ keys: allKeys.slice(0, max).map((k) => ({
2633
+ keyName: k.keyName,
2634
+ applicationKeyId: k.applicationKeyId,
2635
+ capabilities: cloneCapabilities(k.capabilities),
2636
+ accountId: k.accountId,
2637
+ expirationTimestamp: k.expirationTimestamp,
2638
+ bucketIds: cloneBucketIds(k.bucketIds),
2639
+ bucketId: singleBucketId(k.bucketIds),
2640
+ namePrefix: k.namePrefix,
2641
+ options: []
2642
+ })),
2643
+ nextApplicationKeyId: allKeys.length > max ? allKeys[max]?.applicationKeyId ?? null : null
2644
+ }
2645
+ };
2646
+ }
2647
+ deleteKey(req) {
2648
+ const key = this.keys.get(req.applicationKeyId);
2649
+ if (!key) return this.error(400, "bad_request", "Key not found");
2650
+ this.keys.delete(req.applicationKeyId);
2651
+ for (const [token, scope] of this.issuedTokens.entries()) if (scope.applicationKeyId === req.applicationKeyId) this.issuedTokens.delete(token);
2652
+ for (const [token, scope] of this.uploadTokens.entries()) if (scope.applicationKeyId === req.applicationKeyId) {
2653
+ scope.invalidated = true;
2654
+ this.uploadTokens.set(token, scope);
2655
+ }
2656
+ return {
2657
+ status: 200,
2658
+ body: {
2659
+ keyName: key.keyName,
2660
+ applicationKeyId: key.applicationKeyId,
2661
+ capabilities: cloneCapabilities(key.capabilities),
2662
+ accountId: key.accountId,
2663
+ expirationTimestamp: key.expirationTimestamp,
2664
+ bucketIds: cloneBucketIds(key.bucketIds),
2665
+ bucketId: singleBucketId(key.bucketIds),
2666
+ namePrefix: key.namePrefix,
2667
+ options: []
2668
+ }
2669
+ };
2670
+ }
2671
+ updateFileRetention(req, authToken) {
2672
+ const found = this.findFile(req.fileId);
2673
+ if (found === null || found.stored.fileVersion.fileName !== req.fileName) return this.error(404, "file_not_present", "File not found");
2674
+ const fileLockError = this.requireFileLockEnabled(found.bucket);
2675
+ if (fileLockError !== null) return fileLockError;
2676
+ const fileRetention = parseFileRetentionValue(req.fileRetention, Date.now());
2677
+ if (fileRetention === null) return this.error(400, "bad_request", "fileRetention must use a valid mode and retainUntilTimestamp pair");
2678
+ const current = found.stored.fileVersion.fileRetention?.value;
2679
+ if (current?.mode === require_lock.RetentionMode.Compliance && (fileRetention.mode !== require_lock.RetentionMode.Compliance || isRetentionWeakened(current, fileRetention))) return this.error(400, "file_lock_compliance_protected", "Compliance-mode retention cannot be shortened or removed");
2680
+ if (requiresGovernanceBypass(current, fileRetention)) {
2681
+ const bypassError = this.requireGovernanceBypass(req, authToken, "Governance-mode retention cannot be shortened, removed, or converted without bypassGovernance");
2682
+ if (bypassError !== null) return bypassError;
2683
+ }
2684
+ found.versions[found.index] = {
2685
+ fileVersion: {
2686
+ ...found.stored.fileVersion,
2687
+ fileRetention: {
2688
+ isClientAuthorizedToRead: true,
2689
+ value: fileRetention
2690
+ }
2691
+ },
2692
+ data: found.stored.data,
2693
+ serverSideEncryption: found.stored.serverSideEncryption
2694
+ };
2695
+ return {
2696
+ status: 200,
2697
+ body: {
2698
+ fileName: req.fileName,
2699
+ fileId: req.fileId,
2700
+ fileRetention
2701
+ }
2702
+ };
2703
+ }
2704
+ updateFileLegalHold(req) {
2705
+ const found = this.findFile(req.fileId);
2706
+ if (found === null || found.stored.fileVersion.fileName !== req.fileName) return this.error(404, "file_not_present", "File not found");
2707
+ const fileLockError = this.requireFileLockEnabled(found.bucket);
2708
+ if (fileLockError !== null) return fileLockError;
2709
+ if (req.legalHold !== require_lock.LegalHoldValue.On && req.legalHold !== require_lock.LegalHoldValue.Off) return this.error(400, "bad_request", "legalHold must be \"on\" or \"off\"");
2710
+ found.versions[found.index] = {
2711
+ fileVersion: {
2712
+ ...found.stored.fileVersion,
2713
+ legalHold: {
2714
+ isClientAuthorizedToRead: true,
2715
+ value: req.legalHold
2716
+ }
2717
+ },
2718
+ data: found.stored.data,
2719
+ serverSideEncryption: found.stored.serverSideEncryption
2720
+ };
2721
+ return {
2722
+ status: 200,
2723
+ body: {
2724
+ fileName: req.fileName,
2725
+ fileId: req.fileId,
2726
+ legalHold: req.legalHold
2727
+ }
2728
+ };
2729
+ }
2730
+ getBucketNotificationRules(req) {
2731
+ if (!this.buckets.has(req.bucketId)) return this.error(400, "bad_bucket_id", "Bucket not found");
2732
+ const rules = this.notificationRules.get(req.bucketId) ?? [];
2733
+ return {
2734
+ status: 200,
2735
+ body: {
2736
+ bucketId: req.bucketId,
2737
+ eventNotificationRules: rules
2738
+ }
2739
+ };
2740
+ }
2741
+ setBucketNotificationRules(req) {
2742
+ if (!this.buckets.has(req.bucketId)) return this.error(400, "bad_bucket_id", "Bucket not found");
2743
+ const rulesError = require_validation.validateNotificationRules(req.eventNotificationRules);
2744
+ if (rulesError) return this.error(400, rulesError.code, rulesError.message);
2745
+ this.notificationRules.set(req.bucketId, req.eventNotificationRules);
2746
+ return {
2747
+ status: 200,
2748
+ body: {
2749
+ bucketId: req.bucketId,
2750
+ eventNotificationRules: req.eventNotificationRules
2751
+ }
2752
+ };
2753
+ }
2754
+ /**
2755
+ * Locates a stored file version by its `fileId`, scanning every bucket.
2756
+ *
2757
+ * Returns enough context to support read-only inspection (`stored`,
2758
+ * `bucketId`) AND in-place mutation (`versions`, `index`) so callers
2759
+ * that need to splice the version out can do so without re-scanning.
2760
+ *
2761
+ * Real B2 fileIds embed the bucketId, so production lookups are O(1);
2762
+ * the simulator's flat ID generator (`this.genId('4_z')`) doesn't, so this
2763
+ * is O(buckets × files × versions). Acceptable for tests.
2764
+ *
2765
+ * @param fileId - The file version ID to locate.
2766
+ *
2767
+ * @returns The location of the matching version, or `null` if not found.
2768
+ */
2769
+ findFile(fileId) {
2770
+ for (const [bid, bucket] of this.buckets.entries()) for (const versions of bucket.files.values()) {
2771
+ const idx = versions.findIndex((v) => v.fileVersion.fileId === fileId);
2772
+ if (idx !== -1) return {
2773
+ stored: versions[idx],
2774
+ bucketId: bid,
2775
+ bucket,
2776
+ versions,
2777
+ index: idx
2778
+ };
2779
+ }
2780
+ return null;
2781
+ }
2782
+ makeFileVersion(params) {
2783
+ return {
2784
+ accountId: require_ids.accountId(this.accountId),
2785
+ action: params.action,
2786
+ bucketId: require_ids.bucketId(params.bucketId),
2787
+ contentLength: params.contentLength,
2788
+ contentMd5: null,
2789
+ contentSha1: params.contentSha1,
2790
+ contentType: params.contentType,
2791
+ fileId: require_ids.fileId(this.genId("4_z")),
2792
+ fileInfo: params.fileInfo ?? {},
2793
+ fileName: params.fileName,
2794
+ fileRetention: {
2795
+ isClientAuthorizedToRead: true,
2796
+ value: params.fileRetention ?? null
2797
+ },
2798
+ legalHold: {
2799
+ isClientAuthorizedToRead: true,
2800
+ value: params.legalHold ?? null
2801
+ },
2802
+ ...this.replicationStatusMetadataFor(params.replicationStatus),
2803
+ serverSideEncryption: publicServerSideEncryption(params.serverSideEncryption ?? { mode: require_encryption.EncryptionMode.None }),
2804
+ uploadTimestamp: params.uploadTimestamp ?? this.monotonicTimestamp()
2805
+ };
2806
+ }
2807
+ newReplicationStatusField(bucketId, fileName) {
2808
+ return this.replicationStatusMetadataFor(this.replicationStatusForNewFile(bucketId, fileName));
2809
+ }
2810
+ replicationStatusMetadataFor(replicationStatus) {
2811
+ return replicationStatus === void 0 ? {} : { replicationStatus };
2812
+ }
2813
+ replicationStatusForNewFile(bucketId, fileName) {
2814
+ return this.matchingEnabledReplicationRules(bucketId, fileName).length > 0 ? "PENDING" : void 0;
2815
+ }
2816
+ matchingEnabledReplicationRules(bucketId, fileName) {
2817
+ return (this.buckets.get(bucketId)?.info.replicationConfiguration.asReplicationSource?.replicationRules)?.filter((rule) => rule.isEnabled && fileName.startsWith(rule.fileNamePrefix)) ?? [];
2818
+ }
2819
+ error(status, code, message) {
2820
+ return {
2821
+ status,
2822
+ body: {
2823
+ status,
2824
+ code,
2825
+ message
2826
+ }
2827
+ };
2828
+ }
2829
+ /**
2830
+ * Fire the pluggable post-upload hooks for a file that just landed in
2831
+ * a bucket: matching event-notification rules → `onWebhookDeliver`,
2832
+ * configured replication source rules → `onReplicate`. Errors thrown
2833
+ * from user-supplied hooks are swallowed so a buggy listener never
2834
+ * masks an otherwise-successful API response.
2835
+ *
2836
+ * Fired-and-forgotten (no await) by the handler so the synthetic
2837
+ * response is returned to the caller as fast as production B2 would
2838
+ * acknowledge the write.
2839
+ *
2840
+ * @param fileVersion - The freshly-stored file metadata.
2841
+ * @param bucketId - The bucket the upload landed in.
2842
+ * @param eventType - The B2 event-type tag (e.g. `'b2:ObjectCreated:Upload'`)
2843
+ * used to match against `EventNotificationRule.eventTypes` globs.
2844
+ */
2845
+ firePostUploadHooks(fileVersion, bucketId, eventType) {
2846
+ if (!this.buckets.get(bucketId)) return;
2847
+ if (this.onWebhookDeliver !== void 0) {
2848
+ const rules = this.notificationRules.get(bucketId) ?? [];
2849
+ for (const rule of rules) {
2850
+ if (!rule.isEnabled) continue;
2851
+ if (!rule.eventTypes.some((pattern) => eventTypeMatches(pattern, eventType))) continue;
2852
+ const hook = this.onWebhookDeliver;
2853
+ this.dispatchHook("webhook", () => hook({
2854
+ rule,
2855
+ fileVersion,
2856
+ bucketId
2857
+ }));
2858
+ }
2859
+ }
2860
+ if (this.onReplicate !== void 0) for (const rule of this.matchingEnabledReplicationRules(bucketId, fileVersion.fileName)) {
2861
+ const hook = this.onReplicate;
2862
+ this.dispatchHook("replication", () => hook({
2863
+ sourceFileVersion: fileVersion,
2864
+ sourceBucketId: bucketId,
2865
+ destinationBucketId: rule.destinationBucketId
2866
+ }));
2867
+ }
2868
+ }
2869
+ /**
2870
+ * Schedule a user-supplied hook callback. Errors are routed to
2871
+ * `onHookError` if configured, swallowed otherwise. The returned
2872
+ * promise is tracked in {@link pendingHooks} so `flushHooks()` can
2873
+ * wait for every dispatched hook to settle.
2874
+ *
2875
+ * @param kind - Which hook this is (`'webhook'` or `'replication'`).
2876
+ * @param fn - Thunk that performs the hook invocation.
2877
+ */
2878
+ dispatchHook(kind, fn) {
2879
+ const task = Promise.resolve().then(() => fn()).catch((err) => {
2880
+ if (this.onHookError !== void 0) this.onHookError({
2881
+ kind,
2882
+ error: require_to_error.toError(err)
2883
+ });
2884
+ }).finally(() => {
2885
+ this.pendingHooks.delete(task);
2886
+ });
2887
+ this.pendingHooks.add(task);
2888
+ }
2889
+ };
2890
+ /**
2891
+ * Module-local cache of compiled glob regexes. Avoids recompiling the
2892
+ * same `eventTypes` pattern on every upload's hook dispatch — patterns
2893
+ * are stable for the lifetime of a `setBucketNotificationRules` call
2894
+ * and typically reused across thousands of uploads.
2895
+ */
2896
+ var eventTypeRegexCache = /* @__PURE__ */ new Map();
2897
+ /**
2898
+ * Wildcard match for B2 event-type globs. Supports the prefix-glob form
2899
+ * the B2 docs document: `b2:ObjectCreated:*` matches
2900
+ * `b2:ObjectCreated:Upload`, `b2:ObjectCreated:Copy`, etc. Exact
2901
+ * matches without `*` match literally.
2902
+ *
2903
+ * @param pattern - Glob from an `EventNotificationRule.eventTypes` entry.
2904
+ * @param eventType - Concrete event type produced by the simulator.
2905
+ *
2906
+ * @returns `true` when the pattern matches the event type.
2907
+ */
1435
2908
  function eventTypeMatches(pattern, eventType) {
1436
- if (!pattern.includes("*")) return pattern === eventType;
1437
- let compiled = eventTypeRegexCache.get(pattern);
1438
- if (compiled === void 0) {
1439
- const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
1440
- compiled = new RegExp(`^${escaped}$`);
1441
- eventTypeRegexCache.set(pattern, compiled);
1442
- }
1443
- return compiled.test(eventType);
2909
+ if (!pattern.includes("*")) return pattern === eventType;
2910
+ let compiled = eventTypeRegexCache.get(pattern);
2911
+ if (compiled === void 0) {
2912
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
2913
+ compiled = new RegExp(`^${escaped}$`);
2914
+ eventTypeRegexCache.set(pattern, compiled);
2915
+ }
2916
+ return compiled.test(eventType);
1444
2917
  }
2918
+ /**
2919
+ * Build a synthetic {@link HttpResponse} from a consumed {@link FaultSpec}.
2920
+ * Mirrors the shape of real B2 error responses so the SDK's
2921
+ * `RetryTransport` / `classifyError` paths see realistic input.
2922
+ *
2923
+ * @param fault - The fault spec to render.
2924
+ *
2925
+ * @returns An `HttpResponse` ready to return from `transport.send`.
2926
+ */
1445
2927
  function buildFaultResponse(fault) {
1446
- const status = fault.status ?? 503;
1447
- const code = fault.code ?? "service_unavailable";
1448
- const message = fault.message ?? "simulated failure";
1449
- const body = JSON.stringify({ status, code, message });
1450
- const headers = new Headers({ "Content-Type": "application/json" });
1451
- if (fault.retryAfter !== void 0) {
1452
- headers.set("Retry-After", String(fault.retryAfter));
1453
- }
1454
- return {
1455
- status,
1456
- headers,
1457
- body: new ReadableStream({
1458
- start(controller) {
1459
- controller.enqueue(textCodec.utf8Encoder.encode(body));
1460
- controller.close();
1461
- }
1462
- }),
1463
- json: () => Promise.resolve(JSON.parse(body)),
1464
- text: () => Promise.resolve(body),
1465
- arrayBuffer: () => Promise.resolve(textCodec.utf8Encoder.encode(body).buffer)
1466
- };
2928
+ const status = fault.status ?? 503;
2929
+ const code = fault.code ?? "service_unavailable";
2930
+ const message = fault.message ?? "simulated failure";
2931
+ const body = JSON.stringify({
2932
+ status,
2933
+ code,
2934
+ message
2935
+ });
2936
+ const headers = new Headers({ "Content-Type": "application/json" });
2937
+ if (fault.retryAfter !== void 0) headers.set("Retry-After", String(fault.retryAfter));
2938
+ return {
2939
+ status,
2940
+ headers,
2941
+ body: new ReadableStream({ start(controller) {
2942
+ controller.enqueue(require_text_codec.utf8Encoder.encode(body));
2943
+ controller.close();
2944
+ } }),
2945
+ json: () => Promise.resolve(JSON.parse(body)),
2946
+ text: () => Promise.resolve(body),
2947
+ arrayBuffer: () => Promise.resolve(require_text_codec.utf8Encoder.encode(body).buffer)
2948
+ };
2949
+ }
2950
+ function rawUrlPathContainsLiteralBackslash(rawUrl) {
2951
+ const schemeEnd = rawUrl.indexOf("://");
2952
+ const authorityStart = schemeEnd === -1 ? 0 : schemeEnd + 3;
2953
+ const urlEndCandidates = [rawUrl.indexOf("?", authorityStart), rawUrl.indexOf("#", authorityStart)].filter((index) => index !== -1);
2954
+ const urlEnd = urlEndCandidates.length === 0 ? rawUrl.length : Math.min(...urlEndCandidates);
2955
+ const pathStartCandidates = [rawUrl.indexOf("/", authorityStart), rawUrl.indexOf("\\", authorityStart)].filter((index) => index !== -1 && index < urlEnd);
2956
+ if (pathStartCandidates.length === 0) return false;
2957
+ const pathStart = Math.min(...pathStartCandidates);
2958
+ const pathEndCandidates = [rawUrl.indexOf("?", pathStart), rawUrl.indexOf("#", pathStart)].filter((index) => index !== -1);
2959
+ const pathEnd = pathEndCandidates.length === 0 ? rawUrl.length : Math.min(...pathEndCandidates);
2960
+ return rawUrl.slice(pathStart, pathEnd).includes("\\");
2961
+ }
2962
+ function badRequestJson(message) {
2963
+ return {
2964
+ status: 400,
2965
+ body: {
2966
+ status: 400,
2967
+ code: "bad_request",
2968
+ message
2969
+ }
2970
+ };
2971
+ }
2972
+ function checkedUploadBody(data, expectedLength) {
2973
+ if (expectedLength !== null && data.byteLength !== expectedLength) return { error: badRequestJson(contentLengthMismatchMessage(expectedLength, data.byteLength)) };
2974
+ return { data };
2975
+ }
2976
+ function copyBytes(bytes) {
2977
+ const copy = new Uint8Array(bytes.byteLength);
2978
+ copy.set(bytes);
2979
+ return copy;
2980
+ }
2981
+ function concatenateChunks(chunks, totalLength) {
2982
+ if (chunks.length === 0) return /* @__PURE__ */ new Uint8Array(0);
2983
+ if (chunks.length === 1) return copyBytes(chunks[0]);
2984
+ const data = new Uint8Array(totalLength);
2985
+ let offset = 0;
2986
+ for (const chunk of chunks) {
2987
+ data.set(chunk, offset);
2988
+ offset += chunk.byteLength;
2989
+ }
2990
+ return data;
2991
+ }
2992
+ async function readStreamingUploadBody(stream, expectedLength) {
2993
+ const reader = stream.getReader();
2994
+ const chunks = [];
2995
+ let totalLength = 0;
2996
+ try {
2997
+ while (true) {
2998
+ const { done, value } = await reader.read();
2999
+ if (done) break;
3000
+ if (value === void 0) continue;
3001
+ const chunk = value instanceof Uint8Array ? value : new Uint8Array(value);
3002
+ totalLength += chunk.byteLength;
3003
+ if (expectedLength !== null && totalLength > expectedLength) {
3004
+ await reader.cancel().catch(() => void 0);
3005
+ return { error: badRequestJson(contentLengthMismatchMessage(expectedLength, totalLength)) };
3006
+ }
3007
+ chunks.push(chunk);
3008
+ }
3009
+ } finally {
3010
+ reader.releaseLock();
3011
+ }
3012
+ if (expectedLength !== null && totalLength !== expectedLength) return { error: badRequestJson(contentLengthMismatchMessage(expectedLength, totalLength)) };
3013
+ return { data: concatenateChunks(chunks, totalLength) };
1467
3014
  }
1468
- class SimulatorTransport {
1469
- constructor(sim) {
1470
- this.sim = sim;
1471
- }
1472
- async send(request) {
1473
- const url = request.url;
1474
- const fault = this.sim.consumeMatchingFault(url);
1475
- if (fault !== null) {
1476
- return buildFaultResponse(fault);
1477
- }
1478
- const headers = {};
1479
- if (request.headers) {
1480
- for (const [k, v] of Object.entries(request.headers)) {
1481
- headers[k.toLowerCase()] = v;
1482
- }
1483
- }
1484
- const isUpload = url.includes("b2_upload_file") || url.includes("b2_upload_part");
1485
- const parsedUrl = new URL(url);
1486
- const isDownload = parsedUrl.pathname.includes("b2_download_file_by_id") || parsedUrl.pathname.includes("/file/");
1487
- if (isDownload) {
1488
- const method = request.method === "HEAD" ? "HEAD" : "GET";
1489
- const result2 = this.sim.handleDownload(parsedUrl.pathname + parsedUrl.search, headers, method);
1490
- const data = result2.data ?? new Uint8Array(0);
1491
- const responseHeaders = new Headers(result2.headers);
1492
- responseHeaders.set(
1493
- "Content-Type",
1494
- result2.headers["Content-Type"] ?? "application/octet-stream"
1495
- );
1496
- const body = method === "HEAD" || result2.data === null ? null : new ReadableStream({
1497
- start(controller) {
1498
- controller.enqueue(data);
1499
- controller.close();
1500
- }
1501
- });
1502
- return {
1503
- status: result2.status,
1504
- headers: responseHeaders,
1505
- body,
1506
- json: () => Promise.reject(new Error("Download response is not JSON")),
1507
- text: () => Promise.resolve(textCodec.utf8Decoder.decode(data)),
1508
- arrayBuffer: () => Promise.resolve(
1509
- data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)
1510
- )
1511
- };
1512
- }
1513
- let result;
1514
- if (isUpload && request.body) {
1515
- const data = new Uint8Array(
1516
- request.body instanceof ArrayBuffer ? request.body : request.body instanceof Uint8Array ? request.body.buffer.slice(
1517
- request.body.byteOffset,
1518
- request.body.byteOffset + request.body.byteLength
1519
- ) : await new Response(request.body).arrayBuffer()
1520
- );
1521
- result = this.sim.handleUpload(url, headers, data);
1522
- } else {
1523
- let body = null;
1524
- if (request.body) {
1525
- const text = typeof request.body === "string" ? request.body : await new Response(request.body).text();
1526
- try {
1527
- body = JSON.parse(text);
1528
- } catch {
1529
- body = text;
1530
- }
1531
- }
1532
- result = await this.sim.handleRequest(request.method, parsedUrl.pathname, headers, body);
1533
- }
1534
- const responseBody = JSON.stringify(result.body);
1535
- return {
1536
- status: result.status,
1537
- headers: new Headers({ "Content-Type": "application/json" }),
1538
- body: new ReadableStream({
1539
- start(controller) {
1540
- controller.enqueue(textCodec.utf8Encoder.encode(responseBody));
1541
- controller.close();
1542
- }
1543
- }),
1544
- json: () => Promise.resolve(result.body),
1545
- text: () => Promise.resolve(responseBody),
1546
- arrayBuffer: () => Promise.resolve(textCodec.utf8Encoder.encode(responseBody).buffer)
1547
- };
1548
- }
3015
+ async function readUploadBody(body, expectedLength) {
3016
+ if (body instanceof ReadableStream) return readStreamingUploadBody(body, expectedLength);
3017
+ if (body instanceof ArrayBuffer) return checkedUploadBody(new Uint8Array(body), expectedLength);
3018
+ if (ArrayBuffer.isView(body)) {
3019
+ const view = body;
3020
+ return checkedUploadBody(copyBytes(new Uint8Array(view.buffer, view.byteOffset, view.byteLength)), expectedLength);
3021
+ }
3022
+ if (typeof Blob !== "undefined" && body instanceof Blob) {
3023
+ if (expectedLength !== null && body.size !== expectedLength) return { error: badRequestJson(contentLengthMismatchMessage(expectedLength, body.size)) };
3024
+ }
3025
+ return checkedUploadBody(new Uint8Array(await new Response(body).arrayBuffer()), expectedLength);
1549
3026
  }
1550
- exports.BUCKET_INFO_MAX_KEYS = validation.BUCKET_INFO_MAX_KEYS;
1551
- exports.BUCKET_INFO_VALUE_MAX = validation.BUCKET_INFO_VALUE_MAX;
1552
- exports.BUCKET_NAME_MAX = validation.BUCKET_NAME_MAX;
1553
- exports.BUCKET_NAME_MIN = validation.BUCKET_NAME_MIN;
1554
- exports.FILE_INFO_TOTAL_MAX = validation.FILE_INFO_TOTAL_MAX;
1555
- exports.FILE_INFO_VALUE_MAX = validation.FILE_INFO_VALUE_MAX;
1556
- exports.FILE_NAME_MAX_BYTES = validation.FILE_NAME_MAX_BYTES;
1557
- exports.LIST_ENDPOINT_CAPS = validation.LIST_ENDPOINT_CAPS;
3027
+ var SimulatorTransport = class {
3028
+ sim;
3029
+ constructor(sim) {
3030
+ this.sim = sim;
3031
+ }
3032
+ async send(request) {
3033
+ const url = request.url;
3034
+ const fault = this.sim.consumeMatchingFault(url);
3035
+ if (fault !== null) return buildFaultResponse(fault);
3036
+ if (rawUrlPathContainsLiteralBackslash(url)) return buildFaultResponse({
3037
+ on: "\\",
3038
+ status: 400,
3039
+ code: "bad_request",
3040
+ message: "URL path must not contain literal backslashes"
3041
+ });
3042
+ const headers = {};
3043
+ if (request.headers) for (const [k, v] of Object.entries(request.headers)) headers[k.toLowerCase()] = v;
3044
+ const parsedUrl = new URL(url);
3045
+ const endpoint = parsedUrl.pathname.split("/").pop() ?? "";
3046
+ const isUpload = endpoint === "b2_upload_file" || endpoint === "b2_upload_part";
3047
+ if (parsedUrl.pathname.includes("b2_download_file_by_id") || parsedUrl.pathname.includes("/file/")) {
3048
+ const method = request.method === "HEAD" ? "HEAD" : "GET";
3049
+ const result = await this.sim.handleDownload(parsedUrl.pathname + parsedUrl.search, headers, method);
3050
+ const data = result.data ?? /* @__PURE__ */ new Uint8Array(0);
3051
+ const responseHeaders = new Headers(result.headers);
3052
+ responseHeaders.set("Content-Type", result.headers["Content-Type"] ?? "application/octet-stream");
3053
+ let decodedText = null;
3054
+ const text = () => {
3055
+ decodedText ??= require_text_codec.utf8Decoder.decode(data);
3056
+ return decodedText;
3057
+ };
3058
+ const body = method === "HEAD" || result.data === null ? null : new ReadableStream({ start(controller) {
3059
+ controller.enqueue(data);
3060
+ controller.close();
3061
+ } });
3062
+ return {
3063
+ status: result.status,
3064
+ headers: responseHeaders,
3065
+ body,
3066
+ json: () => {
3067
+ try {
3068
+ return Promise.resolve(JSON.parse(text()));
3069
+ } catch {
3070
+ return Promise.reject(/* @__PURE__ */ new Error("Download response is not JSON"));
3071
+ }
3072
+ },
3073
+ text: () => Promise.resolve(text()),
3074
+ arrayBuffer: () => Promise.resolve(data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength))
3075
+ };
3076
+ }
3077
+ let result;
3078
+ if (isUpload) {
3079
+ const parsedContentLength = parseContentLengthHeader(headers);
3080
+ if (parsedContentLength.kind === "error") result = badRequestJson(parsedContentLength.message);
3081
+ else {
3082
+ const uploadBody = await readUploadBody(request.body ?? /* @__PURE__ */ new Uint8Array(0), parsedContentLength.kind === "ok" ? parsedContentLength.expectedLength : null);
3083
+ result = "error" in uploadBody ? uploadBody.error : await this.sim.handleUpload(url, headers, uploadBody.data);
3084
+ }
3085
+ } else {
3086
+ let body = null;
3087
+ if (request.body) {
3088
+ const text = typeof request.body === "string" ? request.body : await new Response(request.body).text();
3089
+ try {
3090
+ body = JSON.parse(text);
3091
+ } catch {
3092
+ body = text;
3093
+ }
3094
+ } else if (request.method.toUpperCase() === "GET" && require_partner.isPartnerQueryEndpoint(apiPathParts(parsedUrl.pathname).endpoint)) body = queryParamsBody(parsedUrl.searchParams);
3095
+ result = await this.sim.handleRequest(request.method, parsedUrl.origin, parsedUrl.pathname, headers, body);
3096
+ }
3097
+ const responseBody = JSON.stringify(result.body);
3098
+ return {
3099
+ status: result.status,
3100
+ headers: new Headers({ "Content-Type": "application/json" }),
3101
+ body: new ReadableStream({ start(controller) {
3102
+ controller.enqueue(require_text_codec.utf8Encoder.encode(responseBody));
3103
+ controller.close();
3104
+ } }),
3105
+ json: () => Promise.resolve(result.body),
3106
+ text: () => Promise.resolve(responseBody),
3107
+ arrayBuffer: () => Promise.resolve(require_text_codec.utf8Encoder.encode(responseBody).buffer)
3108
+ };
3109
+ }
3110
+ };
3111
+ //#endregion
1558
3112
  exports.B2Simulator = B2Simulator;
1559
- //# sourceMappingURL=index.cjs.map
3113
+ exports.BUCKET_INFO_MAX_KEYS = require_validation.BUCKET_INFO_MAX_KEYS;
3114
+ exports.BUCKET_INFO_VALUE_MAX = require_validation.BUCKET_INFO_VALUE_MAX;
3115
+ exports.BUCKET_NAME_MAX = require_b2_naming.BUCKET_NAME_MAX;
3116
+ exports.BUCKET_NAME_MIN = require_b2_naming.BUCKET_NAME_MIN;
3117
+ exports.DOWNLOAD_AUTH_DURATION_MAX_SECONDS = require_validation.DOWNLOAD_AUTH_DURATION_MAX_SECONDS;
3118
+ exports.DOWNLOAD_AUTH_DURATION_MIN_SECONDS = require_validation.DOWNLOAD_AUTH_DURATION_MIN_SECONDS;
3119
+ exports.FILE_INFO_TOTAL_MAX = require_validation.FILE_INFO_TOTAL_MAX;
3120
+ exports.FILE_INFO_VALUE_MAX = require_validation.FILE_INFO_VALUE_MAX;
3121
+ exports.FILE_NAME_MAX_BYTES = require_b2_naming.FILE_NAME_MAX_BYTES;
3122
+ exports.KEY_NAME_MAX = require_validation.KEY_NAME_MAX;
3123
+ exports.KEY_NAME_MIN = require_validation.KEY_NAME_MIN;
3124
+ exports.LIST_ENDPOINT_CAPS = require_validation.LIST_ENDPOINT_CAPS;
3125
+
3126
+ //# sourceMappingURL=index.cjs.map