@open-e2ee/signal-protocol-sdk 2.0.2 → 4.0.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 (576) hide show
  1. package/ADAPTERS.md +14 -21
  2. package/ARCHITECTURE.md +1 -2
  3. package/CHANGELOG.md +90 -0
  4. package/LICENSE +11 -655
  5. package/LICENSE-APACHE +201 -0
  6. package/LICENSE-MIT +21 -0
  7. package/NOTICE +5 -7
  8. package/README.md +11 -11
  9. package/SECURITY.md +2 -2
  10. package/TROUBLESHOOTING.md +6 -10
  11. package/client/README.md +36 -18
  12. package/device/README.md +1 -1
  13. package/dist/blocking/manager.d.ts +2 -2
  14. package/dist/blocking/manager.d.ts.map +1 -1
  15. package/dist/blocking/manager.js.map +1 -1
  16. package/dist/client/client.d.ts +45 -34
  17. package/dist/client/client.d.ts.map +1 -1
  18. package/dist/client/client.js +178 -115
  19. package/dist/client/client.js.map +1 -1
  20. package/dist/client/compose.d.ts +7 -7
  21. package/dist/client/compose.d.ts.map +1 -1
  22. package/dist/client/compose.js +2 -2
  23. package/dist/client/compose.js.map +1 -1
  24. package/dist/client/config.d.ts +24 -28
  25. package/dist/client/config.d.ts.map +1 -1
  26. package/dist/client/config.js.map +1 -1
  27. package/dist/client/content-adapter.d.ts +2 -0
  28. package/dist/client/content-adapter.d.ts.map +1 -1
  29. package/dist/client/content-adapter.js +4 -0
  30. package/dist/client/content-adapter.js.map +1 -1
  31. package/dist/client/dual-store.d.ts +5 -5
  32. package/dist/client/dual-store.d.ts.map +1 -1
  33. package/dist/client/dual-store.js.map +1 -1
  34. package/dist/client/endorsement-manager.d.ts +6 -3
  35. package/dist/client/endorsement-manager.d.ts.map +1 -1
  36. package/dist/client/endorsement-manager.js +14 -6
  37. package/dist/client/endorsement-manager.js.map +1 -1
  38. package/dist/client/files.d.ts +1 -1
  39. package/dist/client/files.js +1 -1
  40. package/dist/client/group-authority.d.ts +8 -0
  41. package/dist/client/group-authority.d.ts.map +1 -0
  42. package/dist/client/group-authority.js +2 -0
  43. package/dist/client/group-authority.js.map +1 -0
  44. package/dist/client/group-outbox.d.ts +4 -4
  45. package/dist/client/group-outbox.d.ts.map +1 -1
  46. package/dist/client/group-sealed-sender.d.ts +2 -2
  47. package/dist/client/group-sealed-sender.d.ts.map +1 -1
  48. package/dist/client/groups.d.ts +1 -1
  49. package/dist/client/groups.js +1 -1
  50. package/dist/client/headless.d.ts +11 -16
  51. package/dist/client/headless.d.ts.map +1 -1
  52. package/dist/client/headless.js +4 -9
  53. package/dist/client/headless.js.map +1 -1
  54. package/dist/client/hosted-anonymous-delivery.d.ts +32 -0
  55. package/dist/client/hosted-anonymous-delivery.d.ts.map +1 -0
  56. package/dist/client/hosted-anonymous-delivery.js +239 -0
  57. package/dist/client/hosted-anonymous-delivery.js.map +1 -0
  58. package/dist/client/hosted-connection.d.ts +1 -1
  59. package/dist/client/hosted-connection.d.ts.map +1 -1
  60. package/dist/client/hosted-connection.js +18 -51
  61. package/dist/client/hosted-connection.js.map +1 -1
  62. package/dist/client/hosted-group-authority.d.ts +11 -0
  63. package/dist/client/hosted-group-authority.d.ts.map +1 -0
  64. package/dist/client/hosted-group-authority.js +96 -0
  65. package/dist/client/hosted-group-authority.js.map +1 -0
  66. package/dist/client/hosted-groups.d.ts +31 -0
  67. package/dist/client/hosted-groups.d.ts.map +1 -0
  68. package/dist/client/hosted-groups.js +217 -0
  69. package/dist/client/hosted-groups.js.map +1 -0
  70. package/dist/client/hosted-mailbox-subscription.d.ts +34 -0
  71. package/dist/client/hosted-mailbox-subscription.d.ts.map +1 -0
  72. package/dist/client/hosted-mailbox-subscription.js +257 -0
  73. package/dist/client/hosted-mailbox-subscription.js.map +1 -0
  74. package/dist/client/hosted-prekey-publication.d.ts +51 -0
  75. package/dist/client/hosted-prekey-publication.d.ts.map +1 -0
  76. package/dist/client/hosted-prekey-publication.js +249 -0
  77. package/dist/client/hosted-prekey-publication.js.map +1 -0
  78. package/dist/client/hosted-push.d.ts +5 -6
  79. package/dist/client/hosted-push.d.ts.map +1 -1
  80. package/dist/client/hosted-push.js +22 -22
  81. package/dist/client/hosted-push.js.map +1 -1
  82. package/dist/client/hosted-transport.d.ts +62 -40
  83. package/dist/client/hosted-transport.d.ts.map +1 -1
  84. package/dist/client/hosted-transport.js +666 -341
  85. package/dist/client/hosted-transport.js.map +1 -1
  86. package/dist/client/hosted-trust.d.ts +29 -0
  87. package/dist/client/hosted-trust.d.ts.map +1 -0
  88. package/dist/client/hosted-trust.js +28 -0
  89. package/dist/client/hosted-trust.js.map +1 -0
  90. package/dist/client/hosted.d.ts +26 -21
  91. package/dist/client/hosted.d.ts.map +1 -1
  92. package/dist/client/hosted.js +80 -36
  93. package/dist/client/hosted.js.map +1 -1
  94. package/dist/client/index.d.ts +15 -15
  95. package/dist/client/index.d.ts.map +1 -1
  96. package/dist/client/index.js +7 -7
  97. package/dist/client/index.js.map +1 -1
  98. package/dist/client/key-rotation-core.d.ts +16 -8
  99. package/dist/client/key-rotation-core.d.ts.map +1 -1
  100. package/dist/client/key-rotation-core.js +14 -3
  101. package/dist/client/key-rotation-core.js.map +1 -1
  102. package/dist/client/key-rotation.d.ts +3 -2
  103. package/dist/client/key-rotation.d.ts.map +1 -1
  104. package/dist/client/key-rotation.js +5 -5
  105. package/dist/client/key-rotation.js.map +1 -1
  106. package/dist/client/media-queue-persistence.d.ts +14 -0
  107. package/dist/client/media-queue-persistence.d.ts.map +1 -0
  108. package/dist/client/media-queue-persistence.js +123 -0
  109. package/dist/client/media-queue-persistence.js.map +1 -0
  110. package/dist/client/media-upload-budget.d.ts +3 -0
  111. package/dist/client/media-upload-budget.d.ts.map +1 -0
  112. package/dist/client/media-upload-budget.js +27 -0
  113. package/dist/client/media-upload-budget.js.map +1 -0
  114. package/dist/client/media.d.ts +51 -15
  115. package/dist/client/media.d.ts.map +1 -1
  116. package/dist/client/media.js +541 -73
  117. package/dist/client/media.js.map +1 -1
  118. package/dist/client/messages.d.ts +1 -1
  119. package/dist/client/messages.d.ts.map +1 -1
  120. package/dist/client/messages.js +14 -15
  121. package/dist/client/messages.js.map +1 -1
  122. package/dist/client/multi-device.d.ts +1 -1
  123. package/dist/client/multi-device.js +1 -1
  124. package/dist/client/prekeys.d.ts +1 -1
  125. package/dist/client/prekeys.d.ts.map +1 -1
  126. package/dist/client/prekeys.js +132 -44
  127. package/dist/client/prekeys.js.map +1 -1
  128. package/dist/client/relay-subscription.d.ts +5 -1
  129. package/dist/client/relay-subscription.d.ts.map +1 -1
  130. package/dist/client/relay-subscription.js +59 -26
  131. package/dist/client/relay-subscription.js.map +1 -1
  132. package/dist/client/retry.d.ts +3 -3
  133. package/dist/client/retry.d.ts.map +1 -1
  134. package/dist/client/retry.js +1 -1
  135. package/dist/client/retry.js.map +1 -1
  136. package/dist/client/sealed-sender.d.ts +5 -5
  137. package/dist/client/sealed-sender.d.ts.map +1 -1
  138. package/dist/client/sealed-sender.js.map +1 -1
  139. package/dist/client/sender-key-distribution.d.ts +8 -0
  140. package/dist/client/sender-key-distribution.d.ts.map +1 -0
  141. package/dist/client/sender-key-distribution.js +59 -0
  142. package/dist/client/sender-key-distribution.js.map +1 -0
  143. package/dist/client/sessions.d.ts +3 -3
  144. package/dist/client/sessions.d.ts.map +1 -1
  145. package/dist/client/sessions.js +1 -1
  146. package/dist/client/sessions.js.map +1 -1
  147. package/dist/client/signal-service-cipher.d.ts +12 -8
  148. package/dist/client/signal-service-cipher.d.ts.map +1 -1
  149. package/dist/client/signal-service-cipher.js +41 -16
  150. package/dist/client/signal-service-cipher.js.map +1 -1
  151. package/dist/client/state.d.ts +1 -1
  152. package/dist/client/state.js +1 -1
  153. package/dist/client/types.d.ts +10 -10
  154. package/dist/client/types.d.ts.map +1 -1
  155. package/dist/client/types.js +1 -1
  156. package/dist/device/connection.d.ts.map +1 -1
  157. package/dist/device/connection.js.map +1 -1
  158. package/dist/device/device-id.d.ts +2 -2
  159. package/dist/device/device-id.d.ts.map +1 -1
  160. package/dist/device/device-id.js.map +1 -1
  161. package/dist/device/{expo-metadata.d.ts → expo/index.d.ts} +3 -3
  162. package/dist/device/expo/index.d.ts.map +1 -0
  163. package/dist/device/{expo-metadata.js → expo/index.js} +2 -2
  164. package/dist/device/expo/index.js.map +1 -0
  165. package/dist/device/index.d.ts +1 -1
  166. package/dist/device/index.d.ts.map +1 -1
  167. package/dist/device/index.js +1 -1
  168. package/dist/device/index.js.map +1 -1
  169. package/dist/device/lifecycle/index.d.ts +1 -1
  170. package/dist/device/lifecycle/index.d.ts.map +1 -1
  171. package/dist/device/lifecycle/types.d.ts +8 -8
  172. package/dist/device/lifecycle/types.d.ts.map +1 -1
  173. package/dist/device/provisioning.d.ts +13 -13
  174. package/dist/device/provisioning.d.ts.map +1 -1
  175. package/dist/device/provisioning.js +1 -1
  176. package/dist/device/provisioning.js.map +1 -1
  177. package/dist/device/transfer.d.ts +13 -13
  178. package/dist/device/transfer.d.ts.map +1 -1
  179. package/dist/device/transfer.js.map +1 -1
  180. package/dist/device/types.d.ts +3 -3
  181. package/dist/device/types.d.ts.map +1 -1
  182. package/dist/groups/index.d.ts +1 -1
  183. package/dist/groups/index.d.ts.map +1 -1
  184. package/dist/groups/server.d.ts +10 -0
  185. package/dist/groups/server.d.ts.map +1 -0
  186. package/dist/groups/server.js +6 -0
  187. package/dist/groups/server.js.map +1 -0
  188. package/dist/hooks/use-connection-presence.d.ts +6 -8
  189. package/dist/hooks/use-connection-presence.d.ts.map +1 -1
  190. package/dist/hooks/use-connection-presence.js +2 -4
  191. package/dist/hooks/use-connection-presence.js.map +1 -1
  192. package/dist/hooks/use-group-membership.d.ts +2 -2
  193. package/dist/hooks/use-group-membership.d.ts.map +1 -1
  194. package/dist/hooks/use-group-membership.js.map +1 -1
  195. package/dist/hooks/use-key-rotation.d.ts +2 -2
  196. package/dist/hooks/use-key-rotation.d.ts.map +1 -1
  197. package/dist/hooks/use-session-health.d.ts +2 -2
  198. package/dist/hooks/use-session-health.d.ts.map +1 -1
  199. package/dist/index.d.ts +57 -55
  200. package/dist/index.d.ts.map +1 -1
  201. package/dist/index.js +27 -26
  202. package/dist/index.js.map +1 -1
  203. package/dist/internal/crypto/ec/x25519-validation.d.ts +4 -4
  204. package/dist/internal/crypto/ec/x25519-validation.d.ts.map +1 -1
  205. package/dist/internal/crypto/ec/x25519-validation.js.map +1 -1
  206. package/dist/internal/groups/authority-certificate.d.ts +22 -0
  207. package/dist/internal/groups/authority-certificate.d.ts.map +1 -0
  208. package/dist/internal/groups/authority-certificate.js +99 -0
  209. package/dist/internal/groups/authority-certificate.js.map +1 -0
  210. package/dist/internal/groups/error-details.d.ts +9 -0
  211. package/dist/internal/groups/error-details.d.ts.map +1 -0
  212. package/dist/internal/groups/error-details.js +30 -0
  213. package/dist/internal/groups/error-details.js.map +1 -0
  214. package/dist/internal/groups/index.d.ts +1 -1
  215. package/dist/internal/groups/index.d.ts.map +1 -1
  216. package/dist/internal/groups/manager.d.ts +9 -4
  217. package/dist/internal/groups/manager.d.ts.map +1 -1
  218. package/dist/internal/groups/manager.js +3 -0
  219. package/dist/internal/groups/manager.js.map +1 -1
  220. package/dist/internal/groups/sdk-store.d.ts +4 -4
  221. package/dist/internal/groups/sdk-store.d.ts.map +1 -1
  222. package/dist/internal/groups/sdk-store.js.map +1 -1
  223. package/dist/internal/groups/server-engine.d.ts +9 -2
  224. package/dist/internal/groups/server-engine.d.ts.map +1 -1
  225. package/dist/internal/groups/server-engine.js +51 -19
  226. package/dist/internal/groups/server-engine.js.map +1 -1
  227. package/dist/internal/groups/wire.d.ts.map +1 -1
  228. package/dist/internal/groups/wire.js +10 -9
  229. package/dist/internal/groups/wire.js.map +1 -1
  230. package/dist/internal/manager/index.d.ts +2 -2
  231. package/dist/internal/manager/index.d.ts.map +1 -1
  232. package/dist/internal/manager/index.js +1 -1
  233. package/dist/internal/manager/index.js.map +1 -1
  234. package/dist/internal/manager/manager.d.ts +23 -23
  235. package/dist/internal/manager/manager.d.ts.map +1 -1
  236. package/dist/internal/manager/manager.js +40 -43
  237. package/dist/internal/manager/manager.js.map +1 -1
  238. package/dist/internal/protocol/double-ratchet/chains.d.ts +9 -9
  239. package/dist/internal/protocol/double-ratchet/chains.d.ts.map +1 -1
  240. package/dist/internal/protocol/double-ratchet/chains.js.map +1 -1
  241. package/dist/internal/protocol/double-ratchet/ratchet.d.ts +2 -2
  242. package/dist/internal/protocol/double-ratchet/ratchet.d.ts.map +1 -1
  243. package/dist/internal/protocol/double-ratchet/ratchet.js.map +1 -1
  244. package/dist/internal/protocol/pqxdh/pqxdh.d.ts +3 -3
  245. package/dist/internal/protocol/pqxdh/pqxdh.d.ts.map +1 -1
  246. package/dist/internal/protocol/pqxdh/pqxdh.js.map +1 -1
  247. package/dist/internal/protocol/sender-keys/manager.d.ts +4 -4
  248. package/dist/internal/protocol/sender-keys/manager.d.ts.map +1 -1
  249. package/dist/internal/protocol/sender-keys/manager.js +27 -14
  250. package/dist/internal/protocol/sender-keys/manager.js.map +1 -1
  251. package/dist/internal/protocol/spqr/ml-kem-braid/authenticator.d.ts +3 -3
  252. package/dist/internal/protocol/spqr/ml-kem-braid/authenticator.d.ts.map +1 -1
  253. package/dist/internal/protocol/spqr/ml-kem-braid/incremental-kem.d.ts +3 -3
  254. package/dist/internal/protocol/spqr/ml-kem-braid/incremental-kem.d.ts.map +1 -1
  255. package/dist/internal/protocol/spqr/ml-kem-braid/index.d.ts +2 -2
  256. package/dist/internal/protocol/spqr/ml-kem-braid/index.d.ts.map +1 -1
  257. package/dist/internal/protocol/spqr/ml-kem-braid/index.js +1 -1
  258. package/dist/internal/protocol/spqr/ml-kem-braid/index.js.map +1 -1
  259. package/dist/internal/protocol/spqr/ml-kem-braid/state-machine.d.ts +3 -3
  260. package/dist/internal/protocol/spqr/ml-kem-braid/state-machine.d.ts.map +1 -1
  261. package/dist/internal/protocol/spqr/ml-kem-braid/state-machine.js +2 -2
  262. package/dist/internal/protocol/spqr/ml-kem-braid/state-machine.js.map +1 -1
  263. package/dist/internal/protocol/spqr/ml-kem-braid/types.d.ts +3 -3
  264. package/dist/internal/protocol/spqr/ml-kem-braid/types.d.ts.map +1 -1
  265. package/dist/internal/protocol/spqr/spqr.d.ts +5 -5
  266. package/dist/internal/protocol/spqr/spqr.d.ts.map +1 -1
  267. package/dist/internal/protocol/spqr/spqr.js.map +1 -1
  268. package/dist/internal/protocol/triple-ratchet/ratchet.d.ts +4 -4
  269. package/dist/internal/protocol/triple-ratchet/ratchet.d.ts.map +1 -1
  270. package/dist/internal/protocol/triple-ratchet/ratchet.js.map +1 -1
  271. package/dist/internal/protocol/x3dh/x3dh.d.ts +3 -3
  272. package/dist/internal/protocol/x3dh/x3dh.d.ts.map +1 -1
  273. package/dist/internal/protocol/x3dh/x3dh.js.map +1 -1
  274. package/dist/internal/sesame/device-registry.d.ts +16 -16
  275. package/dist/internal/sesame/device-registry.d.ts.map +1 -1
  276. package/dist/internal/sesame/device-registry.js +6 -6
  277. package/dist/internal/sesame/device-registry.js.map +1 -1
  278. package/dist/internal/sesame/index.d.ts +4 -4
  279. package/dist/internal/sesame/index.d.ts.map +1 -1
  280. package/dist/internal/sesame/index.js +2 -2
  281. package/dist/internal/sesame/index.js.map +1 -1
  282. package/dist/internal/sesame/manager.d.ts +10 -10
  283. package/dist/internal/sesame/manager.d.ts.map +1 -1
  284. package/dist/internal/sesame/manager.js +13 -13
  285. package/dist/internal/sesame/manager.js.map +1 -1
  286. package/dist/internal/sesame/types.d.ts +5 -5
  287. package/dist/internal/sesame/types.d.ts.map +1 -1
  288. package/dist/internal/session/cipher.d.ts +4 -4
  289. package/dist/internal/session/cipher.d.ts.map +1 -1
  290. package/dist/internal/session/cipher.js +31 -28
  291. package/dist/internal/session/cipher.js.map +1 -1
  292. package/dist/internal/session/decryption.js.map +1 -1
  293. package/dist/internal/session/factory.d.ts +3 -3
  294. package/dist/internal/session/factory.d.ts.map +1 -1
  295. package/dist/internal/session/factory.js.map +1 -1
  296. package/dist/internal/session/handshake.d.ts +2 -2
  297. package/dist/internal/session/handshake.d.ts.map +1 -1
  298. package/dist/internal/session/handshake.js.map +1 -1
  299. package/dist/internal/session/ratchet.d.ts +4 -4
  300. package/dist/internal/session/ratchet.d.ts.map +1 -1
  301. package/dist/internal/session/ratchet.js.map +1 -1
  302. package/dist/internal/session/types.d.ts +5 -5
  303. package/dist/internal/session/types.d.ts.map +1 -1
  304. package/dist/internal/session/validation.d.ts +3 -3
  305. package/dist/internal/session/validation.d.ts.map +1 -1
  306. package/dist/internal/session/validation.js.map +1 -1
  307. package/dist/layers.d.ts +4 -4
  308. package/dist/layers.d.ts.map +1 -1
  309. package/dist/layers.js +12 -12
  310. package/dist/layers.js.map +1 -1
  311. package/dist/local/store/expo/adapter.d.ts +15 -9
  312. package/dist/local/store/expo/adapter.d.ts.map +1 -1
  313. package/dist/local/store/expo/adapter.js +29 -10
  314. package/dist/local/store/expo/adapter.js.map +1 -1
  315. package/dist/local/store/expo/database-key.d.ts +5 -5
  316. package/dist/local/store/expo/database-key.d.ts.map +1 -1
  317. package/dist/local/store/expo/database-key.js.map +1 -1
  318. package/dist/local/store/expo/index.d.ts +3 -3
  319. package/dist/local/store/expo/index.d.ts.map +1 -1
  320. package/dist/local/store/expo/key-storage.d.ts +11 -5
  321. package/dist/local/store/expo/key-storage.d.ts.map +1 -1
  322. package/dist/local/store/expo/key-storage.js +82 -17
  323. package/dist/local/store/expo/key-storage.js.map +1 -1
  324. package/dist/local/store/expo/models/kyber-prekey-used.d.ts +1 -4
  325. package/dist/local/store/expo/models/kyber-prekey-used.d.ts.map +1 -1
  326. package/dist/local/store/expo/models/kyber-prekey-used.js +23 -9
  327. package/dist/local/store/expo/models/kyber-prekey-used.js.map +1 -1
  328. package/dist/local/store/expo/models/kyber-prekey.d.ts +4 -4
  329. package/dist/local/store/expo/models/kyber-prekey.d.ts.map +1 -1
  330. package/dist/local/store/expo/models/kyber-prekey.js +67 -26
  331. package/dist/local/store/expo/models/kyber-prekey.js.map +1 -1
  332. package/dist/local/store/expo/schema.d.ts +21 -2
  333. package/dist/local/store/expo/schema.d.ts.map +1 -1
  334. package/dist/local/store/expo/schema.js +10 -2
  335. package/dist/local/store/expo/schema.js.map +1 -1
  336. package/dist/local/store/index.d.ts +3 -3
  337. package/dist/local/store/index.d.ts.map +1 -1
  338. package/dist/local/store/index.js +1 -1
  339. package/dist/local/store/kyber-prekey-lifecycle.d.ts +46 -0
  340. package/dist/local/store/kyber-prekey-lifecycle.d.ts.map +1 -0
  341. package/dist/local/store/kyber-prekey-lifecycle.js +88 -0
  342. package/dist/local/store/kyber-prekey-lifecycle.js.map +1 -0
  343. package/dist/local/store/memory/adapter.d.ts +14 -6
  344. package/dist/local/store/memory/adapter.d.ts.map +1 -1
  345. package/dist/local/store/memory/adapter.js +114 -29
  346. package/dist/local/store/memory/adapter.js.map +1 -1
  347. package/dist/local/store/node/adapter.d.ts +9 -3
  348. package/dist/local/store/node/adapter.d.ts.map +1 -1
  349. package/dist/local/store/node/adapter.js +31 -13
  350. package/dist/local/store/node/adapter.js.map +1 -1
  351. package/dist/local/store/node/database-file-commit.d.ts +8 -0
  352. package/dist/local/store/node/database-file-commit.d.ts.map +1 -0
  353. package/dist/local/store/node/database-file-commit.js +62 -0
  354. package/dist/local/store/node/database-file-commit.js.map +1 -0
  355. package/dist/local/store/node/database-key.d.ts +6 -1
  356. package/dist/local/store/node/database-key.d.ts.map +1 -1
  357. package/dist/local/store/node/database-key.js +79 -44
  358. package/dist/local/store/node/database-key.js.map +1 -1
  359. package/dist/local/store/node/database-lock.d.ts +8 -0
  360. package/dist/local/store/node/database-lock.d.ts.map +1 -0
  361. package/dist/local/store/node/database-lock.js +44 -0
  362. package/dist/local/store/node/database-lock.js.map +1 -0
  363. package/dist/local/store/node/database.d.ts +17 -16
  364. package/dist/local/store/node/database.d.ts.map +1 -1
  365. package/dist/local/store/node/database.js +197 -202
  366. package/dist/local/store/node/database.js.map +1 -1
  367. package/dist/local/store/react-native/adapter.d.ts +10 -4
  368. package/dist/local/store/react-native/adapter.d.ts.map +1 -1
  369. package/dist/local/store/react-native/adapter.js +151 -66
  370. package/dist/local/store/react-native/adapter.js.map +1 -1
  371. package/dist/local/store/received-content.d.ts +9 -0
  372. package/dist/local/store/received-content.d.ts.map +1 -0
  373. package/dist/local/store/received-content.js +46 -0
  374. package/dist/local/store/received-content.js.map +1 -0
  375. package/dist/local/store/reliability.d.ts +4 -4
  376. package/dist/local/store/reliability.d.ts.map +1 -1
  377. package/dist/local/store/reliability.js +7 -4
  378. package/dist/local/store/reliability.js.map +1 -1
  379. package/dist/local/store/web/adapter.d.ts +11 -5
  380. package/dist/local/store/web/adapter.d.ts.map +1 -1
  381. package/dist/local/store/web/adapter.js +207 -74
  382. package/dist/local/store/web/adapter.js.map +1 -1
  383. package/dist/local/vault/expo-secure-store.d.ts +2 -2
  384. package/dist/local/vault/expo-secure-store.d.ts.map +1 -1
  385. package/dist/local/vault/index.d.ts +1 -1
  386. package/dist/local/vault/index.d.ts.map +1 -1
  387. package/dist/logger.d.ts +4 -4
  388. package/dist/logger.d.ts.map +1 -1
  389. package/dist/logger.js.map +1 -1
  390. package/dist/media/index.d.ts +71 -61
  391. package/dist/media/index.d.ts.map +1 -1
  392. package/dist/media/index.js +550 -386
  393. package/dist/media/index.js.map +1 -1
  394. package/dist/media/prepared-upload.d.ts +37 -0
  395. package/dist/media/prepared-upload.d.ts.map +1 -0
  396. package/dist/media/prepared-upload.js +46 -0
  397. package/dist/media/prepared-upload.js.map +1 -0
  398. package/dist/profile/contact-state.d.ts +2 -2
  399. package/dist/profile/contact-state.d.ts.map +1 -1
  400. package/dist/profile/contact-state.js.map +1 -1
  401. package/dist/profile/profile-key.d.ts +2 -2
  402. package/dist/profile/profile-key.d.ts.map +1 -1
  403. package/dist/profile/profile-key.js.map +1 -1
  404. package/dist/profile/update-service.d.ts +2 -2
  405. package/dist/profile/update-service.d.ts.map +1 -1
  406. package/dist/profile/update-service.js.map +1 -1
  407. package/dist/remote/object-store/convex-r2/server.d.ts +2 -1
  408. package/dist/remote/object-store/convex-r2/server.d.ts.map +1 -1
  409. package/dist/remote/object-store/convex-r2/server.js +4 -0
  410. package/dist/remote/object-store/convex-r2/server.js.map +1 -1
  411. package/dist/remote/object-store/convex-r2/storage.d.ts.map +1 -1
  412. package/dist/remote/object-store/convex-r2/storage.js +1 -0
  413. package/dist/remote/object-store/convex-r2/storage.js.map +1 -1
  414. package/dist/remote/object-store/index.d.ts +3 -1
  415. package/dist/remote/object-store/index.d.ts.map +1 -1
  416. package/dist/remote/object-store/index.js +1 -1
  417. package/dist/remote/object-store/index.js.map +1 -1
  418. package/dist/remote/object-store/s3/storage.d.ts +3 -1
  419. package/dist/remote/object-store/s3/storage.d.ts.map +1 -1
  420. package/dist/remote/object-store/s3/storage.js +9 -2
  421. package/dist/remote/object-store/s3/storage.js.map +1 -1
  422. package/dist/remote/object-store/types.d.ts +33 -4
  423. package/dist/remote/object-store/types.d.ts.map +1 -1
  424. package/dist/remote/object-store/upload-error.d.ts +23 -0
  425. package/dist/remote/object-store/upload-error.d.ts.map +1 -0
  426. package/dist/remote/object-store/upload-error.js +33 -0
  427. package/dist/remote/object-store/upload-error.js.map +1 -0
  428. package/dist/remote/object-store/validation.d.ts +7 -1
  429. package/dist/remote/object-store/validation.d.ts.map +1 -1
  430. package/dist/remote/object-store/validation.js +39 -25
  431. package/dist/remote/object-store/validation.js.map +1 -1
  432. package/dist/remote/relay/index.d.ts +7 -14
  433. package/dist/remote/relay/index.d.ts.map +1 -1
  434. package/dist/remote/relay/index.js +6 -13
  435. package/dist/remote/relay/index.js.map +1 -1
  436. package/dist/remote/relay/memory/adapter.d.ts +5 -4
  437. package/dist/remote/relay/memory/adapter.d.ts.map +1 -1
  438. package/dist/remote/relay/memory/adapter.js +14 -4
  439. package/dist/remote/relay/memory/adapter.js.map +1 -1
  440. package/dist/remote/relay/types.d.ts +36 -25
  441. package/dist/remote/relay/types.d.ts.map +1 -1
  442. package/dist/remote/relay/types.js +1 -1
  443. package/dist/types/api.d.ts +59 -24
  444. package/dist/types/api.d.ts.map +1 -1
  445. package/dist/types/index.js +1 -1
  446. package/dist/types/index.js.map +1 -1
  447. package/dist/types/session.d.ts +6 -0
  448. package/dist/types/session.d.ts.map +1 -1
  449. package/dist/types/session.js.map +1 -1
  450. package/docs/ASSURANCE.md +7 -7
  451. package/docs/CLIENT_COMPOSITION.md +16 -23
  452. package/docs/DEVIATIONS.md +1 -1
  453. package/docs/DOCUMENTATION_STANDARDS.md +4 -0
  454. package/docs/ERROR_HANDLING.md +2 -2
  455. package/docs/GETTING_STARTED.md +23 -38
  456. package/docs/INTERFACES.md +36 -27
  457. package/docs/PACKAGE_SURFACE.md +9 -16
  458. package/docs/RECIPES.md +10 -23
  459. package/examples/browser/index.html +2 -2
  460. package/groups/README.md +4 -4
  461. package/local/store/README.md +22 -7
  462. package/local/store/expo/README.md +24 -20
  463. package/local/store/memory/README.md +1 -1
  464. package/local/store/node/README.md +31 -2
  465. package/local/store/react-native/README.md +1 -1
  466. package/local/store/web/README.md +1 -1
  467. package/local/vault/README.md +1 -1
  468. package/media/README.md +94 -0
  469. package/package.json +17 -27
  470. package/remote/README.md +24 -24
  471. package/remote/object-store/README.md +8 -0
  472. package/remote/object-store/s3/README.md +10 -1
  473. package/remote/relay/README.md +4 -3
  474. package/remote/relay/memory/README.md +1 -1
  475. package/types/README.md +2 -2
  476. package/COMMERCIAL.md +0 -56
  477. package/dist/device/expo-metadata.d.ts.map +0 -1
  478. package/dist/device/expo-metadata.js.map +0 -1
  479. package/dist/remote/relay/convex/backend.d.ts +0 -394
  480. package/dist/remote/relay/convex/backend.d.ts.map +0 -1
  481. package/dist/remote/relay/convex/backend.js +0 -678
  482. package/dist/remote/relay/convex/backend.js.map +0 -1
  483. package/dist/remote/relay/convex/component/_generated/api.d.ts +0 -58
  484. package/dist/remote/relay/convex/component/_generated/api.d.ts.map +0 -1
  485. package/dist/remote/relay/convex/component/_generated/api.js +0 -31
  486. package/dist/remote/relay/convex/component/_generated/api.js.map +0 -1
  487. package/dist/remote/relay/convex/component/_generated/component.d.ts +0 -475
  488. package/dist/remote/relay/convex/component/_generated/component.d.ts.map +0 -1
  489. package/dist/remote/relay/convex/component/_generated/component.js +0 -11
  490. package/dist/remote/relay/convex/component/_generated/component.js.map +0 -1
  491. package/dist/remote/relay/convex/component/_generated/dataModel.d.ts +0 -46
  492. package/dist/remote/relay/convex/component/_generated/dataModel.d.ts.map +0 -1
  493. package/dist/remote/relay/convex/component/_generated/dataModel.js +0 -11
  494. package/dist/remote/relay/convex/component/_generated/dataModel.js.map +0 -1
  495. package/dist/remote/relay/convex/component/_generated/server.d.ts +0 -129
  496. package/dist/remote/relay/convex/component/_generated/server.d.ts.map +0 -1
  497. package/dist/remote/relay/convex/component/_generated/server.js +0 -79
  498. package/dist/remote/relay/convex/component/_generated/server.js.map +0 -1
  499. package/dist/remote/relay/convex/component/accounts.d.ts +0 -45
  500. package/dist/remote/relay/convex/component/accounts.d.ts.map +0 -1
  501. package/dist/remote/relay/convex/component/accounts.js +0 -184
  502. package/dist/remote/relay/convex/component/accounts.js.map +0 -1
  503. package/dist/remote/relay/convex/component/certificates.d.ts +0 -10
  504. package/dist/remote/relay/convex/component/certificates.d.ts.map +0 -1
  505. package/dist/remote/relay/convex/component/certificates.js +0 -126
  506. package/dist/remote/relay/convex/component/certificates.js.map +0 -1
  507. package/dist/remote/relay/convex/component/cleanup.d.ts +0 -32
  508. package/dist/remote/relay/convex/component/cleanup.d.ts.map +0 -1
  509. package/dist/remote/relay/convex/component/cleanup.js +0 -146
  510. package/dist/remote/relay/convex/component/cleanup.js.map +0 -1
  511. package/dist/remote/relay/convex/component/convex.config.d.ts +0 -5
  512. package/dist/remote/relay/convex/component/convex.config.d.ts.map +0 -1
  513. package/dist/remote/relay/convex/component/convex.config.js +0 -35
  514. package/dist/remote/relay/convex/component/convex.config.js.map +0 -1
  515. package/dist/remote/relay/convex/component/crons.d.ts +0 -3
  516. package/dist/remote/relay/convex/component/crons.d.ts.map +0 -1
  517. package/dist/remote/relay/convex/component/crons.js +0 -10
  518. package/dist/remote/relay/convex/component/crons.js.map +0 -1
  519. package/dist/remote/relay/convex/component/devices.d.ts +0 -102
  520. package/dist/remote/relay/convex/component/devices.d.ts.map +0 -1
  521. package/dist/remote/relay/convex/component/devices.js +0 -300
  522. package/dist/remote/relay/convex/component/devices.js.map +0 -1
  523. package/dist/remote/relay/convex/component/errors.d.ts +0 -22
  524. package/dist/remote/relay/convex/component/errors.d.ts.map +0 -1
  525. package/dist/remote/relay/convex/component/errors.js +0 -17
  526. package/dist/remote/relay/convex/component/errors.js.map +0 -1
  527. package/dist/remote/relay/convex/component/groups.d.ts +0 -63
  528. package/dist/remote/relay/convex/component/groups.d.ts.map +0 -1
  529. package/dist/remote/relay/convex/component/groups.js +0 -341
  530. package/dist/remote/relay/convex/component/groups.js.map +0 -1
  531. package/dist/remote/relay/convex/component/keys.d.ts +0 -130
  532. package/dist/remote/relay/convex/component/keys.d.ts.map +0 -1
  533. package/dist/remote/relay/convex/component/keys.js +0 -578
  534. package/dist/remote/relay/convex/component/keys.js.map +0 -1
  535. package/dist/remote/relay/convex/component/messages.d.ts +0 -105
  536. package/dist/remote/relay/convex/component/messages.d.ts.map +0 -1
  537. package/dist/remote/relay/convex/component/messages.js +0 -702
  538. package/dist/remote/relay/convex/component/messages.js.map +0 -1
  539. package/dist/remote/relay/convex/component/provisioning.d.ts +0 -92
  540. package/dist/remote/relay/convex/component/provisioning.d.ts.map +0 -1
  541. package/dist/remote/relay/convex/component/provisioning.js +0 -360
  542. package/dist/remote/relay/convex/component/provisioning.js.map +0 -1
  543. package/dist/remote/relay/convex/component/runtime.d.ts +0 -18
  544. package/dist/remote/relay/convex/component/runtime.d.ts.map +0 -1
  545. package/dist/remote/relay/convex/component/runtime.js +0 -144
  546. package/dist/remote/relay/convex/component/runtime.js.map +0 -1
  547. package/dist/remote/relay/convex/component/schema.d.ts +0 -358
  548. package/dist/remote/relay/convex/component/schema.d.ts.map +0 -1
  549. package/dist/remote/relay/convex/component/schema.js +0 -288
  550. package/dist/remote/relay/convex/component/schema.js.map +0 -1
  551. package/dist/remote/relay/convex/component/zkAuth.d.ts +0 -18
  552. package/dist/remote/relay/convex/component/zkAuth.d.ts.map +0 -1
  553. package/dist/remote/relay/convex/component/zkAuth.js +0 -86
  554. package/dist/remote/relay/convex/component/zkAuth.js.map +0 -1
  555. package/dist/remote/relay/convex/constants.d.ts +0 -3
  556. package/dist/remote/relay/convex/constants.d.ts.map +0 -1
  557. package/dist/remote/relay/convex/constants.js +0 -3
  558. package/dist/remote/relay/convex/constants.js.map +0 -1
  559. package/dist/remote/relay/convex/group-server.d.ts +0 -123
  560. package/dist/remote/relay/convex/group-server.d.ts.map +0 -1
  561. package/dist/remote/relay/convex/group-server.js +0 -184
  562. package/dist/remote/relay/convex/group-server.js.map +0 -1
  563. package/dist/remote/relay/convex/index.d.ts +0 -42
  564. package/dist/remote/relay/convex/index.d.ts.map +0 -1
  565. package/dist/remote/relay/convex/index.js +0 -38
  566. package/dist/remote/relay/convex/index.js.map +0 -1
  567. package/dist/remote/relay/convex/relay.d.ts +0 -323
  568. package/dist/remote/relay/convex/relay.d.ts.map +0 -1
  569. package/dist/remote/relay/convex/relay.js +0 -1144
  570. package/dist/remote/relay/convex/relay.js.map +0 -1
  571. package/dist/remote/relay/convex/types.d.ts +0 -24
  572. package/dist/remote/relay/convex/types.d.ts.map +0 -1
  573. package/dist/remote/relay/convex/types.js +0 -14
  574. package/dist/remote/relay/convex/types.js.map +0 -1
  575. package/remote/relay/convex/README.md +0 -61
  576. package/remote/relay/convex/component/README.md +0 -462
@@ -5,10 +5,12 @@
5
5
  * live in a remote object store. The pointer, key, and integrity metadata
6
6
  * travel inside an end-to-end encrypted application message.
7
7
  */
8
- import { base64ToBytes, bytesToBase64, bytesToUrlSafeBase64, concatBytes, constantTimeEqual, generateRandomBytes, secureZeroBytes, sha256, streamingDecrypt, streamingEncrypt, } from '../internal/crypto/index.js';
9
- import { toBase64 } from '../types/utils.js';
8
+ import { base64ToBytes, bytesToBase64, bytesToUrlSafeBase64, concatBytes, constantTimeEqual, generateRandomBytes, secureZeroBytes, sha256, streamingDecrypt, streamingEncrypt, urlSafeToBase64, } from "../internal/crypto/index.js";
9
+ import { RemoteObjectUploadError } from "../remote/object-store/index.js";
10
+ import { matchesUploadReceipt } from "../remote/object-store/validation.js";
11
+ import { toBase64 } from "../types/utils.js";
10
12
  export const MediaAttachmentMessageType = {
11
- Attachment: 'attachment',
13
+ Attachment: "attachment",
12
14
  };
13
15
  export const MediaAttachmentFlag = {
14
16
  VoiceMessage: 1,
@@ -25,22 +27,24 @@ const KNOWN_MEDIA_ATTACHMENT_FLAG_VALUES = new Set([
25
27
  MediaAttachmentFlag.VoiceMessage + MediaAttachmentFlag.Borderless,
26
28
  MediaAttachmentFlag.VoiceMessage + MediaAttachmentFlag.Gif,
27
29
  MediaAttachmentFlag.Borderless + MediaAttachmentFlag.Gif,
28
- MediaAttachmentFlag.VoiceMessage + MediaAttachmentFlag.Borderless + MediaAttachmentFlag.Gif,
30
+ MediaAttachmentFlag.VoiceMessage +
31
+ MediaAttachmentFlag.Borderless +
32
+ MediaAttachmentFlag.Gif,
29
33
  ]);
30
34
  const UUID_PATTERN = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
31
35
  export function isMediaAttachmentFlagSet(value) {
32
- return (typeof value === 'number' &&
36
+ return (typeof value === "number" &&
33
37
  Number.isSafeInteger(value) &&
34
38
  KNOWN_MEDIA_ATTACHMENT_FLAG_VALUES.has(value));
35
39
  }
36
40
  function hexByte(value) {
37
- return value.toString(16).padStart(2, '0');
41
+ return value.toString(16).padStart(2, "0");
38
42
  }
39
43
  async function generateMediaAttachmentClientUuid() {
40
44
  const bytes = await generateRandomBytes(16);
41
45
  bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
42
46
  bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
43
- const hex = Array.from(bytes, hexByte).join('');
47
+ const hex = Array.from(bytes, hexByte).join("");
44
48
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
45
49
  }
46
50
  /** @internal */
@@ -49,31 +53,31 @@ export async function generateMediaAttachmentUploadRequestId() {
49
53
  return `media-upload/${bytesToUrlSafeBase64(bytes)}`;
50
54
  }
51
55
  export const MediaAttachmentErrorCode = {
52
- UploadFailed: 'upload-failed',
53
- UploadIdentityChanged: 'upload-identity-changed',
54
- DownloadFailed: 'download-failed',
55
- Cancelled: 'cancelled',
56
- DeleteUnavailable: 'delete-unavailable',
57
- DeleteFailed: 'delete-failed',
58
- BlobNotFound: 'blob-not-found',
59
- ResumeStateInvalid: 'resume-state-invalid',
60
- JobHandlerMissing: 'job-handler-missing',
61
- PolicyViolation: 'policy-violation',
62
- InvalidPointer: 'invalid-pointer',
63
- CiphertextSizeMismatch: 'ciphertext-size-mismatch',
64
- DigestMismatch: 'digest-mismatch',
65
- DecryptionFailed: 'decryption-failed',
66
- PlaintextSizeMismatch: 'plaintext-size-mismatch',
56
+ UploadFailed: "upload-failed",
57
+ UploadIdentityChanged: "upload-identity-changed",
58
+ DownloadFailed: "download-failed",
59
+ Cancelled: "cancelled",
60
+ DeleteUnavailable: "delete-unavailable",
61
+ DeleteFailed: "delete-failed",
62
+ BlobNotFound: "blob-not-found",
63
+ ResumeStateInvalid: "resume-state-invalid",
64
+ JobHandlerMissing: "job-handler-missing",
65
+ PolicyViolation: "policy-violation",
66
+ InvalidPointer: "invalid-pointer",
67
+ CiphertextSizeMismatch: "ciphertext-size-mismatch",
68
+ DigestMismatch: "digest-mismatch",
69
+ DecryptionFailed: "decryption-failed",
70
+ PlaintextSizeMismatch: "plaintext-size-mismatch",
67
71
  };
68
72
  export class MediaAttachmentError extends Error {
69
73
  code;
70
74
  status;
71
75
  constructor(message, code, options) {
72
76
  super(message);
73
- this.name = 'MediaAttachmentError';
77
+ this.name = "MediaAttachmentError";
74
78
  this.code = code;
75
79
  this.status = options?.status;
76
- if (options && 'cause' in options) {
80
+ if (options && "cause" in options) {
77
81
  this.cause = options.cause;
78
82
  }
79
83
  }
@@ -91,67 +95,67 @@ export const MEDIA_ATTACHMENT_POLICY_DEFAULTS = {
91
95
  };
92
96
  export const MEDIA_ATTACHMENT_POLICY_PRESETS = {
93
97
  Image: {
94
- allowedContentTypes: ['image/*'],
98
+ allowedContentTypes: ["image/*"],
95
99
  maxPlaintextSizeBytes: 25 * 1024 * 1024,
96
100
  maxCiphertextSizeBytes: 32 * 1024 * 1024,
97
101
  maxThumbnailBytes: 256 * 1024,
98
102
  },
99
103
  Video: {
100
- allowedContentTypes: ['video/*'],
104
+ allowedContentTypes: ["video/*"],
101
105
  maxPlaintextSizeBytes: 100 * 1024 * 1024,
102
106
  maxCiphertextSizeBytes: 128 * 1024 * 1024,
103
107
  maxDurationMs: 4 * 60 * 60 * 1_000,
104
108
  maxThumbnailBytes: 512 * 1024,
105
109
  },
106
110
  Audio: {
107
- allowedContentTypes: ['audio/*'],
111
+ allowedContentTypes: ["audio/*"],
108
112
  maxPlaintextSizeBytes: 100 * 1024 * 1024,
109
113
  maxCiphertextSizeBytes: 128 * 1024 * 1024,
110
114
  maxDurationMs: 4 * 60 * 60 * 1_000,
111
115
  maxWaveformSamples: 4_096,
112
116
  },
113
117
  Document: {
114
- allowedContentTypes: ['application/pdf', 'text/*'],
118
+ allowedContentTypes: ["application/pdf", "text/*"],
115
119
  maxPlaintextSizeBytes: 50 * 1024 * 1024,
116
120
  maxCiphertextSizeBytes: 64 * 1024 * 1024,
117
121
  },
118
122
  };
119
123
  export const MediaAttachmentCleanupReason = {
120
- ViewOnceOpened: 'view-once-opened',
121
- MessageDeleted: 'message-deleted',
122
- MessageExpired: 'message-expired',
123
- OrphanedUpload: 'orphaned-upload',
124
+ ViewOnceOpened: "view-once-opened",
125
+ MessageDeleted: "message-deleted",
126
+ MessageExpired: "message-expired",
127
+ OrphanedUpload: "orphaned-upload",
124
128
  };
125
129
  export const MediaAttachmentJobOperation = {
126
- Upload: 'upload',
127
- Download: 'download',
128
- DeleteLocal: 'delete-local',
129
- DeleteRemote: 'delete-remote',
130
- SyncDelete: 'sync-delete',
130
+ Upload: "upload",
131
+ Download: "download",
132
+ DeleteLocal: "delete-local",
133
+ DeleteRemote: "delete-remote",
134
+ SyncDelete: "sync-delete",
131
135
  };
132
136
  export const MediaAttachmentJobSource = {
133
- ComposePreUpload: 'compose-pre-upload',
134
- IncomingMessage: 'incoming-message',
135
- SentSync: 'sent-sync',
136
- UserAction: 'user-action',
137
- Retry: 'retry',
138
- BackgroundRecovery: 'background-recovery',
139
- MessageDeleted: 'message-deleted',
140
- MessageExpired: 'message-expired',
141
- OrphanCleanup: 'orphan-cleanup',
142
- LinkedDeviceSync: 'linked-device-sync',
137
+ ComposePreUpload: "compose-pre-upload",
138
+ IncomingMessage: "incoming-message",
139
+ SentSync: "sent-sync",
140
+ UserAction: "user-action",
141
+ Retry: "retry",
142
+ BackgroundRecovery: "background-recovery",
143
+ MessageDeleted: "message-deleted",
144
+ MessageExpired: "message-expired",
145
+ OrphanCleanup: "orphan-cleanup",
146
+ LinkedDeviceSync: "linked-device-sync",
143
147
  };
144
148
  export const MediaAttachmentJobPriority = {
145
- High: 'high',
146
- Normal: 'normal',
147
- Low: 'low',
149
+ High: "high",
150
+ Normal: "normal",
151
+ Low: "low",
148
152
  };
149
153
  export const MediaAttachmentJobExecutionStatus = {
150
- Completed: 'completed',
151
- Skipped: 'skipped',
154
+ Completed: "completed",
155
+ Skipped: "skipped",
152
156
  };
153
157
  function assertString(value, field) {
154
- if (typeof value !== 'string' || value.length === 0) {
158
+ if (typeof value !== "string" || value.length === 0) {
155
159
  throw new TypeError(`Invalid media attachment pointer: ${field} must be a non-empty string`);
156
160
  }
157
161
  }
@@ -176,7 +180,9 @@ function assertBase64String(value, field) {
176
180
  }
177
181
  function assertInteger(value, field, options) {
178
182
  const min = options?.allowZero ? 0 : 1;
179
- if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min) {
183
+ if (typeof value !== "number" ||
184
+ !Number.isSafeInteger(value) ||
185
+ value < min) {
180
186
  throw new TypeError(`Invalid media attachment pointer: ${field} must be an integer >= ${min}`);
181
187
  }
182
188
  }
@@ -193,7 +199,7 @@ function assertPolicy(condition, message) {
193
199
  }
194
200
  }
195
201
  function assertMetadataString(value, field) {
196
- assertPolicy(typeof value === 'string' && value.length > 0, `Media attachment ${field} must be a non-empty string`);
202
+ assertPolicy(typeof value === "string" && value.length > 0, `Media attachment ${field} must be a non-empty string`);
197
203
  }
198
204
  function assertOptionalMetadataString(value, field) {
199
205
  if (value === undefined)
@@ -204,24 +210,27 @@ function assertOptionalMetadataInteger(value, field, options) {
204
210
  if (value === undefined)
205
211
  return;
206
212
  const min = options?.allowZero ? 0 : 1;
207
- assertPolicy(typeof value === 'number' && Number.isSafeInteger(value) && value >= min, `Media attachment ${field} must be an integer >= ${min}`);
213
+ assertPolicy(typeof value === "number" && Number.isSafeInteger(value) && value >= min, `Media attachment ${field} must be an integer >= ${min}`);
208
214
  }
209
215
  function assertOptionalMetadataBoolean(value, field) {
210
216
  if (value === undefined)
211
217
  return;
212
- assertPolicy(typeof value === 'boolean', `Media attachment ${field} must be a boolean`);
218
+ assertPolicy(typeof value === "boolean", `Media attachment ${field} must be a boolean`);
213
219
  }
214
220
  function assertOptionalMetadataWaveform(value) {
215
221
  if (value === undefined)
216
222
  return;
217
223
  assertPolicy(Array.isArray(value) &&
218
- value.every((sample) => typeof sample === 'number' && Number.isSafeInteger(sample) && sample >= 0 && sample <= 255), 'Media attachment waveform must contain integer samples from 0 to 255');
224
+ value.every((sample) => typeof sample === "number" &&
225
+ Number.isSafeInteger(sample) &&
226
+ sample >= 0 &&
227
+ sample <= 255), "Media attachment waveform must contain integer samples from 0 to 255");
219
228
  }
220
229
  function isContentTypeAllowed(contentType, allowedContentTypes) {
221
230
  if (allowedContentTypes.length === 0)
222
231
  return true;
223
232
  return allowedContentTypes.some((allowed) => {
224
- if (allowed.endsWith('/*')) {
233
+ if (allowed.endsWith("/*")) {
225
234
  return contentType.startsWith(`${allowed.slice(0, -2)}/`);
226
235
  }
227
236
  return contentType === allowed;
@@ -229,37 +238,43 @@ function isContentTypeAllowed(contentType, allowedContentTypes) {
229
238
  }
230
239
  function validateMediaAttachmentMetadata(input, policy) {
231
240
  const resolvedPolicy = resolvePolicy(policy);
232
- assertMetadataString(input.contentType, 'contentType');
233
- assertOptionalMetadataString(input.fileName, 'fileName');
234
- assertOptionalMetadataString(input.caption, 'caption');
235
- assertOptionalMetadataString(input.blurHash, 'blurHash');
236
- assertOptionalMetadataString(input.thumbnail, 'thumbnail');
237
- assertOptionalMetadataString(input.clientUuid, 'clientUuid');
238
- assertOptionalMetadataInteger(input.size, 'size', { allowZero: true });
239
- assertOptionalMetadataInteger(input.ciphertextSize, 'ciphertextSize');
240
- assertOptionalMetadataInteger(input.width, 'width');
241
- assertOptionalMetadataInteger(input.height, 'height');
242
- assertOptionalMetadataInteger(input.durationMs, 'durationMs', {
241
+ assertMetadataString(input.contentType, "contentType");
242
+ assertOptionalMetadataString(input.fileName, "fileName");
243
+ assertOptionalMetadataString(input.caption, "caption");
244
+ assertOptionalMetadataString(input.blurHash, "blurHash");
245
+ assertOptionalMetadataString(input.thumbnail, "thumbnail");
246
+ assertOptionalMetadataString(input.clientUuid, "clientUuid");
247
+ assertOptionalMetadataInteger(input.size, "size", { allowZero: true });
248
+ assertOptionalMetadataInteger(input.ciphertextSize, "ciphertextSize");
249
+ assertOptionalMetadataInteger(input.width, "width");
250
+ assertOptionalMetadataInteger(input.height, "height");
251
+ assertOptionalMetadataInteger(input.durationMs, "durationMs", {
243
252
  allowZero: true,
244
253
  });
245
- assertOptionalMetadataInteger(input.flags, 'flags', { allowZero: true });
246
- assertOptionalMetadataInteger(input.cdnNumber, 'cdnNumber');
247
- assertOptionalMetadataBoolean(input.isViewOnce, 'isViewOnce');
254
+ assertOptionalMetadataInteger(input.flags, "flags", { allowZero: true });
255
+ assertOptionalMetadataInteger(input.cdnNumber, "cdnNumber");
256
+ assertOptionalMetadataBoolean(input.isViewOnce, "isViewOnce");
248
257
  assertOptionalMetadataWaveform(input.waveform);
249
- assertPolicy(input.clientUuid === undefined || UUID_PATTERN.test(input.clientUuid), 'Media attachment clientUuid must be a UUID string');
250
- assertPolicy(input.flags === undefined || isMediaAttachmentFlagSet(input.flags), 'Media attachment flags contains unknown media flag bits');
251
- assertPolicy(input.size === undefined || input.size <= resolvedPolicy.maxPlaintextSizeBytes, `Media attachment plaintext size ${input.size} exceeds limit ${resolvedPolicy.maxPlaintextSizeBytes}`);
258
+ assertPolicy(input.clientUuid === undefined || UUID_PATTERN.test(input.clientUuid), "Media attachment clientUuid must be a UUID string");
259
+ assertPolicy(input.flags === undefined || isMediaAttachmentFlagSet(input.flags), "Media attachment flags contains unknown media flag bits");
260
+ assertPolicy(input.size === undefined ||
261
+ input.size <= resolvedPolicy.maxPlaintextSizeBytes, `Media attachment plaintext size ${input.size} exceeds limit ${resolvedPolicy.maxPlaintextSizeBytes}`);
252
262
  assertPolicy(input.ciphertextSize === undefined ||
253
263
  input.ciphertextSize <= resolvedPolicy.maxCiphertextSizeBytes, `Media attachment ciphertext size ${input.ciphertextSize} exceeds limit ${resolvedPolicy.maxCiphertextSizeBytes}`);
254
264
  assertPolicy(isContentTypeAllowed(input.contentType, resolvedPolicy.allowedContentTypes), `Media attachment content type ${input.contentType} is not allowed`);
255
- assertPolicy(input.fileName === undefined || input.fileName.length <= resolvedPolicy.maxFileNameLength, `Media attachment file name exceeds limit ${resolvedPolicy.maxFileNameLength}`);
256
- assertPolicy(input.caption === undefined || input.caption.length <= resolvedPolicy.maxCaptionLength, `Media attachment caption exceeds limit ${resolvedPolicy.maxCaptionLength}`);
265
+ assertPolicy(input.fileName === undefined ||
266
+ input.fileName.length <= resolvedPolicy.maxFileNameLength, `Media attachment file name exceeds limit ${resolvedPolicy.maxFileNameLength}`);
267
+ assertPolicy(input.caption === undefined ||
268
+ input.caption.length <= resolvedPolicy.maxCaptionLength, `Media attachment caption exceeds limit ${resolvedPolicy.maxCaptionLength}`);
257
269
  assertPolicy(input.width === undefined || input.width <= resolvedPolicy.maxWidth, `Media attachment width ${input.width} exceeds limit ${resolvedPolicy.maxWidth}`);
258
270
  assertPolicy(input.height === undefined || input.height <= resolvedPolicy.maxHeight, `Media attachment height ${input.height} exceeds limit ${resolvedPolicy.maxHeight}`);
259
- assertPolicy(input.durationMs === undefined || input.durationMs <= resolvedPolicy.maxDurationMs, `Media attachment duration ${input.durationMs} exceeds limit ${resolvedPolicy.maxDurationMs}`);
271
+ assertPolicy(input.durationMs === undefined ||
272
+ input.durationMs <= resolvedPolicy.maxDurationMs, `Media attachment duration ${input.durationMs} exceeds limit ${resolvedPolicy.maxDurationMs}`);
260
273
  assertPolicy(input.thumbnail === undefined ||
261
- getBase64ByteLength(input.thumbnail, 'thumbnail') <= resolvedPolicy.maxThumbnailBytes, `Media attachment thumbnail exceeds limit ${resolvedPolicy.maxThumbnailBytes}`);
262
- assertPolicy(input.waveform === undefined || input.waveform.length <= resolvedPolicy.maxWaveformSamples, `Media attachment waveform exceeds limit ${resolvedPolicy.maxWaveformSamples}`);
274
+ getBase64ByteLength(input.thumbnail, "thumbnail") <=
275
+ resolvedPolicy.maxThumbnailBytes, `Media attachment thumbnail exceeds limit ${resolvedPolicy.maxThumbnailBytes}`);
276
+ assertPolicy(input.waveform === undefined ||
277
+ input.waveform.length <= resolvedPolicy.maxWaveformSamples, `Media attachment waveform exceeds limit ${resolvedPolicy.maxWaveformSamples}`);
263
278
  }
264
279
  export function validateMediaAttachmentPolicy(attachment, policy) {
265
280
  const pointer = createMediaAttachmentPointer(attachment);
@@ -277,9 +292,9 @@ function copyOptionalClientUuid(target, source) {
277
292
  const value = source.clientUuid;
278
293
  if (value === undefined)
279
294
  return;
280
- assertString(value, 'clientUuid');
295
+ assertString(value, "clientUuid");
281
296
  if (!UUID_PATTERN.test(value)) {
282
- throw new TypeError('Invalid media attachment pointer: clientUuid must be a UUID string');
297
+ throw new TypeError("Invalid media attachment pointer: clientUuid must be a UUID string");
283
298
  }
284
299
  target.clientUuid = value;
285
300
  }
@@ -287,8 +302,8 @@ function copyOptionalThumbnail(target, source) {
287
302
  const value = source.thumbnail;
288
303
  if (value === undefined)
289
304
  return;
290
- assertString(value, 'thumbnail');
291
- assertBase64String(value, 'thumbnail');
305
+ assertString(value, "thumbnail");
306
+ assertBase64String(value, "thumbnail");
292
307
  target.thumbnail = value;
293
308
  }
294
309
  function getBase64ByteLength(value, field) {
@@ -303,16 +318,16 @@ function copyOptionalInteger(target, source, field) {
303
318
  const value = source[field];
304
319
  if (value === undefined)
305
320
  return;
306
- assertInteger(value, field, { allowZero: field === 'durationMs' });
321
+ assertInteger(value, field, { allowZero: field === "durationMs" });
307
322
  target[field] = value;
308
323
  }
309
324
  function copyOptionalFlags(target, source) {
310
325
  const value = source.flags;
311
326
  if (value === undefined)
312
327
  return;
313
- assertInteger(value, 'flags', { allowZero: true });
328
+ assertInteger(value, "flags", { allowZero: true });
314
329
  if (!isMediaAttachmentFlagSet(value)) {
315
- throw new TypeError('Invalid media attachment pointer: flags contains unknown media flag bits');
330
+ throw new TypeError("Invalid media attachment pointer: flags contains unknown media flag bits");
316
331
  }
317
332
  target.flags = value;
318
333
  }
@@ -320,22 +335,25 @@ function copyOptionalWaveform(target, source) {
320
335
  if (source.waveform === undefined)
321
336
  return;
322
337
  if (!Array.isArray(source.waveform) ||
323
- !source.waveform.every((sample) => typeof sample === 'number' && Number.isInteger(sample) && sample >= 0 && sample <= 255)) {
324
- throw new TypeError('Invalid media attachment pointer: waveform must contain integer samples from 0 to 255');
338
+ !source.waveform.every((sample) => typeof sample === "number" &&
339
+ Number.isInteger(sample) &&
340
+ sample >= 0 &&
341
+ sample <= 255)) {
342
+ throw new TypeError("Invalid media attachment pointer: waveform must contain integer samples from 0 to 255");
325
343
  }
326
344
  target.waveform = [...source.waveform];
327
345
  }
328
346
  export function createMediaAttachmentPointer(input) {
329
- assertString(input.storageId, 'storageId');
330
- assertString(input.key, 'key');
331
- assertString(input.digest, 'digest');
332
- assertBase64ByteLength(input.key, 'key', MEDIA_ATTACHMENT_KEY_BYTES);
333
- assertBase64ByteLength(input.digest, 'digest', MEDIA_ATTACHMENT_DIGEST_BYTES);
334
- assertString(input.contentType, 'contentType');
335
- assertInteger(input.segmentSize, 'segmentSize');
336
- assertInteger(input.ciphertextSize, 'ciphertextSize');
337
- assertInteger(input.size, 'size', { allowZero: true });
338
- assertInteger(input.uploadTimestamp, 'uploadTimestamp');
347
+ assertString(input.storageId, "storageId");
348
+ assertString(input.key, "key");
349
+ assertString(input.digest, "digest");
350
+ assertBase64ByteLength(input.key, "key", MEDIA_ATTACHMENT_KEY_BYTES);
351
+ assertBase64ByteLength(input.digest, "digest", MEDIA_ATTACHMENT_DIGEST_BYTES);
352
+ assertString(input.contentType, "contentType");
353
+ assertInteger(input.segmentSize, "segmentSize");
354
+ assertInteger(input.ciphertextSize, "ciphertextSize");
355
+ assertInteger(input.size, "size", { allowZero: true });
356
+ assertInteger(input.uploadTimestamp, "uploadTimestamp");
339
357
  const pointer = {
340
358
  version: 1,
341
359
  storageId: input.storageId,
@@ -347,20 +365,29 @@ export function createMediaAttachmentPointer(input) {
347
365
  size: input.size,
348
366
  uploadTimestamp: input.uploadTimestamp,
349
367
  };
368
+ if (input.readCapability !== undefined) {
369
+ if (!/^[A-Za-z0-9_-]{43}$/.test(input.readCapability))
370
+ throw new TypeError("The attachment read capability is invalid.");
371
+ const capability = base64ToBytes(toBase64(urlSafeToBase64(input.readCapability)));
372
+ if (capability.length !== 32 ||
373
+ bytesToUrlSafeBase64(capability) !== input.readCapability)
374
+ throw new TypeError("The attachment read capability is invalid.");
375
+ pointer.readCapability = input.readCapability;
376
+ }
350
377
  copyOptionalClientUuid(pointer, input);
351
- copyOptionalString(pointer, input, 'blurHash');
378
+ copyOptionalString(pointer, input, "blurHash");
352
379
  copyOptionalThumbnail(pointer, input);
353
- copyOptionalString(pointer, input, 'fileName');
354
- copyOptionalString(pointer, input, 'caption');
355
- copyOptionalInteger(pointer, input, 'cdnNumber');
356
- copyOptionalInteger(pointer, input, 'width');
357
- copyOptionalInteger(pointer, input, 'height');
358
- copyOptionalInteger(pointer, input, 'durationMs');
380
+ copyOptionalString(pointer, input, "fileName");
381
+ copyOptionalString(pointer, input, "caption");
382
+ copyOptionalInteger(pointer, input, "cdnNumber");
383
+ copyOptionalInteger(pointer, input, "width");
384
+ copyOptionalInteger(pointer, input, "height");
385
+ copyOptionalInteger(pointer, input, "durationMs");
359
386
  copyOptionalFlags(pointer, input);
360
387
  copyOptionalWaveform(pointer, input);
361
388
  if (input.isViewOnce !== undefined) {
362
- if (typeof input.isViewOnce !== 'boolean') {
363
- throw new TypeError('Invalid media attachment pointer: isViewOnce must be a boolean');
389
+ if (typeof input.isViewOnce !== "boolean") {
390
+ throw new TypeError("Invalid media attachment pointer: isViewOnce must be a boolean");
364
391
  }
365
392
  pointer.isViewOnce = input.isViewOnce;
366
393
  }
@@ -372,34 +399,34 @@ function encodeAttachmentIdentityPart(value) {
372
399
  export function createMediaAttachmentId(attachment) {
373
400
  const pointer = createMediaAttachmentPointer(attachment);
374
401
  return [
375
- 'media-v1',
402
+ "media-v1",
376
403
  encodeAttachmentIdentityPart(pointer.storageId),
377
404
  pointer.ciphertextSize,
378
405
  encodeAttachmentIdentityPart(pointer.digest),
379
- ].join('.');
406
+ ].join(".");
380
407
  }
381
408
  export function createMediaAttachmentDeliveryId(input) {
382
- assertString(input.senderUserId, 'senderUserId');
383
- assertInteger(input.timestamp, 'timestamp');
409
+ assertString(input.senderUserId, "senderUserId");
410
+ assertInteger(input.timestamp, "timestamp");
384
411
  return [
385
- 'media-delivery-v1',
412
+ "media-delivery-v1",
386
413
  encodeAttachmentIdentityPart(input.senderUserId),
387
414
  input.timestamp,
388
415
  createMediaAttachmentId(input.attachment),
389
- ].join('.');
416
+ ].join(".");
390
417
  }
391
418
  function knownIdsIncludes(ids, id) {
392
419
  if (!ids)
393
420
  return false;
394
421
  const candidate = ids;
395
- if (typeof candidate.has === 'function') {
422
+ if (typeof candidate.has === "function") {
396
423
  return candidate.has(id);
397
424
  }
398
425
  return ids.includes(id);
399
426
  }
400
427
  function assertMediaAttachmentCleanupReason(reason) {
401
428
  if (!isMediaAttachmentCleanupReason(reason)) {
402
- throw new TypeError('Invalid media attachment cleanup reason');
429
+ throw new TypeError("Invalid media attachment cleanup reason");
403
430
  }
404
431
  }
405
432
  function isMediaAttachmentCleanupReason(value) {
@@ -410,32 +437,32 @@ function isMediaAttachmentCleanupReason(value) {
410
437
  }
411
438
  function assertMediaAttachmentJobSource(source) {
412
439
  if (!Object.values(MediaAttachmentJobSource).includes(source)) {
413
- throw new TypeError('Invalid media attachment job source');
440
+ throw new TypeError("Invalid media attachment job source");
414
441
  }
415
442
  }
416
443
  function assertMediaAttachmentJobPriority(priority) {
417
444
  if (!Object.values(MediaAttachmentJobPriority).includes(priority)) {
418
- throw new TypeError('Invalid media attachment job priority');
445
+ throw new TypeError("Invalid media attachment job priority");
419
446
  }
420
447
  }
421
448
  function createMediaAttachmentBackgroundJob(input) {
422
- assertString(input.attachmentId, 'attachmentId');
449
+ assertString(input.attachmentId, "attachmentId");
423
450
  assertMediaAttachmentJobSource(input.source);
424
451
  const priority = input.priority ?? MediaAttachmentJobPriority.Normal;
425
452
  assertMediaAttachmentJobPriority(priority);
426
453
  const attempt = input.attempt ?? 0;
427
454
  const createdAt = input.createdAt ?? Date.now();
428
455
  const notBefore = input.notBefore ?? createdAt;
429
- assertInteger(attempt, 'attempt', { allowZero: true });
430
- assertInteger(createdAt, 'createdAt', { allowZero: true });
431
- assertInteger(notBefore, 'notBefore', { allowZero: true });
456
+ assertInteger(attempt, "attempt", { allowZero: true });
457
+ assertInteger(createdAt, "createdAt", { allowZero: true });
458
+ assertInteger(notBefore, "notBefore", { allowZero: true });
432
459
  const jobId = [
433
- 'media-job-v1',
460
+ "media-job-v1",
434
461
  input.operation,
435
462
  encodeAttachmentIdentityPart(input.attachmentId),
436
- input.deliveryId ? encodeAttachmentIdentityPart(input.deliveryId) : 'none',
437
- input.reason ? encodeAttachmentIdentityPart(input.reason) : 'none',
438
- ].join('.');
463
+ input.deliveryId ? encodeAttachmentIdentityPart(input.deliveryId) : "none",
464
+ input.reason ? encodeAttachmentIdentityPart(input.reason) : "none",
465
+ ].join(".");
439
466
  return {
440
467
  jobId,
441
468
  operation: input.operation,
@@ -453,9 +480,9 @@ function createMediaAttachmentBackgroundJob(input) {
453
480
  };
454
481
  }
455
482
  export function planMediaAttachmentUploadJob(input) {
456
- assertString(input.localMediaId, 'localMediaId');
457
- assertString(input.contentType, 'contentType');
458
- assertInteger(input.size, 'size', { allowZero: true });
483
+ assertString(input.localMediaId, "localMediaId");
484
+ assertString(input.contentType, "contentType");
485
+ assertInteger(input.size, "size", { allowZero: true });
459
486
  validateMediaAttachmentMetadata({
460
487
  contentType: input.contentType,
461
488
  size: input.size,
@@ -550,8 +577,8 @@ export function planMediaAttachmentCleanupJobs(input) {
550
577
  }
551
578
  export function planMediaAttachmentOpen(input) {
552
579
  const attachment = createMediaAttachmentPointer(input.attachment);
553
- assertString(input.senderUserId, 'senderUserId');
554
- assertInteger(input.timestamp, 'timestamp');
580
+ assertString(input.senderUserId, "senderUserId");
581
+ assertInteger(input.timestamp, "timestamp");
555
582
  if (!attachment.isViewOnce) {
556
583
  return {
557
584
  attachment,
@@ -572,8 +599,8 @@ export function planMediaAttachmentOpen(input) {
572
599
  }
573
600
  export function planMediaAttachmentProcessing(input) {
574
601
  const attachment = createMediaAttachmentPointer(input.attachment);
575
- assertString(input.senderUserId, 'senderUserId');
576
- assertInteger(input.timestamp, 'timestamp');
602
+ assertString(input.senderUserId, "senderUserId");
603
+ assertInteger(input.timestamp, "timestamp");
577
604
  const attachmentId = createMediaAttachmentId(attachment);
578
605
  const deliveryId = createMediaAttachmentDeliveryId({
579
606
  attachment,
@@ -582,12 +609,13 @@ export function planMediaAttachmentProcessing(input) {
582
609
  });
583
610
  const isDuplicateDelivery = knownIdsIncludes(input.processedDeliveryIds, deliveryId);
584
611
  const hasLocalCopy = knownIdsIncludes(input.cachedAttachmentIds, attachmentId);
585
- const isViewOnceOpened = attachment.isViewOnce === true && knownIdsIncludes(input.openedViewOnceDeliveryIds, deliveryId);
612
+ const isViewOnceOpened = attachment.isViewOnce === true &&
613
+ knownIdsIncludes(input.openedViewOnceDeliveryIds, deliveryId);
586
614
  const shouldDownload = !hasLocalCopy && !isViewOnceOpened;
587
615
  const downloadReason = shouldDownload
588
616
  ? isDuplicateDelivery
589
- ? 'duplicate-missing-local-copy'
590
- : 'new-delivery'
617
+ ? "duplicate-missing-local-copy"
618
+ : "new-delivery"
591
619
  : null;
592
620
  return {
593
621
  attachment,
@@ -632,7 +660,7 @@ export function planMediaAttachmentDownloadJob(input) {
632
660
  }).downloadJob;
633
661
  }
634
662
  export function planMediaAttachmentDeleteSync(input) {
635
- assertInteger(input.deletedAt, 'deletedAt');
663
+ assertInteger(input.deletedAt, "deletedAt");
636
664
  assertMediaAttachmentCleanupReason(input.reason);
637
665
  const attachment = createMediaAttachmentPointer(input.attachment);
638
666
  return {
@@ -662,19 +690,27 @@ function skippedMediaAttachmentJob(job, skipReason) {
662
690
  };
663
691
  }
664
692
  async function loadRequiredAttachmentPointer(job, options) {
665
- const loadAttachmentPointer = requireMediaAttachmentJobHandler(options.loadAttachmentPointer, 'loadAttachmentPointer', job.operation);
693
+ const loadAttachmentPointer = requireMediaAttachmentJobHandler(options.loadAttachmentPointer, "loadAttachmentPointer", job.operation);
666
694
  const attachment = await loadAttachmentPointer(job);
667
695
  return attachment ? createMediaAttachmentPointer(attachment) : null;
668
696
  }
669
697
  export async function executeMediaAttachmentJob(job, options) {
670
698
  switch (job.operation) {
671
699
  case MediaAttachmentJobOperation.Upload: {
672
- const loadUploadData = requireMediaAttachmentJobHandler(options.loadUploadData, 'loadUploadData', job.operation);
700
+ const completed = await options.loadUploadedAttachment?.(job);
701
+ if (completed) {
702
+ const attachment = createMediaAttachmentPointer(completed);
703
+ await options.saveUploadedAttachment?.(job, attachment);
704
+ return completedMediaAttachmentJob(job, {
705
+ uploadedAttachment: attachment,
706
+ });
707
+ }
708
+ const loadUploadData = requireMediaAttachmentJobHandler(options.loadUploadData, "loadUploadData", job.operation);
673
709
  const uploadData = await loadUploadData(job);
674
710
  if (!uploadData) {
675
- return skippedMediaAttachmentJob(job, 'missing-upload-data');
711
+ return skippedMediaAttachmentJob(job, "missing-upload-data");
676
712
  }
677
- const attachment = await prepareMediaAttachmentUpload(uploadData.data, {
713
+ const uploadOptions = {
678
714
  ...uploadData.options,
679
715
  remoteObjectStore: options.remoteObjectStore,
680
716
  transfer: uploadData.options?.transfer ?? options.transfer,
@@ -684,7 +720,10 @@ export async function executeMediaAttachmentJob(job, options) {
684
720
  onProgress: uploadData.options?.onProgress ?? options.onProgress,
685
721
  onCheckpoint: uploadData.options?.onCheckpoint ?? options.onCheckpoint,
686
722
  resume: uploadData.options?.resume ?? job.resume,
687
- });
723
+ };
724
+ const attachment = uploadData.prepared
725
+ ? await uploadPreparedMediaAttachment(uploadData.prepared, uploadOptions)
726
+ : await prepareMediaAttachmentUpload(uploadData.data, uploadOptions);
688
727
  await options.saveUploadedAttachment?.(job, attachment);
689
728
  return completedMediaAttachmentJob(job, {
690
729
  uploadedAttachment: attachment,
@@ -693,7 +732,7 @@ export async function executeMediaAttachmentJob(job, options) {
693
732
  case MediaAttachmentJobOperation.Download: {
694
733
  const attachment = await loadRequiredAttachmentPointer(job, options);
695
734
  if (!attachment) {
696
- return skippedMediaAttachmentJob(job, 'missing-attachment-pointer');
735
+ return skippedMediaAttachmentJob(job, "missing-attachment-pointer");
697
736
  }
698
737
  const downloadedAttachment = await resolveMediaAttachment(attachment, {
699
738
  remoteObjectStore: options.remoteObjectStore,
@@ -709,14 +748,14 @@ export async function executeMediaAttachmentJob(job, options) {
709
748
  return completedMediaAttachmentJob(job, { downloadedAttachment });
710
749
  }
711
750
  case MediaAttachmentJobOperation.DeleteLocal: {
712
- const deleteLocalAttachment = requireMediaAttachmentJobHandler(options.deleteLocalAttachment, 'deleteLocalAttachment', job.operation);
751
+ const deleteLocalAttachment = requireMediaAttachmentJobHandler(options.deleteLocalAttachment, "deleteLocalAttachment", job.operation);
713
752
  await deleteLocalAttachment(job);
714
753
  return completedMediaAttachmentJob(job, { deletedLocalCache: true });
715
754
  }
716
755
  case MediaAttachmentJobOperation.DeleteRemote: {
717
756
  const attachment = await loadRequiredAttachmentPointer(job, options);
718
757
  if (!attachment) {
719
- return skippedMediaAttachmentJob(job, 'missing-attachment-pointer');
758
+ return skippedMediaAttachmentJob(job, "missing-attachment-pointer");
720
759
  }
721
760
  const result = await deleteMediaAttachment(attachment, {
722
761
  remoteObjectStore: options.remoteObjectStore,
@@ -729,11 +768,11 @@ export async function executeMediaAttachmentJob(job, options) {
729
768
  }
730
769
  case MediaAttachmentJobOperation.SyncDelete: {
731
770
  if (!options.syncDelete) {
732
- return skippedMediaAttachmentJob(job, 'sync-delete-not-configured');
771
+ return skippedMediaAttachmentJob(job, "sync-delete-not-configured");
733
772
  }
734
773
  const attachment = await loadRequiredAttachmentPointer(job, options);
735
774
  if (!attachment) {
736
- return skippedMediaAttachmentJob(job, 'missing-attachment-pointer');
775
+ return skippedMediaAttachmentJob(job, "missing-attachment-pointer");
737
776
  }
738
777
  const deleteSync = planMediaAttachmentDeleteSync({
739
778
  attachment,
@@ -748,7 +787,7 @@ export async function executeMediaAttachmentJob(job, options) {
748
787
  }
749
788
  }
750
789
  export function createMediaAttachmentMessage(input) {
751
- assertInteger(input.timestamp, 'timestamp');
790
+ assertInteger(input.timestamp, "timestamp");
752
791
  return {
753
792
  type: MediaAttachmentMessageType.Attachment,
754
793
  version: 1,
@@ -760,12 +799,12 @@ export function serializeMediaAttachmentMessage(input) {
760
799
  return JSON.stringify(createMediaAttachmentMessage(input));
761
800
  }
762
801
  function isRecord(value) {
763
- return value !== null && typeof value === 'object' && !Array.isArray(value);
802
+ return value !== null && typeof value === "object" && !Array.isArray(value);
764
803
  }
765
804
  function assertNotAborted(signal) {
766
805
  if (!signal?.aborted)
767
806
  return;
768
- throw new MediaAttachmentError('Media attachment operation cancelled', MediaAttachmentErrorCode.Cancelled, { cause: signal.reason });
807
+ throw new MediaAttachmentError("Media attachment operation cancelled", MediaAttachmentErrorCode.Cancelled, { cause: signal.reason });
769
808
  }
770
809
  function emitProgress(onProgress, progress) {
771
810
  onProgress?.(progress);
@@ -777,7 +816,7 @@ function emitCheckpoint(onCheckpoint, checkpoint) {
777
816
  });
778
817
  }
779
818
  function createResumeStateFromCheckpoint(checkpoint, previous) {
780
- if (checkpoint.phase !== 'transfer') {
819
+ if (checkpoint.phase !== "transfer") {
781
820
  return previous;
782
821
  }
783
822
  const offsetBytes = Number.isInteger(checkpoint.bytesTransferred)
@@ -792,7 +831,9 @@ function createResumeStateFromCheckpoint(checkpoint, previous) {
792
831
  ...(offsetBytes !== undefined ? { offsetBytes } : {}),
793
832
  ...(resumeToken !== undefined ? { resumeToken } : {}),
794
833
  updatedAt: checkpoint.updatedAt,
795
- ...(previous?.expiresAt !== undefined ? { expiresAt: previous.expiresAt } : {}),
834
+ ...(previous?.expiresAt !== undefined
835
+ ? { expiresAt: previous.expiresAt }
836
+ : {}),
796
837
  };
797
838
  }
798
839
  function trackResumeCheckpoints(operation, onCheckpoint, setResume, getResume) {
@@ -820,7 +861,7 @@ export function parseMediaAttachmentMessage(plaintext) {
820
861
  return null;
821
862
  if (parsed.version !== 1)
822
863
  return null;
823
- if (typeof parsed.timestamp !== 'number')
864
+ if (typeof parsed.timestamp !== "number")
824
865
  return null;
825
866
  if (!isRecord(parsed.attachment))
826
867
  return null;
@@ -836,12 +877,12 @@ export function parseMediaAttachmentMessage(plaintext) {
836
877
  }
837
878
  async function defaultUpload(url, data, options = {}) {
838
879
  assertNotAborted(options.signal);
839
- if (typeof globalThis.fetch !== 'function') {
840
- throw new MediaAttachmentError('Cannot upload media attachment: fetch is not available', MediaAttachmentErrorCode.UploadFailed);
880
+ if (typeof globalThis.fetch !== "function") {
881
+ throw new MediaAttachmentError("Cannot upload media attachment: fetch is not available", MediaAttachmentErrorCode.UploadFailed);
841
882
  }
842
883
  emitProgress(options.onProgress, {
843
- operation: 'upload',
844
- phase: 'transfer',
884
+ operation: "upload",
885
+ phase: "transfer",
845
886
  attempt: options.attempt,
846
887
  requestId: options.requestId,
847
888
  storageId: options.storageId,
@@ -849,8 +890,8 @@ async function defaultUpload(url, data, options = {}) {
849
890
  totalBytes: options.totalBytes ?? data.length,
850
891
  });
851
892
  emitCheckpoint(options.onCheckpoint, {
852
- operation: 'upload',
853
- phase: 'transfer',
893
+ operation: "upload",
894
+ phase: "transfer",
854
895
  attempt: options.attempt,
855
896
  requestId: options.requestId,
856
897
  storageId: options.storageId,
@@ -861,11 +902,11 @@ async function defaultUpload(url, data, options = {}) {
861
902
  });
862
903
  const body = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
863
904
  const headers = { ...options.headers };
864
- if (!Object.keys(headers).some((name) => name.toLowerCase() === 'content-type')) {
865
- headers['Content-Type'] = 'application/octet-stream';
905
+ if (!Object.keys(headers).some((name) => name.toLowerCase() === "content-type")) {
906
+ headers["Content-Type"] = "application/octet-stream";
866
907
  }
867
908
  const response = await globalThis.fetch(url, {
868
- method: 'PUT',
909
+ method: "PUT",
869
910
  body,
870
911
  signal: options.signal,
871
912
  headers,
@@ -879,8 +920,8 @@ async function defaultUpload(url, data, options = {}) {
879
920
  };
880
921
  }
881
922
  emitProgress(options.onProgress, {
882
- operation: 'upload',
883
- phase: 'transfer',
923
+ operation: "upload",
924
+ phase: "transfer",
884
925
  attempt: options.attempt,
885
926
  requestId: options.requestId,
886
927
  storageId: options.storageId,
@@ -888,8 +929,8 @@ async function defaultUpload(url, data, options = {}) {
888
929
  totalBytes: options.totalBytes ?? data.length,
889
930
  });
890
931
  emitCheckpoint(options.onCheckpoint, {
891
- operation: 'upload',
892
- phase: 'complete',
932
+ operation: "upload",
933
+ phase: "complete",
893
934
  attempt: options.attempt,
894
935
  requestId: options.requestId,
895
936
  storageId: options.storageId,
@@ -904,17 +945,19 @@ async function defaultUpload(url, data, options = {}) {
904
945
  statusText: response.statusText,
905
946
  };
906
947
  }
907
- function getFetchImplementation(fetchOverride, operation = 'upload') {
948
+ function getFetchImplementation(fetchOverride, operation = "upload") {
908
949
  const fetchImpl = fetchOverride ?? globalThis.fetch;
909
- if (typeof fetchImpl !== 'function') {
910
- throw new MediaAttachmentError(`Cannot ${operation} media attachment: fetch is not available`, operation === 'upload'
950
+ if (typeof fetchImpl !== "function") {
951
+ throw new MediaAttachmentError(`Cannot ${operation} media attachment: fetch is not available`, operation === "upload"
911
952
  ? MediaAttachmentErrorCode.UploadFailed
912
953
  : MediaAttachmentErrorCode.DownloadFailed);
913
954
  }
914
955
  return fetchImpl;
915
956
  }
916
957
  function getHeader(response, header) {
917
- return response.headers?.get?.(header) ?? response.headers?.get?.(header.toLowerCase()) ?? null;
958
+ return (response.headers?.get?.(header) ??
959
+ response.headers?.get?.(header.toLowerCase()) ??
960
+ null);
918
961
  }
919
962
  function parseTusOffset(value, context) {
920
963
  if (value === null) {
@@ -933,7 +976,7 @@ function parseTusOffset(value, context) {
933
976
  function parseTusCreationOffset(value, totalBytes) {
934
977
  if (value === null)
935
978
  return 0;
936
- return assertTusOffsetWithinUpload(parseTusOffset(value, 'creation response'), totalBytes);
979
+ return assertTusOffsetWithinUpload(parseTusOffset(value, "creation response"), totalBytes);
937
980
  }
938
981
  function assertTusOffsetWithinUpload(offset, totalBytes) {
939
982
  if (offset > totalBytes) {
@@ -950,24 +993,24 @@ function assertTusPatchAdvancedToExpectedOffset(offset, expectedOffset) {
950
993
  function assertTusUploadResumeState(resume) {
951
994
  if (!resume)
952
995
  return;
953
- if (resume.operation !== 'upload') {
954
- throwInvalidResumeState('TUS media upload received non-upload resume state');
996
+ if (resume.operation !== "upload") {
997
+ throwInvalidResumeState("TUS media upload received non-upload resume state");
955
998
  }
956
999
  if (resume.offsetBytes !== undefined &&
957
1000
  (!Number.isSafeInteger(resume.offsetBytes) || resume.offsetBytes < 0)) {
958
- throwInvalidResumeState('TUS media upload resume offset is invalid');
1001
+ throwInvalidResumeState("TUS media upload resume offset is invalid");
959
1002
  }
960
1003
  }
961
1004
  function resolveTusChunkSizeBytes(chunkSizeBytes, payloadBytes) {
962
1005
  const resolved = chunkSizeBytes ?? payloadBytes;
963
1006
  if (!Number.isSafeInteger(resolved) || resolved <= 0) {
964
- throw new MediaAttachmentError('TUS media upload chunk size must be a positive safe integer', MediaAttachmentErrorCode.UploadFailed);
1007
+ throw new MediaAttachmentError("TUS media upload chunk size must be a positive safe integer", MediaAttachmentErrorCode.UploadFailed);
965
1008
  }
966
1009
  return resolved;
967
1010
  }
968
1011
  function resolveTusLocation(location, creationUrl) {
969
1012
  if (!location) {
970
- throw new MediaAttachmentError('TUS media upload did not return a resume location', MediaAttachmentErrorCode.UploadFailed);
1013
+ throw new MediaAttachmentError("TUS media upload did not return a resume location", MediaAttachmentErrorCode.UploadFailed);
971
1014
  }
972
1015
  return new URL(location, creationUrl).toString();
973
1016
  }
@@ -986,8 +1029,8 @@ function sliceBytes(data, start, end) {
986
1029
  }
987
1030
  function emitUploadTransferProgress(options, bytesTransferred, totalBytes, resumeToken) {
988
1031
  emitProgress(options.onProgress, {
989
- operation: 'upload',
990
- phase: 'transfer',
1032
+ operation: "upload",
1033
+ phase: "transfer",
991
1034
  attempt: options.attempt,
992
1035
  requestId: options.requestId,
993
1036
  storageId: options.storageId,
@@ -995,8 +1038,8 @@ function emitUploadTransferProgress(options, bytesTransferred, totalBytes, resum
995
1038
  totalBytes,
996
1039
  });
997
1040
  emitCheckpoint(options.onCheckpoint, {
998
- operation: 'upload',
999
- phase: bytesTransferred >= totalBytes ? 'complete' : 'transfer',
1041
+ operation: "upload",
1042
+ phase: bytesTransferred >= totalBytes ? "complete" : "transfer",
1000
1043
  attempt: options.attempt,
1001
1044
  requestId: options.requestId,
1002
1045
  storageId: options.storageId,
@@ -1011,7 +1054,7 @@ export function createTusMediaAttachmentTransfer(tusOptions = {}) {
1011
1054
  async upload(creationUrl, data, options = {}) {
1012
1055
  assertNotAborted(options.signal);
1013
1056
  const fetchImpl = getFetchImplementation(tusOptions.fetch);
1014
- const tusVersion = tusOptions.tusVersion ?? '1.0.0';
1057
+ const tusVersion = tusOptions.tusVersion ?? "1.0.0";
1015
1058
  const totalBytes = options.totalBytes ?? data.length;
1016
1059
  if (totalBytes !== data.length) {
1017
1060
  throw new MediaAttachmentError(`TUS media upload length mismatch: totalBytes ${totalBytes} does not match payload length ${data.length}`, MediaAttachmentErrorCode.UploadFailed);
@@ -1022,17 +1065,17 @@ export function createTusMediaAttachmentTransfer(tusOptions = {}) {
1022
1065
  let offset = options.resume?.offsetBytes ?? 0;
1023
1066
  if (resumeUrl) {
1024
1067
  const head = await fetchImpl(resumeUrl, {
1025
- method: 'HEAD',
1068
+ method: "HEAD",
1026
1069
  signal: options.signal,
1027
1070
  headers: {
1028
1071
  ...options.headers,
1029
- 'Tus-Resumable': tusVersion,
1072
+ "Tus-Resumable": tusVersion,
1030
1073
  },
1031
1074
  });
1032
1075
  assertNotAborted(options.signal);
1033
1076
  if (!head.ok) {
1034
1077
  if (isInvalidTusResumeResponse(head)) {
1035
- throwInvalidResumeState('TUS media upload resume location is invalid', head.status);
1078
+ throwInvalidResumeState("TUS media upload resume location is invalid", head.status);
1036
1079
  }
1037
1080
  return {
1038
1081
  ok: false,
@@ -1040,16 +1083,16 @@ export function createTusMediaAttachmentTransfer(tusOptions = {}) {
1040
1083
  statusText: head.statusText,
1041
1084
  };
1042
1085
  }
1043
- offset = assertTusOffsetWithinUpload(parseTusOffset(getHeader(head, 'Upload-Offset'), 'resume response'), totalBytes);
1086
+ offset = assertTusOffsetWithinUpload(parseTusOffset(getHeader(head, "Upload-Offset"), "resume response"), totalBytes);
1044
1087
  }
1045
1088
  else {
1046
1089
  const create = await fetchImpl(creationUrl, {
1047
- method: 'POST',
1090
+ method: "POST",
1048
1091
  signal: options.signal,
1049
1092
  headers: {
1050
1093
  ...options.headers,
1051
- 'Tus-Resumable': tusVersion,
1052
- 'Upload-Length': String(totalBytes),
1094
+ "Tus-Resumable": tusVersion,
1095
+ "Upload-Length": String(totalBytes),
1053
1096
  },
1054
1097
  });
1055
1098
  assertNotAborted(options.signal);
@@ -1060,28 +1103,28 @@ export function createTusMediaAttachmentTransfer(tusOptions = {}) {
1060
1103
  statusText: create.statusText,
1061
1104
  };
1062
1105
  }
1063
- resumeUrl = resolveTusLocation(getHeader(create, 'Location'), creationUrl);
1064
- offset = parseTusCreationOffset(getHeader(create, 'Upload-Offset'), totalBytes);
1106
+ resumeUrl = resolveTusLocation(getHeader(create, "Location"), creationUrl);
1107
+ offset = parseTusCreationOffset(getHeader(create, "Upload-Offset"), totalBytes);
1065
1108
  }
1066
1109
  emitUploadTransferProgress(options, offset, totalBytes, resumeUrl);
1067
1110
  while (offset < data.length) {
1068
1111
  assertNotAborted(options.signal);
1069
1112
  const nextOffset = Math.min(offset + chunkSizeBytes, data.length);
1070
1113
  const patch = await fetchImpl(resumeUrl, {
1071
- method: 'PATCH',
1114
+ method: "PATCH",
1072
1115
  body: sliceBytes(data, offset, nextOffset),
1073
1116
  signal: options.signal,
1074
1117
  headers: {
1075
1118
  ...options.headers,
1076
- 'Tus-Resumable': tusVersion,
1077
- 'Upload-Offset': String(offset),
1078
- 'Content-Type': 'application/offset+octet-stream',
1119
+ "Tus-Resumable": tusVersion,
1120
+ "Upload-Offset": String(offset),
1121
+ "Content-Type": "application/offset+octet-stream",
1079
1122
  },
1080
1123
  });
1081
1124
  assertNotAborted(options.signal);
1082
1125
  if (!patch.ok) {
1083
1126
  if (isInvalidTusResumeResponse(patch)) {
1084
- throwInvalidResumeState('TUS media upload resume offset is invalid', patch.status);
1127
+ throwInvalidResumeState("TUS media upload resume offset is invalid", patch.status);
1085
1128
  }
1086
1129
  return {
1087
1130
  ok: false,
@@ -1089,15 +1132,15 @@ export function createTusMediaAttachmentTransfer(tusOptions = {}) {
1089
1132
  statusText: patch.statusText,
1090
1133
  };
1091
1134
  }
1092
- offset = assertTusPatchAdvancedToExpectedOffset(assertTusOffsetWithinUpload(parseTusOffset(getHeader(patch, 'Upload-Offset'), 'PATCH response'), totalBytes), nextOffset);
1135
+ offset = assertTusPatchAdvancedToExpectedOffset(assertTusOffsetWithinUpload(parseTusOffset(getHeader(patch, "Upload-Offset"), "PATCH response"), totalBytes), nextOffset);
1093
1136
  emitUploadTransferProgress(options, offset, totalBytes, resumeUrl);
1094
1137
  }
1095
- return { ok: true, status: 204, statusText: 'No Content' };
1138
+ return { ok: true, status: 204, statusText: "No Content" };
1096
1139
  },
1097
1140
  };
1098
1141
  }
1099
1142
  function parseContentLength(response) {
1100
- const contentLength = getHeader(response, 'content-length');
1143
+ const contentLength = getHeader(response, "content-length");
1101
1144
  if (!contentLength || !/^\d+$/.test(contentLength))
1102
1145
  return undefined;
1103
1146
  return Number(contentLength);
@@ -1124,11 +1167,15 @@ function parseContentRange(value) {
1124
1167
  return null;
1125
1168
  const start = Number(match[1]);
1126
1169
  const end = Number(match[2]);
1127
- const totalBytes = match[3] === '*' ? undefined : Number(match[3]);
1128
- if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start) {
1170
+ const totalBytes = match[3] === "*" ? undefined : Number(match[3]);
1171
+ if (!Number.isSafeInteger(start) ||
1172
+ !Number.isSafeInteger(end) ||
1173
+ start < 0 ||
1174
+ end < start) {
1129
1175
  return null;
1130
1176
  }
1131
- if (totalBytes !== undefined && (!Number.isSafeInteger(totalBytes) || totalBytes <= end)) {
1177
+ if (totalBytes !== undefined &&
1178
+ (!Number.isSafeInteger(totalBytes) || totalBytes <= end)) {
1132
1179
  return null;
1133
1180
  }
1134
1181
  return { start, end, totalBytes };
@@ -1166,16 +1213,16 @@ async function readResponseBodyBytes(response, signal) {
1166
1213
  function resolveByteRangeResumeToken(url, options, rangeOptions) {
1167
1214
  if (options.resume?.resumeToken)
1168
1215
  return options.resume.resumeToken;
1169
- if (typeof rangeOptions.resumeToken === 'function') {
1216
+ if (typeof rangeOptions.resumeToken === "function") {
1170
1217
  return rangeOptions.resumeToken(url, options);
1171
1218
  }
1172
- if (typeof rangeOptions.resumeToken === 'string')
1219
+ if (typeof rangeOptions.resumeToken === "string")
1173
1220
  return rangeOptions.resumeToken;
1174
1221
  return options.attachmentId ?? options.storageId ?? url;
1175
1222
  }
1176
1223
  function createDownloadResumeState(options, offsetBytes, resumeToken) {
1177
1224
  return {
1178
- operation: 'download',
1225
+ operation: "download",
1179
1226
  offsetBytes,
1180
1227
  resumeToken,
1181
1228
  updatedAt: Date.now(),
@@ -1184,16 +1231,16 @@ function createDownloadResumeState(options, offsetBytes, resumeToken) {
1184
1231
  }
1185
1232
  function emitDownloadTransferProgress(options, bytesTransferred, totalBytes, resumeToken, complete = false) {
1186
1233
  emitProgress(options.onProgress, {
1187
- operation: 'download',
1188
- phase: 'transfer',
1234
+ operation: "download",
1235
+ phase: "transfer",
1189
1236
  attempt: options.attempt,
1190
1237
  storageId: options.storageId,
1191
1238
  bytesTransferred,
1192
1239
  totalBytes,
1193
1240
  });
1194
1241
  emitCheckpoint(options.onCheckpoint, {
1195
- operation: 'download',
1196
- phase: complete ? 'complete' : 'transfer',
1242
+ operation: "download",
1243
+ phase: complete ? "complete" : "transfer",
1197
1244
  attempt: options.attempt,
1198
1245
  storageId: options.storageId,
1199
1246
  attachmentId: options.attachmentId,
@@ -1204,10 +1251,10 @@ function emitDownloadTransferProgress(options, bytesTransferred, totalBytes, res
1204
1251
  }
1205
1252
  function handleDownloadHttpFailure(response) {
1206
1253
  if (response.status === 404) {
1207
- throw new MediaAttachmentError('Media attachment blob not found', MediaAttachmentErrorCode.BlobNotFound, { status: response.status });
1254
+ throw new MediaAttachmentError("Media attachment blob not found", MediaAttachmentErrorCode.BlobNotFound, { status: response.status });
1208
1255
  }
1209
1256
  if (response.status === 416) {
1210
- throwInvalidResumeState('Byte-range media download resume offset is invalid', response.status);
1257
+ throwInvalidResumeState("Byte-range media download resume offset is invalid", response.status);
1211
1258
  }
1212
1259
  throw new MediaAttachmentError(`Media attachment download failed: ${response.status} ${response.statusText}`, MediaAttachmentErrorCode.DownloadFailed, { status: response.status });
1213
1260
  }
@@ -1215,16 +1262,16 @@ async function loadByteRangePrefix(resume, partialStore) {
1215
1262
  if (!resume || (resume.offsetBytes ?? 0) === 0) {
1216
1263
  return new Uint8Array();
1217
1264
  }
1218
- if (resume.operation !== 'download') {
1219
- throwInvalidResumeState('Byte-range media download received non-download resume state');
1265
+ if (resume.operation !== "download") {
1266
+ throwInvalidResumeState("Byte-range media download received non-download resume state");
1220
1267
  }
1221
1268
  if (!partialStore) {
1222
- throwInvalidResumeState('Byte-range media download resume requires a partial-byte store');
1269
+ throwInvalidResumeState("Byte-range media download resume requires a partial-byte store");
1223
1270
  }
1224
1271
  const prefix = await partialStore.load(resume);
1225
1272
  if (!prefix || prefix.length !== resume.offsetBytes) {
1226
1273
  await clearByteRangePrefixes(partialStore, [resume]);
1227
- throwInvalidResumeState('Byte-range media download partial state is missing or truncated');
1274
+ throwInvalidResumeState("Byte-range media download partial state is missing or truncated");
1228
1275
  }
1229
1276
  return prefix;
1230
1277
  }
@@ -1241,7 +1288,7 @@ function dedupeByteRangeResumeStates(resumes) {
1241
1288
  for (const resume of resumes) {
1242
1289
  if (!resume)
1243
1290
  continue;
1244
- const key = `${resume.operation}:${resume.resumeToken ?? ''}:${resume.offsetBytes ?? ''}`;
1291
+ const key = `${resume.operation}:${resume.resumeToken ?? ""}:${resume.offsetBytes ?? ""}`;
1245
1292
  if (seen.has(key))
1246
1293
  continue;
1247
1294
  seen.add(key);
@@ -1274,7 +1321,7 @@ export function createByteRangeMediaAttachmentTransfer(rangeOptions = {}) {
1274
1321
  return {
1275
1322
  async download(url, options = {}) {
1276
1323
  assertNotAborted(options.signal);
1277
- const fetchImpl = getFetchImplementation(rangeOptions.fetch, 'download');
1324
+ const fetchImpl = getFetchImplementation(rangeOptions.fetch, "download");
1278
1325
  const resumeToken = resolveByteRangeResumeToken(url, options, rangeOptions);
1279
1326
  let bytes = await loadByteRangePrefix(options.resume, rangeOptions.partialStore);
1280
1327
  let offset = bytes.length;
@@ -1283,7 +1330,9 @@ export function createByteRangeMediaAttachmentTransfer(rangeOptions = {}) {
1283
1330
  emitDownloadTransferProgress(options, offset, totalBytes, resumeToken);
1284
1331
  if (totalBytes !== undefined && offset >= totalBytes) {
1285
1332
  emitDownloadTransferProgress(options, offset, totalBytes, resumeToken, true);
1286
- await clearByteRangePrefixes(rangeOptions.partialStore, [options.resume]);
1333
+ await clearByteRangePrefixes(rangeOptions.partialStore, [
1334
+ options.resume,
1335
+ ]);
1287
1336
  return bytes;
1288
1337
  }
1289
1338
  while (totalBytes === undefined || offset < totalBytes) {
@@ -1296,13 +1345,15 @@ export function createByteRangeMediaAttachmentTransfer(rangeOptions = {}) {
1296
1345
  : requestedRangeEnd;
1297
1346
  const shouldRequestRange = offset > 0 || rangeOptions.chunkSizeBytes !== undefined;
1298
1347
  const response = await fetchImpl(url, {
1299
- method: 'GET',
1348
+ method: "GET",
1300
1349
  signal: options.signal,
1350
+ redirect: "manual",
1351
+ credentials: "omit",
1301
1352
  headers: {
1302
1353
  ...options.headers,
1303
1354
  ...(shouldRequestRange
1304
1355
  ? {
1305
- Range: `bytes=${offset}-${rangeEnd !== undefined ? rangeEnd : ''}`,
1356
+ Range: `bytes=${offset}-${rangeEnd !== undefined ? rangeEnd : ""}`,
1306
1357
  }
1307
1358
  : {}),
1308
1359
  },
@@ -1319,12 +1370,12 @@ export function createByteRangeMediaAttachmentTransfer(rangeOptions = {}) {
1319
1370
  if (shouldRequestRange) {
1320
1371
  if (response.status === 206) {
1321
1372
  rangedResponse = true;
1322
- responseContentRange = parseContentRange(getHeader(response, 'content-range'));
1373
+ responseContentRange = parseContentRange(getHeader(response, "content-range"));
1323
1374
  if (!responseContentRange ||
1324
1375
  responseContentRange.start !== offset ||
1325
1376
  (rangeEnd !== undefined && responseContentRange.end > rangeEnd)) {
1326
1377
  await clearCurrentByteRangePrefix(rangeOptions.partialStore, options, offset, resumeToken);
1327
- throwInvalidResumeState('Byte-range media download returned an unexpected range');
1378
+ throwInvalidResumeState("Byte-range media download returned an unexpected range");
1328
1379
  }
1329
1380
  try {
1330
1381
  assertContentRangeTotalMatchesExpected(responseContentRange, totalBytes);
@@ -1337,7 +1388,7 @@ export function createByteRangeMediaAttachmentTransfer(rangeOptions = {}) {
1337
1388
  }
1338
1389
  else if (response.status === 200 && offset > 0) {
1339
1390
  await clearCurrentByteRangePrefix(rangeOptions.partialStore, options, offset, resumeToken);
1340
- throwInvalidResumeState('Byte-range media download server ignored resume offset');
1391
+ throwInvalidResumeState("Byte-range media download server ignored resume offset");
1341
1392
  }
1342
1393
  else if (response.status !== 200) {
1343
1394
  handleDownloadHttpFailure(response);
@@ -1355,10 +1406,12 @@ export function createByteRangeMediaAttachmentTransfer(rangeOptions = {}) {
1355
1406
  }
1356
1407
  }
1357
1408
  assertCiphertextSizeWithinExpected(totalBytes, offset + chunk.length);
1358
- if (chunk.length === 0 && (totalBytes === undefined || offset < totalBytes)) {
1359
- throw new MediaAttachmentError('Media attachment download returned an empty partial response', MediaAttachmentErrorCode.DownloadFailed, { status: response.status });
1409
+ if (chunk.length === 0 &&
1410
+ (totalBytes === undefined || offset < totalBytes)) {
1411
+ throw new MediaAttachmentError("Media attachment download returned an empty partial response", MediaAttachmentErrorCode.DownloadFailed, { status: response.status });
1360
1412
  }
1361
- bytes = offset === 0 && !rangedResponse ? chunk : concatBytes(bytes, chunk);
1413
+ bytes =
1414
+ offset === 0 && !rangedResponse ? chunk : concatBytes(bytes, chunk);
1362
1415
  offset = bytes.length;
1363
1416
  const persistedPrefix = await persistByteRangePrefix(rangeOptions.partialStore, options, bytes, resumeToken);
1364
1417
  if (persistedPrefix) {
@@ -1385,21 +1438,24 @@ export function createByteRangeMediaAttachmentTransfer(rangeOptions = {}) {
1385
1438
  };
1386
1439
  }
1387
1440
  async function readResponseBytes(response, options) {
1388
- const totalBytesHeader = getHeader(response, 'content-length');
1389
- const headerBytes = totalBytesHeader && /^\d+$/.test(totalBytesHeader) ? Number(totalBytesHeader) : undefined;
1441
+ const totalBytesHeader = getHeader(response, "content-length");
1442
+ const headerBytes = totalBytesHeader && /^\d+$/.test(totalBytesHeader)
1443
+ ? Number(totalBytesHeader)
1444
+ : undefined;
1390
1445
  assertCiphertextSizeEqualsExpected(options.totalBytes, headerBytes);
1391
- const totalBytes = options.totalBytes ?? (headerBytes !== undefined ? Number(headerBytes) : undefined);
1446
+ const totalBytes = options.totalBytes ??
1447
+ (headerBytes !== undefined ? Number(headerBytes) : undefined);
1392
1448
  emitProgress(options.onProgress, {
1393
- operation: 'download',
1394
- phase: 'transfer',
1449
+ operation: "download",
1450
+ phase: "transfer",
1395
1451
  attempt: options.attempt,
1396
1452
  storageId: options.storageId,
1397
1453
  bytesTransferred: 0,
1398
1454
  totalBytes,
1399
1455
  });
1400
1456
  emitCheckpoint(options.onCheckpoint, {
1401
- operation: 'download',
1402
- phase: 'transfer',
1457
+ operation: "download",
1458
+ phase: "transfer",
1403
1459
  attempt: options.attempt,
1404
1460
  storageId: options.storageId,
1405
1461
  attachmentId: options.attachmentId,
@@ -1421,16 +1477,16 @@ async function readResponseBytes(response, options) {
1421
1477
  chunks.push(value);
1422
1478
  bytesTransferred = nextBytesTransferred;
1423
1479
  emitProgress(options.onProgress, {
1424
- operation: 'download',
1425
- phase: 'transfer',
1480
+ operation: "download",
1481
+ phase: "transfer",
1426
1482
  attempt: options.attempt,
1427
1483
  storageId: options.storageId,
1428
1484
  bytesTransferred,
1429
1485
  totalBytes,
1430
1486
  });
1431
1487
  emitCheckpoint(options.onCheckpoint, {
1432
- operation: 'download',
1433
- phase: 'transfer',
1488
+ operation: "download",
1489
+ phase: "transfer",
1434
1490
  attempt: options.attempt,
1435
1491
  storageId: options.storageId,
1436
1492
  attachmentId: options.attachmentId,
@@ -1441,8 +1497,8 @@ async function readResponseBytes(response, options) {
1441
1497
  }
1442
1498
  const data = concatBytes(...chunks);
1443
1499
  emitCheckpoint(options.onCheckpoint, {
1444
- operation: 'download',
1445
- phase: 'complete',
1500
+ operation: "download",
1501
+ phase: "complete",
1446
1502
  attempt: options.attempt,
1447
1503
  storageId: options.storageId,
1448
1504
  attachmentId: options.attachmentId,
@@ -1456,16 +1512,16 @@ async function readResponseBytes(response, options) {
1456
1512
  assertNotAborted(options.signal);
1457
1513
  assertCiphertextSizeEqualsExpected(options.totalBytes, data.length);
1458
1514
  emitProgress(options.onProgress, {
1459
- operation: 'download',
1460
- phase: 'transfer',
1515
+ operation: "download",
1516
+ phase: "transfer",
1461
1517
  attempt: options.attempt,
1462
1518
  storageId: options.storageId,
1463
1519
  bytesTransferred: data.length,
1464
1520
  totalBytes: totalBytes ?? data.length,
1465
1521
  });
1466
1522
  emitCheckpoint(options.onCheckpoint, {
1467
- operation: 'download',
1468
- phase: 'complete',
1523
+ operation: "download",
1524
+ phase: "complete",
1469
1525
  attempt: options.attempt,
1470
1526
  storageId: options.storageId,
1471
1527
  attachmentId: options.attachmentId,
@@ -1477,17 +1533,19 @@ async function readResponseBytes(response, options) {
1477
1533
  }
1478
1534
  async function defaultDownload(url, options = {}) {
1479
1535
  assertNotAborted(options.signal);
1480
- if (typeof globalThis.fetch !== 'function') {
1481
- throw new MediaAttachmentError('Cannot download media attachment: fetch is not available', MediaAttachmentErrorCode.DownloadFailed);
1536
+ if (typeof globalThis.fetch !== "function") {
1537
+ throw new MediaAttachmentError("Cannot download media attachment: fetch is not available", MediaAttachmentErrorCode.DownloadFailed);
1482
1538
  }
1483
1539
  const response = await globalThis.fetch(url, {
1484
1540
  signal: options.signal,
1485
1541
  headers: options.headers,
1542
+ redirect: "manual",
1543
+ credentials: "omit",
1486
1544
  });
1487
1545
  assertNotAborted(options.signal);
1488
1546
  if (!response.ok) {
1489
1547
  if (response.status === 404) {
1490
- throw new MediaAttachmentError('Media attachment blob not found', MediaAttachmentErrorCode.BlobNotFound, { status: response.status });
1548
+ throw new MediaAttachmentError("Media attachment blob not found", MediaAttachmentErrorCode.BlobNotFound, { status: response.status });
1491
1549
  }
1492
1550
  throw new MediaAttachmentError(`Media attachment download failed: ${response.status} ${response.statusText}`, MediaAttachmentErrorCode.DownloadFailed, { status: response.status });
1493
1551
  }
@@ -1525,11 +1583,14 @@ function isRetryableUploadStatus(status) {
1525
1583
  return status >= 500;
1526
1584
  }
1527
1585
  function isRetryableUploadError(error) {
1586
+ if (error instanceof RemoteObjectUploadError)
1587
+ return false;
1528
1588
  if (error instanceof MediaAttachmentError) {
1529
1589
  if (error.code === MediaAttachmentErrorCode.ResumeStateInvalid) {
1530
1590
  return true;
1531
1591
  }
1532
- return (error.code === MediaAttachmentErrorCode.UploadFailed && isRetryableUploadStatus(error.status));
1592
+ return (error.code === MediaAttachmentErrorCode.UploadFailed &&
1593
+ isRetryableUploadStatus(error.status));
1533
1594
  }
1534
1595
  return true;
1535
1596
  }
@@ -1557,16 +1618,17 @@ function isRetryableDownloadError(error) {
1557
1618
  }
1558
1619
  function normalizeDownloadError(error) {
1559
1620
  if (error instanceof MediaAttachmentError) {
1560
- if (error.status === 404 && error.code === MediaAttachmentErrorCode.DownloadFailed) {
1561
- return new MediaAttachmentError('Media attachment blob not found', MediaAttachmentErrorCode.BlobNotFound, { cause: error, status: 404 });
1621
+ if (error.status === 404 &&
1622
+ error.code === MediaAttachmentErrorCode.DownloadFailed) {
1623
+ return new MediaAttachmentError("Media attachment blob not found", MediaAttachmentErrorCode.BlobNotFound, { cause: error, status: 404 });
1562
1624
  }
1563
1625
  return error;
1564
1626
  }
1565
- const message = error instanceof Error ? error.message.toLowerCase() : '';
1566
- if (message.includes('blob not found') ||
1567
- message.includes('attachment blob not found') ||
1568
- message.includes('media attachment not found')) {
1569
- return new MediaAttachmentError('Media attachment blob not found', MediaAttachmentErrorCode.BlobNotFound, { cause: error });
1627
+ const message = error instanceof Error ? error.message.toLowerCase() : "";
1628
+ if (message.includes("blob not found") ||
1629
+ message.includes("attachment blob not found") ||
1630
+ message.includes("media attachment not found")) {
1631
+ return new MediaAttachmentError("Media attachment blob not found", MediaAttachmentErrorCode.BlobNotFound, { cause: error });
1570
1632
  }
1571
1633
  return error;
1572
1634
  }
@@ -1576,91 +1638,141 @@ function getRetryStatus(error) {
1576
1638
  function getRetryReason(error) {
1577
1639
  if (error instanceof MediaAttachmentError &&
1578
1640
  error.code === MediaAttachmentErrorCode.ResumeStateInvalid) {
1579
- return 'invalid-resume';
1641
+ return "invalid-resume";
1580
1642
  }
1581
1643
  const status = getRetryStatus(error);
1582
1644
  if (status === 403)
1583
- return 'expired-url';
1645
+ return "expired-url";
1584
1646
  if (status !== undefined)
1585
- return 'retryable-status';
1586
- return 'transient-failure';
1647
+ return "retryable-status";
1648
+ return "transient-failure";
1587
1649
  }
1588
1650
  async function uploadCiphertextWithRetry(input) {
1589
1651
  const retry = resolveUploadRetryOptions(input.retry);
1590
1652
  const digest = await sha256(input.ciphertext);
1653
+ const readCapabilityDigest = input.readCapability === undefined
1654
+ ? undefined
1655
+ : await sha256(base64ToBytes(toBase64(urlSafeToBase64(input.readCapability))));
1591
1656
  let lastError;
1592
1657
  let resume = input.resume;
1593
1658
  let canonicalObjectId;
1594
- const onCheckpoint = trackResumeCheckpoints('upload', input.onCheckpoint, (nextResume) => {
1659
+ let transferredObjectId;
1660
+ let reconciliationPending = false;
1661
+ const reconcileTransfer = async () => {
1662
+ const objectId = canonicalObjectId;
1663
+ const receipt = await input.remoteObjectStore.reconcileUpload({
1664
+ objectId,
1665
+ });
1666
+ assertNotAborted(input.signal);
1667
+ if (receipt === null) {
1668
+ reconciliationPending = false;
1669
+ return false;
1670
+ }
1671
+ if (!matchesUploadReceipt(receipt, {
1672
+ objectId,
1673
+ contentLength: input.ciphertext.length,
1674
+ digest,
1675
+ })) {
1676
+ throw new MediaAttachmentError("The stored upload differs from its immutable preparation.", MediaAttachmentErrorCode.UploadIdentityChanged);
1677
+ }
1678
+ transferredObjectId = objectId;
1679
+ reconciliationPending = false;
1680
+ return true;
1681
+ };
1682
+ const onCheckpoint = trackResumeCheckpoints("upload", input.onCheckpoint, (nextResume) => {
1595
1683
  resume = nextResume;
1596
1684
  }, () => resume);
1597
1685
  for (let attempt = 0; attempt <= retry.maxRetries; attempt++) {
1598
1686
  try {
1599
1687
  assertNotAborted(input.signal);
1600
- emitProgress(input.onProgress, {
1601
- operation: 'upload',
1602
- phase: 'request-url',
1603
- attempt,
1604
- requestId: input.requestId,
1605
- });
1606
- emitCheckpoint(onCheckpoint, {
1607
- operation: 'upload',
1608
- phase: 'request-url',
1609
- attempt,
1610
- requestId: input.requestId,
1611
- storageId: canonicalObjectId,
1612
- bytesTransferred: resume?.offsetBytes ?? 0,
1613
- totalBytes: input.ciphertext.length,
1614
- resumeToken: resume?.resumeToken,
1615
- });
1616
- const { uploadUrl, objectId, headers, protocol } = await input.remoteObjectStore.createUpload({
1617
- requestId: input.requestId,
1618
- contentType: 'application/octet-stream',
1619
- contentLength: input.ciphertext.length,
1620
- digest,
1621
- });
1622
- if (canonicalObjectId !== undefined && canonicalObjectId !== objectId) {
1623
- throw new MediaAttachmentError('Remote object storage returned a different object ID for an upload retry', MediaAttachmentErrorCode.UploadIdentityChanged);
1624
- }
1625
- canonicalObjectId = objectId;
1626
- assertNotAborted(input.signal);
1627
- const transfer = input.transfer ?? (protocol === 'tus' ? createTusMediaAttachmentTransfer() : undefined);
1628
- const uploadHeaders = { ...headers };
1629
- if (!Object.keys(uploadHeaders).some((name) => name.toLowerCase() === 'content-type')) {
1630
- uploadHeaders['Content-Type'] = 'application/octet-stream';
1631
- }
1632
- const response = transfer?.upload
1633
- ? await transfer.upload(uploadUrl, input.ciphertext, {
1634
- headers: uploadHeaders,
1635
- signal: input.signal,
1636
- onProgress: input.onProgress,
1637
- onCheckpoint,
1638
- resume,
1688
+ if (reconciliationPending)
1689
+ await reconcileTransfer();
1690
+ if (transferredObjectId === undefined) {
1691
+ emitProgress(input.onProgress, {
1692
+ operation: "upload",
1693
+ phase: "request-url",
1639
1694
  attempt,
1640
- totalBytes: input.ciphertext.length,
1641
1695
  requestId: input.requestId,
1642
- storageId: objectId,
1643
- })
1644
- : await defaultUpload(uploadUrl, input.ciphertext, {
1645
- headers: uploadHeaders,
1646
- signal: input.signal,
1647
- onProgress: input.onProgress,
1648
- onCheckpoint,
1649
- resume,
1696
+ });
1697
+ emitCheckpoint(onCheckpoint, {
1698
+ operation: "upload",
1699
+ phase: "request-url",
1650
1700
  attempt,
1701
+ requestId: input.requestId,
1702
+ storageId: canonicalObjectId,
1703
+ bytesTransferred: resume?.offsetBytes ?? 0,
1651
1704
  totalBytes: input.ciphertext.length,
1705
+ resumeToken: resume?.resumeToken,
1706
+ });
1707
+ const { uploadUrl, objectId, headers, protocol } = await input.remoteObjectStore.createUpload({
1652
1708
  requestId: input.requestId,
1653
- storageId: objectId,
1709
+ preparedAt: input.preparedAt,
1710
+ contentType: "application/octet-stream",
1711
+ contentLength: input.ciphertext.length,
1712
+ digest,
1713
+ ...(readCapabilityDigest === undefined
1714
+ ? {}
1715
+ : { readCapabilityDigest }),
1654
1716
  });
1655
- if (!response.ok) {
1656
- throw new MediaAttachmentError(`Media attachment upload failed: ${response.status} ${response.statusText}`, MediaAttachmentErrorCode.UploadFailed, { status: response.status });
1717
+ if (canonicalObjectId !== undefined && canonicalObjectId !== objectId) {
1718
+ throw new MediaAttachmentError("Remote object storage returned a different object ID for an upload retry", MediaAttachmentErrorCode.UploadIdentityChanged);
1719
+ }
1720
+ canonicalObjectId = objectId;
1721
+ assertNotAborted(input.signal);
1722
+ const transfer = input.transfer ??
1723
+ (protocol === "tus" ? createTusMediaAttachmentTransfer() : undefined);
1724
+ const uploadHeaders = { ...headers };
1725
+ if (!Object.keys(uploadHeaders).some((name) => name.toLowerCase() === "content-type")) {
1726
+ uploadHeaders["Content-Type"] = "application/octet-stream";
1727
+ }
1728
+ try {
1729
+ const response = transfer?.upload
1730
+ ? await transfer.upload(uploadUrl, input.ciphertext, {
1731
+ headers: uploadHeaders,
1732
+ signal: input.signal,
1733
+ onProgress: input.onProgress,
1734
+ onCheckpoint,
1735
+ resume,
1736
+ attempt,
1737
+ totalBytes: input.ciphertext.length,
1738
+ requestId: input.requestId,
1739
+ storageId: objectId,
1740
+ })
1741
+ : await defaultUpload(uploadUrl, input.ciphertext, {
1742
+ headers: uploadHeaders,
1743
+ signal: input.signal,
1744
+ onProgress: input.onProgress,
1745
+ onCheckpoint,
1746
+ resume,
1747
+ attempt,
1748
+ totalBytes: input.ciphertext.length,
1749
+ requestId: input.requestId,
1750
+ storageId: objectId,
1751
+ });
1752
+ if (!response.ok) {
1753
+ throw new MediaAttachmentError(`Media attachment upload failed: ${response.status} ${response.statusText}`, MediaAttachmentErrorCode.UploadFailed, { status: response.status });
1754
+ }
1755
+ transferredObjectId = objectId;
1756
+ }
1757
+ catch (error) {
1758
+ if (input.signal?.aborted || !input.remoteObjectStore.reconcileUpload)
1759
+ throw error;
1760
+ reconciliationPending = true;
1761
+ if (!(await reconcileTransfer()))
1762
+ throw error;
1763
+ }
1764
+ }
1765
+ if (transferredObjectId === undefined) {
1766
+ throw new MediaAttachmentError("The upload has no verified transfer result.", MediaAttachmentErrorCode.UploadFailed);
1657
1767
  }
1658
- await input.remoteObjectStore.completeUpload?.({ objectId });
1659
- return objectId;
1768
+ await input.remoteObjectStore.completeUpload?.({
1769
+ objectId: transferredObjectId,
1770
+ });
1771
+ return transferredObjectId;
1660
1772
  }
1661
1773
  catch (error) {
1662
1774
  if (input.signal?.aborted) {
1663
- throw new MediaAttachmentError('Media attachment operation cancelled', MediaAttachmentErrorCode.Cancelled, { cause: input.signal.reason });
1775
+ throw new MediaAttachmentError("Media attachment operation cancelled", MediaAttachmentErrorCode.Cancelled, { cause: input.signal.reason });
1664
1776
  }
1665
1777
  lastError = error;
1666
1778
  const shouldClearResume = error instanceof MediaAttachmentError &&
@@ -1673,8 +1785,8 @@ async function uploadCiphertextWithRetry(input) {
1673
1785
  }
1674
1786
  const delay = calculateUploadRetryDelay(attempt, retry);
1675
1787
  emitProgress(input.onProgress, {
1676
- operation: 'upload',
1677
- phase: 'retry',
1788
+ operation: "upload",
1789
+ phase: "retry",
1678
1790
  attempt,
1679
1791
  requestId: input.requestId,
1680
1792
  storageId: canonicalObjectId,
@@ -1683,8 +1795,8 @@ async function uploadCiphertextWithRetry(input) {
1683
1795
  reason: getRetryReason(error),
1684
1796
  });
1685
1797
  emitCheckpoint(onCheckpoint, {
1686
- operation: 'upload',
1687
- phase: 'retry',
1798
+ operation: "upload",
1799
+ phase: "retry",
1688
1800
  attempt,
1689
1801
  requestId: input.requestId,
1690
1802
  storageId: canonicalObjectId,
@@ -1697,30 +1809,31 @@ async function uploadCiphertextWithRetry(input) {
1697
1809
  }
1698
1810
  }
1699
1811
  }
1700
- if (lastError instanceof MediaAttachmentError) {
1812
+ if (lastError instanceof MediaAttachmentError ||
1813
+ lastError instanceof RemoteObjectUploadError) {
1701
1814
  throw lastError;
1702
1815
  }
1703
- throw new MediaAttachmentError('Media attachment upload failed', MediaAttachmentErrorCode.UploadFailed, { cause: lastError });
1816
+ throw new MediaAttachmentError("Media attachment upload failed", MediaAttachmentErrorCode.UploadFailed, { cause: lastError });
1704
1817
  }
1705
1818
  async function downloadCiphertextWithRetry(input) {
1706
1819
  const retry = resolveUploadRetryOptions(input.retry);
1707
1820
  let lastError;
1708
1821
  let resume = input.resume;
1709
- const onCheckpoint = trackResumeCheckpoints('download', input.onCheckpoint, (nextResume) => {
1822
+ const onCheckpoint = trackResumeCheckpoints("download", input.onCheckpoint, (nextResume) => {
1710
1823
  resume = nextResume;
1711
1824
  }, () => resume);
1712
1825
  for (let attempt = 0; attempt <= retry.maxRetries; attempt++) {
1713
1826
  try {
1714
1827
  assertNotAborted(input.signal);
1715
1828
  emitProgress(input.onProgress, {
1716
- operation: 'download',
1717
- phase: 'request-url',
1829
+ operation: "download",
1830
+ phase: "request-url",
1718
1831
  attempt,
1719
1832
  storageId: input.storageId,
1720
1833
  });
1721
1834
  emitCheckpoint(onCheckpoint, {
1722
- operation: 'download',
1723
- phase: 'request-url',
1835
+ operation: "download",
1836
+ phase: "request-url",
1724
1837
  attempt,
1725
1838
  storageId: input.storageId,
1726
1839
  attachmentId: input.attachmentId,
@@ -1730,6 +1843,9 @@ async function downloadCiphertextWithRetry(input) {
1730
1843
  });
1731
1844
  const { downloadUrl, headers } = await input.remoteObjectStore.createDownload({
1732
1845
  objectId: input.storageId,
1846
+ ...(input.readCapability === undefined
1847
+ ? {}
1848
+ : { readCapability: input.readCapability }),
1733
1849
  });
1734
1850
  assertNotAborted(input.signal);
1735
1851
  return input.transfer?.download
@@ -1758,7 +1874,7 @@ async function downloadCiphertextWithRetry(input) {
1758
1874
  }
1759
1875
  catch (error) {
1760
1876
  if (input.signal?.aborted) {
1761
- throw new MediaAttachmentError('Media attachment operation cancelled', MediaAttachmentErrorCode.Cancelled, { cause: input.signal.reason });
1877
+ throw new MediaAttachmentError("Media attachment operation cancelled", MediaAttachmentErrorCode.Cancelled, { cause: input.signal.reason });
1762
1878
  }
1763
1879
  const normalizedError = normalizeDownloadError(error);
1764
1880
  lastError = normalizedError;
@@ -1767,13 +1883,14 @@ async function downloadCiphertextWithRetry(input) {
1767
1883
  if (shouldClearResume) {
1768
1884
  resume = undefined;
1769
1885
  }
1770
- if (attempt >= retry.maxRetries || !isRetryableDownloadError(normalizedError)) {
1886
+ if (attempt >= retry.maxRetries ||
1887
+ !isRetryableDownloadError(normalizedError)) {
1771
1888
  break;
1772
1889
  }
1773
1890
  const delay = calculateUploadRetryDelay(attempt, retry);
1774
1891
  emitProgress(input.onProgress, {
1775
- operation: 'download',
1776
- phase: 'retry',
1892
+ operation: "download",
1893
+ phase: "retry",
1777
1894
  attempt,
1778
1895
  storageId: input.storageId,
1779
1896
  status: getRetryStatus(normalizedError),
@@ -1781,8 +1898,8 @@ async function downloadCiphertextWithRetry(input) {
1781
1898
  reason: getRetryReason(normalizedError),
1782
1899
  });
1783
1900
  emitCheckpoint(onCheckpoint, {
1784
- operation: 'download',
1785
- phase: 'retry',
1901
+ operation: "download",
1902
+ phase: "retry",
1786
1903
  attempt,
1787
1904
  storageId: input.storageId,
1788
1905
  attachmentId: input.attachmentId,
@@ -1798,7 +1915,7 @@ async function downloadCiphertextWithRetry(input) {
1798
1915
  if (lastError instanceof MediaAttachmentError) {
1799
1916
  throw lastError;
1800
1917
  }
1801
- throw new MediaAttachmentError('Media attachment download failed', MediaAttachmentErrorCode.DownloadFailed, { cause: lastError });
1918
+ throw new MediaAttachmentError("Media attachment download failed", MediaAttachmentErrorCode.DownloadFailed, { cause: lastError });
1802
1919
  }
1803
1920
  function decodeAttachmentKey(key) {
1804
1921
  try {
@@ -1809,7 +1926,7 @@ function decodeAttachmentKey(key) {
1809
1926
  return keyBytes;
1810
1927
  }
1811
1928
  catch (cause) {
1812
- throw new MediaAttachmentError('Invalid media attachment pointer: key must be a base64-encoded 32-byte key', MediaAttachmentErrorCode.InvalidPointer, { cause });
1929
+ throw new MediaAttachmentError("Invalid media attachment pointer: key must be a base64-encoded 32-byte key", MediaAttachmentErrorCode.InvalidPointer, { cause });
1813
1930
  }
1814
1931
  }
1815
1932
  async function assertDigestMatches(ciphertext, expectedDigest) {
@@ -1818,28 +1935,31 @@ async function assertDigestMatches(ciphertext, expectedDigest) {
1818
1935
  expectedDigestBytes = base64ToBytes(toBase64(expectedDigest));
1819
1936
  }
1820
1937
  catch (cause) {
1821
- throw new MediaAttachmentError('Invalid media attachment pointer: digest must be base64-encoded SHA-256', MediaAttachmentErrorCode.InvalidPointer, { cause });
1938
+ throw new MediaAttachmentError("Invalid media attachment pointer: digest must be base64-encoded SHA-256", MediaAttachmentErrorCode.InvalidPointer, { cause });
1822
1939
  }
1823
1940
  const actualDigestBytes = await sha256(ciphertext);
1824
1941
  if (expectedDigestBytes.length !== actualDigestBytes.length ||
1825
1942
  !constantTimeEqual(expectedDigestBytes, actualDigestBytes)) {
1826
- throw new MediaAttachmentError('Media attachment digest mismatch', MediaAttachmentErrorCode.DigestMismatch);
1943
+ throw new MediaAttachmentError("Media attachment digest mismatch", MediaAttachmentErrorCode.DigestMismatch);
1827
1944
  }
1828
1945
  }
1829
1946
  /**
1830
- * Encrypt and upload media bytes, returning a SDK attachment pointer.
1831
- *
1832
- * The client computes the encrypted object digest and object ID once. Upload
1833
- * retries request fresh presigned URLs for that same key. This handles expired
1834
- * upload URLs without changing the pointer metadata that the client later
1835
- * encrypts into the Signal Protocol message.
1947
+ * Encrypt and upload media bytes within one invocation.
1948
+ * For restart recovery, persist prepareMediaAttachmentUploadData before calling uploadPreparedMediaAttachment.
1836
1949
  */
1837
1950
  export async function prepareMediaAttachmentUpload(data, options) {
1951
+ return uploadPreparedMediaAttachment(await prepareMediaAttachmentUploadData(data, options), options);
1952
+ }
1953
+ /** Prepare exact encrypted bytes without contacting the remote object store. */
1954
+ export async function prepareMediaAttachmentUploadData(data, options = {}) {
1838
1955
  assertNotAborted(options.signal);
1839
- const contentType = options.contentType ?? 'application/octet-stream';
1956
+ const preparedAt = Date.now();
1957
+ data = data.slice();
1958
+ options = { ...options, waveform: options.waveform?.slice() };
1959
+ const contentType = options.contentType ?? "application/octet-stream";
1840
1960
  const clientUuid = options.clientUuid ?? (await generateMediaAttachmentClientUuid());
1841
1961
  const requestId = options.requestId ?? (await generateMediaAttachmentUploadRequestId());
1842
- assertString(requestId, 'requestId');
1962
+ assertString(requestId, "requestId");
1843
1963
  assertNotAborted(options.signal);
1844
1964
  validateMediaAttachmentMetadata({
1845
1965
  contentType,
@@ -1858,8 +1978,8 @@ export async function prepareMediaAttachmentUpload(data, options) {
1858
1978
  cdnNumber: options.cdnNumber,
1859
1979
  }, options.policy);
1860
1980
  emitProgress(options.onProgress, {
1861
- operation: 'upload',
1862
- phase: 'encrypt',
1981
+ operation: "upload",
1982
+ phase: "encrypt",
1863
1983
  bytesTransferred: 0,
1864
1984
  totalBytes: data.length,
1865
1985
  });
@@ -1870,59 +1990,102 @@ export async function prepareMediaAttachmentUpload(data, options) {
1870
1990
  const { ciphertext, segmentSize } = await streamingEncrypt(masterKey, data);
1871
1991
  assertNotAborted(options.signal);
1872
1992
  emitProgress(options.onProgress, {
1873
- operation: 'upload',
1874
- phase: 'encrypt',
1993
+ operation: "upload",
1994
+ phase: "encrypt",
1875
1995
  bytesTransferred: data.length,
1876
1996
  totalBytes: data.length,
1877
1997
  });
1878
1998
  const digest = bytesToBase64(await sha256(ciphertext));
1879
- const storageId = await uploadCiphertextWithRetry({
1880
- remoteObjectStore: options.remoteObjectStore,
1881
- transfer: options.transfer,
1882
- retry: options.retry,
1883
- signal: options.signal,
1884
- onProgress: options.onProgress,
1885
- onCheckpoint: options.onCheckpoint,
1886
- resume: options.resume,
1887
- ciphertext,
1888
- requestId,
1889
- });
1890
- const pointer = createMediaAttachmentPointer({
1891
- storageId,
1999
+ const pointer = {
2000
+ version: 1,
2001
+ readCapability: bytesToUrlSafeBase64(await generateRandomBytes(32)),
1892
2002
  key: masterKeyBase64,
1893
2003
  digest,
1894
2004
  segmentSize,
1895
2005
  ciphertextSize: ciphertext.length,
1896
2006
  contentType,
1897
2007
  size: data.length,
1898
- uploadTimestamp: Date.now(),
1899
2008
  blurHash: options.blurHash,
1900
2009
  thumbnail: options.thumbnail,
1901
2010
  width: options.width,
1902
2011
  height: options.height,
1903
2012
  durationMs: options.durationMs,
1904
- waveform: options.waveform,
2013
+ waveform: options.waveform?.slice(),
1905
2014
  fileName: options.fileName,
1906
2015
  caption: options.caption,
1907
2016
  isViewOnce: options.isViewOnce,
1908
2017
  flags: options.flags,
1909
2018
  clientUuid,
1910
2019
  cdnNumber: options.cdnNumber,
1911
- });
2020
+ };
1912
2021
  validateMediaAttachmentMetadata(pointer, options.policy);
1913
- emitProgress(options.onProgress, {
1914
- operation: 'upload',
1915
- phase: 'complete',
1916
- storageId: pointer.storageId,
1917
- bytesTransferred: ciphertext.length,
1918
- totalBytes: ciphertext.length,
1919
- });
1920
- return pointer;
2022
+ return {
2023
+ requestId,
2024
+ preparedAt,
2025
+ ciphertext,
2026
+ pointer,
2027
+ plaintextDigest: bytesToBase64(await sha256(data)),
2028
+ };
1921
2029
  }
1922
2030
  finally {
1923
2031
  secureZeroBytes(masterKey);
1924
2032
  }
1925
2033
  }
2034
+ /** Upload a saved preparation without generating new encryption material. */
2035
+ export async function uploadPreparedMediaAttachment(prepared, options) {
2036
+ assertNotAborted(options.signal);
2037
+ assertString(prepared.requestId, "requestId");
2038
+ const preparedAt = prepared.preparedAt;
2039
+ if (!Number.isSafeInteger(preparedAt) || preparedAt < 1) {
2040
+ throw new MediaAttachmentError("The prepared upload time is invalid. Recover the original preparation.", MediaAttachmentErrorCode.UploadIdentityChanged);
2041
+ }
2042
+ if (options.requestId !== undefined &&
2043
+ options.requestId !== prepared.requestId) {
2044
+ throw new MediaAttachmentError("The prepared upload request ID changed.", MediaAttachmentErrorCode.UploadIdentityChanged);
2045
+ }
2046
+ // Copy before asynchronous work so the caller cannot change the accepted bytes.
2047
+ const ciphertext = prepared.ciphertext.slice();
2048
+ const metadata = {
2049
+ ...prepared.pointer,
2050
+ waveform: prepared.pointer.waveform?.slice(),
2051
+ };
2052
+ const pointer = createMediaAttachmentPointer({
2053
+ ...metadata,
2054
+ storageId: "prepared-upload",
2055
+ uploadTimestamp: Date.now(),
2056
+ });
2057
+ validateMediaAttachmentMetadata(pointer, options.policy);
2058
+ if (ciphertext.length !== pointer.ciphertextSize) {
2059
+ throw new MediaAttachmentError("The prepared ciphertext length changed.", MediaAttachmentErrorCode.CiphertextSizeMismatch);
2060
+ }
2061
+ await assertDigestMatches(ciphertext, pointer.digest);
2062
+ const storageId = await uploadCiphertextWithRetry({
2063
+ remoteObjectStore: options.remoteObjectStore,
2064
+ transfer: options.transfer,
2065
+ retry: options.retry,
2066
+ signal: options.signal,
2067
+ onProgress: options.onProgress,
2068
+ onCheckpoint: options.onCheckpoint,
2069
+ resume: options.resume,
2070
+ ciphertext,
2071
+ requestId: prepared.requestId,
2072
+ preparedAt,
2073
+ readCapability: pointer.readCapability,
2074
+ });
2075
+ const attachment = createMediaAttachmentPointer({
2076
+ ...metadata,
2077
+ storageId,
2078
+ uploadTimestamp: Date.now(),
2079
+ });
2080
+ emitProgress(options.onProgress, {
2081
+ operation: "upload",
2082
+ phase: "complete",
2083
+ storageId,
2084
+ bytesTransferred: ciphertext.length,
2085
+ totalBytes: ciphertext.length,
2086
+ });
2087
+ return attachment;
2088
+ }
1926
2089
  /**
1927
2090
  * Download, verify, and decrypt a Signal Protocol media attachment pointer.
1928
2091
  *
@@ -1944,14 +2107,15 @@ export async function resolveMediaAttachment(attachment, options) {
1944
2107
  storageId: pointer.storageId,
1945
2108
  attachmentId: createMediaAttachmentId(pointer),
1946
2109
  expectedCiphertextSize: pointer.ciphertextSize,
2110
+ readCapability: pointer.readCapability,
1947
2111
  });
1948
2112
  assertNotAborted(options.signal);
1949
2113
  if (ciphertext.length !== pointer.ciphertextSize) {
1950
2114
  throw new MediaAttachmentError(`Media attachment ciphertext size mismatch: expected ${pointer.ciphertextSize}, received ${ciphertext.length}`, MediaAttachmentErrorCode.CiphertextSizeMismatch);
1951
2115
  }
1952
2116
  emitProgress(options.onProgress, {
1953
- operation: 'download',
1954
- phase: 'verify',
2117
+ operation: "download",
2118
+ phase: "verify",
1955
2119
  storageId: pointer.storageId,
1956
2120
  bytesTransferred: ciphertext.length,
1957
2121
  totalBytes: pointer.ciphertextSize,
@@ -1961,8 +2125,8 @@ export async function resolveMediaAttachment(attachment, options) {
1961
2125
  const keyBytes = decodeAttachmentKey(pointer.key);
1962
2126
  try {
1963
2127
  emitProgress(options.onProgress, {
1964
- operation: 'download',
1965
- phase: 'decrypt',
2128
+ operation: "download",
2129
+ phase: "decrypt",
1966
2130
  storageId: pointer.storageId,
1967
2131
  bytesTransferred: 0,
1968
2132
  totalBytes: pointer.size,
@@ -1975,15 +2139,15 @@ export async function resolveMediaAttachment(attachment, options) {
1975
2139
  throw new MediaAttachmentError(`Media attachment plaintext size mismatch: expected ${pointer.size}, received ${data.length}`, MediaAttachmentErrorCode.PlaintextSizeMismatch);
1976
2140
  }
1977
2141
  emitProgress(options.onProgress, {
1978
- operation: 'download',
1979
- phase: 'decrypt',
2142
+ operation: "download",
2143
+ phase: "decrypt",
1980
2144
  storageId: pointer.storageId,
1981
2145
  bytesTransferred: data.length,
1982
2146
  totalBytes: pointer.size,
1983
2147
  });
1984
2148
  emitProgress(options.onProgress, {
1985
- operation: 'download',
1986
- phase: 'complete',
2149
+ operation: "download",
2150
+ phase: "complete",
1987
2151
  storageId: pointer.storageId,
1988
2152
  bytesTransferred: data.length,
1989
2153
  totalBytes: pointer.size,
@@ -2012,7 +2176,7 @@ export async function resolveMediaAttachment(attachment, options) {
2012
2176
  if (error instanceof MediaAttachmentError) {
2013
2177
  throw error;
2014
2178
  }
2015
- throw new MediaAttachmentError('Media attachment decryption failed', MediaAttachmentErrorCode.DecryptionFailed, { cause: error });
2179
+ throw new MediaAttachmentError("Media attachment decryption failed", MediaAttachmentErrorCode.DecryptionFailed, { cause: error });
2016
2180
  }
2017
2181
  finally {
2018
2182
  secureZeroBytes(keyBytes);
@@ -2022,12 +2186,12 @@ export async function deleteMediaAttachment(attachment, options) {
2022
2186
  const pointer = createMediaAttachmentPointer(attachment);
2023
2187
  assertNotAborted(options.signal);
2024
2188
  if (!options.remoteObjectStore.deleteObject) {
2025
- throw new MediaAttachmentError('Media attachment remote delete is unavailable for the configured object store', MediaAttachmentErrorCode.DeleteUnavailable);
2189
+ throw new MediaAttachmentError("Media attachment remote delete is unavailable for the configured object store", MediaAttachmentErrorCode.DeleteUnavailable);
2026
2190
  }
2027
2191
  try {
2028
2192
  emitProgress(options.onProgress, {
2029
- operation: 'delete',
2030
- phase: 'delete',
2193
+ operation: "delete",
2194
+ phase: "delete",
2031
2195
  storageId: pointer.storageId,
2032
2196
  });
2033
2197
  await options.remoteObjectStore.deleteObject({
@@ -2035,8 +2199,8 @@ export async function deleteMediaAttachment(attachment, options) {
2035
2199
  });
2036
2200
  assertNotAborted(options.signal);
2037
2201
  emitProgress(options.onProgress, {
2038
- operation: 'delete',
2039
- phase: 'complete',
2202
+ operation: "delete",
2203
+ phase: "complete",
2040
2204
  storageId: pointer.storageId,
2041
2205
  });
2042
2206
  return {
@@ -2046,9 +2210,9 @@ export async function deleteMediaAttachment(attachment, options) {
2046
2210
  }
2047
2211
  catch (cause) {
2048
2212
  if (options.signal?.aborted) {
2049
- throw new MediaAttachmentError('Media attachment operation cancelled', MediaAttachmentErrorCode.Cancelled, { cause: options.signal.reason });
2213
+ throw new MediaAttachmentError("Media attachment operation cancelled", MediaAttachmentErrorCode.Cancelled, { cause: options.signal.reason });
2050
2214
  }
2051
- throw new MediaAttachmentError('Media attachment remote delete failed', MediaAttachmentErrorCode.DeleteFailed, { cause });
2215
+ throw new MediaAttachmentError("Media attachment remote delete failed", MediaAttachmentErrorCode.DeleteFailed, { cause });
2052
2216
  }
2053
2217
  }
2054
2218
  export const downloadMediaAttachment = resolveMediaAttachment;