@ghostlytools/cli 1.11.4 → 1.12.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 (218) hide show
  1. package/README.md +28 -11
  2. package/dist/assets/{api-MYc6QNRs.js → api-DLzCtePC.js} +363 -125
  3. package/dist/assets/api-DLzCtePC.js.map +1 -0
  4. package/dist/assets/{api-BwyFq4lA.js → api-DYMKyb1k.js} +2 -2
  5. package/dist/assets/{apiKit-CfsNx9ZR.js → apiKit-CVaEzKWQ.js} +48 -11
  6. package/dist/assets/apiKit-CVaEzKWQ.js.map +1 -0
  7. package/dist/assets/appFetch-D56GsYuq.js +602 -0
  8. package/dist/assets/appFetch-D56GsYuq.js.map +1 -0
  9. package/dist/assets/apps-BPFW19Wc.js +1 -0
  10. package/dist/assets/{apps-h12II1us.js → apps-XnZ8VEuj.js} +20 -14
  11. package/dist/assets/apps-XnZ8VEuj.js.map +1 -0
  12. package/dist/assets/{argon2id-088uQfnH.js → argon2id-B9wFdSj6.js} +2 -3
  13. package/dist/assets/{argon2id-088uQfnH.js.map → argon2id-B9wFdSj6.js.map} +1 -1
  14. package/dist/assets/{arkade-Bw_4PZRG.js → arkade-DryM-q5n.js} +6 -7
  15. package/dist/assets/arkade-DryM-q5n.js.map +1 -0
  16. package/dist/assets/backup-COX6j1_W.js +1 -0
  17. package/dist/assets/{backup-Chvy79SN.js → backup-DpyvT9Z6.js} +66 -21
  18. package/dist/assets/backup-DpyvT9Z6.js.map +1 -0
  19. package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js +5 -0
  20. package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js.map +1 -0
  21. package/dist/assets/{bark_ffi_wasm_bg-Bxru_BVW.wasm → bark_ffi_wasm_bg-VNmaJsc9.wasm} +0 -0
  22. package/dist/assets/{bitcoind-CdSmvy2y.js → bitcoind-DTsrd7TF.js} +4 -5
  23. package/dist/assets/{bitcoind-CdSmvy2y.js.map → bitcoind-DTsrd7TF.js.map} +1 -1
  24. package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js +5 -0
  25. package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js.map +1 -0
  26. package/dist/assets/bitcoindevkit_bg-DXil67yS.wasm +0 -0
  27. package/dist/assets/{blobFiles-BmsrvZc3.js → blobFiles-DDs34n0r.js} +4 -5
  28. package/dist/assets/{blobFiles-BmsrvZc3.js.map → blobFiles-DDs34n0r.js.map} +1 -1
  29. package/dist/assets/breez_sdk_spark_wasm_bg.wasm +0 -0
  30. package/dist/assets/buttons-Bq7pTXqF.js +1 -0
  31. package/dist/assets/{buttons-BgoExb4E.js → buttons-BvWqHJeh.js} +45 -23
  32. package/dist/assets/buttons-BvWqHJeh.js.map +1 -0
  33. package/dist/assets/bytes-C1DNGY18.js +132 -0
  34. package/dist/assets/bytes-C1DNGY18.js.map +1 -0
  35. package/dist/assets/{childEnv-K_IzUqQx.js → childEnv-C-99hdbL.js} +2 -3
  36. package/dist/assets/{childEnv-K_IzUqQx.js.map → childEnv-C-99hdbL.js.map} +1 -1
  37. package/dist/assets/{client-DY8tZZWi.js → client-kGZ3ZdUW.js} +5 -8
  38. package/dist/assets/{client-DY8tZZWi.js.map → client-kGZ3ZdUW.js.map} +1 -1
  39. package/dist/assets/{codec-BnMg-Grj.js → codec-B2rH1mfx.js} +2 -4
  40. package/dist/assets/{codec-BnMg-Grj.js.map → codec-B2rH1mfx.js.map} +1 -1
  41. package/dist/assets/domainProofs-BDNP1dIy.js +280 -0
  42. package/dist/assets/domainProofs-BDNP1dIy.js.map +1 -0
  43. package/dist/assets/{endpoint-DarqblYE.js → endpoint-B0vE5ojY.js} +421 -420
  44. package/dist/assets/endpoint-B0vE5ojY.js.map +1 -0
  45. package/dist/assets/engineErrors--9hfgKlK.js +150 -0
  46. package/dist/assets/engineErrors--9hfgKlK.js.map +1 -0
  47. package/dist/assets/{envelope-CdV7vHVZ.js → envelope-Bi2kMqbp.js} +3 -4
  48. package/dist/assets/{envelope-CdV7vHVZ.js.map → envelope-Bi2kMqbp.js.map} +1 -1
  49. package/dist/assets/{errors-CAh6GLJZ.js → errors-DDLFO4Gf.js} +5 -4
  50. package/dist/assets/errors-DDLFO4Gf.js.map +1 -0
  51. package/dist/assets/{fedimintSdk-CPFfVK-G.js → fedimintSdk-D-6H9Pe7.js} +4 -5
  52. package/dist/assets/{fedimintSdk-CPFfVK-G.js.map → fedimintSdk-D-6H9Pe7.js.map} +1 -1
  53. package/dist/assets/fedimint_client_wasm_bg-Cr5xGD-w.js +5 -0
  54. package/dist/assets/{fedimint_client_wasm_bg-BtHHlFpp.js.map → fedimint_client_wasm_bg-Cr5xGD-w.js.map} +1 -1
  55. package/dist/assets/fileBytes-CCKbwqG_.js +1 -0
  56. package/dist/assets/{fileBytes-BLPZq9YU.js → fileBytes-CfvUXdSy.js} +5 -7
  57. package/dist/assets/fileBytes-CfvUXdSy.js.map +1 -0
  58. package/dist/assets/{fileBytes-B0z9A6Le.js → fileBytes-tj6-VZcB.js} +3 -4
  59. package/dist/assets/{fileBytes-B0z9A6Le.js.map → fileBytes-tj6-VZcB.js.map} +1 -1
  60. package/dist/assets/fileBytesIdb-B0zzJ6p7.js +1 -0
  61. package/dist/assets/{fileBytesIdb-Bmlrl9EO.js → fileBytesIdb-BJirUAjI.js} +4 -5
  62. package/dist/assets/{fileBytesIdb-Bmlrl9EO.js.map → fileBytesIdb-BJirUAjI.js.map} +1 -1
  63. package/dist/assets/{fileBytesOpfs-DBS0kbPT.js → fileBytesOpfs-DRUYLER4.js} +4 -5
  64. package/dist/assets/{fileBytesOpfs-DBS0kbPT.js.map → fileBytesOpfs-DRUYLER4.js.map} +1 -1
  65. package/dist/assets/{fixedHosts-CbgqrIKs.js → fixedHosts-CPSsGOI2.js} +4 -5
  66. package/dist/assets/{fixedHosts-CbgqrIKs.js.map → fixedHosts-CPSsGOI2.js.map} +1 -1
  67. package/dist/assets/{ghostly_iroh_web-BzAXJUYH.js → ghostly_iroh_web-DIj5xGmR.js} +2 -3
  68. package/dist/assets/{ghostly_iroh_web-BzAXJUYH.js.map → ghostly_iroh_web-DIj5xGmR.js.map} +1 -1
  69. package/dist/assets/{src-DJe-OYxd.js → groupMeta-DTQAJG50.js} +4693 -24241
  70. package/dist/assets/groupMeta-DTQAJG50.js.map +1 -0
  71. package/dist/assets/{host-C0NMNQLl.js → host-z0FAHP9Z.js} +209 -134
  72. package/dist/assets/host-z0FAHP9Z.js.map +1 -0
  73. package/dist/assets/{hyperdhtRelay-Dz7pvcBA.js → hyperdhtRelay-CvsAfQRQ.js} +5 -6
  74. package/dist/assets/hyperdhtRelay-CvsAfQRQ.js.map +1 -0
  75. package/dist/assets/hyperdhtRelay-bjNGacf5.js +32 -0
  76. package/dist/assets/hyperdhtRelay-bjNGacf5.js.map +1 -0
  77. package/dist/assets/{idb-CEuoNsTv.js → idb-ewvbqyDI.js} +2 -3
  78. package/dist/assets/{idb-CEuoNsTv.js.map → idb-ewvbqyDI.js.map} +1 -1
  79. package/dist/assets/identityProofs-Cksc_K7_.js +940 -0
  80. package/dist/assets/identityProofs-Cksc_K7_.js.map +1 -0
  81. package/dist/assets/{irohWeb-caAj4Dms.js → irohWeb-CLBx5MIv.js} +3061 -86
  82. package/dist/assets/irohWeb-CLBx5MIv.js.map +1 -0
  83. package/dist/assets/joinTrace-CBr1jbch.js +1 -0
  84. package/dist/assets/{joinTrace-CjRDFy85.js → joinTrace-xKBe73j9.js} +2 -3
  85. package/dist/assets/{joinTrace-CjRDFy85.js.map → joinTrace-xKBe73j9.js.map} +1 -1
  86. package/dist/assets/{legacy_ciphers-JJOu0JXL.js → legacy_ciphers-BnYATjxo.js} +2 -3
  87. package/dist/assets/{legacy_ciphers-JJOu0JXL.js.map → legacy_ciphers-BnYATjxo.js.map} +1 -1
  88. package/dist/assets/linkPreview-DdMf-YAc.js +252 -0
  89. package/dist/assets/linkPreview-DdMf-YAc.js.map +1 -0
  90. package/dist/assets/{main-C6t5zrD5.js → main-CVqkvuIo.js} +268 -111
  91. package/dist/assets/main-CVqkvuIo.js.map +1 -0
  92. package/dist/assets/{mainline-DCuGUSZF.js → mainline-CVrd0C1n.js} +72 -18
  93. package/dist/assets/mainline-CVrd0C1n.js.map +1 -0
  94. package/dist/assets/mints-BcBODVVW.js +1 -0
  95. package/dist/assets/{mints-j5XAOk4f.js → mints-CMDLbMeH.js} +8 -6
  96. package/dist/assets/mints-CMDLbMeH.js.map +1 -0
  97. package/dist/assets/{nacl-fast-CDhNCYHs.js → nacl-fast-B1ThWvuM.js} +2 -3
  98. package/dist/assets/{nacl-fast-CDhNCYHs.js.map → nacl-fast-B1ThWvuM.js.map} +1 -1
  99. package/dist/assets/{networkReason-BbQW1Xpc.js → networkReason-Be-hMghr.js} +10 -14
  100. package/dist/assets/{networkReason-BbQW1Xpc.js.map → networkReason-Be-hMghr.js.map} +1 -1
  101. package/dist/assets/{noble_curves-DDWn5AH0.js → noble_curves-DqpNlhAU.js} +3 -4
  102. package/dist/assets/{noble_curves-DDWn5AH0.js.map → noble_curves-DqpNlhAU.js.map} +1 -1
  103. package/dist/assets/{noble_hashes-B7AZyFyS.js → noble_hashes-LFe1N2xt.js} +3 -4
  104. package/dist/assets/{noble_hashes-B7AZyFyS.js.map → noble_hashes-LFe1N2xt.js.map} +1 -1
  105. package/dist/assets/{nwc-CSDRMZ0e.js → nwc-DKE2FXr6.js} +5 -6
  106. package/dist/assets/{nwc-CSDRMZ0e.js.map → nwc-DKE2FXr6.js.map} +1 -1
  107. package/dist/assets/nwcProvider-pL2XqSbW.js +208 -0
  108. package/dist/assets/nwcProvider-pL2XqSbW.js.map +1 -0
  109. package/dist/assets/{openpgp-BBFr-zHQ.js → openpgp-LkR_Zof0.js} +14 -15
  110. package/dist/assets/{openpgp-BBFr-zHQ.js.map → openpgp-LkR_Zof0.js.map} +1 -1
  111. package/dist/assets/ownDid-DY3rYqDI.js +862 -0
  112. package/dist/assets/ownDid-DY3rYqDI.js.map +1 -0
  113. package/dist/assets/{ownStatus-BoTf5WqQ.js → ownStatus-DMEhrpkd.js} +69 -20
  114. package/dist/assets/ownStatus-DMEhrpkd.js.map +1 -0
  115. package/dist/assets/pairedTransports-BKmvlKz1.js +581 -0
  116. package/dist/assets/pairedTransports-BKmvlKz1.js.map +1 -0
  117. package/dist/assets/paymentIntent-DySU3Ajm.js +349 -0
  118. package/dist/assets/paymentIntent-DySU3Ajm.js.map +1 -0
  119. package/dist/assets/pkarr-BQo4PcCg.js +367 -0
  120. package/dist/assets/pkarr-BQo4PcCg.js.map +1 -0
  121. package/dist/assets/{profiles-DszHjEJi.js → profiles-BFSGqDFC.js} +9 -10
  122. package/dist/assets/profiles-BFSGqDFC.js.map +1 -0
  123. package/dist/assets/registry-B15Yg_1C.js +1 -0
  124. package/dist/assets/{registry-Da-r6eC3.js → registry-rXgaZeNn.js} +1261 -53
  125. package/dist/assets/registry-rXgaZeNn.js.map +1 -0
  126. package/dist/assets/relay-Cjfmdec0.js +2219 -0
  127. package/dist/assets/relay-Cjfmdec0.js.map +1 -0
  128. package/dist/assets/resolve-CIc3KZMV.js +970 -0
  129. package/dist/assets/resolve-CIc3KZMV.js.map +1 -0
  130. package/dist/assets/{restoredRows-C3LcxmOw.js → restoredRows-D_WSHE7H.js} +3 -4
  131. package/dist/assets/{restoredRows-C3LcxmOw.js.map → restoredRows-D_WSHE7H.js.map} +1 -1
  132. package/dist/assets/{secretGuard-CsVHDdYk.js → secretGuard-B4-LlMjv.js} +11 -14
  133. package/dist/assets/{secretGuard-CsVHDdYk.js.map → secretGuard-B4-LlMjv.js.map} +1 -1
  134. package/dist/assets/secretGuard-BmmnEbYf.js +1 -0
  135. package/dist/assets/{server-C1jZZ61O.js → server-CQR7NLCz.js} +9565 -461
  136. package/dist/assets/server-CQR7NLCz.js.map +1 -0
  137. package/dist/assets/{sha512-BYId-G-T.js → sha512-DST9fbWH.js} +2 -3
  138. package/dist/assets/{sha512-BYId-G-T.js.map → sha512-DST9fbWH.js.map} +1 -1
  139. package/dist/assets/sshForges-BnvwmNj-.js +539 -0
  140. package/dist/assets/sshForges-BnvwmNj-.js.map +1 -0
  141. package/dist/assets/{storage-Bya5b2Xt.js → storage-BpjdxvO2.js} +243 -34
  142. package/dist/assets/storage-BpjdxvO2.js.map +1 -0
  143. package/dist/assets/text-li76pThX.js +106 -0
  144. package/dist/assets/text-li76pThX.js.map +1 -0
  145. package/dist/assets/{translate-CUuC5szR.js → translate-BcbSWkuq.js} +21 -26
  146. package/dist/assets/{translate-CUuC5szR.js.map → translate-BcbSWkuq.js.map} +1 -1
  147. package/dist/assets/{tree-store-N362nuzZ.js → tree-store-CAchkO_l.js} +22 -6
  148. package/dist/assets/tree-store-CAchkO_l.js.map +1 -0
  149. package/dist/assets/{types-Clyb52K2.js → types-CdWwgvyt.js} +2 -3
  150. package/dist/assets/{types-Clyb52K2.js.map → types-CdWwgvyt.js.map} +1 -1
  151. package/dist/assets/{unbzip2-stream-B1C-JX9L.js → unbzip2-stream-BtkYGpC5.js} +2 -3
  152. package/dist/assets/{unbzip2-stream-B1C-JX9L.js.map → unbzip2-stream-BtkYGpC5.js.map} +1 -1
  153. package/dist/assets/{usdt-DI51znt-.js → usdt-CBJ4Q5Ji.js} +7 -7
  154. package/dist/assets/usdt-CBJ4Q5Ji.js.map +1 -0
  155. package/dist/assets/{waitNotice-Cn0WJ-He.js → waitNotice-BGM0QOS2.js} +27 -4
  156. package/dist/assets/waitNotice-BGM0QOS2.js.map +1 -0
  157. package/dist/assets/{web-DwgdhfcY.js → web-68CYFCl9.js} +314 -91
  158. package/dist/assets/web-68CYFCl9.js.map +1 -0
  159. package/dist/ghostly.mjs +3 -5
  160. package/dist/ghostly.mjs.map +1 -1
  161. package/npm-shrinkwrap.json +225 -200
  162. package/package.json +16 -16
  163. package/dist/assets/api-MYc6QNRs.js.map +0 -1
  164. package/dist/assets/apiKit-CfsNx9ZR.js.map +0 -1
  165. package/dist/assets/appFetch-DVYZOZFw.js +0 -194
  166. package/dist/assets/appFetch-DVYZOZFw.js.map +0 -1
  167. package/dist/assets/apps-Dbw2Hcko.js +0 -2
  168. package/dist/assets/apps-h12II1us.js.map +0 -1
  169. package/dist/assets/arkade-Bw_4PZRG.js.map +0 -1
  170. package/dist/assets/backup-CdEzTq5C.js +0 -2
  171. package/dist/assets/backup-Chvy79SN.js.map +0 -1
  172. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js +0 -6
  173. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +0 -1
  174. package/dist/assets/bitcoindProvider-BvoRh0D5.js +0 -97
  175. package/dist/assets/bitcoindProvider-BvoRh0D5.js.map +0 -1
  176. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js +0 -6
  177. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +0 -1
  178. package/dist/assets/bitcoindevkit_bg-CRkZTSbO.wasm +0 -0
  179. package/dist/assets/buttons-BgoExb4E.js.map +0 -1
  180. package/dist/assets/buttons-DK2aAGat.js +0 -2
  181. package/dist/assets/endpoint-DarqblYE.js.map +0 -1
  182. package/dist/assets/errors-CAh6GLJZ.js.map +0 -1
  183. package/dist/assets/fedimint_client_wasm_bg-BtHHlFpp.js +0 -6
  184. package/dist/assets/fileBytes-BLPZq9YU.js.map +0 -1
  185. package/dist/assets/fileBytes-BtIyoDF2.js +0 -2
  186. package/dist/assets/fileBytesIdb-D8mAK4pF.js +0 -2
  187. package/dist/assets/host-C0NMNQLl.js.map +0 -1
  188. package/dist/assets/hyperdhtRelay-1wzya_0L.js +0 -25
  189. package/dist/assets/hyperdhtRelay-1wzya_0L.js.map +0 -1
  190. package/dist/assets/hyperdhtRelay-Dz7pvcBA.js.map +0 -1
  191. package/dist/assets/irohWeb-caAj4Dms.js.map +0 -1
  192. package/dist/assets/joinTrace-D-fnt2p3.js +0 -2
  193. package/dist/assets/jsonOut-POtMBS_V.js +0 -16
  194. package/dist/assets/jsonOut-POtMBS_V.js.map +0 -1
  195. package/dist/assets/main-C6t5zrD5.js.map +0 -1
  196. package/dist/assets/mainline-DCuGUSZF.js.map +0 -1
  197. package/dist/assets/mints-BaOmx517.js +0 -2
  198. package/dist/assets/mints-j5XAOk4f.js.map +0 -1
  199. package/dist/assets/nwcProvider-PE0wli8n.js +0 -88
  200. package/dist/assets/nwcProvider-PE0wli8n.js.map +0 -1
  201. package/dist/assets/ownDid-C1R5Kd8q.js +0 -282
  202. package/dist/assets/ownDid-C1R5Kd8q.js.map +0 -1
  203. package/dist/assets/ownStatus-BoTf5WqQ.js.map +0 -1
  204. package/dist/assets/profiles-DszHjEJi.js.map +0 -1
  205. package/dist/assets/registry-Da-r6eC3.js.map +0 -1
  206. package/dist/assets/registry-zUZBSHYv.js +0 -2
  207. package/dist/assets/resolve-tUzh4lHh.js +0 -400
  208. package/dist/assets/resolve-tUzh4lHh.js.map +0 -1
  209. package/dist/assets/secretGuard-DCb1I0_B.js +0 -2
  210. package/dist/assets/server-C1jZZ61O.js.map +0 -1
  211. package/dist/assets/src-DJe-OYxd.js.map +0 -1
  212. package/dist/assets/sshForges-C9zTO72R.js +0 -261
  213. package/dist/assets/sshForges-C9zTO72R.js.map +0 -1
  214. package/dist/assets/storage-Bya5b2Xt.js.map +0 -1
  215. package/dist/assets/tree-store-N362nuzZ.js.map +0 -1
  216. package/dist/assets/usdt-DI51znt-.js.map +0 -1
  217. package/dist/assets/waitNotice-Cn0WJ-He.js.map +0 -1
  218. package/dist/assets/web-DwgdhfcY.js.map +0 -1
@@ -1,15 +1,2971 @@
1
- import { $i as identityStatement, $u as budgetRetryMs, Cd as randomBytes, Gi as IDENTITY_REVOCATION_LABEL, Gn as videoMetadataPatches, Hn as audioMetadataPatches, Ji as boundIdentityDisplay, Jn as PICTURE_METADATA_LIMITS, Jr as ChatFiles, Ki as IdentityCheckUnavailable, Kn as withoutVideoMetadata, Mn as resolveLightningDestination, Nn as decodeBolt11, Qi as identityRevocationValue, Qr as transferEnded, To as replySnippet, Un as withoutAudioMetadata, Wi as IDENTITY_MAX_VALIDITY, Xi as emptyIdentityLedger, Xn as stripPictureMetadata, Xr as FileUplink, Ya as fileMessageText, Yn as isStrippedPicture, Z as meshMessageRef, Zi as identityRefusal, _d as hasVisible, _r as readGroupHave, cn as WALLET_NETWORKS, da as irohDescriptor, ea as isIdentityBinding, ed as isDiscoveryBudgetError, fa as irohRelayUrl, fr as GROUP_WANT_NO_FRAME, gd as dropLoneJoiners, hn as walletNetworkOf, hr as isGroupMessageId, io as RateWindow, jn as requestLnurlInvoice, lr as GROUP_FILE_LIMITS, mr as groupFileFallback, na as receivedIdentityStatus, or as engineError, pr as fetchesByItself, qi as IdentityExchange, qn as NO_PICTURE_METADATA, ra as revokesIdentity, sr as engineText, ta as newIdentityBinding, ua as dialableIrohRelay, ur as GROUP_HAVE_FRAME, vr as readGroupWant, wd as toBase64Url, xd as fromBase64Url, yd as stripHidden, yr as readGroupWantNo } from "./src-DJe-OYxd.js";
2
- import { a as describeProvider, c as offeredIn, d as sourceProblem, n as PROVIDER_PLATFORMS, o as isNothingSpentError, s as networkMode, t as NothingSpentError, u as redact } from "./types-Clyb52K2.js";
3
- import { r as nwcWalletName, t as nwc } from "./nwcProvider-PE0wli8n.js";
4
- import { b as transact, f as errorLine, p as fileStore, s as STORES, u as databaseName, x as wrap, y as store } from "./idb-CEuoNsTv.js";
5
- import { a as sealSeed, g as whenDataKeyDropped, h as sealSecret, i as newDeviceKey, m as openSecret, o as unsealSeed, t as networkReason } from "./networkReason-BbQW1Xpc.js";
6
- import { f as FILE_BYTES_STEP, o as fileBytes, r as blobDigest, s as fileBytesOf } from "./fileBytes-BLPZq9YU.js";
7
- import { t as BITCOIN_INVOICE_ON_TESTNET, u as mintNetwork } from "./mints-j5XAOk4f.js";
8
- import { c as boundedIdentityFetch, l as verifyIdentity } from "./ownDid-C1R5Kd8q.js";
1
+ import { d as utf8Decode, f as utf8Encode, i as fromBase64Url, l as toBase64Url, n as concatBytes, s as randomBytes } from "./bytes-C1DNGY18.js";
2
+ import { a as stripHidden, n as hasVisible, s as unwrapPasted, t as dropLoneJoiners } from "./text-li76pThX.js";
3
+ import { c as irohRelayUrl, d as relayUrlTooLong, o as dialableIrohRelay, s as irohDescriptor, u as relayUrl } from "./pairedTransports-BKmvlKz1.js";
4
+ import { _ as identityFromSeed, y as publicKeyFromZ32 } from "./pkarr-BQo4PcCg.js";
5
+ import { m as isDiscoveryBudgetError, p as budgetRetryMs } from "./relay-Cjfmdec0.js";
6
+ import { A as GROUP_WANT_NO_FRAME, An as fileMessageText, D as GROUP_FILE_LIMITS, F as readGroupHave, Hn as validRemovalNumber, I as readGroupWant, Ir as GROUP_ID, Ka as exifOrientation, L as readGroupWantNo, M as groupFileFallback, N as isGroupMessageId, O as GROUP_HAVE_FRAME, On as baseMime, Tr as readStatusCard, Vn as validEditNumber, gt as FileUplink, ii as edgeParams, j as fetchesByItself, mt as ChatFiles, or as replySnippet, vt as transferEnded, xr as cardEditNumber, zn as RateWindow, zr as MEMBER_KEY } from "./groupMeta-DTQAJG50.js";
7
+ import { _ as receivedIdentityStatus, c as IdentityExchange, d as emptyIdentityLedger, f as identityRefusal, g as newIdentityBinding, h as isIdentityBinding, i as IDENTITY_MAX_VALIDITY, l as boundIdentityDisplay, m as identityStatement, o as IDENTITY_REVOCATION_LABEL, p as identityRevocationValue, s as IdentityCheckUnavailable, v as revokesIdentity } from "./identityProofs-Cksc_K7_.js";
8
+ import { n as engineError, r as engineText } from "./engineErrors--9hfgKlK.js";
9
+ import { g as walletNetworkOf, l as WALLET_NETWORKS } from "./paymentIntent-DySU3Ajm.js";
10
+ import { a as decodeBolt11, r as nwcWalletName, t as nwc } from "./nwcProvider-pL2XqSbW.js";
11
+ import { c as boundedIdentityFetch, l as verifyIdentity } from "./ownDid-DY3rYqDI.js";
12
+ import { a as describeProvider, c as offeredIn, d as sourceProblem, n as PROVIDER_PLATFORMS, o as isNothingSpentError, s as networkMode, t as NothingSpentError, u as redact } from "./types-CdWwgvyt.js";
13
+ import { b as transact, f as errorLine, p as fileStore, s as STORES, u as databaseName, x as wrap, y as store } from "./idb-ewvbqyDI.js";
14
+ import { a as sealSeed, g as whenDataKeyDropped, h as sealSecret, i as newDeviceKey, m as openSecret, o as unsealSeed, t as networkReason } from "./networkReason-Be-hMghr.js";
15
+ import { f as FILE_BYTES_STEP, o as fileBytes, r as blobDigest, s as fileBytesOf } from "./fileBytes-CfvUXdSy.js";
16
+ import { t as BITCOIN_INVOICE_ON_TESTNET, u as mintNetwork } from "./mints-CMDLbMeH.js";
9
17
  import { sha256 } from "@noble/hashes/sha2.js";
18
+ import { hkdf } from "@noble/hashes/hkdf.js";
19
+ import { bech32 } from "@scure/base";
20
+ import { xchacha20poly1305 } from "@noble/ciphers/chacha.js";
10
21
  import { validateMnemonic } from "@scure/bip39";
11
22
  import { wordlist } from "@scure/bip39/wordlists/english.js";
12
- //#region ../browser/src/engine/paymentAdapters/away.ts
23
+ // ../core/src/pictureMetadata.ts
24
+ /**
25
+ * What a picture leaves with. A photo's file says more than its pixels: its Exif and XMP hold where it was taken, the
26
+ * device, the time, often a thumbnail of the uncropped original. The sender removes them before the file is stored and
27
+ * its digest computed, so what the contact (or anyone in a community) receives is the picture alone: JPEG, PNG, WebP
28
+ * and HEIF (HEIC, AVIF), without decoding or re-encoding a pixel.
29
+ *
30
+ * Fail-closed: a file that is one of these pictures, by its bytes or by its type, and whose metadata cannot be removed
31
+ * (truncated, malformed, a part this does not know) is refused with `NO_PICTURE_METADATA`, never sent as it was. So is
32
+ * a JPEG XL or a JPEG 2000 in its boxes (their Exif, XMP and GeoJP2 boxes are not removed here). Any other file goes
33
+ * as it is.
34
+ */
35
+ var PICTURE_METADATA_LIMITS = {
36
+ /** The largest picture read whole to remove its metadata: past this it is refused. */
37
+ maxBytes: 268435456,
38
+ /** Bytes read first to tell a picture from another file. */
39
+ headBytes: 64
40
+ };
41
+ /** Why a picture is refused: its metadata could not be removed, so it does not go at all. */
42
+ var NO_PICTURE_METADATA = "This picture cannot be sent: Ghostly could not remove the details saved in it, like where it was taken";
43
+ /** The types of the pictures stripped here: a file of one of them whose bytes are not that picture is refused. */
44
+ var STRIPPED_TYPES$1 = /* @__PURE__ */ new Set([
45
+ "image/jpeg",
46
+ "image/jpg",
47
+ "image/pjpeg",
48
+ "image/png",
49
+ "image/apng",
50
+ "image/webp",
51
+ "image/heic",
52
+ "image/heif",
53
+ "image/heic-sequence",
54
+ "image/heif-sequence",
55
+ "image/avif",
56
+ "image/gif",
57
+ "image/tiff",
58
+ "image/tiff-fx"
59
+ ]);
60
+ /** HEIF brands (HEIC, AVIF, the generic `mif1`): an MP4 video's `ftyp` names none of them. */
61
+ var HEIF_BRANDS = /* @__PURE__ */ new Set([
62
+ "heic",
63
+ "heix",
64
+ "heim",
65
+ "heis",
66
+ "hevc",
67
+ "hevx",
68
+ "mif1",
69
+ "mif2",
70
+ "msf1",
71
+ "avif",
72
+ "avis"
73
+ ]);
74
+ /** The signature box a JPEG XL (`JXL `) or a JPEG 2000 (`jP `) in boxes starts with. */
75
+ var SIGNATURE_BOXES = /* @__PURE__ */ new Set(["JXL ", "jP "]);
76
+ var u16be = (b, at) => b[at] << 8 | b[at + 1];
77
+ var u32be$2 = (b, at) => (b[at] << 24 >>> 0) + (b[at + 1] << 16) + (b[at + 2] << 8) + b[at + 3];
78
+ var u32le$2 = (b, at) => (b[at] | b[at + 1] << 8 | b[at + 2] << 16 | b[at + 3] << 24) >>> 0;
79
+ var text$2 = (b, at, length) => String.fromCharCode(...b.subarray(at, at + length));
80
+ var starts = (b, at, prefix) => at + prefix.length <= b.length && text$2(b, at, prefix.length) === prefix;
81
+ /** A picture this strips, by its first bytes. */
82
+ function kindOf(b) {
83
+ if (b.length >= 3 && b[0] === 255 && b[1] === 216 && b[2] === 255) return "jpeg";
84
+ if (b.length >= 8 && b[0] === 137 && starts(b, 1, "PNG\r\n\n")) return "png";
85
+ if (b.length >= 12 && starts(b, 0, "RIFF") && starts(b, 8, "WEBP")) return "webp";
86
+ if (starts(b, 0, "GIF87a") || starts(b, 0, "GIF89a")) return "gif";
87
+ if (starts(b, 0, "II*\0") || starts(b, 0, "MM\0*") || starts(b, 0, "II+\0") || starts(b, 0, "MM\0+")) return "tiff";
88
+ if (b.length >= 12 && u32be$2(b, 0) === 12 && SIGNATURE_BOXES.has(text$2(b, 4, 4)) && u32be$2(b, 8) === 218793738) return "boxes";
89
+ if (b.length >= 16 && starts(b, 4, "ftyp")) {
90
+ const end = Math.min(b.length, u32be$2(b, 0));
91
+ for (let at = 8; at + 4 <= end; at += 4) if (at !== 12 && HEIF_BRANDS.has(text$2(b, at, 4))) return "heif";
92
+ }
93
+ }
94
+ /** Refuses the picture where its bytes are not what this expects. */
95
+ function check$2(ok) {
96
+ if (!ok) throw new Error(NO_PICTURE_METADATA);
97
+ }
98
+ /** SOFn markers: every frame type but DHT (C4), JPG (C8) and DAC (CC). */
99
+ var JPEG_FRAME = /* @__PURE__ */ new Set([
100
+ 192,
101
+ 193,
102
+ 194,
103
+ 195,
104
+ 197,
105
+ 198,
106
+ 199,
107
+ 201,
108
+ 202,
109
+ 203,
110
+ 205,
111
+ 206,
112
+ 207
113
+ ]);
114
+ function jpegKeeps(marker, b, payload) {
115
+ if (marker >= 192 && marker <= 207 || marker >= 218 && marker <= 223) return true;
116
+ if (marker === 224) return starts(b, payload, "JFIF\0");
117
+ if (marker === 226) return starts(b, payload, "ICC_PROFILE\0");
118
+ if (marker === 238) return starts(b, payload, "Adobe");
119
+ return false;
120
+ }
121
+ /** An Exif (its TIFF), big-endian, whose IFD0 holds `orientation` alone: all a picture keeps of its Exif. */
122
+ var orientationTiff = (orientation) => Uint8Array.of(77, 77, 0, 42, 0, 0, 0, 8, 0, 1, 1, 18, 0, 3, 0, 0, 0, 1, 0, orientation, 0, 0, 0, 0, 0, 0);
123
+ /** An APP1 Exif whose IFD0 holds `orientation` alone. */
124
+ var orientationOnly = (orientation) => Uint8Array.of(255, 225, 0, 34, 69, 120, 105, 102, 0, 0, ...orientationTiff(orientation));
125
+ function stripJpeg(b) {
126
+ const parts = [b.subarray(0, 2)];
127
+ let at = 2, framed = false, scanned = false, exif = false;
128
+ for (;;) {
129
+ check$2(at < b.length && b[at] === 255);
130
+ while (at < b.length && b[at] === 255) at++;
131
+ check$2(at < b.length);
132
+ const marker = b[at++];
133
+ if (marker === 217) {
134
+ check$2(framed && scanned);
135
+ parts.push(Uint8Array.of(255, 217));
136
+ return parts;
137
+ }
138
+ if (marker === 1 || marker >= 208 && marker <= 215) {
139
+ parts.push(Uint8Array.of(255, marker));
140
+ continue;
141
+ }
142
+ check$2(marker !== 0 && marker !== 216 && at + 2 <= b.length);
143
+ const length = u16be(b, at);
144
+ check$2(length >= 2 && at + length <= b.length);
145
+ if (marker === 224 && length > 16 && starts(b, at + 2, "JFIF\0")) parts.push(Uint8Array.of(255, 224, 0, 16, ...b.subarray(at + 2, at + 14), 0, 0));
146
+ else if (jpegKeeps(marker, b, at + 2)) {
147
+ parts.push(Uint8Array.of(255, marker), b.subarray(at, at + length));
148
+ if (JPEG_FRAME.has(marker)) framed = true;
149
+ } else if (marker === 225 && !scanned && !exif && starts(b, at + 2, "Exif\0\0")) {
150
+ exif = true;
151
+ const orientation = exifOrientation(b, at + 8, at + length);
152
+ if (orientation >= 2) parts.push(orientationOnly(orientation));
153
+ }
154
+ at += length;
155
+ if (marker !== 218) continue;
156
+ check$2(framed);
157
+ scanned = true;
158
+ let end = at;
159
+ for (;;) {
160
+ end = b.indexOf(255, end);
161
+ check$2(end >= 0);
162
+ let next = end + 1;
163
+ while (next < b.length && b[next] === 255) next++;
164
+ check$2(next < b.length);
165
+ if (b[next] !== 0 && !(b[next] >= 208 && b[next] <= 215)) break;
166
+ end = next + 1;
167
+ }
168
+ parts.push(b.subarray(at, end));
169
+ at = end;
170
+ }
171
+ }
172
+ var PNG_CRITICAL = /* @__PURE__ */ new Set([
173
+ "IHDR",
174
+ "PLTE",
175
+ "IDAT",
176
+ "IEND"
177
+ ]);
178
+ var PNG_DRAWS = /* @__PURE__ */ new Set([
179
+ "tRNS",
180
+ "gAMA",
181
+ "cHRM",
182
+ "sRGB",
183
+ "iCCP",
184
+ "sBIT",
185
+ "bKGD",
186
+ "pHYs",
187
+ "cICP",
188
+ "mDCV",
189
+ "cLLI",
190
+ "acTL",
191
+ "fcTL",
192
+ "fdAT"
193
+ ]);
194
+ var CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
195
+ for (let k = 0; k < 8; k++) n = n & 1 ? 3988292384 ^ n >>> 1 : n >>> 1;
196
+ return n >>> 0;
197
+ });
198
+ /** A PNG chunk: its length, type, data and the CRC of its type and data. */
199
+ function pngChunk(type, data) {
200
+ const out = new Uint8Array(12 + data.length), view = new DataView(out.buffer);
201
+ view.setUint32(0, data.length);
202
+ for (let i = 0; i < 4; i++) out[4 + i] = type.charCodeAt(i);
203
+ out.set(data, 8);
204
+ let crc = -1;
205
+ for (const byte of out.subarray(4, 8 + data.length)) crc = CRC_TABLE[(crc ^ byte) & 255] ^ crc >>> 8;
206
+ view.setUint32(8 + data.length, ~crc >>> 0);
207
+ return out;
208
+ }
209
+ function stripPng(b) {
210
+ const parts = [b.subarray(0, 8)];
211
+ let at = 8, exif = false, imaged = false;
212
+ for (;;) {
213
+ check$2(at + 12 <= b.length);
214
+ const length = u32be$2(b, at), type = text$2(b, at + 4, 4);
215
+ check$2(at + 12 + length <= b.length && (at > 8 || type === "IHDR"));
216
+ const critical = (b[at + 4] & 32) === 0;
217
+ check$2(!critical || PNG_CRITICAL.has(type));
218
+ if (critical || PNG_DRAWS.has(type)) parts.push(b.subarray(at, at + 12 + length));
219
+ else if (type === "eXIf" && !exif && !imaged) {
220
+ exif = true;
221
+ const orientation = exifOrientation(b, at + 8, at + 8 + length);
222
+ if (orientation >= 2) parts.push(pngChunk("eXIf", orientationTiff(orientation)));
223
+ }
224
+ if (type === "IDAT") imaged = true;
225
+ at += 12 + length;
226
+ if (type === "IEND") return parts;
227
+ }
228
+ }
229
+ var WEBP_KEEPS = /* @__PURE__ */ new Set([
230
+ "VP8 ",
231
+ "VP8L",
232
+ "VP8X",
233
+ "ALPH",
234
+ "ANIM",
235
+ "ANMF",
236
+ "ICCP"
237
+ ]);
238
+ function stripWebp(b) {
239
+ check$2(b.length >= 20);
240
+ const riffEnd = 8 + u32le$2(b, 4);
241
+ check$2(riffEnd <= b.length && riffEnd % 2 === 0);
242
+ const parts = [];
243
+ let at = 12, size = 4, drawn = false, exif = false, vp8x;
244
+ while (at < riffEnd) {
245
+ check$2(at + 8 <= riffEnd);
246
+ const type = text$2(b, at, 4), length = u32le$2(b, at + 4), end = at + 8 + length + (length & 1);
247
+ check$2(end <= riffEnd && (at > 12 || type === "VP8 " || type === "VP8L" || type === "VP8X"));
248
+ let chunk;
249
+ if (WEBP_KEEPS.has(type)) {
250
+ chunk = b.subarray(at, end);
251
+ if (type === "VP8X") {
252
+ check$2(length >= 10);
253
+ chunk = vp8x = chunk.slice();
254
+ chunk[8] = chunk[8] & -13;
255
+ }
256
+ if (type === "VP8 " || type === "VP8L" || type === "ANMF") drawn = true;
257
+ } else if (type === "EXIF" && !exif && vp8x) {
258
+ exif = true;
259
+ const tiff = starts(b, at + 8, "Exif\0\0") ? at + 14 : at + 8;
260
+ const orientation = exifOrientation(b, tiff, at + 8 + length);
261
+ if (orientation >= 2) {
262
+ const data = orientationTiff(orientation);
263
+ chunk = new Uint8Array(8 + data.length);
264
+ chunk.set([
265
+ 69,
266
+ 88,
267
+ 73,
268
+ 70,
269
+ data.length
270
+ ]);
271
+ chunk.set(data, 8);
272
+ vp8x[8] = vp8x[8] | 8;
273
+ }
274
+ }
275
+ if (chunk) {
276
+ parts.push(chunk);
277
+ size += chunk.length;
278
+ }
279
+ at = end;
280
+ }
281
+ check$2(drawn);
282
+ const header = /* @__PURE__ */ new Uint8Array(12);
283
+ header.set(b.subarray(0, 12));
284
+ new DataView(header.buffer).setUint32(4, size, true);
285
+ return [header, ...parts];
286
+ }
287
+ var HEIF_TOP = /* @__PURE__ */ new Set([
288
+ "ftyp",
289
+ "meta",
290
+ "mdat",
291
+ "free",
292
+ "skip"
293
+ ]);
294
+ var HEIF_META = /* @__PURE__ */ new Set([
295
+ "hdlr",
296
+ "dinf",
297
+ "pitm",
298
+ "iloc",
299
+ "iinf",
300
+ "iref",
301
+ "iprp",
302
+ "idat",
303
+ "grpl",
304
+ "free",
305
+ "skip"
306
+ ]);
307
+ /** Items that hold metadata: Exif, and XMP (or any other document) as a MIME item. */
308
+ var HEIF_METADATA_ITEMS = /* @__PURE__ */ new Set([
309
+ "Exif",
310
+ "mime",
311
+ "uri "
312
+ ]);
313
+ /**
314
+ * Item properties that only draw the picture: the codec's configuration (HEVC, AV1, AVC, VVC, JPEG, JPEG 2000,
315
+ * uncompressed and its components, layered HEVC with its operating points and layers), the size (`ispe`), the bits
316
+ * per channel (`pixi`), colour (`colr`, its light levels and display volumes `clli`, `mdcv`, `cclv`, `amve`), geometry
317
+ * (`irot`, `imir`, `clap`, `pasp`, `rloc`, `iscl`), what an auxiliary image is (`auxC`: alpha, depth, a gain map), and
318
+ * AV1's operating point and layers (`a1op`, `a1lx`).
319
+ */
320
+ var HEIF_DRAWS = /* @__PURE__ */ new Set([
321
+ "hvcC",
322
+ "av1C",
323
+ "avcC",
324
+ "vvcC",
325
+ "jpgC",
326
+ "j2kH",
327
+ "uncC",
328
+ "cmpd",
329
+ "lhvC",
330
+ "oinf",
331
+ "tols",
332
+ "lsel",
333
+ "ispe",
334
+ "pixi",
335
+ "colr",
336
+ "clli",
337
+ "mdcv",
338
+ "cclv",
339
+ "amve",
340
+ "irot",
341
+ "imir",
342
+ "clap",
343
+ "pasp",
344
+ "rloc",
345
+ "iscl",
346
+ "auxC",
347
+ "a1op",
348
+ "a1lx"
349
+ ]);
350
+ /** Item properties about the picture: its user description (name, description, tags), accessibility text, creation and modification times, TAI clock and timestamp; and `free`, `skip`. */
351
+ var HEIF_ABOUT = /* @__PURE__ */ new Set([
352
+ "udes",
353
+ "altt",
354
+ "crtt",
355
+ "mdft",
356
+ "taic",
357
+ "itai",
358
+ "free",
359
+ "skip"
360
+ ]);
361
+ function boxes$1(b, start, end) {
362
+ const found = [];
363
+ for (let at = start; at < end;) {
364
+ check$2(at + 8 <= end);
365
+ let size = u32be$2(b, at), body = at + 8;
366
+ const type = text$2(b, at + 4, 4);
367
+ if (size === 1) {
368
+ check$2(at + 16 <= end);
369
+ size = u32be$2(b, at + 8) * 2 ** 32 + u32be$2(b, at + 12);
370
+ body = at + 16;
371
+ } else if (size === 0) size = end - at;
372
+ if (type === "uuid") body += 16;
373
+ check$2(size >= body - at && at + size <= end);
374
+ found.push({
375
+ type,
376
+ start: at,
377
+ body,
378
+ end: at + size
379
+ });
380
+ at += size;
381
+ }
382
+ return found;
383
+ }
384
+ function stripHeif(b) {
385
+ const top = boxes$1(b, 0, b.length);
386
+ check$2(top[0]?.type === "ftyp" && top.every((box) => HEIF_TOP.has(box.type)));
387
+ const metas = top.filter((box) => box.type === "meta");
388
+ check$2(metas.length === 1);
389
+ const meta = metas[0];
390
+ const children = boxes$1(b, meta.body + 4, meta.end);
391
+ check$2(children.every((box) => HEIF_META.has(box.type)));
392
+ const one = (type) => {
393
+ const of = children.filter((box) => box.type === type);
394
+ check$2(of.length <= 1);
395
+ return of[0];
396
+ };
397
+ const iinf = one("iinf"), iloc = one("iloc"), idat = one("idat");
398
+ check$2(!!iinf && !!iloc);
399
+ const metadata = /* @__PURE__ */ new Set();
400
+ const infeVersion = b[iinf.body];
401
+ const entries = boxes$1(b, iinf.body + 4 + (infeVersion === 0 ? 2 : 4), iinf.end);
402
+ for (const infe of entries) {
403
+ check$2(infe.type === "infe" && infe.body + 4 <= infe.end);
404
+ const version = b[infe.body];
405
+ check$2(version === 2 || version === 3);
406
+ let at = infe.body + 4;
407
+ const id = version === 2 ? u16be(b, at) : u32be$2(b, at);
408
+ at += version === 2 ? 2 : 4;
409
+ check$2(at + 6 <= infe.end);
410
+ if (HEIF_METADATA_ITEMS.has(text$2(b, at + 2, 4))) metadata.add(id);
411
+ }
412
+ const iprp = one("iprp"), properties = [];
413
+ if (iprp) {
414
+ const held = boxes$1(b, iprp.body, iprp.end);
415
+ const ipco = held.filter((box) => box.type === "ipco");
416
+ check$2(ipco.length === 1 && held.every((box) => box.type === "ipco" || box.type === "ipma"));
417
+ properties.push(...boxes$1(b, ipco[0].body, ipco[0].end));
418
+ check$2(properties.every((box) => HEIF_DRAWS.has(box.type) || HEIF_ABOUT.has(box.type)));
419
+ }
420
+ /** `free` and `skip` boxes, at the top and in `meta`, and the properties about the picture: their bodies go as zeros. */
421
+ const space = [...[...top, ...children].filter((box) => box.type === "free" || box.type === "skip"), ...properties.filter((box) => HEIF_ABOUT.has(box.type))];
422
+ const out = b.slice();
423
+ const version = b[iloc.body];
424
+ check$2(version <= 2);
425
+ let at = iloc.body + 4;
426
+ /** The next field of `size` bytes (0, 2, 4 or 8), big-endian. */
427
+ const read = (size) => {
428
+ check$2(at + size <= iloc.end);
429
+ const value = size === 0 ? 0 : size === 2 ? u16be(b, at) : size === 4 ? u32be$2(b, at) : size === 8 ? u32be$2(b, at) * 2 ** 32 + u32be$2(b, at + 4) : NaN;
430
+ check$2(Number.isSafeInteger(value));
431
+ at += size;
432
+ return value;
433
+ };
434
+ const read2 = () => read(2);
435
+ check$2(at + 2 <= iloc.end);
436
+ const offsetSize = b[at] >> 4, lengthSize = b[at] & 15, baseSize = b[at + 1] >> 4, indexSize = version > 0 ? b[at + 1] & 15 : 0;
437
+ check$2([
438
+ offsetSize,
439
+ lengthSize,
440
+ baseSize,
441
+ indexSize
442
+ ].every((size) => size === 0 || size === 4 || size === 8));
443
+ at += 2;
444
+ const count = read(version < 2 ? 2 : 4);
445
+ for (let i = 0; i < count; i++) {
446
+ const id = version < 2 ? read2() : read(4);
447
+ const method = version > 0 ? read2() & 15 : 0;
448
+ const reference = read2();
449
+ const base = read(baseSize);
450
+ const extents = read2();
451
+ for (let e = 0; e < extents; e++) {
452
+ if (indexSize) read(indexSize);
453
+ const offset = read(offsetSize), length = read(lengthSize);
454
+ if (!metadata.has(id)) {
455
+ const start = base + offset, end = length ? start + length : b.length;
456
+ check$2(reference !== 0 || method !== 0 || !space.some((box) => start < box.end && end > box.body));
457
+ continue;
458
+ }
459
+ check$2(reference === 0 && length > 0 && (method === 0 || method === 1 && !!idat));
460
+ const start = (method === 1 ? idat.body : 0) + base + offset, limit = method === 1 ? idat.end : b.length;
461
+ check$2(start + length <= limit);
462
+ out.fill(0, start, start + length);
463
+ }
464
+ }
465
+ for (const box of space) out.fill(0, box.body, box.end);
466
+ return [out];
467
+ }
468
+ var GIF_APPS_KEPT = /* @__PURE__ */ new Set([
469
+ "NETSCAPE2.0",
470
+ "ANIMEXTS1.0",
471
+ "ICCRGBG1012"
472
+ ]);
473
+ function stripGif(b) {
474
+ check$2(b.length >= 13);
475
+ /** A colour table's bytes, from the flags that say it is there and its size. */
476
+ const table = (flags) => flags & 128 ? 3 << (flags & 7) + 1 : 0;
477
+ /** The end of the data sub-blocks at `at`, past their empty block. */
478
+ const blocks = (at) => {
479
+ for (;;) {
480
+ check$2(at < b.length);
481
+ const length = b[at];
482
+ at += 1 + length;
483
+ if (!length) return at;
484
+ }
485
+ };
486
+ let at = 13 + table(b[10]), framed = false;
487
+ check$2(at <= b.length);
488
+ const parts = [b.subarray(0, at)];
489
+ for (;;) {
490
+ check$2(at < b.length);
491
+ const introducer = b[at];
492
+ if (introducer === 59) {
493
+ check$2(framed);
494
+ parts.push(Uint8Array.of(59));
495
+ return parts;
496
+ }
497
+ if (introducer === 44) {
498
+ check$2(at + 10 <= b.length);
499
+ const data = at + 10 + table(b[at + 9]);
500
+ check$2(data < b.length);
501
+ const end = blocks(data + 1);
502
+ parts.push(b.subarray(at, end));
503
+ framed = true;
504
+ at = end;
505
+ continue;
506
+ }
507
+ check$2(introducer === 33 && at + 2 < b.length);
508
+ const label = b[at + 1], end = blocks(at + 2);
509
+ const app = label === 255 && b[at + 2] === 11 && GIF_APPS_KEPT.has(text$2(b, at + 3, 11));
510
+ if (label === 249 || label === 1 || app) parts.push(b.subarray(at, end));
511
+ else check$2(label === 254 || label === 255);
512
+ at = end;
513
+ }
514
+ }
515
+ var TIFF_DRAWS = /* @__PURE__ */ new Set([
516
+ 254,
517
+ 255,
518
+ 256,
519
+ 257,
520
+ 258,
521
+ 259,
522
+ 262,
523
+ 263,
524
+ 264,
525
+ 265,
526
+ 266,
527
+ 273,
528
+ 274,
529
+ 277,
530
+ 278,
531
+ 279,
532
+ 280,
533
+ 281,
534
+ 282,
535
+ 283,
536
+ 284,
537
+ 286,
538
+ 287,
539
+ 290,
540
+ 291,
541
+ 292,
542
+ 293,
543
+ 296,
544
+ 297,
545
+ 301,
546
+ 317,
547
+ 318,
548
+ 319,
549
+ 320,
550
+ 321,
551
+ 322,
552
+ 323,
553
+ 324,
554
+ 325,
555
+ 332,
556
+ 334,
557
+ 336,
558
+ 338,
559
+ 339,
560
+ 340,
561
+ 341,
562
+ 529,
563
+ 530,
564
+ 531,
565
+ 532,
566
+ 34675
567
+ ]);
568
+ /** Text and documents about the picture: DocumentName to HostComputer, InkNames, XMP, Copyright, IPTC, Photoshop, Windows' XP tags, PrintIM. */
569
+ var TIFF_METADATA = /* @__PURE__ */ new Set([
570
+ 269,
571
+ 270,
572
+ 271,
573
+ 272,
574
+ 285,
575
+ 305,
576
+ 306,
577
+ 315,
578
+ 316,
579
+ 333,
580
+ 700,
581
+ 33432,
582
+ 33723,
583
+ 34377,
584
+ 18246,
585
+ 18249,
586
+ 40091,
587
+ 40092,
588
+ 40093,
589
+ 40094,
590
+ 40095,
591
+ 50341
592
+ ]);
593
+ /** The IFDs of Exif, GPS and interoperability, emptied whole. */
594
+ var TIFF_METADATA_IFDS = /* @__PURE__ */ new Set([
595
+ 34665,
596
+ 34853,
597
+ 40965
598
+ ]);
599
+ /** Compression without JPEG: none, CCITT, LZW, Deflate, PackBits. */
600
+ var TIFF_COMPRESSION = /* @__PURE__ */ new Set([
601
+ 1,
602
+ 2,
603
+ 3,
604
+ 4,
605
+ 5,
606
+ 8,
607
+ 32773,
608
+ 32946
609
+ ]);
610
+ /** Bytes per value of each field type. */
611
+ var TIFF_TYPE_BYTES = [
612
+ 0,
613
+ 1,
614
+ 1,
615
+ 2,
616
+ 4,
617
+ 8,
618
+ 1,
619
+ 1,
620
+ 2,
621
+ 4,
622
+ 8,
623
+ 4,
624
+ 8,
625
+ 4
626
+ ];
627
+ function stripTiff(b) {
628
+ const little = b[0] === 73;
629
+ const u16 = (at) => {
630
+ check$2(at + 2 <= b.length);
631
+ return little ? b[at] | b[at + 1] << 8 : u16be(b, at);
632
+ };
633
+ const u32 = (at) => {
634
+ check$2(at + 4 <= b.length);
635
+ return little ? u32le$2(b, at) : u32be$2(b, at);
636
+ };
637
+ check$2(b.length >= 8 && u16(2) === 42);
638
+ const out = b.slice(), seen = /* @__PURE__ */ new Set();
639
+ /** An IFD's entries: tag, type, the value's first byte (in the entry or where it points) and its bytes. */
640
+ const entries = (ifd) => {
641
+ check$2(ifd >= 8 && !seen.has(ifd) && seen.size < 1024);
642
+ seen.add(ifd);
643
+ const count = u16(ifd), next = ifd + 2 + count * 12;
644
+ u32(next);
645
+ return {
646
+ next,
647
+ list: Array.from({ length: count }, (_, i) => {
648
+ const at = ifd + 2 + i * 12, tag = u16(at), type = u16(at + 2);
649
+ check$2(type >= 1 && type < TIFF_TYPE_BYTES.length);
650
+ const bytes = TIFF_TYPE_BYTES[type] * u32(at + 4);
651
+ const value = bytes <= 4 ? at + 8 : u32(at + 8);
652
+ check$2(Number.isSafeInteger(bytes) && value + bytes <= b.length);
653
+ return {
654
+ at,
655
+ tag,
656
+ type,
657
+ value,
658
+ bytes
659
+ };
660
+ })
661
+ };
662
+ };
663
+ /** An Exif, GPS or interoperability IFD: every value zeroed, then the IFD itself, so it holds no entry. */
664
+ const empty = (ifd) => {
665
+ const { next, list } = entries(ifd);
666
+ for (const entry of list) {
667
+ check$2(entry.tag !== 37500);
668
+ if (TIFF_METADATA_IFDS.has(entry.tag)) empty(u32(entry.value));
669
+ out.fill(0, entry.value, entry.value + entry.bytes);
670
+ }
671
+ out.fill(0, ifd, next + 4);
672
+ };
673
+ for (let ifd = u32(4); ifd;) {
674
+ const { next, list } = entries(ifd);
675
+ let kept = 0;
676
+ for (const { at, tag, value, bytes } of list) {
677
+ if (tag === 259) check$2(TIFF_COMPRESSION.has(u16(value)));
678
+ if (TIFF_METADATA_IFDS.has(tag)) {
679
+ empty(u32(value));
680
+ continue;
681
+ }
682
+ if (TIFF_METADATA.has(tag)) out.fill(0, value, value + bytes);
683
+ else check$2(TIFF_DRAWS.has(tag));
684
+ out.copyWithin(ifd + 2 + kept++ * 12, at, at + 12);
685
+ }
686
+ check$2(kept > 0);
687
+ const end = ifd + 2 + kept * 12;
688
+ out.set(little ? [kept & 255, kept >> 8] : [kept >> 8, kept & 255], ifd);
689
+ out.set(b.subarray(next, next + 4), end);
690
+ out.fill(0, end + 4, next + 4);
691
+ ifd = u32(next);
692
+ }
693
+ return [out];
694
+ }
695
+ /** A JPEG XL or a JPEG 2000 in boxes: refused. */
696
+ function refuse() {
697
+ throw new Error(NO_PICTURE_METADATA);
698
+ }
699
+ var STRIP = {
700
+ jpeg: stripJpeg,
701
+ png: stripPng,
702
+ webp: stripWebp,
703
+ heif: stripHeif,
704
+ gif: stripGif,
705
+ tiff: stripTiff,
706
+ boxes: refuse
707
+ };
708
+ /**
709
+ * A picture's bytes without its metadata, as parts to put in a Blob; undefined when the file is not a picture this
710
+ * strips (by its bytes and its type), so it goes as it is. Throws `NO_PICTURE_METADATA` when it is one but its
711
+ * metadata cannot be removed.
712
+ */
713
+ function stripPictureMetadata(bytes, mime) {
714
+ const kind = kindOf(bytes);
715
+ if (!kind) {
716
+ if (STRIPPED_TYPES$1.has(mime.split(";")[0].trim().toLowerCase())) throw new Error(NO_PICTURE_METADATA);
717
+ return;
718
+ }
719
+ return STRIP[kind](bytes);
720
+ }
721
+ /**
722
+ * Whether a file is a picture whose metadata goes before it is sent, by its first `PICTURE_METADATA_LIMITS.headBytes`
723
+ * bytes or by its type: then it is read whole and stripped (`stripPictureMetadata`), else it goes as it is.
724
+ */
725
+ function isStrippedPicture(head, mime) {
726
+ return !!kindOf(head) || STRIPPED_TYPES$1.has(mime.split(";")[0].trim().toLowerCase());
727
+ }
728
+ /**
729
+ * `source` as it is sent: without its metadata when it is a picture (`stripPictureMetadata`), or undefined when it is
730
+ * not one and goes as it is. Only its first bytes are read for any other file. Throws `NO_PICTURE_METADATA` for a
731
+ * picture that cannot be stripped or is past `PICTURE_METADATA_LIMITS.maxBytes`; an error reading `source` as it is.
732
+ */
733
+ async function withoutPictureMetadata(source, mime) {
734
+ if (!isStrippedPicture(new Uint8Array(await source.slice(0, PICTURE_METADATA_LIMITS.headBytes).arrayBuffer()), mime)) return void 0;
735
+ if (source.size > PICTURE_METADATA_LIMITS.maxBytes) throw new Error(NO_PICTURE_METADATA);
736
+ const parts = stripPictureMetadata(new Uint8Array(await source.arrayBuffer()), mime);
737
+ return parts && new Blob(parts, { type: mime });
738
+ }
739
+ // ../core/src/videoMetadata.ts
740
+ /**
741
+ * What a video leaves with. An MP4 or QuickTime file says more than its frames: its `udta` and `meta` boxes hold where
742
+ * it was recorded (`©xyz`, `com.apple.quicktime.location.ISO6709`), the device, often its software; a timed metadata
743
+ * track (an iPhone's location and motion, a GoPro's GPS) holds them sample by sample, a caption track (a drone's, a
744
+ * dashcam's) a line of them each second; the movie's, each track's and
745
+ * each track's media header (`mvhd`, `tkhd`, `mdhd`) say when it was recorded, to the second, and a camera's timecode
746
+ * track the time of day. The sender removes them before the file is stored and its digest computed, without decoding
747
+ * or re-encoding a frame: each such box becomes a `free` box of the same size, zeroed, the headers' creation and
748
+ * modification times are zeroed (0 is "unknown"), the space already left in it (`free`, `skip`, `wide`: what an edit in
749
+ * place left behind, a recorder's GPS log) is zeroed after its header, so are the names of its handlers and of the
750
+ * compressor that made its frames, and each metadata, timecode and caption track's samples are zeroed where they are, so no
751
+ * offset in the file moves and it plays as it did. Only the boxes' headers, `moov` and `moof` are read; the
752
+ * media goes untouched.
753
+ *
754
+ * Fail-closed: a file that is an MP4 or QuickTime video, by its bytes or by its type, and whose metadata cannot be
755
+ * removed (truncated, malformed, a part of its movie this does not know) is refused with `NO_VIDEO_METADATA`, never sent as it was.
756
+ * A picture (HEIF is pictureMetadata.ts's) and any other file go as they are; so does a file without a video track (an
757
+ * M4A) here: audioMetadata.ts strips it.
758
+ *
759
+ * An AVI (a dashcam's, an older camera's) goes without what its header and its `INFO` list say: each chunk but the
760
+ * ones its frames and sound are made of (`avih`, `strh`, `strf`, `indx`, `vprp`, `dmlh`) becomes `JUNK`, zeroed (a
761
+ * stream's name `strn` and data `strd`, `IDIT`'s date, a camera's `LIST ncdt`), and the chunks of a stream that is
762
+ * neither pictures nor sound (a GPS or subtitle text stream) are zeroed in `movi`, so no offset moves. An ASF (WMV,
763
+ * WMA), an FLV and an MPEG transport stream are refused with `NO_VIDEO_METADATA` (a WMA, typed as audio, with
764
+ * `NO_AUDIO_METADATA`): their titles, places and dates are not removed here.
765
+ */
766
+ var VIDEO_METADATA_LIMITS = {
767
+ /** The largest `moov` or `moof` read whole, and the most bytes of a metadata track's chunk: past this the video is refused. */
768
+ maxBoxBytes: 67108864,
769
+ /** The most top-level boxes walked (a fragmented MP4 has two per fragment). */
770
+ maxBoxes: 1e5,
771
+ /** The most chunks of an AVI walked (one per frame and per piece of sound). */
772
+ maxChunks: 4e6,
773
+ /** Bytes read first to tell a video from another file. */
774
+ headBytes: 64,
775
+ /** Bytes read at once for a box's header or a small box, so the next headers and `moof`s are read with it. */
776
+ readAhead: 65536,
777
+ /** The most a walk going on from its window reads at once (an Ogg's pages, a live WebM's blocks: the whole file). */
778
+ readAheadMax: 4194304,
779
+ /** The most bytes between two parts replaced that are read and sent with them as one part of the stripped video. */
780
+ joinGap: 65536,
781
+ /** The most bytes of such a part. */
782
+ joinedBytes: 4194304
783
+ };
784
+ /** Why a video is refused: its metadata could not be removed, so it does not go at all. */
785
+ var NO_VIDEO_METADATA = "This video cannot be sent: Ghostly could not remove the details saved in it, like where it was recorded";
786
+ /** The types of the videos stripped here: a file of one of them whose bytes are not one is refused. */
787
+ var STRIPPED_TYPES = /* @__PURE__ */ new Set([
788
+ "video/mp4",
789
+ "video/quicktime",
790
+ "video/x-m4v",
791
+ "video/3gpp",
792
+ "video/3gpp2"
793
+ ]);
794
+ /**
795
+ * The first box of an MP4 (`ftyp`), of a QuickTime file written without one, or of one a tool or a preview was put
796
+ * before (`uuid`, `pnot`): a file that starts with one is a movie, refused when it is not one.
797
+ */
798
+ var FIRST_BOXES = /* @__PURE__ */ new Set([
799
+ "ftyp",
800
+ "moov",
801
+ "mdat",
802
+ "wide",
803
+ "free",
804
+ "skip",
805
+ "uuid",
806
+ "pnot",
807
+ "PICT"
808
+ ]);
809
+ /** Boxes that hold metadata wherever they are: emptied into `free`. */
810
+ var METADATA = /* @__PURE__ */ new Set([
811
+ "udta",
812
+ "meta",
813
+ "uuid"
814
+ ]);
815
+ /**
816
+ * Space left in a file (padding, or an old `moov` or `udta` an edit in place left behind), and what a recorder puts
817
+ * there (a dashcam's GPS log, a thumbnail): kept where it is, its body zeroed.
818
+ */
819
+ var SPACE = /* @__PURE__ */ new Set([
820
+ "free",
821
+ "skip",
822
+ "wide"
823
+ ]);
824
+ /**
825
+ * At the top: what makes the movie, kept (`moov` and `moof` looked into). Any other box is emptied, unless the movie's
826
+ * samples are in it: the ones known at a movie's top (a preview picture, an event message, the wall-clock time a
827
+ * fragment was made, `prft`) and a device's own (Samsung's `sefd`, a GPS track's `gps0`) alike.
828
+ */
829
+ var TOP_KEEPS = /* @__PURE__ */ new Set([
830
+ "ftyp",
831
+ "styp",
832
+ "moov",
833
+ "mdat",
834
+ "moof",
835
+ "mfra",
836
+ "sidx",
837
+ "ssix",
838
+ "pdin",
839
+ ...SPACE
840
+ ]);
841
+ /** The boxes emptied that are known at a movie's top: a file that starts with one is read as boxes. */
842
+ var TOP_EMPTIED = /* @__PURE__ */ new Set([
843
+ ...METADATA,
844
+ "pnot",
845
+ "PICT",
846
+ "emsg",
847
+ "Xtra",
848
+ "prft"
849
+ ]);
850
+ var MOOV_KEEPS = /* @__PURE__ */ new Set([
851
+ "mvhd",
852
+ "trak",
853
+ "mvex",
854
+ "iods",
855
+ "ctab",
856
+ ...SPACE
857
+ ]);
858
+ var TRAK_KEEPS = /* @__PURE__ */ new Set([
859
+ "tkhd",
860
+ "edts",
861
+ "mdia",
862
+ "tref",
863
+ "tapt",
864
+ "load",
865
+ "txas",
866
+ "matt",
867
+ ...SPACE
868
+ ]);
869
+ /** Boxes looked into below a track (and in a fragment) for the metadata boxes in them. */
870
+ var CONTAINERS = /* @__PURE__ */ new Set([
871
+ "mdia",
872
+ "minf",
873
+ "dinf",
874
+ "stbl",
875
+ "edts",
876
+ "mvex",
877
+ "traf"
878
+ ]);
879
+ /** Track handlers kept as they are: picture, sound, timecode, hints. `meta` tracks have their samples zeroed, `tmcd` ones and `CAPTIONS` too. */
880
+ var HANDLERS = /* @__PURE__ */ new Set([
881
+ "vide",
882
+ "soun",
883
+ "tmcd",
884
+ "hint",
885
+ "auxv",
886
+ "pict",
887
+ "sdsm",
888
+ "odsm",
889
+ "subp"
890
+ ]);
891
+ /**
892
+ * Text, subtitle and caption tracks: what a recorder writes there is a log (a drone's or a dashcam's GPS, home point,
893
+ * date and time each second), so their samples are zeroed, in `moov`'s tables and in fragments alike; they show nothing.
894
+ */
895
+ var CAPTIONS = /* @__PURE__ */ new Set([
896
+ "text",
897
+ "sbtl",
898
+ "subt",
899
+ "clcp"
900
+ ]);
901
+ /** The handlers whose sample descriptions are a visual one's, a compressor's name in each. */
902
+ var VISUAL = /* @__PURE__ */ new Set([
903
+ "vide",
904
+ "auxv",
905
+ "pict"
906
+ ]);
907
+ /** Zeros put in a Blob a slice at a time: a Blob's Blob parts are not copied, so a zeroed range of any size holds no more. */
908
+ var ZEROS$1 = new Blob([/* @__PURE__ */ new Uint8Array(1048576)]);
909
+ var u32be$1 = (b, at) => (b[at] << 24 >>> 0) + (b[at + 1] << 16) + (b[at + 2] << 8) + b[at + 3];
910
+ var text$1 = (b, at, length) => String.fromCharCode(...b.subarray(at, at + length));
911
+ /** Refuses the video where its bytes are not what this expects. */
912
+ function check$1(ok) {
913
+ if (!ok) throw new Error(NO_VIDEO_METADATA);
914
+ }
915
+ /** A box's header at `at` of `b` (`base` its offset in the file), up to `end` (a size of 0 runs to it). */
916
+ function header(b, at, end, base = 0) {
917
+ check$1(at + 8 <= b.length);
918
+ let size = u32be$1(b, at), body = at + 8;
919
+ const type = text$1(b, at + 4, 4);
920
+ if (size === 1) {
921
+ check$1(at + 16 <= b.length);
922
+ size = u32be$1(b, at + 8) * 2 ** 32 + u32be$1(b, at + 12);
923
+ body = at + 16;
924
+ } else if (size === 0) size = end - (base + at);
925
+ if (type === "uuid") body += 16;
926
+ check$1(Number.isSafeInteger(size) && size >= body - at && base + at + size <= end);
927
+ return {
928
+ type,
929
+ start: base + at,
930
+ body: base + body,
931
+ end: base + at + size
932
+ };
933
+ }
934
+ function boxes(b, start, end) {
935
+ const found = [];
936
+ for (let at = start; at < end;) {
937
+ check$1(at + 8 <= end);
938
+ const box = header(b.subarray(0, end), at, end);
939
+ found.push(box);
940
+ at = box.end;
941
+ }
942
+ return found;
943
+ }
944
+ /** A box made `free` where it is: its size kept, everything after its size zeroed. */
945
+ function empty(b, box) {
946
+ b.set([
947
+ 102,
948
+ 114,
949
+ 101,
950
+ 101
951
+ ], box.start + 4);
952
+ b.fill(0, box.start + (u32be$1(b, box.start) === 1 ? 16 : 8), box.end);
953
+ }
954
+ /**
955
+ * Every metadata box in a container's children (and in theirs, for the containers below a track) emptied, every
956
+ * free space's body zeroed, and every handler's name (an `hdlr`'s after its 24 bytes of fields: "Core Media Video",
957
+ * an encoder's or an app's) zeroed in place, its type kept.
958
+ */
959
+ function emptyWithin(b, start, end) {
960
+ for (const box of boxes(b, start, end)) if (METADATA.has(box.type)) empty(b, box);
961
+ else if (SPACE.has(box.type)) b.fill(0, box.body, box.end);
962
+ else if (box.type === "hdlr") b.fill(0, Math.min(box.body + 24, box.end), box.end);
963
+ else if (CONTAINERS.has(box.type)) emptyWithin(b, box.body, box.end);
964
+ }
965
+ /**
966
+ * A visual track's sample descriptions with the name of the compressor that made them zeroed (32 bytes at 42 of each
967
+ * entry's body, MP4's `compressorname` and QuickTime's alike: an encoder's version, a camera's).
968
+ */
969
+ function zeroCompressorNames(b, stbl) {
970
+ const stsd = child(b, stbl, "stsd");
971
+ check$1(!!stsd && stsd.body + 8 <= stsd.end);
972
+ for (const entry of boxes(b, stsd.body + 8, stsd.end)) {
973
+ check$1(entry.body + 74 <= entry.end);
974
+ b.fill(0, entry.body + 42, entry.body + 74);
975
+ }
976
+ }
977
+ /** A `mvhd`, `tkhd` or `mdhd` with its creation and modification times zeroed: 32 bits each in version 0, 64 in 1. */
978
+ function zeroTimes(b, box) {
979
+ const version = b[box.body], bytes = version === 1 ? 16 : 8;
980
+ check$1(version <= 1 && box.body + 4 + bytes <= box.end);
981
+ b.fill(0, box.body + 4, box.body + 4 + bytes);
982
+ }
983
+ var child = (b, parent, type) => {
984
+ if (!parent) return void 0;
985
+ const of = boxes(b, parent.body, parent.end).filter((box) => box.type === type);
986
+ check$1(of.length <= 1);
987
+ return of[0];
988
+ };
989
+ /** A sample table's chunks, from its `stco` or `co64`: how many, and where each starts in the file. */
990
+ function chunkOffsets(b, stbl) {
991
+ const stco = child(b, stbl, "stco"), co64 = child(b, stbl, "co64");
992
+ check$1(!!stco !== !!co64);
993
+ const offsets = stco ?? co64;
994
+ check$1(offsets.body + 8 <= offsets.end);
995
+ const chunks = u32be$1(b, offsets.body + 4);
996
+ check$1(offsets.body + 8 + chunks * (co64 ? 8 : 4) <= offsets.end);
997
+ const offsetOf = (i) => co64 ? u32be$1(b, co64.body + 8 + i * 8) * 2 ** 32 + u32be$1(b, co64.body + 12 + i * 8) : u32be$1(b, stco.body + 8 + i * 4);
998
+ return {
999
+ chunks,
1000
+ offsetOf
1001
+ };
1002
+ }
1003
+ /** The byte ranges of a track's samples in the file, one per chunk, from its sample table. */
1004
+ function sampleRanges(b, stbl) {
1005
+ const stsz = child(b, stbl, "stsz"), stz2 = child(b, stbl, "stz2"), stsc = child(b, stbl, "stsc");
1006
+ check$1(!!stsc && !!stsz !== !!stz2);
1007
+ const need = (box, at, bytes) => check$1(at + bytes <= box.end);
1008
+ const sizeTable = stsz ?? stz2;
1009
+ need(sizeTable, sizeTable.body, 12);
1010
+ const count = u32be$1(b, sizeTable.body + 8);
1011
+ let sizeOf;
1012
+ /** Samples of one size: a chunk's length is counted, not added up a sample at a time. */
1013
+ let uniform = 0;
1014
+ if (stsz) {
1015
+ uniform = u32be$1(b, stsz.body + 4);
1016
+ if (!uniform) need(stsz, stsz.body + 12, count * 4);
1017
+ sizeOf = (i) => u32be$1(b, stsz.body + 12 + i * 4);
1018
+ } else {
1019
+ const field = b[stz2.body + 7];
1020
+ check$1(field === 4 || field === 8 || field === 16);
1021
+ need(stz2, stz2.body + 12, Math.ceil(count * field / 8));
1022
+ const at = stz2.body + 12;
1023
+ sizeOf = field === 16 ? (i) => b[at + i * 2] << 8 | b[at + i * 2 + 1] : field === 8 ? (i) => b[at + i] : (i) => i & 1 ? b[at + (i >> 1)] & 15 : b[at + (i >> 1)] >> 4;
1024
+ }
1025
+ const { chunks, offsetOf } = chunkOffsets(b, stbl);
1026
+ need(stsc, stsc.body, 8);
1027
+ const runs = u32be$1(b, stsc.body + 4);
1028
+ need(stsc, stsc.body + 8, runs * 12);
1029
+ const ranges = [];
1030
+ let sample = 0;
1031
+ for (let run = 0; run < runs; run++) {
1032
+ const first = u32be$1(b, stsc.body + 8 + run * 12), perChunk = u32be$1(b, stsc.body + 12 + run * 12);
1033
+ const last = run + 1 < runs ? u32be$1(b, stsc.body + 8 + (run + 1) * 12) : chunks + 1;
1034
+ check$1(first >= 1 && last > first && last <= chunks + 1);
1035
+ for (let chunk = first; chunk < last; chunk++) {
1036
+ const start = offsetOf(chunk - 1);
1037
+ check$1(sample + perChunk <= count);
1038
+ let length = uniform * perChunk;
1039
+ if (!uniform) for (let i = 0; i < perChunk; i++) length += sizeOf(sample + i);
1040
+ sample += perChunk;
1041
+ check$1(Number.isSafeInteger(start) && length <= VIDEO_METADATA_LIMITS.maxBoxBytes);
1042
+ if (length) ranges.push([start, start + length]);
1043
+ }
1044
+ }
1045
+ check$1(sample === count);
1046
+ return ranges;
1047
+ }
1048
+ /** Each track's default sample size in fragments, from `moov`'s `mvex/trex` boxes, by track ID. */
1049
+ function defaultSampleSizes(moov) {
1050
+ const sizes = /* @__PURE__ */ new Map();
1051
+ const mvex = child(moov, header(moov, 0, moov.length), "mvex");
1052
+ for (const trex of mvex ? boxes(moov, mvex.body, mvex.end) : []) {
1053
+ if (trex.type !== "trex") continue;
1054
+ check$1(trex.body + 24 <= trex.end);
1055
+ sizes.set(u32be$1(moov, trex.body + 4), u32be$1(moov, trex.body + 16));
1056
+ }
1057
+ return sizes;
1058
+ }
1059
+ /**
1060
+ * The byte ranges of a fragment's samples in the file, one per track run (`trun`), from its `moof` read whole (`at` its
1061
+ * offset in the file): each run starts at its data offset from its track fragment's base (`tfhd`'s base data offset,
1062
+ * else the `moof`'s start for the first track fragment or one that says so, else where the previous one's data ended),
1063
+ * or where the previous run ended; its length is its samples' sizes, its own or `tfhd`'s or `trex`'s default. Each
1064
+ * with its track's ID.
1065
+ */
1066
+ function fragmentRanges(b, at, sizes) {
1067
+ const ranges = [];
1068
+ let previous = at;
1069
+ for (const traf of boxes(b, header(b, 0, b.length).body, b.length)) {
1070
+ if (traf.type !== "traf") continue;
1071
+ const tfhd = child(b, traf, "tfhd");
1072
+ check$1(!!tfhd && tfhd.body + 8 <= tfhd.end);
1073
+ const flags = u32be$1(b, tfhd.body) & 16777215;
1074
+ let field = tfhd.body + 8, base = flags & 131072 ? at : previous;
1075
+ if (flags & 1) {
1076
+ check$1(field + 8 <= tfhd.end);
1077
+ base = u32be$1(b, field) * 2 ** 32 + u32be$1(b, field + 4);
1078
+ field += 8;
1079
+ }
1080
+ if (flags & 2) field += 4;
1081
+ if (flags & 8) field += 4;
1082
+ const track = u32be$1(b, tfhd.body + 4);
1083
+ let size = sizes.get(track);
1084
+ if (flags & 16) {
1085
+ check$1(field + 4 <= tfhd.end);
1086
+ size = u32be$1(b, field);
1087
+ }
1088
+ let next = base;
1089
+ for (const trun of boxes(b, traf.body, traf.end)) {
1090
+ if (trun.type !== "trun") continue;
1091
+ check$1(trun.body + 8 <= trun.end);
1092
+ const runFlags = u32be$1(b, trun.body) & 16777215, count = u32be$1(b, trun.body + 4);
1093
+ let field = trun.body + 8;
1094
+ if (runFlags & 1) {
1095
+ check$1(field + 4 <= trun.end);
1096
+ next = base + (u32be$1(b, field) | 0);
1097
+ field += 4;
1098
+ }
1099
+ if (runFlags & 4) field += 4;
1100
+ const stride = [
1101
+ 256,
1102
+ 512,
1103
+ 1024,
1104
+ 2048
1105
+ ].filter((flag) => runFlags & flag).length * 4;
1106
+ check$1(field + count * stride <= trun.end);
1107
+ let length = 0;
1108
+ if (runFlags & 512) {
1109
+ const sizeAt = field + (runFlags & 256 ? 4 : 0);
1110
+ for (let i = 0; i < count; i++) length += u32be$1(b, sizeAt + i * stride);
1111
+ } else if (count) {
1112
+ check$1(size !== void 0);
1113
+ length = count * size;
1114
+ }
1115
+ check$1(Number.isSafeInteger(next) && Number.isSafeInteger(next + length));
1116
+ if (length) ranges.push([
1117
+ next,
1118
+ next + length,
1119
+ track
1120
+ ]);
1121
+ next += length;
1122
+ }
1123
+ previous = next;
1124
+ }
1125
+ return ranges;
1126
+ }
1127
+ /** Whether every data reference of a track is this file (a self-contained `url ` or `alis`). */
1128
+ function selfContained(b, minf) {
1129
+ const dref = child(b, child(b, minf, "dinf"), "dref");
1130
+ if (!dref) return false;
1131
+ return boxes(b, dref.body + 8, dref.end).every((entry) => entry.body + 4 <= entry.end && (b[entry.body + 3] & 1) === 1);
1132
+ }
1133
+ /**
1134
+ * `moov` with its metadata boxes emptied and its headers' times zeroed, read whole: whether it has a video track, the
1135
+ * byte ranges of its metadata, timecode and caption tracks' samples (zeroed by the caller where they are), whether it
1136
+ * has a metadata or timecode track, every track's sample table, and the IDs of its caption tracks (their samples in
1137
+ * fragments zeroed too).
1138
+ */
1139
+ function stripMoov(b) {
1140
+ let video = false, fragmented = false, metadata = false;
1141
+ const zeroed = [], tables = [], captions = /* @__PURE__ */ new Set();
1142
+ for (const box of boxes(b, header(b, 0, b.length).body, b.length)) {
1143
+ if (METADATA.has(box.type)) {
1144
+ empty(b, box);
1145
+ continue;
1146
+ }
1147
+ check$1(MOOV_KEEPS.has(box.type));
1148
+ if (SPACE.has(box.type)) b.fill(0, box.body, box.end);
1149
+ if (box.type === "mvhd") zeroTimes(b, box);
1150
+ if (box.type === "mvex") {
1151
+ fragmented = true;
1152
+ emptyWithin(b, box.body, box.end);
1153
+ }
1154
+ if (box.type !== "trak") continue;
1155
+ let mdia, tkhd;
1156
+ for (const part of boxes(b, box.body, box.end)) {
1157
+ if (METADATA.has(part.type)) {
1158
+ empty(b, part);
1159
+ continue;
1160
+ }
1161
+ check$1(TRAK_KEEPS.has(part.type));
1162
+ if (part.type === "tkhd") {
1163
+ check$1(!tkhd);
1164
+ tkhd = part;
1165
+ zeroTimes(b, part);
1166
+ }
1167
+ if (part.type === "mdia") {
1168
+ check$1(!mdia);
1169
+ mdia = part;
1170
+ }
1171
+ }
1172
+ check$1(!!mdia);
1173
+ const hdlr = child(b, mdia, "hdlr"), minf = child(b, mdia, "minf"), mdhd = child(b, mdia, "mdhd");
1174
+ check$1(!!hdlr && !!minf && hdlr.body + 12 <= hdlr.end);
1175
+ if (mdhd) zeroTimes(b, mdhd);
1176
+ const handler = text$1(b, hdlr.body + 8, 4);
1177
+ const stbl = child(b, minf, "stbl");
1178
+ check$1(!!stbl);
1179
+ tables.push(stbl);
1180
+ if (handler === "meta") {
1181
+ check$1(selfContained(b, minf));
1182
+ metadata = true;
1183
+ for (const range of sampleRanges(b, stbl)) zeroed.push(range);
1184
+ } else if (handler === "tmcd" && selfContained(b, minf)) {
1185
+ metadata = true;
1186
+ for (const range of sampleRanges(b, stbl)) zeroed.push(range);
1187
+ } else if (CAPTIONS.has(handler)) {
1188
+ check$1(selfContained(b, minf) && !!tkhd);
1189
+ const id = tkhd.body + 4 + (b[tkhd.body] === 1 ? 16 : 8);
1190
+ check$1(id + 4 <= tkhd.end);
1191
+ captions.add(u32be$1(b, id));
1192
+ for (const range of sampleRanges(b, stbl)) zeroed.push(range);
1193
+ } else check$1(HANDLERS.has(handler));
1194
+ if (handler === "vide") video = true;
1195
+ if (VISUAL.has(handler)) zeroCompressorNames(b, stbl);
1196
+ emptyWithin(b, box.body, box.end);
1197
+ }
1198
+ return {
1199
+ video,
1200
+ fragmented,
1201
+ metadata,
1202
+ zeroed,
1203
+ tables,
1204
+ captions
1205
+ };
1206
+ }
1207
+ /**
1208
+ * Whether `start` to `end` of the file meets one of `ranges` (in file order, apart): the first one that ends past
1209
+ * `start` is the only one that can, found by halves, so a fragment per range is not checked against every other.
1210
+ */
1211
+ function meets(ranges, start, end) {
1212
+ let low = 0, high = ranges.length;
1213
+ while (low < high) {
1214
+ const middle = low + high >>> 1;
1215
+ if (ranges[middle][1] > start) high = middle;
1216
+ else low = middle + 1;
1217
+ }
1218
+ return low < ranges.length && ranges[low][0] < end;
1219
+ }
1220
+ /**
1221
+ * Whether `start` to `end` of the file is within one of `boxes` (in file order, apart): the first one that ends at or
1222
+ * past `end` is the only one that can hold it, found by halves, so a caption run per fragment is not checked against
1223
+ * every fragment's `mdat`.
1224
+ */
1225
+ function within(boxes, start, end) {
1226
+ let low = 0, high = boxes.length;
1227
+ while (low < high) {
1228
+ const middle = low + high >>> 1;
1229
+ if (boxes[middle].end >= end) high = middle;
1230
+ else low = middle + 1;
1231
+ }
1232
+ return low < boxes.length && start >= boxes[low].body;
1233
+ }
1234
+ /**
1235
+ * `source` read a window at a time: a read that fits in `readAhead` bytes reads that many from where it starts, and
1236
+ * the reads after it within them (the next boxes' headers, a fragment's `moof`) are served from it, as copies (they
1237
+ * are changed in place). A Blob's read costs most for being one (in Chromium ~0.3 ms, and ~0.9 ms per MiB), so a
1238
+ * fragment costs one, not three.
1239
+ *
1240
+ * A walk that goes on from its window (an Ogg's pages, a live WebM's blocks: headers less than a window apart, through
1241
+ * the whole file) reads twice as much each time, up to `readAheadMax`, so it makes a few large reads, not one per
1242
+ * 64 KiB. One that jumps farther (over a fragment's samples) or back reads `readAhead` again.
1243
+ */
1244
+ function readingAhead(source) {
1245
+ let start = 0, window = /* @__PURE__ */ new Uint8Array(0), ahead = VIDEO_METADATA_LIMITS.readAhead;
1246
+ return {
1247
+ size: source.size,
1248
+ async read(offset, length) {
1249
+ const end = start + window.length;
1250
+ if (offset < start || offset + length > end && end < source.size) {
1251
+ ahead = window.length > 0 && offset >= start && offset - end < ahead ? Math.min(ahead * 2, VIDEO_METADATA_LIMITS.readAheadMax) : VIDEO_METADATA_LIMITS.readAhead;
1252
+ if (length > ahead) return source.read(offset, length);
1253
+ start = offset;
1254
+ window = await source.read(offset, ahead);
1255
+ }
1256
+ return window.slice(offset - start, offset - start + length);
1257
+ }
1258
+ };
1259
+ }
1260
+ /** A whole box's header in the file at `at`, read from it; undefined where none fits (bytes after the last box). */
1261
+ async function headerAt(source, at) {
1262
+ const head = await source.read(at, 16);
1263
+ try {
1264
+ return header(head, 0, source.size, at);
1265
+ } catch {
1266
+ return;
1267
+ }
1268
+ }
1269
+ /** A box read whole, within the limit. */
1270
+ async function whole(source, box) {
1271
+ check$1(box.end - box.start <= VIDEO_METADATA_LIMITS.maxBoxBytes);
1272
+ const bytes = await source.read(box.start, box.end - box.start);
1273
+ check$1(bytes.length === box.end - box.start);
1274
+ return bytes;
1275
+ }
1276
+ var u32le$1 = (b, at) => (b[at] | b[at + 1] << 8 | b[at + 2] << 16 | b[at + 3] << 24) >>> 0;
1277
+ var JUNK = Uint8Array.from("JUNK", (c) => c.charCodeAt(0));
1278
+ /** The chunks of an AVI's header its frames and sound are read with, kept; any other becomes `JUNK`. */
1279
+ var AVI_HEADER_KEEPS = /* @__PURE__ */ new Set([
1280
+ "avih",
1281
+ "strh",
1282
+ "strf",
1283
+ "indx",
1284
+ "vprp",
1285
+ "dmlh"
1286
+ ]);
1287
+ /** The lists of an AVI's header looked into. */
1288
+ var AVI_HEADER_LISTS = /* @__PURE__ */ new Set([
1289
+ "hdrl",
1290
+ "strl",
1291
+ "odml"
1292
+ ]);
1293
+ /** The streams whose chunks in `movi` are kept: pictures and sound. */
1294
+ var AVI_STREAMS = /* @__PURE__ */ new Set(["vids", "auds"]);
1295
+ /** A frame's or a piece of sound's chunk in `movi`: its stream's number, then what it is. */
1296
+ var AVI_DATA = /^\d\d(dc|db|wb|pc)$/;
1297
+ /** An AVI: `RIFF` `AVI `, then any `RIFF` `AVIX` (an OpenDML one past 1 GiB). */
1298
+ var isAvi = (head) => head.length >= 12 && text$1(head, 0, 4) === "RIFF" && text$1(head, 8, 4) === "AVI ";
1299
+ /** An AVI without what its header and `INFO` say, nor its text and data streams' chunks; the patches in file order. */
1300
+ async function avi(source) {
1301
+ const patches = [], size = source.size;
1302
+ /** Whether each stream, in order, is kept (pictures or sound). */
1303
+ const streams = [];
1304
+ let chunks = 0;
1305
+ const chunkAt = async (at, end) => {
1306
+ check$1(++chunks <= VIDEO_METADATA_LIMITS.maxChunks && at + 8 <= end);
1307
+ const head = await source.read(at, 12);
1308
+ check$1(head.length >= 8);
1309
+ const id = text$1(head, 0, 4), length = u32le$1(head, 4), list = id === "LIST" || id === "RIFF";
1310
+ check$1(!list || length >= 4 && head.length >= 12);
1311
+ return {
1312
+ id,
1313
+ type: list ? text$1(head, 8, 4) : "",
1314
+ start: at,
1315
+ body: at + (list ? 12 : 8),
1316
+ end: at + 8 + length,
1317
+ next: at + 8 + length + (length & 1)
1318
+ };
1319
+ };
1320
+ /** Zeros from `start` to `end`; a chunk made `JUNK` (`junk`) has its id replaced too. */
1321
+ const zero = (start, end) => {
1322
+ if (end > start) patches.push({
1323
+ start,
1324
+ end
1325
+ });
1326
+ };
1327
+ const junk = (chunk, end = chunk.end) => {
1328
+ if (chunk.id !== "JUNK") patches.push({
1329
+ start: chunk.start,
1330
+ end: chunk.start + 4,
1331
+ bytes: JUNK
1332
+ });
1333
+ zero(chunk.start + 8, end);
1334
+ };
1335
+ const header = async (start, end) => {
1336
+ for (let at = start; at < end;) {
1337
+ const chunk = await chunkAt(at, end);
1338
+ check$1(chunk.end <= end);
1339
+ if (chunk.id === "LIST" && AVI_HEADER_LISTS.has(chunk.type)) await header(chunk.body, chunk.end);
1340
+ else if (chunk.id === "strh") {
1341
+ check$1(chunk.end - chunk.body >= 4);
1342
+ streams.push(AVI_STREAMS.has(text$1(await source.read(chunk.body, 4), 0, 4)));
1343
+ } else if (chunk.id === "JUNK") zero(chunk.body, chunk.end);
1344
+ else if (!AVI_HEADER_KEEPS.has(chunk.id)) junk(chunk);
1345
+ at = Math.min(chunk.next, end);
1346
+ }
1347
+ };
1348
+ const movi = async (start, end) => {
1349
+ let at = start;
1350
+ for (; at + 8 <= end;) {
1351
+ const chunk = await chunkAt(at, end), until = Math.min(chunk.end, end);
1352
+ if (chunk.id === "LIST" && chunk.type === "rec ") await movi(chunk.body, until);
1353
+ else if (chunk.id.startsWith("ix") || AVI_DATA.test(chunk.id) && streams[Number(chunk.id.slice(0, 2))]) {} else if (/^\d\d/.test(chunk.id)) zero(chunk.body, until);
1354
+ else junk(chunk, until);
1355
+ at = Math.min(chunk.next, end);
1356
+ }
1357
+ zero(at, end);
1358
+ };
1359
+ let at = 0;
1360
+ for (let first = true; at + 12 <= size; first = false) {
1361
+ const head = await source.read(at, 12);
1362
+ if (text$1(head, 0, 4) !== "RIFF" || text$1(head, 8, 4) !== (first ? "AVI " : "AVIX")) break;
1363
+ const form = await chunkAt(at, size), end = Math.min(form.end, size);
1364
+ for (let inner = form.body; inner + 8 <= end;) {
1365
+ const chunk = await chunkAt(inner, end);
1366
+ if (first && chunk.id === "LIST" && chunk.type === "hdrl") {
1367
+ check$1(!streams.length && chunk.end <= end);
1368
+ await header(chunk.body, chunk.end);
1369
+ } else if (chunk.id === "LIST" && chunk.type === "movi") {
1370
+ check$1(streams.length > 0);
1371
+ await movi(chunk.body, Math.min(chunk.end, end));
1372
+ } else if (chunk.id === "JUNK") zero(chunk.body, Math.min(chunk.end, end));
1373
+ else if (chunk.id !== "idx1") junk(chunk, Math.min(chunk.end, end));
1374
+ inner = Math.min(chunk.next, end);
1375
+ }
1376
+ at = Math.min(form.next, size);
1377
+ }
1378
+ zero(at, size);
1379
+ return patches;
1380
+ }
1381
+ /** An ASF (WMV, WMA): its header object's GUID. */
1382
+ var ASF = [
1383
+ 48,
1384
+ 38,
1385
+ 178,
1386
+ 117,
1387
+ 142,
1388
+ 102,
1389
+ 207,
1390
+ 17,
1391
+ 166,
1392
+ 217,
1393
+ 0,
1394
+ 170,
1395
+ 0,
1396
+ 98,
1397
+ 206,
1398
+ 108
1399
+ ];
1400
+ var isAsf = (head) => head.length >= 16 && ASF.every((byte, i) => head[i] === byte);
1401
+ /** A video whose metadata is not removed here, so it is refused: an ASF, an FLV, an MPEG transport stream (`.ts`, `.m2ts`). */
1402
+ async function refused(source, head) {
1403
+ if (isAsf(head) || head.length >= 4 && text$1(head, 0, 3) === "FLV" && head[3] === 1) return true;
1404
+ const packetAt = (b, at) => b[at] === 71 && (b[at + 3] & 48) !== 0;
1405
+ for (const [packet, offset] of [[188, 0], [192, 4]]) {
1406
+ if (!packetAt(head, offset) || source.size < offset + 2 * packet + 4) continue;
1407
+ const next = await source.read(offset + packet, packet + 4);
1408
+ if (packetAt(next, 0) && packetAt(next, packet)) return true;
1409
+ }
1410
+ return false;
1411
+ }
1412
+ /**
1413
+ * What a file is by its first box: a movie (`FIRST_BOXES`), a file of boxes that is one when it holds a `moov` (any
1414
+ * other box found at the top of a movie: a stream's segment holds none), or another file. An HEIF picture is
1415
+ * pictureMetadata.ts's.
1416
+ */
1417
+ function containerOf(head, mime) {
1418
+ const first = head.length >= 8 ? text$1(head, 4, 4) : "";
1419
+ if (isStrippedPicture(head, mime)) return void 0;
1420
+ if (FIRST_BOXES.has(first)) return "movie";
1421
+ return TOP_KEEPS.has(first) || TOP_EMPTIED.has(first) ? "boxes" : void 0;
1422
+ }
1423
+ /**
1424
+ * `source` as it is sent: an MP4 or QuickTime video without its metadata, made of `source`'s own bytes but for the
1425
+ * boxes and samples zeroed; undefined when it goes as it is (not one of these videos, a file without a video track).
1426
+ * Throws `NO_VIDEO_METADATA` for a video whose metadata cannot be removed; an error reading `source` as it is.
1427
+ */
1428
+ async function withoutVideoMetadata(source, mime) {
1429
+ const patches = await videoMetadataPatches({
1430
+ size: source.size,
1431
+ read: async (offset, length) => new Uint8Array(await source.slice(offset, offset + length).arrayBuffer())
1432
+ }, mime);
1433
+ if (!patches) return void 0;
1434
+ const parts = [];
1435
+ let at = 0;
1436
+ for (let i = 0; i < patches.length;) {
1437
+ const patch = patches[i];
1438
+ let last = i;
1439
+ while (last + 1 < patches.length && patches[last + 1].start - patches[last].end <= VIDEO_METADATA_LIMITS.joinGap && patches[last + 1].end - patch.start <= VIDEO_METADATA_LIMITS.joinedBytes) last++;
1440
+ if (patch.start > at) parts.push(source.slice(at, patch.start));
1441
+ if (last > i) {
1442
+ const joined = new Uint8Array(await source.slice(patch.start, patches[last].end).arrayBuffer());
1443
+ for (const { start, end, bytes } of patches.slice(i, last + 1)) if (bytes) joined.set(bytes, start - patch.start);
1444
+ else joined.fill(0, start - patch.start, end - patch.start);
1445
+ parts.push(joined);
1446
+ } else if (patch.bytes) parts.push(patch.bytes);
1447
+ else for (let left = patch.end - patch.start; left > 0; left -= ZEROS$1.size) parts.push(ZEROS$1.slice(0, Math.min(left, ZEROS$1.size)));
1448
+ at = patches[last].end;
1449
+ i = last + 1;
1450
+ }
1451
+ if (at < source.size) parts.push(source.slice(at));
1452
+ return new Blob(parts, { type: mime });
1453
+ }
1454
+ /**
1455
+ * What `withoutVideoMetadata` changes in a video read from `source` (one not held in a Blob: a file kept in storage):
1456
+ * the parts replaced, in order and apart, the rest of its bytes going as they are; undefined when it goes as it is.
1457
+ * Throws `NO_VIDEO_METADATA` as it does. With `audio`, a movie without a video track (an M4A) is stripped too.
1458
+ */
1459
+ async function videoMetadataPatches(file, mime, audio = false) {
1460
+ const source = readingAhead(file);
1461
+ const head = await source.read(0, VIDEO_METADATA_LIMITS.headBytes);
1462
+ if (isAvi(head)) {
1463
+ const patches = await avi(source);
1464
+ return patches.length ? patches : void 0;
1465
+ }
1466
+ if (!(isAsf(head) && mime.toLowerCase().startsWith("audio/"))) check$1(!await refused(source, head));
1467
+ const typed = STRIPPED_TYPES.has(mime.split(";")[0].trim().toLowerCase());
1468
+ const container = containerOf(head, mime);
1469
+ if (!container) {
1470
+ if (typed && !isStrippedPicture(head, mime)) throw new Error(NO_VIDEO_METADATA);
1471
+ return;
1472
+ }
1473
+ /** What replaces the file's bytes, by where it starts: a box rewritten, or zeros (no `bytes`). */
1474
+ const patches = [];
1475
+ const top = [];
1476
+ /** What goes as zeros at the top, in file order: the boxes emptied, the space's bodies, and the bytes after the last box. */
1477
+ const dropped = [];
1478
+ let trailer = false;
1479
+ for (let at = 0; at < source.size;) {
1480
+ check$1(top.length < VIDEO_METADATA_LIMITS.maxBoxes);
1481
+ const box = await headerAt(source, at);
1482
+ if (!box || top.length && box.type === "\0\0\0\0") {
1483
+ patches.push({
1484
+ start: at,
1485
+ end: source.size
1486
+ });
1487
+ dropped.push([at, source.size]);
1488
+ trailer = !box || box.end !== source.size;
1489
+ break;
1490
+ }
1491
+ top.push(box);
1492
+ if (SPACE.has(box.type)) dropped.push([box.body, box.end]);
1493
+ else if (!TOP_KEEPS.has(box.type)) dropped.push([box.start, box.end]);
1494
+ at = box.end;
1495
+ }
1496
+ const moovs = top.filter((box) => box.type === "moov");
1497
+ if (!moovs.length && container === "boxes" && !typed) {
1498
+ check$1(!trailer && top.every((box) => TOP_KEEPS.has(box.type) || TOP_EMPTIED.has(box.type)));
1499
+ return;
1500
+ }
1501
+ check$1(moovs.length === 1);
1502
+ const moov = await whole(source, moovs[0]);
1503
+ const { video, fragmented, metadata, zeroed, tables, captions } = stripMoov(moov);
1504
+ if (!video && !typed && !audio) return void 0;
1505
+ patches.push({
1506
+ start: moovs[0].start,
1507
+ end: moovs[0].end,
1508
+ bytes: moov
1509
+ });
1510
+ if (dropped.length) for (const stbl of tables) {
1511
+ const { chunks, offsetOf } = chunkOffsets(moov, stbl);
1512
+ for (let i = 0; i < chunks; i++) {
1513
+ const offset = offsetOf(i);
1514
+ check$1(!meets(dropped, offset, offset + 1));
1515
+ }
1516
+ }
1517
+ check$1(!fragmented || !metadata);
1518
+ const sizes = (dropped.length || captions.size) && fragmented ? defaultSampleSizes(moov) : void 0;
1519
+ for (const box of top) if (box.type === "moof") {
1520
+ const moof = await whole(source, box);
1521
+ if (dropped.length || captions.size) for (const [start, end, track] of fragmentRanges(moof, box.start, sizes ?? /* @__PURE__ */ new Map())) {
1522
+ check$1(!meets(dropped, start, end));
1523
+ if (captions.has(track)) zeroed.push([start, end]);
1524
+ }
1525
+ emptyWithin(moof, box.body - box.start, moof.length);
1526
+ patches.push({
1527
+ start: box.start,
1528
+ end: box.end,
1529
+ bytes: moof
1530
+ });
1531
+ } else if (SPACE.has(box.type)) {
1532
+ if (box.body < box.end) patches.push({
1533
+ start: box.body,
1534
+ end: box.end
1535
+ });
1536
+ } else if (!TOP_KEEPS.has(box.type)) {
1537
+ const head = await source.read(box.start, box.body - box.start);
1538
+ empty(head, {
1539
+ type: box.type,
1540
+ start: 0,
1541
+ body: head.length,
1542
+ end: head.length
1543
+ });
1544
+ patches.push({
1545
+ start: box.start,
1546
+ end: box.body,
1547
+ bytes: head
1548
+ }, {
1549
+ start: box.body,
1550
+ end: box.end
1551
+ });
1552
+ }
1553
+ const mdats = top.filter((box) => box.type === "mdat");
1554
+ const merged = [];
1555
+ for (const [start, end] of zeroed.sort((a, b) => a[0] - b[0])) {
1556
+ check$1(within(mdats, start, end));
1557
+ const last = merged[merged.length - 1];
1558
+ if (last && start <= last[1]) last[1] = Math.max(last[1], end);
1559
+ else merged.push([start, end]);
1560
+ }
1561
+ for (const [start, end] of merged) patches.push({
1562
+ start,
1563
+ end
1564
+ });
1565
+ let at = 0;
1566
+ for (const patch of patches.sort((a, b) => a.start - b.start)) {
1567
+ check$1(patch.start >= at);
1568
+ at = patch.end;
1569
+ }
1570
+ return patches;
1571
+ }
1572
+ // ../core/src/audioMetadata.ts
1573
+ /**
1574
+ * What an audio file leaves with. A recording made in another app, or a song a tagger went through, says more than its
1575
+ * sound: a title or a file name that is where it was recorded (a phone's recorder names it after the place), a comment,
1576
+ * a location tag, a picture, the date. The sender removes them before the file is stored and its digest computed, as
1577
+ * pictures' and videos' are (pictureMetadata.ts, videoMetadata.ts), without decoding or re-encoding a sample, and the
1578
+ * file keeps its size, so no offset in it moves and it plays as it did:
1579
+ *
1580
+ * - MP4 audio (M4A, a voice note recorded in MP4): videoMetadata.ts's box walk, its `udta` and `meta` emptied.
1581
+ * - MP3 and AAC: an ID3v2 tag at the start becomes an empty one (its frames zeros: padding), one at the end (with its
1582
+ * footer), an APEv2 tag's items, a Lyrics3v2 tag and an ID3v1 tag's fields become zeros. One typed as MP3 or AAC
1583
+ * whose first bytes are neither (junk before its first frame) still has the tags at its end emptied.
1584
+ * - FLAC: every metadata block but its stream info and seek table (a Vorbis comment, a picture, a cue sheet, an
1585
+ * application's) becomes padding, zeroed.
1586
+ * - Ogg Opus, Vorbis, Speex and Theora: the comment header keeps its vendor (the encoder's name) and has no comment,
1587
+ * the bytes after it zeros. FLAC in Ogg: its metadata blocks as a FLAC's. Each page changed has its checksum made again.
1588
+ * - WAV (RIFF, RF64 or BW64): every chunk but its format, data and the ones of the sound itself (`fact`, `cue `,
1589
+ * `smpl`, `inst`, an RF64's `ds64`) becomes `JUNK`, zeroed (an INFO list, an `id3 ` chunk, a broadcast `bext` with
1590
+ * its date and originator, iXML, XMP).
1591
+ * - AIFF and AIFF-C: every chunk but its sound's (`COMM`, `SSND`, `FVER`, `MARK`, `INST`, `AESD`, `chan`) becomes
1592
+ * `JUNK`, zeroed (NAME, AUTH, ANNO, `(c) `, COMT, an `ID3 ` chunk, an app's `APPL`).
1593
+ * - CAF: every chunk but its sound's (`desc`, `data`, `pakt`, `kuki`, `chan`, `peak`, `ovvw`) becomes `free`, zeroed
1594
+ * (its `info` strings, a marker's names in `strg`, `edct` comments, `uuid` chunks).
1595
+ * - WavPack: its APEv2 and ID3v1 tags at the end as an MP3's, and the source file's header and trailer each block may
1596
+ * keep for a lossless restore (a WAV's INFO list, an AIFF's NAME) made a sub-block that says nothing, zeroed.
1597
+ * - TTA: its tags at the end (and an ID3v2 before it) as an MP3's.
1598
+ * - Sun AU: its annotation, zeros.
1599
+ * - WebM and Matroska, audio or video: `Tags`, `Attachments`, `Chapters`, the title, the date, the file names and each
1600
+ * track's name become `Void` elements (and the SeekHead's entries for them); the muxer's and the writing app's names
1601
+ * are zeroed. A Vorbis, Theora or FLAC track's CodecPrivate (its Ogg headers or its FLAC metadata blocks) has its
1602
+ * comments emptied as an Ogg's or a FLAC's. Clusters, cues and other track settings are kept as they are.
1603
+ *
1604
+ * Fail-closed: a file that is one of these by its bytes and whose tags cannot be removed (truncated, malformed) is
1605
+ * refused with `NO_AUDIO_METADATA`, never sent as it was. So is a WMA (ASF): its title, place and date are not removed
1606
+ * here. Any other file goes as it is (other audio formats too).
1607
+ */
1608
+ var AUDIO_METADATA_LIMITS = {
1609
+ /** The largest header, element or tag read whole (an Ogg comment header with a picture in it): past this the file is refused. */
1610
+ maxReadBytes: 67108864,
1611
+ /** The most pages, chunks, blocks or elements walked. */
1612
+ maxParts: 1e6,
1613
+ /** Bytes read first to tell an audio file from another file. */
1614
+ headBytes: 64
1615
+ };
1616
+ /** Why an audio file is refused: its tags could not be removed, so it does not go at all. */
1617
+ var NO_AUDIO_METADATA = "This audio cannot be sent: Ghostly could not remove the details saved in it, like where it was recorded";
1618
+ /** Zeros put in a Blob a slice at a time: a Blob's Blob parts are not copied, so a zeroed range of any size holds no more. */
1619
+ var ZEROS = new Blob([/* @__PURE__ */ new Uint8Array(1048576)]);
1620
+ var text = (b, at, length) => String.fromCharCode(...b.subarray(at, at + length));
1621
+ var u32le = (b, at) => (b[at] | b[at + 1] << 8 | b[at + 2] << 16 | b[at + 3] << 24) >>> 0;
1622
+ var u32be = (b, at) => (b[at] << 24 >>> 0) + (b[at + 1] << 16) + (b[at + 2] << 8) + b[at + 3];
1623
+ var syncsafe = (b, at) => b[at] << 21 | b[at + 1] << 14 | b[at + 2] << 7 | b[at + 3];
1624
+ var latin = (s) => Uint8Array.from(s, (c) => c.charCodeAt(0));
1625
+ /** Refuses the file where its bytes are not what this expects. */
1626
+ function check(ok) {
1627
+ if (!ok) throw new Error(NO_AUDIO_METADATA);
1628
+ }
1629
+ function exactly(source) {
1630
+ return async (offset, length) => {
1631
+ check(offset >= 0 && length >= 0 && length <= AUDIO_METADATA_LIMITS.maxReadBytes && offset + length <= source.size);
1632
+ const bytes = await source.read(offset, length);
1633
+ check(bytes.length === length);
1634
+ return bytes;
1635
+ };
1636
+ }
1637
+ /** Counts the parts walked, so a file of millions of tiny ones is refused rather than walked forever. */
1638
+ function counter() {
1639
+ let parts = 0;
1640
+ return () => check(++parts <= AUDIO_METADATA_LIMITS.maxParts);
1641
+ }
1642
+ /** An ID3v2 header at `at` of `b`: its version 2 to 4 and its size four 7-bit bytes, or none. */
1643
+ var isId3 = (b, at = 0) => b.length >= at + 10 && text(b, at, 3) === "ID3" && b[at + 3] >= 2 && b[at + 3] <= 4 && b[at + 4] !== 255 && [
1644
+ 6,
1645
+ 7,
1646
+ 8,
1647
+ 9
1648
+ ].every((i) => b[at + i] < 128);
1649
+ /**
1650
+ * The ID3v2 tag whose header is `head`, at `at`: made an empty one where it is, its frames (and an extended header)
1651
+ * zeros, which is its padding, its flags but the footer's cleared. Returns where it ends.
1652
+ */
1653
+ async function emptyId3(read, size, at, head, patches) {
1654
+ const body = syncsafe(head, 6), footer = head[3] === 4 && head[5] & 16 ? 10 : 0, end = at + 10 + body + footer;
1655
+ check(end <= size);
1656
+ const flags = Uint8Array.of(footer ? 16 : 0);
1657
+ patches.push({
1658
+ start: at + 5,
1659
+ end: at + 6,
1660
+ bytes: flags
1661
+ });
1662
+ if (body) patches.push({
1663
+ start: at + 10,
1664
+ end: at + 10 + body
1665
+ });
1666
+ if (footer) {
1667
+ check(text(await read(at + 10 + body, 3), 0, 3) === "3DI");
1668
+ patches.push({
1669
+ start: at + 10 + body + 5,
1670
+ end: at + 10 + body + 6,
1671
+ bytes: flags
1672
+ });
1673
+ }
1674
+ return end;
1675
+ }
1676
+ /**
1677
+ * The tags at the end of an MP3 or AAC file (after `start`): an ID3v1 (and its extended part), then any of an APEv2
1678
+ * tag, a Lyrics3v2 tag and an ID3v2 tag with a footer, in any order. Each found is emptied where it is.
1679
+ */
1680
+ async function trailingTags(read, size, start, patches) {
1681
+ let end = size;
1682
+ if (end - 128 >= start && text(await read(end - 128, 3), 0, 3) === "TAG") {
1683
+ patches.push({
1684
+ start: end - 125,
1685
+ end: end - 1
1686
+ }, {
1687
+ start: end - 1,
1688
+ end,
1689
+ bytes: Uint8Array.of(255)
1690
+ });
1691
+ end -= 128;
1692
+ if (end - 227 >= start && text(await read(end - 227, 4), 0, 4) === "TAG+") {
1693
+ patches.push({
1694
+ start: end - 223,
1695
+ end
1696
+ });
1697
+ end -= 227;
1698
+ }
1699
+ }
1700
+ const count = counter();
1701
+ for (;;) {
1702
+ count();
1703
+ if (end - 32 >= start) {
1704
+ const footer = await read(end - 32, 32);
1705
+ if (text(footer, 0, 8) === "APETAGEX") {
1706
+ const length = u32le(footer, 12), header = footer[23] & 128 ? 32 : 0, tagStart = end - length - header;
1707
+ check(length >= 32 && tagStart >= start);
1708
+ if (header) {
1709
+ check(text(await read(tagStart, 8), 0, 8) === "APETAGEX");
1710
+ patches.push({
1711
+ start: tagStart + 16,
1712
+ end: tagStart + 20
1713
+ });
1714
+ }
1715
+ if (length > 32) patches.push({
1716
+ start: tagStart + header,
1717
+ end: end - 32
1718
+ });
1719
+ patches.push({
1720
+ start: end - 16,
1721
+ end: end - 12
1722
+ });
1723
+ end = tagStart;
1724
+ continue;
1725
+ }
1726
+ }
1727
+ if (end - 15 >= start) {
1728
+ const footer = await read(end - 15, 15);
1729
+ if (text(footer, 6, 9) === "LYRICS200") {
1730
+ const length = /^\d{6}$/.test(text(footer, 0, 6)) ? Number(text(footer, 0, 6)) : -1, tagStart = end - 15 - length;
1731
+ check(length >= 11 && tagStart >= start && text(await read(tagStart, 11), 0, 11) === "LYRICSBEGIN");
1732
+ if (length > 11) patches.push({
1733
+ start: tagStart + 11,
1734
+ end: end - 15
1735
+ });
1736
+ end = tagStart;
1737
+ continue;
1738
+ }
1739
+ }
1740
+ if (end - 10 >= start) {
1741
+ const footer = await read(end - 10, 10);
1742
+ if (text(footer, 0, 3) === "3DI") {
1743
+ check([
1744
+ 6,
1745
+ 7,
1746
+ 8,
1747
+ 9
1748
+ ].every((i) => footer[i] < 128));
1749
+ const tagStart = end - 20 - syncsafe(footer, 6);
1750
+ check(tagStart >= start);
1751
+ const head = await read(tagStart, 10);
1752
+ check(isId3(head));
1753
+ check(await emptyId3(read, size, tagStart, head, patches) === end);
1754
+ end = tagStart;
1755
+ continue;
1756
+ }
1757
+ }
1758
+ return;
1759
+ }
1760
+ }
1761
+ /** The types an MP3 or AAC file is sent as: one whose first bytes are no frame still has its tags at the end read. */
1762
+ var MPEG_AUDIO = /* @__PURE__ */ new Set([
1763
+ "audio/mpeg",
1764
+ "audio/mp3",
1765
+ "audio/mpeg3",
1766
+ "audio/x-mpeg",
1767
+ "audio/x-mp3",
1768
+ "audio/aac",
1769
+ "audio/x-aac",
1770
+ "audio/aacp"
1771
+ ]);
1772
+ /** An MPEG audio frame's or an ADTS header's first bytes: 11 bits set, a version and a layer that are some. */
1773
+ var isFrame = (b, at) => b.length >= at + 2 && b[at] === 255 && (b[at + 1] & 224) === 224 && (b[at + 1] & 24) !== 8;
1774
+ var FLAC_KEEPS = /* @__PURE__ */ new Set([0, 3]);
1775
+ /** A FLAC's metadata blocks from `at` (its `fLaC`): all but its stream info and seek table become padding, zeroed. */
1776
+ async function flac(read, size, at, patches) {
1777
+ const count = counter();
1778
+ for (at += 4;;) {
1779
+ count();
1780
+ const head = await read(at, 4);
1781
+ const last = head[0] & 128, type = head[0] & 127, end = at + 4 + (head[1] << 16 | head[2] << 8 | head[3]);
1782
+ check(type !== 127 && end <= size);
1783
+ if (!FLAC_KEEPS.has(type)) {
1784
+ if (type !== 1) patches.push({
1785
+ start: at,
1786
+ end: at + 1,
1787
+ bytes: Uint8Array.of(last | 1)
1788
+ });
1789
+ if (end > at + 4) patches.push({
1790
+ start: at + 4,
1791
+ end
1792
+ });
1793
+ }
1794
+ at = end;
1795
+ if (last) return at;
1796
+ }
1797
+ }
1798
+ var OGG_CRC = (() => {
1799
+ const table = /* @__PURE__ */ new Uint32Array(256);
1800
+ for (let i = 0; i < 256; i++) {
1801
+ let crc = i << 24;
1802
+ for (let bit = 0; bit < 8; bit++) crc = crc & 2147483648 ? crc << 1 ^ 79764919 : crc << 1;
1803
+ table[i] = crc >>> 0;
1804
+ }
1805
+ return table;
1806
+ })();
1807
+ /** Ogg's page checksum, over the page with its checksum's four bytes zeroed. */
1808
+ function oggCrc(page) {
1809
+ let crc = 0;
1810
+ for (let i = 0; i < page.length; i++) crc = (crc << 8 ^ OGG_CRC[(crc >>> 24 ^ (i >= 22 && i < 26 ? 0 : page[i])) & 255]) >>> 0;
1811
+ return crc;
1812
+ }
1813
+ /**
1814
+ * A comment header with no comment: its magic and vendor kept, its count 0 (and Vorbis's framing bit set), the rest
1815
+ * zeros: padding after the comments, which Opus says may be there and Vorbis's, Speex's and Theora's readers do not read.
1816
+ */
1817
+ function noComments(packet, comments, framing) {
1818
+ const magic = comments.length;
1819
+ check(text(packet, 0, magic) === comments && packet.length >= magic + 4);
1820
+ const count = magic + 4 + u32le(packet, magic);
1821
+ check(count + 4 + (framing ? 1 : 0) <= packet.length);
1822
+ const out = new Uint8Array(packet.length);
1823
+ out.set(packet.subarray(0, count));
1824
+ if (framing) out[count + 4] = 1;
1825
+ return out;
1826
+ }
1827
+ /** A FLAC metadata block that is a whole packet (FLAC in Ogg): kept, or made padding as `flac` makes it. */
1828
+ function noFlacBlock(packet) {
1829
+ check(packet.length >= 4 && packet.length === 4 + (packet[1] << 16 | packet[2] << 8 | packet[3]) && (packet[0] & 127) !== 127);
1830
+ const type = packet[0] & 127;
1831
+ if (FLAC_KEEPS.has(type)) return packet;
1832
+ const out = new Uint8Array(packet.length);
1833
+ out[0] = type === 1 ? packet[0] : packet[0] & 128 | 1;
1834
+ return out;
1835
+ }
1836
+ /** A codec whose second packet is its comment header: its magic, and whether a framing bit follows its comments (Vorbis). */
1837
+ var commentHeader = (head, comments, framing) => ({
1838
+ head,
1839
+ tagged: (_, index) => index === 0,
1840
+ empty: (packet) => noComments(packet, comments, framing)
1841
+ });
1842
+ var OGG_CODECS = [
1843
+ commentHeader("OpusHead", "OpusTags", false),
1844
+ commentHeader("vorbis", "vorbis", true),
1845
+ commentHeader("Speex ", "", false),
1846
+ commentHeader("€theora", "theora", false),
1847
+ {
1848
+ head: "FLAC",
1849
+ tagged: (packet, index) => {
1850
+ if (index) return !(packet[0] & 128);
1851
+ check(packet.length >= 17 && text(packet, 9, 4) === "fLaC");
1852
+ return !(packet[13] & 128);
1853
+ },
1854
+ empty: noFlacBlock
1855
+ }
1856
+ ];
1857
+ /**
1858
+ * An Ogg file's pages walked: each logical stream's comment header (a chained file has one per link) made one with no
1859
+ * comment where it is, across the pages it spans, and those pages' checksums made again.
1860
+ */
1861
+ async function ogg(read, size, patches) {
1862
+ const streams = /* @__PURE__ */ new Map();
1863
+ /** The bytes put in the pages changed, by where each page starts: by where they go in the file. */
1864
+ const pages = /* @__PURE__ */ new Map();
1865
+ const packetOf = async (ranges) => {
1866
+ const length = ranges.reduce((sum, [start, end]) => sum + end - start, 0);
1867
+ check(length <= AUDIO_METADATA_LIMITS.maxReadBytes);
1868
+ const packet = new Uint8Array(length);
1869
+ let at = 0;
1870
+ for (const [start, end] of ranges) {
1871
+ packet.set(await read(start, end - start), at);
1872
+ at += end - start;
1873
+ }
1874
+ return packet;
1875
+ };
1876
+ const count = counter();
1877
+ for (let at = 0; at < size;) {
1878
+ count();
1879
+ const head = await read(at, 27);
1880
+ check(text(head, 0, 4) === "OggS" && head[4] === 0);
1881
+ const lacing = await read(at + 27, head[26]);
1882
+ const end = at + 27 + lacing.length + lacing.reduce((sum, l) => sum + l, 0);
1883
+ check(end <= size);
1884
+ const serial = u32le(head, 14);
1885
+ if (head[5] & 2) streams.set(serial, {
1886
+ packet: 0,
1887
+ ranges: [],
1888
+ tagged: true
1889
+ });
1890
+ const stream = streams.get(serial);
1891
+ check(!!stream);
1892
+ let offset = at + 27 + lacing.length;
1893
+ for (const length of lacing) {
1894
+ if (stream.tagged) stream.ranges.push([
1895
+ offset,
1896
+ offset + length,
1897
+ at
1898
+ ]);
1899
+ offset += length;
1900
+ if (length === 255) continue;
1901
+ if (stream.packet === 0) {
1902
+ const first = await packetOf(stream.ranges);
1903
+ stream.codec = OGG_CODECS.find((codec) => text(first, 0, codec.head.length) === codec.head) ?? null;
1904
+ stream.tagged = !!stream.codec?.tagged(first, 0);
1905
+ } else if (stream.tagged && stream.codec) {
1906
+ const packet = await packetOf(stream.ranges), emptied = stream.codec.empty(packet);
1907
+ stream.tagged = stream.codec.tagged(packet, stream.packet);
1908
+ let from = 0;
1909
+ for (const [start, until, page] of stream.ranges) {
1910
+ if (!pages.has(page)) pages.set(page, []);
1911
+ pages.get(page).push([start, emptied.subarray(from, from + until - start)]);
1912
+ from += until - start;
1913
+ }
1914
+ }
1915
+ stream.packet++;
1916
+ stream.ranges = [];
1917
+ }
1918
+ at = end;
1919
+ }
1920
+ for (const stream of streams.values()) check(!stream.tagged);
1921
+ for (const [start, changes] of pages) {
1922
+ const head = await read(start, 27), lacing = await read(start + 27, head[26]);
1923
+ const end = start + 27 + lacing.length + lacing.reduce((sum, l) => sum + l, 0);
1924
+ const page = (await read(start, end - start)).slice();
1925
+ for (const [where, bytes] of changes) page.set(bytes, where - start);
1926
+ const crc = oggCrc(page);
1927
+ page.set([
1928
+ crc & 255,
1929
+ crc >>> 8 & 255,
1930
+ crc >>> 16 & 255,
1931
+ crc >>> 24
1932
+ ], 22);
1933
+ patches.push({
1934
+ start,
1935
+ end,
1936
+ bytes: page
1937
+ });
1938
+ }
1939
+ }
1940
+ /** The chunks a WAV's sound is made of, kept; any other becomes `JUNK`. */
1941
+ var WAV_KEEPS = /* @__PURE__ */ new Set([
1942
+ "fmt ",
1943
+ "data",
1944
+ "fact",
1945
+ "cue ",
1946
+ "smpl",
1947
+ "inst"
1948
+ ]);
1949
+ var WAV_SPACE = /* @__PURE__ */ new Set([
1950
+ "JUNK",
1951
+ "junk",
1952
+ "PAD ",
1953
+ "FLLR"
1954
+ ]);
1955
+ /** A WAV's chunks from its `WAVE`; an RF64 or BW64 one (`rf64`) has its `ds64` first, which says `data`'s size when its own is all ones. */
1956
+ async function wav(read, size, rf64, patches) {
1957
+ let dataSize;
1958
+ if (rf64) {
1959
+ const ds64 = await read(12, 24);
1960
+ check(text(ds64, 0, 4) === "ds64" && u32le(ds64, 4) >= 28);
1961
+ dataSize = u32le(ds64, 16) + u32le(ds64, 20) * 2 ** 32;
1962
+ }
1963
+ const count = counter();
1964
+ for (let at = 12; at + 8 <= size;) {
1965
+ count();
1966
+ const head = await read(at, 8);
1967
+ const id = text(head, 0, 4), length = id === "data" && dataSize !== void 0 && u32le(head, 4) === 4294967295 ? dataSize : u32le(head, 4);
1968
+ let end = at + 8 + length + length % 2;
1969
+ if (id === "data") end = length ? Math.min(end, size) : size;
1970
+ else check(at + 8 + length <= size);
1971
+ if (!WAV_KEEPS.has(id) && !(rf64 && at === 12)) {
1972
+ if (!WAV_SPACE.has(id)) patches.push({
1973
+ start: at,
1974
+ end: at + 4,
1975
+ bytes: latin("JUNK")
1976
+ });
1977
+ if (length) patches.push({
1978
+ start: at + 8,
1979
+ end: at + 8 + length
1980
+ });
1981
+ }
1982
+ at = Math.min(end, size);
1983
+ }
1984
+ }
1985
+ /** The chunks an AIFF's or AIFF-C's sound is made of, kept; any other becomes `JUNK`. */
1986
+ var AIFF_KEEPS = /* @__PURE__ */ new Set([
1987
+ "COMM",
1988
+ "SSND",
1989
+ "FVER",
1990
+ "MARK",
1991
+ "INST",
1992
+ "AESD",
1993
+ "chan"
1994
+ ]);
1995
+ /** An AIFF's chunks from its form type: big-endian sizes, each padded to an even length. */
1996
+ async function aiff(read, size, patches) {
1997
+ const count = counter();
1998
+ for (let at = 12; at + 8 <= size;) {
1999
+ count();
2000
+ const head = await read(at, 8);
2001
+ const id = text(head, 0, 4), length = u32be(head, 4);
2002
+ let end = at + 8 + length + length % 2;
2003
+ if (id === "SSND") end = length ? Math.min(end, size) : size;
2004
+ else check(at + 8 + length <= size);
2005
+ if (!AIFF_KEEPS.has(id)) {
2006
+ if (id !== "JUNK") patches.push({
2007
+ start: at,
2008
+ end: at + 4,
2009
+ bytes: latin("JUNK")
2010
+ });
2011
+ if (length) patches.push({
2012
+ start: at + 8,
2013
+ end: at + 8 + length
2014
+ });
2015
+ }
2016
+ at = Math.min(end, size);
2017
+ }
2018
+ }
2019
+ /** The chunks a CAF's sound is made of, kept; any other becomes `free`. */
2020
+ var CAF_KEEPS = /* @__PURE__ */ new Set([
2021
+ "desc",
2022
+ "data",
2023
+ "pakt",
2024
+ "kuki",
2025
+ "chan",
2026
+ "peak",
2027
+ "ovvw"
2028
+ ]);
2029
+ /** A CAF's chunks after its 8-byte header: big-endian 64-bit sizes, `data`'s -1 when it runs to the end. */
2030
+ async function caf(read, size, patches) {
2031
+ const count = counter();
2032
+ for (let at = 8; at + 12 <= size;) {
2033
+ count();
2034
+ const head = await read(at, 12);
2035
+ const id = text(head, 0, 4), high = u32be(head, 4), length = high * 2 ** 32 + u32be(head, 8);
2036
+ const toEnd = id === "data" && high === 4294967295 && u32be(head, 8) === 4294967295;
2037
+ check(toEnd || Number.isSafeInteger(length) && at + 12 + length <= size);
2038
+ const end = toEnd ? size : at + 12 + length;
2039
+ if (!CAF_KEEPS.has(id)) {
2040
+ if (id !== "free") patches.push({
2041
+ start: at,
2042
+ end: at + 4,
2043
+ bytes: latin("free")
2044
+ });
2045
+ if (end > at + 12) patches.push({
2046
+ start: at + 12,
2047
+ end
2048
+ });
2049
+ }
2050
+ at = end;
2051
+ }
2052
+ }
2053
+ /** A WavPack sub-block's own id (its flags apart): the source file's header and trailer, a WAV's or another's. */
2054
+ var WAVPACK_SOURCE = /* @__PURE__ */ new Set([
2055
+ 33,
2056
+ 34,
2057
+ 35,
2058
+ 36
2059
+ ]);
2060
+ /** A WavPack's blocks from `at`, their source file's header and trailer emptied; returns where they end (its tags). */
2061
+ async function wavpack(read, size, at, patches) {
2062
+ const count = counter();
2063
+ while (at + 32 <= size && text(await read(at, 4), 0, 4) === "wvpk") {
2064
+ count();
2065
+ const end = at + 8 + u32le(await read(at + 4, 4), 0);
2066
+ check(end >= at + 32 && end <= size);
2067
+ for (let sub = at + 32; sub < end;) {
2068
+ count();
2069
+ const head = await read(sub, Math.min(4, end - sub));
2070
+ const large = (head[0] & 128) !== 0, body = sub + (large ? 4 : 2);
2071
+ check(body <= end);
2072
+ const length = (large ? head[1] | head[2] << 8 | head[3] << 16 : head[1]) * 2;
2073
+ check(body + length <= end);
2074
+ if (WAVPACK_SOURCE.has(head[0] & 63)) {
2075
+ patches.push({
2076
+ start: sub,
2077
+ end: sub + 1,
2078
+ bytes: Uint8Array.of(head[0] & 192 | 32)
2079
+ });
2080
+ if (length) patches.push({
2081
+ start: body,
2082
+ end: body + length
2083
+ });
2084
+ }
2085
+ sub = body + length;
2086
+ }
2087
+ at = end;
2088
+ }
2089
+ return at;
2090
+ }
2091
+ /** A Sun AU's annotation: from its 24-byte header to its sound. */
2092
+ async function au(read, size, patches) {
2093
+ const offset = u32be(await read(4, 4), 0);
2094
+ check(offset >= 24 && offset <= size);
2095
+ if (offset > 24) patches.push({
2096
+ start: 24,
2097
+ end: offset
2098
+ });
2099
+ }
2100
+ var EBML_HEADER = 440786851;
2101
+ var SEGMENT = 408125543;
2102
+ var CLUSTER = 524531317;
2103
+ var VOID = 236;
2104
+ var CRC32 = 191;
2105
+ var SEEK_HEAD = 290298740;
2106
+ var INFO = 357149030;
2107
+ var TRACKS = 374648427;
2108
+ /** What a segment's sound and pictures are made of, kept; any other top-level element (Tags, Attachments, Chapters) becomes Void. */
2109
+ var SEGMENT_KEEPS = /* @__PURE__ */ new Set([
2110
+ SEEK_HEAD,
2111
+ INFO,
2112
+ TRACKS,
2113
+ CLUSTER,
2114
+ 475249515
2115
+ ]);
2116
+ /** What a cluster holds: one of unknown size ends where an element that is none of these starts. */
2117
+ var CLUSTER_CHILDREN = /* @__PURE__ */ new Set([
2118
+ 231,
2119
+ 22612,
2120
+ 167,
2121
+ 171,
2122
+ 163,
2123
+ 160,
2124
+ 175,
2125
+ VOID,
2126
+ CRC32
2127
+ ]);
2128
+ /** What Info keeps: the timing, the segment's IDs; the muxer's and writing app's names, zeroed. Any other (a title, a date, file names) becomes Void. */
2129
+ var INFO_KEEPS = /* @__PURE__ */ new Set([
2130
+ 2807729,
2131
+ 17545,
2132
+ 29604,
2133
+ 17476,
2134
+ 3979555,
2135
+ 4110627,
2136
+ 26916
2137
+ ]);
2138
+ var INFO_ZEROED = /* @__PURE__ */ new Set([19840, 22337]);
2139
+ var TRACK_ENTRY = 174;
2140
+ var TRACK_NAME = 21358;
2141
+ var CODEC_ID = 134;
2142
+ var CODEC_PRIVATE = 25506;
2143
+ var SEEK = 19899;
2144
+ var SEEK_ID = 21419;
2145
+ /** The codecs whose CodecPrivate is their Ogg headers Xiph-laced: the second a comment header, its magic, and whether a framing bit follows its comments. */
2146
+ var XIPH_PRIVATE = /* @__PURE__ */ new Map([["A_VORBIS", ["vorbis", true]], ["V_THEORA", ["theora", false]]]);
2147
+ /** The element whose header is at `at` of `b` (`base` its offset in the file); one of unknown size ends at `limit`. */
2148
+ function element(b, at, limit, base = 0) {
2149
+ check(at < b.length);
2150
+ const idLength = Math.clz32(b[at]) - 23;
2151
+ check(idLength >= 1 && idLength <= 4 && at + idLength < b.length);
2152
+ let id = 0;
2153
+ for (let i = 0; i < idLength; i++) id = id * 256 + b[at + i];
2154
+ const sizeAt = at + idLength, sizeLength = Math.clz32(b[sizeAt]) - 23;
2155
+ check(sizeLength >= 1 && sizeLength <= 8 && sizeAt + sizeLength <= b.length);
2156
+ let size = b[sizeAt] & 255 >> sizeLength, ones = size === 255 >> sizeLength;
2157
+ for (let i = 1; i < sizeLength; i++) {
2158
+ size = size * 256 + b[sizeAt + i];
2159
+ ones &&= b[sizeAt + i] === 255;
2160
+ }
2161
+ const body = base + sizeAt + sizeLength;
2162
+ return {
2163
+ id,
2164
+ start: base + at,
2165
+ body,
2166
+ end: ones ? limit : body + size,
2167
+ unknown: ones
2168
+ };
2169
+ }
2170
+ /** An element's header read from the file at `at`. */
2171
+ async function elementAt(source, at, limit) {
2172
+ return element(await source.read(at, 12), 0, limit, at);
2173
+ }
2174
+ /** A Void element `length` bytes long: its ID, its size in as many bytes as it takes to fill it, the rest zeros. */
2175
+ function voidHeader(length) {
2176
+ for (let sizeLength = 1; sizeLength <= 8; sizeLength++) {
2177
+ const body = length - 1 - sizeLength;
2178
+ if (body < 0 || body >= 2 ** (7 * sizeLength) - 1) continue;
2179
+ const header = new Uint8Array(1 + sizeLength);
2180
+ header[0] = VOID;
2181
+ for (let i = sizeLength, rest = body; i >= 1; i--, rest = Math.floor(rest / 256)) header[i] = rest % 256;
2182
+ header[1] |= 128 >> sizeLength - 1;
2183
+ return header;
2184
+ }
2185
+ check(false);
2186
+ }
2187
+ /** `el` of `b` (read whole, `el`'s offsets in it) made Void where it is. */
2188
+ function voidIn(b, el) {
2189
+ const header = voidHeader(el.end - el.start);
2190
+ b.fill(0, el.start, el.end);
2191
+ b.set(header, el.start);
2192
+ }
2193
+ /** The children of `parent` (in `b`, read whole) as elements, each within it. */
2194
+ function childrenOf(b, parent) {
2195
+ const found = [];
2196
+ for (let at = parent.body; at < parent.end;) {
2197
+ const child = element(b.subarray(0, parent.end), at, parent.end);
2198
+ check(!child.unknown && child.end <= parent.end);
2199
+ found.push(child);
2200
+ at = child.end;
2201
+ }
2202
+ return found;
2203
+ }
2204
+ /**
2205
+ * A track's CodecPrivate (`b`, changed in it) by its codec: a Vorbis or Theora track's headers (their count less one,
2206
+ * each size but the last's in Xiph lacing, them) with a comment header that has no comment, its sizes kept; a FLAC
2207
+ * track's `fLaC` and metadata blocks as a FLAC's, any byte after the last zeroed. Another codec's is kept as it is.
2208
+ */
2209
+ async function noPrivateTags(b, codec) {
2210
+ const xiph = XIPH_PRIVATE.get(codec);
2211
+ if (xiph) {
2212
+ check(b.length >= 1 && b[0] === 2);
2213
+ let at = 1;
2214
+ const sizes = [];
2215
+ while (sizes.length < 2) {
2216
+ let size = 0;
2217
+ for (let byte = 255; byte === 255; size += byte) {
2218
+ check(at < b.length);
2219
+ byte = b[at++];
2220
+ }
2221
+ sizes.push(size);
2222
+ }
2223
+ const start = at + sizes[0], end = start + sizes[1];
2224
+ check(end <= b.length);
2225
+ b.set(noComments(b.subarray(start, end), ...xiph), start);
2226
+ } else if (codec === "A_FLAC") {
2227
+ check(b.length >= 4 && text(b, 0, 4) === "fLaC");
2228
+ const patches = [];
2229
+ const end = await flac(async (offset, length) => {
2230
+ check(offset >= 0 && length >= 0 && offset + length <= b.length);
2231
+ return b.subarray(offset, offset + length);
2232
+ }, b.length, 0, patches);
2233
+ for (const patch of patches) if (patch.bytes) b.set(patch.bytes, patch.start);
2234
+ else b.fill(0, patch.start, patch.end);
2235
+ b.fill(0, end);
2236
+ }
2237
+ }
2238
+ /**
2239
+ * A top-level element of a segment read whole and changed in it: Info without its title, date and file names (its
2240
+ * muxer's and writing app's names zeroed), Tracks without their names and the comments in their CodecPrivate, a
2241
+ * SeekHead without the entries for what became Void. A CRC-32 in them, wrong once they changed, becomes Void too.
2242
+ */
2243
+ async function stripTopLevel(b) {
2244
+ const top = element(b, 0, b.length);
2245
+ check(!top.unknown && top.end === b.length);
2246
+ for (const child of childrenOf(b, top)) {
2247
+ if (child.id === CRC32) voidIn(b, child);
2248
+ else if (top.id === INFO) {
2249
+ if (INFO_ZEROED.has(child.id)) b.fill(0, child.body, child.end);
2250
+ else if (!INFO_KEEPS.has(child.id) && child.id !== VOID) voidIn(b, child);
2251
+ } else if (top.id === TRACKS && child.id === TRACK_ENTRY) {
2252
+ const parts = childrenOf(b, child), ids = parts.filter((part) => part.id === CODEC_ID);
2253
+ check(ids.length <= 1);
2254
+ const codec = ids[0] ? text(b, ids[0].body, ids[0].end - ids[0].body).replace(/\0+$/, "") : "";
2255
+ for (const part of parts) if (part.id === TRACK_NAME || part.id === CRC32) voidIn(b, part);
2256
+ else if (part.id === CODEC_PRIVATE) await noPrivateTags(b.subarray(part.body, part.end), codec);
2257
+ } else if (top.id === SEEK_HEAD && child.id === SEEK) {
2258
+ const target = childrenOf(b, child).find((part) => part.id === SEEK_ID);
2259
+ let id = 0;
2260
+ if (target) for (let i = target.body; i < target.end; i++) id = id * 256 + b[i];
2261
+ if (!SEGMENT_KEEPS.has(id)) voidIn(b, child);
2262
+ }
2263
+ if (child.id === VOID) b.fill(0, child.body, child.end);
2264
+ }
2265
+ }
2266
+ /** Where a cluster of unknown size ends: at the first element that is not a cluster's, or the segment's end. */
2267
+ async function clusterEnd(source, at, limit, count) {
2268
+ for (;;) {
2269
+ count();
2270
+ if (at >= limit) return limit;
2271
+ const child = await elementAt(source, at, limit);
2272
+ if (!CLUSTER_CHILDREN.has(child.id)) return at;
2273
+ check(!child.unknown);
2274
+ if (child.end >= limit) return limit;
2275
+ at = child.end;
2276
+ }
2277
+ }
2278
+ async function matroska(source, read, patches) {
2279
+ const count = counter();
2280
+ const toVoid = (el) => {
2281
+ const header = voidHeader(el.end - el.start);
2282
+ patches.push({
2283
+ start: el.start,
2284
+ end: el.start + header.length,
2285
+ bytes: header
2286
+ });
2287
+ if (el.end > el.start + header.length) patches.push({
2288
+ start: el.start + header.length,
2289
+ end: el.end
2290
+ });
2291
+ };
2292
+ for (let at = 0; at < source.size;) {
2293
+ count();
2294
+ const top = await elementAt(source, at, source.size);
2295
+ check(top.end <= source.size);
2296
+ if (top.id === EBML_HEADER) check(!top.unknown);
2297
+ else if (top.id === VOID) {
2298
+ if (top.end > top.body) patches.push({
2299
+ start: top.body,
2300
+ end: top.end
2301
+ });
2302
+ } else if (top.id !== SEGMENT) {
2303
+ check(!top.unknown);
2304
+ toVoid(top);
2305
+ } else for (let in_ = top.body; in_ < top.end;) {
2306
+ count();
2307
+ const el = await elementAt(source, in_, top.end);
2308
+ if (el.id === CLUSTER) {
2309
+ in_ = el.unknown ? await clusterEnd(source, el.body, top.end, count) : Math.min(el.end, top.end);
2310
+ continue;
2311
+ }
2312
+ check(!el.unknown && el.end <= top.end);
2313
+ if (el.id === INFO || el.id === TRACKS || el.id === SEEK_HEAD) {
2314
+ const bytes = (await read(el.start, el.end - el.start)).slice();
2315
+ await stripTopLevel(bytes);
2316
+ patches.push({
2317
+ start: el.start,
2318
+ end: el.end,
2319
+ bytes
2320
+ });
2321
+ } else if (el.id === VOID) {
2322
+ if (el.end > el.body) patches.push({
2323
+ start: el.body,
2324
+ end: el.end
2325
+ });
2326
+ } else if (!SEGMENT_KEEPS.has(el.id)) toVoid(el);
2327
+ in_ = el.end;
2328
+ }
2329
+ at = top.end;
2330
+ }
2331
+ }
2332
+ /**
2333
+ * What `withoutAudioMetadata` changes in an audio file read from `source` (one not held in a Blob: a file kept in
2334
+ * storage): the parts replaced, in order and apart, the rest of its bytes going as they are; undefined when it goes as
2335
+ * it is. Throws `NO_AUDIO_METADATA` for one whose tags cannot be removed; an error reading `source` as it is.
2336
+ */
2337
+ async function audioMetadataPatches(file, mime) {
2338
+ const source = readingAhead(file), read = exactly(source), size = source.size;
2339
+ const head = await source.read(0, Math.min(AUDIO_METADATA_LIMITS.headBytes, size));
2340
+ const patches = [];
2341
+ if (head.length >= 8 && text(head, 4, 4) === "ftyp") try {
2342
+ return await videoMetadataPatches(file, mime, true);
2343
+ } catch (error) {
2344
+ if (error instanceof Error && error.message === "This video cannot be sent: Ghostly could not remove the details saved in it, like where it was recorded") throw Object.assign(/* @__PURE__ */ new Error(NO_AUDIO_METADATA), { cause: error });
2345
+ throw error;
2346
+ }
2347
+ else if (text(head, 0, 4) === "OggS") await ogg(read, size, patches);
2348
+ else if (head.length >= 12 && [
2349
+ "RIFF",
2350
+ "RF64",
2351
+ "BW64"
2352
+ ].includes(text(head, 0, 4)) && text(head, 8, 4) === "WAVE") await wav(read, size, text(head, 0, 4) !== "RIFF", patches);
2353
+ else if (text(head, 0, 4) === "Eߣ") await matroska(source, read, patches);
2354
+ else if (head.length >= 12 && text(head, 0, 4) === "FORM" && ["AIFF", "AIFC"].includes(text(head, 8, 4))) await aiff(read, size, patches);
2355
+ else if (head.length >= 8 && text(head, 0, 4) === "caff") await caf(read, size, patches);
2356
+ else if (head.length >= 24 && text(head, 0, 4) === ".snd") await au(read, size, patches);
2357
+ else if (text(head, 0, 4) === "wvpk") await trailingTags(read, size, await wavpack(read, size, 0, patches), patches);
2358
+ else if (text(head, 0, 4) === "TTA1") await trailingTags(read, size, 0, patches);
2359
+ else if (isAsf(head)) check(false);
2360
+ else if (text(head, 0, 4) === "fLaC") await trailingTags(read, size, await flac(read, size, 0, patches), patches);
2361
+ else if (isId3(head) || isFrame(head, 0)) {
2362
+ let at = 0;
2363
+ const count = counter();
2364
+ for (let next = head; isId3(next); next = at + 10 <= size ? await read(at, 10) : /* @__PURE__ */ new Uint8Array(0)) {
2365
+ count();
2366
+ at = await emptyId3(read, size, at, next, patches);
2367
+ }
2368
+ if (at + 4 <= size && text(await read(at, 4), 0, 4) === "fLaC") at = await flac(read, size, at, patches);
2369
+ else if (at + 4 <= size && text(await read(at, 4), 0, 4) === "wvpk") at = await wavpack(read, size, at, patches);
2370
+ await trailingTags(read, size, at, patches);
2371
+ } else if (MPEG_AUDIO.has(baseMime(mime))) await trailingTags(read, size, 0, patches);
2372
+ else return void 0;
2373
+ if (!patches.length) return void 0;
2374
+ patches.sort((a, b) => a.start - b.start);
2375
+ for (let i = 1; i < patches.length; i++) check(patches[i].start >= patches[i - 1].end);
2376
+ return patches;
2377
+ }
2378
+ /**
2379
+ * `source` as it is sent: an audio file without its tags, made of `source`'s own bytes but for the parts emptied;
2380
+ * undefined when it goes as it is (not one of these, or one with nothing to remove). Throws `NO_AUDIO_METADATA` for
2381
+ * one whose tags cannot be removed; an error reading `source` as it is.
2382
+ */
2383
+ async function withoutAudioMetadata(source, mime) {
2384
+ const patches = await audioMetadataPatches({
2385
+ size: source.size,
2386
+ read: async (offset, length) => new Uint8Array(await source.slice(offset, offset + length).arrayBuffer())
2387
+ }, mime);
2388
+ if (!patches) return void 0;
2389
+ const parts = [];
2390
+ let at = 0;
2391
+ for (const patch of patches) {
2392
+ if (patch.start > at) parts.push(source.slice(at, patch.start));
2393
+ if (patch.bytes) parts.push(patch.bytes);
2394
+ else for (let left = patch.end - patch.start; left > 0; left -= ZEROS.size) parts.push(ZEROS.slice(0, Math.min(left, ZEROS.size)));
2395
+ at = patch.end;
2396
+ }
2397
+ if (at < source.size) parts.push(source.slice(at));
2398
+ return new Blob(parts, { type: mime });
2399
+ }
2400
+ // ../core/src/lnurl.ts
2401
+ var LNURL_LIMITS = {
2402
+ timeoutMs: 15e3,
2403
+ maxBytes: 65536,
2404
+ maxRedirects: 5,
2405
+ maxUrlLength: 2048,
2406
+ maxMetadataLength: 8192,
2407
+ maxComment: 2e3
2408
+ };
2409
+ var ADDRESS = /^([a-z0-9._+-]{1,64})@([a-z0-9-]+(?:\.[a-z0-9-]+)*(?::\d{1,5})?)$/i;
2410
+ var LNURL_BECH32 = /^lnurl1[02-9ac-hj-np-z]{6,}$/i;
2411
+ var REDIRECTS = [
2412
+ 301,
2413
+ 302,
2414
+ 303,
2415
+ 307,
2416
+ 308
2417
+ ];
2418
+ /**
2419
+ * A host that is not on the public internet, as far as its name tells: this machine, a single label, `.local` and its
2420
+ * kin, private and reserved IP addresses. (What a public name resolves to is checked where the client resolves names
2421
+ * itself, as Ghostly Desktop does.)
2422
+ */
2423
+ function isLocalHost(hostname) {
2424
+ const host = hostname.toLowerCase().replace(/\.$/, "").replace(/^\[|\]$/g, "");
2425
+ if (!host.includes(".") && !host.includes(":")) return true;
2426
+ if (/(^|\.)(localhost|local|internal|lan|home\.arpa)$/.test(host)) return true;
2427
+ const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
2428
+ if (v4) {
2429
+ const [a, b] = [Number(v4[1]), Number(v4[2])];
2430
+ return a === 0 || a === 10 || a === 127 || a >= 224 || a === 169 && b === 254 || a === 172 && b >= 16 && b < 32 || a === 192 && b === 168 || a === 100 && b >= 64 && b < 128 || a === 198 && (b === 18 || b === 19) || a === 192 && b === 0;
2431
+ }
2432
+ if (host.includes(":")) return !/^[23][0-9a-f]{0,3}:/.test(host) || host.includes(".") || /^2001:0?db8:/.test(host);
2433
+ return false;
2434
+ }
2435
+ var isLoopback = (hostname) => [
2436
+ "localhost",
2437
+ "127.0.0.1",
2438
+ "[::1]"
2439
+ ].includes(hostname);
2440
+ /** HTTPS, or plain HTTP only for a hidden service or a test server on this machine; never credentials. */
2441
+ function acceptUrl(text) {
2442
+ if (text.length > LNURL_LIMITS.maxUrlLength) throw new Error("That LNURL is too long");
2443
+ let url;
2444
+ try {
2445
+ url = new URL(text);
2446
+ } catch {
2447
+ throw new Error("That LNURL does not point to a valid address");
2448
+ }
2449
+ const plainAllowed = url.hostname.endsWith(".onion") || isLoopback(url.hostname);
2450
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && plainAllowed)) throw new Error("Lightning addresses and LNURLs must use HTTPS");
2451
+ if (url.username || url.password) throw new Error("That LNURL carries credentials, which is not allowed");
2452
+ return url;
2453
+ }
2454
+ /** Reads what was pasted as a Lightning address or an LNURL; null when it is neither. Throws when it is one, but a bad one. */
2455
+ function parseLightningDestination(input) {
2456
+ const text = input.trim().replace(/^(lightning:|⚡\s*)/i, "").trim();
2457
+ if (!text) return null;
2458
+ if (LNURL_BECH32.test(text)) {
2459
+ let decoded;
2460
+ try {
2461
+ decoded = bech32.decode(text.toLowerCase(), LNURL_LIMITS.maxUrlLength);
2462
+ } catch {
2463
+ throw new Error("That LNURL is not valid");
2464
+ }
2465
+ const url = acceptUrl(new TextDecoder().decode(bech32.fromWords(decoded.words)));
2466
+ return {
2467
+ kind: "lnurl",
2468
+ text: text.toLowerCase(),
2469
+ url: url.href,
2470
+ domain: url.host
2471
+ };
2472
+ }
2473
+ if (/^lnurlp:\/\//i.test(text)) {
2474
+ const bare = text.slice(9);
2475
+ const host = bare.split(/[/?#]/)[0].toLowerCase();
2476
+ const url = acceptUrl(`${host.endsWith(".onion") || isLoopback(host.replace(/:\d+$/, "")) ? "http" : "https"}://${bare}`);
2477
+ return {
2478
+ kind: "lnurl",
2479
+ text: `lnurlp://${bare}`,
2480
+ url: url.href,
2481
+ domain: url.host
2482
+ };
2483
+ }
2484
+ const address = ADDRESS.exec(text);
2485
+ if (!address) return null;
2486
+ const name = address[1].toLowerCase(), domain = address[2].toLowerCase();
2487
+ const hostname = domain.replace(/:\d+$/, "");
2488
+ if (!hostname.includes(".") && !isLoopback(hostname)) return null;
2489
+ const url = acceptUrl(`${hostname.endsWith(".onion") || isLoopback(hostname) ? "http" : "https"}://${domain}/.well-known/lnurlp/${name}`);
2490
+ return {
2491
+ kind: "address",
2492
+ text: `${name}@${domain}`,
2493
+ url: url.href,
2494
+ domain: url.host,
2495
+ name
2496
+ };
2497
+ }
2498
+ var hex$3 = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
2499
+ /** A server's own words on one line, bounded, with no character that hides text or reorders what follows it. */
2500
+ var reason = (value) => typeof value === "string" ? stripHidden(value.replace(/\s+/g, " ")).slice(0, 200) : "";
2501
+ var isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
2502
+ async function readBounded(response, maxBytes) {
2503
+ const reader = response.body?.getReader?.();
2504
+ if (!reader) {
2505
+ const text = await response.text();
2506
+ if (text.length > maxBytes) throw new Error("The server's answer is too large");
2507
+ return text;
2508
+ }
2509
+ const chunks = [];
2510
+ let size = 0;
2511
+ for (;;) {
2512
+ const { done, value } = await reader.read();
2513
+ if (done) break;
2514
+ size += value.byteLength;
2515
+ if (size > maxBytes) {
2516
+ await reader.cancel().catch(() => {});
2517
+ throw new Error("The server's answer is too large");
2518
+ }
2519
+ chunks.push(value);
2520
+ }
2521
+ const all = new Uint8Array(size);
2522
+ let at = 0;
2523
+ for (const chunk of chunks) {
2524
+ all.set(chunk, at);
2525
+ at += chunk.byteLength;
2526
+ }
2527
+ return new TextDecoder().decode(all);
2528
+ }
2529
+ /** One GET to an LNURL service (and to each checked redirect of it): bounded in time and size, no credentials, no referrer, and the answer must be JSON. */
2530
+ async function fetchLnurlJson(url, options = {}) {
2531
+ const target = acceptUrl(url);
2532
+ const doFetch = options.fetch ?? globalThis.fetch;
2533
+ if (!doFetch) throw new Error("No way to reach the network here");
2534
+ const controller = new AbortController();
2535
+ const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("The server took too long to answer")), options.timeoutMs ?? LNURL_LIMITS.timeoutMs);
2536
+ const onAbort = () => controller.abort(options.signal?.reason);
2537
+ options.signal?.addEventListener("abort", onAbort, { once: true });
2538
+ try {
2539
+ let response;
2540
+ for (let at = target, hops = 0;; hops++) {
2541
+ try {
2542
+ response = await doFetch(at.href, {
2543
+ signal: controller.signal,
2544
+ headers: { accept: "application/json" },
2545
+ credentials: "omit",
2546
+ referrerPolicy: "no-referrer",
2547
+ redirect: "manual"
2548
+ });
2549
+ } catch {
2550
+ if (controller.signal.aborted) throw controller.signal.reason instanceof Error ? controller.signal.reason : /* @__PURE__ */ new Error("The request was cancelled");
2551
+ throw engineError("lnurlUnreachable", { host: target.host });
2552
+ }
2553
+ if (response.url) acceptUrl(response.url);
2554
+ if (response.type === "opaqueredirect") throw new Error(`${target.host} redirects to another address, which cannot be checked here`);
2555
+ const location = REDIRECTS.includes(response.status) ? response.headers.get("location") : null;
2556
+ if (!location) break;
2557
+ await response.body?.cancel().catch(() => {});
2558
+ if (hops >= LNURL_LIMITS.maxRedirects) throw new Error(`${target.host} redirects too many times`);
2559
+ let next;
2560
+ try {
2561
+ next = new URL(location, at);
2562
+ } catch {
2563
+ throw new Error(`${target.host} redirects to an invalid address`);
2564
+ }
2565
+ next = acceptUrl(next.href);
2566
+ if (next.host !== at.host) {
2567
+ if (next.protocol !== "https:") throw new Error("Lightning addresses and LNURLs must use HTTPS");
2568
+ if (isLocalHost(next.hostname)) throw new Error(`${target.host} redirects to a local address`);
2569
+ }
2570
+ at = next;
2571
+ }
2572
+ const text = await readBounded(response, options.maxBytes ?? LNURL_LIMITS.maxBytes);
2573
+ let body;
2574
+ try {
2575
+ body = JSON.parse(text);
2576
+ } catch {
2577
+ throw new Error(`${target.host} did not answer with JSON${response.ok ? "" : ` (HTTP ${response.status})`}`);
2578
+ }
2579
+ if (isRecord(body) && body.status === "ERROR") throw new Error(`${target.host} refused: ${reason(body.reason) || "no reason given"}`);
2580
+ if (!response.ok) throw new Error(`${target.host} answered HTTP ${response.status}`);
2581
+ return body;
2582
+ } finally {
2583
+ clearTimeout(timer);
2584
+ options.signal?.removeEventListener("abort", onAbort);
2585
+ }
2586
+ }
2587
+ /** Checks a service's `payRequest` answer (LUD-06), and reads what a person needs to see of it. */
2588
+ function parsePayParams(body, destination) {
2589
+ if (!isRecord(body)) throw new Error(`${destination.domain} did not answer with a pay request`);
2590
+ if (body.tag !== "payRequest") throw new Error(`${destination.domain} answered with something other than a pay request${typeof body.tag === "string" ? ` (${reason(body.tag)})` : ""}`);
2591
+ if (typeof body.callback !== "string") throw new Error("The pay request has no callback");
2592
+ const callback = acceptUrl(body.callback);
2593
+ if (callback.host !== new URL(destination.url).host) {
2594
+ if (callback.protocol !== "https:") throw new Error("Lightning addresses and LNURLs must use HTTPS");
2595
+ if (isLocalHost(callback.hostname)) throw new Error(`${destination.domain} asks for the invoice at a local address`);
2596
+ }
2597
+ const { minSendable, maxSendable, metadata, commentAllowed } = body;
2598
+ if (!Number.isSafeInteger(minSendable) || !Number.isSafeInteger(maxSendable) || minSendable <= 0 || maxSendable < minSendable) throw new Error("The pay request has invalid amount limits");
2599
+ const minSat = Math.ceil(minSendable / 1e3), maxSat = Math.floor(maxSendable / 1e3);
2600
+ if (minSat > maxSat) throw new Error("The pay request only takes fractions of a sat, which cannot be paid here");
2601
+ if (typeof metadata !== "string" || metadata.length > LNURL_LIMITS.maxMetadataLength) throw new Error("The pay request has no usable metadata");
2602
+ let entries;
2603
+ try {
2604
+ entries = JSON.parse(metadata);
2605
+ } catch {
2606
+ throw new Error("The pay request's metadata is not JSON");
2607
+ }
2608
+ if (!Array.isArray(entries) || !entries.every((e) => Array.isArray(e) && typeof e[0] === "string")) throw new Error("The pay request's metadata is malformed");
2609
+ const entry = (type) => entries.find((e) => e[0] === type)?.[1];
2610
+ const description = entry("text/plain");
2611
+ if (typeof description !== "string") throw new Error("The pay request says nothing about what it is for (no text/plain metadata)");
2612
+ const identifier = [entry("text/identifier"), entry("text/email")].find((v) => typeof v === "string")?.toLowerCase();
2613
+ if (destination.kind === "address" && identifier && identifier !== destination.text) throw new Error(`${destination.domain} answered for ${identifier}, not ${destination.text}`);
2614
+ const comment = Number.isSafeInteger(commentAllowed) && commentAllowed > 0 ? Math.min(commentAllowed, LNURL_LIMITS.maxComment) : 0;
2615
+ return {
2616
+ destination,
2617
+ callback: callback.href,
2618
+ callbackDomain: callback.host,
2619
+ minSendable,
2620
+ maxSendable,
2621
+ minSat,
2622
+ maxSat,
2623
+ metadata,
2624
+ descriptionHash: hex$3(sha256(new TextEncoder().encode(metadata))),
2625
+ description: stripHidden(description.replace(/\s+/g, " ")).slice(0, 280),
2626
+ identifier,
2627
+ commentAllowed: comment
2628
+ };
2629
+ }
2630
+ /** Where to ask for the invoice of `amountSat` (and a comment, LUD-12). Throws when the amount or comment is not allowed. */
2631
+ function invoiceCallbackUrl(params, amountSat, comment) {
2632
+ if (!Number.isSafeInteger(amountSat) || amountSat <= 0) throw new Error("Enter a whole number of sats");
2633
+ if (amountSat < params.minSat || amountSat > params.maxSat) throw params.minSat === params.maxSat ? engineError("lnurlExactly", {
2634
+ domain: params.destination.domain,
2635
+ amount: params.minSat.toLocaleString()
2636
+ }) : engineError("lnurlRange", {
2637
+ domain: params.destination.domain,
2638
+ min: params.minSat.toLocaleString(),
2639
+ max: params.maxSat.toLocaleString()
2640
+ });
2641
+ const url = new URL(params.callback);
2642
+ url.searchParams.set("amount", String(amountSat * 1e3));
2643
+ const text = comment?.trim();
2644
+ if (text) {
2645
+ if (!params.commentAllowed) throw new Error(`${params.destination.domain} does not take a comment`);
2646
+ if (text.length > params.commentAllowed) throw new Error(`The comment can be at most ${params.commentAllowed} characters`);
2647
+ url.searchParams.set("comment", text);
2648
+ }
2649
+ return url.href;
2650
+ }
2651
+ /**
2652
+ * A success action's link: HTTPS, bounded, no user part ("https://www.paypal.com@evil.example" opens evil.example),
2653
+ * and on the callback's own host (LUD-09), so a service cannot hand out a link to somewhere else.
2654
+ */
2655
+ function successUrl(text, host) {
2656
+ if (!/^https:\/\//i.test(text) || text.length > LNURL_LIMITS.maxUrlLength) return false;
2657
+ try {
2658
+ const url = new URL(text);
2659
+ return !url.username && !url.password && url.host === host;
2660
+ } catch {
2661
+ return false;
2662
+ }
2663
+ }
2664
+ /**
2665
+ * Checks the invoice a service answered with (LUD-06): the amount asked, a payment hash, not expired, and
2666
+ * a commitment to the metadata the person was shown: the `h` tag is its sha256, or the invoice carries the
2667
+ * metadata itself as its description (the same commitment, unhashed).
2668
+ */
2669
+ function parseInvoiceCallback(body, params, amountSat) {
2670
+ if (!isRecord(body) || typeof body.pr !== "string") throw new Error(`${params.callbackDomain} did not answer with an invoice`);
2671
+ const invoice = decodeBolt11(body.pr);
2672
+ if (!invoice) throw new Error(`${params.callbackDomain} answered with an invoice that does not decode`);
2673
+ if (invoice.amountMsat !== BigInt(amountSat) * 1000n) throw new Error(`The invoice asks for ${invoice.amountSat === null ? "any amount" : `${invoice.amountSat.toLocaleString("en-US")} sats`}, not the ${amountSat.toLocaleString("en-US")} sats you chose`);
2674
+ if (!invoice.paymentHash) throw new Error("The invoice has no payment hash");
2675
+ if (invoice.descriptionHash !== params.descriptionHash && invoice.description !== params.metadata) throw new Error("The invoice does not commit to what the service said the payment is for");
2676
+ if (invoice.expiresAt * 1e3 < Date.now()) throw new Error("The invoice the service answered with has already expired");
2677
+ let successAction;
2678
+ const action = body.successAction;
2679
+ if (isRecord(action)) {
2680
+ if (action.tag === "message" && typeof action.message === "string") successAction = {
2681
+ tag: "message",
2682
+ message: reason(action.message)
2683
+ };
2684
+ else if (action.tag === "url" && typeof action.url === "string" && successUrl(action.url, params.callbackDomain)) successAction = {
2685
+ tag: "url",
2686
+ description: reason(action.description),
2687
+ url: action.url
2688
+ };
2689
+ }
2690
+ return {
2691
+ invoice,
2692
+ successAction
2693
+ };
2694
+ }
2695
+ /** Fetches and checks what a Lightning address or LNURL asks for. The service's domain learns of it. */
2696
+ async function resolveLightningDestination(text, options = {}) {
2697
+ const destination = parseLightningDestination(text);
2698
+ if (!destination) throw new Error("That is not a Lightning address or an LNURL");
2699
+ return parsePayParams(await fetchLnurlJson(destination.url, options), destination);
2700
+ }
2701
+ /** Asks the service for an invoice of `amountSat`, and checks it before it is handed to any wallet. */
2702
+ async function requestLnurlInvoice(params, amountSat, comment, options = {}) {
2703
+ return parseInvoiceCallback(await fetchLnurlJson(invoiceCallbackUrl(params, amountSat, comment), options), params, amountSat);
2704
+ }
2705
+ var MENTION_LIMITS = {
2706
+ /** Mentions in one message. A longer list is refused whole. */
2707
+ count: 16,
2708
+ /** Code points of one mention in the text, its "@" included. */
2709
+ chars: 65
2710
+ };
2711
+ var NOT_IN_A_NAME = /[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/;
2712
+ var isInt = (v) => Number.isSafeInteger(v) && v >= 0;
2713
+ /**
2714
+ * The mentions of a message as a receiver (or the sender) takes them: at most `count` of them, each naming a
2715
+ * member key (or everyone, when `everyone` allows it), at a place of the text that starts with "@" and holds no
2716
+ * line break or control character, in order and not overlapping. An entry that is none of that is dropped; a list
2717
+ * longer than the bound is dropped whole.
2718
+ */
2719
+ function validMentions(raw, text, everyone) {
2720
+ if (!Array.isArray(raw) || raw.length > MENTION_LIMITS.count) return [];
2721
+ const points = Array.from(text);
2722
+ const kept = [];
2723
+ for (const entry of raw) {
2724
+ if (!entry || typeof entry !== "object") continue;
2725
+ const { k, o, l } = entry;
2726
+ if (typeof k !== "string" || !(MEMBER_KEY.test(k) || everyone && k === "*")) continue;
2727
+ if (!isInt(o) || !isInt(l) || l < 2 || l > MENTION_LIMITS.chars || o + l > points.length || points[o] !== "@") continue;
2728
+ if (NOT_IN_A_NAME.test(points.slice(o, o + l).join(""))) continue;
2729
+ kept.push({
2730
+ k,
2731
+ o,
2732
+ l
2733
+ });
2734
+ }
2735
+ kept.sort((a, b) => a.o - b.o);
2736
+ return kept.filter((m, i) => i === 0 || m.o >= kept[i - 1].o + kept[i - 1].l);
2737
+ }
2738
+ /** Whether a message's mentions name this member (by key, or everyone). */
2739
+ function mentionsMember(mentions, key) {
2740
+ return !!mentions?.some((m) => m.k === key || m.k === "*");
2741
+ }
2742
+ /** The bytes a list of mentions adds to a message, as JSON: counted against the text's bound. */
2743
+ function mentionsBytes(mentions) {
2744
+ return mentions.length ? utf8Encode(JSON.stringify(mentions)).length : 0;
2745
+ }
2746
+ /** Only the wire fields, in a fixed order (what the sender seals). */
2747
+ var wireMentions = (mentions) => mentions.map(({ k, o, l }) => ({
2748
+ k,
2749
+ o,
2750
+ l
2751
+ }));
2752
+ // ../core/src/groupEdits.ts
2753
+ /**
2754
+ * Editing a sent text in a group (WISP 902 § Edits, both profiles). As in a 1:1 chat (WISP 401 § Edits), the author says
2755
+ * the whole new text of one of its own messages with an edit number of its own per message, and the highest number
2756
+ * wins whatever order edits arrive in. A group has no receipts: the author says an edit to every member it can, and
2757
+ * again later (a private group: when an edge opens; a community: its members catch up from each other).
2758
+ *
2759
+ * - A private group (`group-mesh/1`) sends a `group-edit` frame of its own over each edge, sealed under the key of the
2760
+ * epoch the message was sent in and signed by its author (`GroupSession.sendEdit`).
2761
+ * - A community (`group-community/1`) sends an application frame through the group, sealed and signed like any payload,
2762
+ * so every hub carries it and a member who was away gets it with the catch-up:
2763
+ *
2764
+ * { "x": { "t": "edit", "id": <message id>, "v": 3, "ts": 1790000000000, "text": "Done: 12 of 12", "m"?: [mentions], "sc"?: {card} } }
2765
+ *
2766
+ * `sc` is the status card of this version (WISP 405 · Status Cards); an edit with one may be numbered up to
2767
+ * `STATUS_CARD_LIMITS.edits`, one without only up to `MAX_EDITS_PER_MESSAGE`.
2768
+ *
2769
+ * A removal (WISP 400 § Delete for everyone) is an edit with `rm: true` and a fallback text, nothing else beside it,
2770
+ * numbered up to `MAX_REMOVAL_NUMBER`: in a mesh group's box as `{ "text", "rm": true }`, in a community's frame beside
2771
+ * `text`. A `rm` other than `true` is no edit.
2772
+ *
2773
+ * Older apps drop both: a mesh session ignores a `t` it does not know, a community app the `x` frames it does not know.
2774
+ */
2775
+ var GROUP_EDIT_FRAME = "group-edit";
2776
+ var COMMUNITY_EDIT_FRAME = "edit";
2777
+ /** The text bound of a group edit, as a message's: 16 KiB of UTF-8. */
2778
+ var GROUP_EDIT_TEXT_BYTES = 16384;
2779
+ var MESH_ID = /^([a-km-uw-z13-9]{52}):(\d{1,9}):(\d{1,9})$/;
2780
+ var COMMUNITY_ID = /^([a-km-uw-z13-9]{52}):(\d{1,9}):([0-9a-f]{16}):(\d{1,9})$/;
2781
+ /** A private group's message id (`<sender>:<epoch>:<seq>`), split; null when it is not one. */
2782
+ function meshMessageRef(id) {
2783
+ const match = MESH_ID.exec(id);
2784
+ if (!match || !MEMBER_KEY.test(match[1])) return null;
2785
+ return {
2786
+ s: match[1],
2787
+ e: Number(match[2]),
2788
+ n: Number(match[3])
2789
+ };
2790
+ }
2791
+ /** Whose message a community's id names (`<sender>:<epoch>:<commit>:<seq>`); null when it is not one. */
2792
+ function communityMessageAuthor(id) {
2793
+ const match = COMMUNITY_ID.exec(id);
2794
+ return match && MEMBER_KEY.test(match[1]) ? match[1] : null;
2795
+ }
2796
+ /** A text an edit may carry: trimmed, not empty, within the bound. */
2797
+ function validEditText(text) {
2798
+ return typeof text === "string" && !!text && text === text.trim() && utf8Encode(text).length <= 16384;
2799
+ }
2800
+ /** The `x` frame a community edit travels as. */
2801
+ function communityEditFrame(edit) {
2802
+ if (edit.rm) return {
2803
+ t: COMMUNITY_EDIT_FRAME,
2804
+ id: edit.id,
2805
+ v: edit.e,
2806
+ ts: edit.ts,
2807
+ text: edit.m,
2808
+ rm: true
2809
+ };
2810
+ return {
2811
+ t: COMMUNITY_EDIT_FRAME,
2812
+ id: edit.id,
2813
+ v: edit.e,
2814
+ ts: edit.ts,
2815
+ text: edit.m,
2816
+ ...edit.k?.length ? { m: edit.k } : {},
2817
+ ...edit.sc ? { sc: edit.sc } : {}
2818
+ };
2819
+ }
2820
+ /**
2821
+ * The edit a community `x` frame says, from `sender` (whom the group authenticated it as), or null when it is not a
2822
+ * valid edit of one of the sender's own messages. Mentions that do not hold are left out, never the edit; a community
2823
+ * names no one as everyone.
2824
+ */
2825
+ function parseCommunityEdit(frame, sender) {
2826
+ if (frame?.t !== "edit") return null;
2827
+ const { id, v, ts, text, rm } = frame;
2828
+ if (rm !== void 0 && rm !== true) return null;
2829
+ if (typeof id !== "string" || communityMessageAuthor(id) !== sender || typeof v !== "number" || !(rm ? validRemovalNumber(v) : cardEditNumber(v))) return null;
2830
+ if (typeof ts !== "number" || !Number.isSafeInteger(ts) || ts <= 0 || !validEditText(text)) return null;
2831
+ if (rm) return {
2832
+ id,
2833
+ e: v,
2834
+ ts,
2835
+ m: text,
2836
+ rm
2837
+ };
2838
+ const sc = frame.sc === void 0 ? void 0 : readStatusCard(frame.sc);
2839
+ if (!validEditNumber(v) && !sc) return null;
2840
+ const k = validMentions(frame.m, text, false);
2841
+ return {
2842
+ id,
2843
+ e: v,
2844
+ ts,
2845
+ m: text,
2846
+ ...k.length ? { k } : {},
2847
+ ...sc ? { sc } : {}
2848
+ };
2849
+ }
2850
+ /**
2851
+ * The mentions of an edited text: the places the message named that are still there, found by their words (the text
2852
+ * around them may have changed, or their order), and those `added` while editing. Where two overlap, `added` wins.
2853
+ */
2854
+ function carryMentions(before, after, added, everyone) {
2855
+ const was = Array.from(before.text), now = Array.from(after);
2856
+ const overlaps = (a, b) => a.o < b.o + b.l && b.o < a.o + a.l;
2857
+ const carried = [];
2858
+ for (const m of [...before.mentions ?? []].sort((a, b) => a.o - b.o)) {
2859
+ const words = was.slice(m.o, m.o + m.l);
2860
+ for (let at = indexOf(now, words, 0); at >= 0; at = indexOf(now, words, at + 1)) {
2861
+ const place = {
2862
+ k: m.k,
2863
+ o: at,
2864
+ l: m.l
2865
+ };
2866
+ if (carried.some((c) => overlaps(c, place))) continue;
2867
+ carried.push(place);
2868
+ break;
2869
+ }
2870
+ }
2871
+ const fresh = validMentions(added.map(({ k, o, l }) => ({
2872
+ k,
2873
+ o,
2874
+ l
2875
+ })), after, everyone);
2876
+ return validMentions([...fresh, ...carried.filter((m) => !fresh.some((a) => overlaps(a, m)))].sort((a, b) => a.o - b.o).slice(0, MENTION_LIMITS.count), after, everyone);
2877
+ }
2878
+ function indexOf(points, words, from) {
2879
+ if (!words.length) return -1;
2880
+ outer: for (let i = from; i + words.length <= points.length; i++) {
2881
+ for (let j = 0; j < words.length; j++) if (points[i + j] !== words[j]) continue outer;
2882
+ return i;
2883
+ }
2884
+ return -1;
2885
+ }
2886
+ // ../core/src/groupEntry.ts
2887
+ var PREFIX$1 = "group1";
2888
+ /** A knock older than this is not answered: the joiner republishes while it waits. */
2889
+ var KNOCK_TTL_MS = 18e4;
2890
+ var KNOCK_LABEL = "_knock";
2891
+ var NONCE_LENGTH = 24;
2892
+ var info = (label) => utf8Encode(`ghostly-group-entry/1 ${label}`);
2893
+ /** `group1/<group id>/<entry key>` */
2894
+ function encodeGroupEntryLink(link) {
2895
+ return `${PREFIX$1}/${link.g}/${link.host}`;
2896
+ }
2897
+ /**
2898
+ * A pasted link, a `/join/…` path or the bare code; null when it is none of them. Copied with the words around it
2899
+ * ("Join our group: <https://…/join/group1/…>."), it is read as the token in it (`unwrapPasted`).
2900
+ */
2901
+ function decodeGroupEntryLink(input) {
2902
+ return readGroupEntryLink(input) ?? readGroupEntryLink(unwrapPasted(input));
2903
+ }
2904
+ function readGroupEntryLink(input) {
2905
+ const parts = input.trim().replace(/^.*#/, "").replace(/^.*?\/join\//, "").replace(/^\/+/, "").split("/");
2906
+ if (parts.length !== 3 || parts[0] !== PREFIX$1) return null;
2907
+ const [, g, host] = parts;
2908
+ if (!GROUP_ID.test(g) || !MEMBER_KEY.test(host)) return null;
2909
+ try {
2910
+ publicKeyFromZ32(host);
2911
+ } catch {
2912
+ return null;
2913
+ }
2914
+ return {
2915
+ g,
2916
+ host
2917
+ };
2918
+ }
2919
+ function knockMaterial(link, label) {
2920
+ return hkdf(sha256, publicKeyFromZ32(link.host), utf8Encode(link.g), info(label), 32);
2921
+ }
2922
+ /** The Pkarr identity every holder of the link can publish knocks under. */
2923
+ function knockIdentity(link) {
2924
+ return identityFromSeed(knockMaterial(link, "knock seed"));
2925
+ }
2926
+ /**
2927
+ * The knocks under the knock identity, sealed with a key from the link: a
2928
+ * relay sees an opaque value on a key it cannot tie to the group.
2929
+ */
2930
+ function knockRecords(link, knocks) {
2931
+ const nonce = randomBytes(NONCE_LENGTH);
2932
+ const body = utf8Encode(JSON.stringify(knocks.slice(-6).map((k) => [k.key, k.ts])));
2933
+ const box = xchacha20poly1305(knockMaterial(link, "knock key"), nonce, utf8Encode(link.g)).encrypt(body);
2934
+ return [{
2935
+ label: KNOCK_LABEL,
2936
+ value: toBase64Url(concatBytes(nonce, box))
2937
+ }];
2938
+ }
2939
+ /** Knocks that open with the link's key and are well formed; anything else is nobody. */
2940
+ function readKnocks(link, records) {
2941
+ const value = records.find((r) => r.label === KNOCK_LABEL)?.value;
2942
+ if (!value || value.length > 900) return [];
2943
+ try {
2944
+ const bytes = fromBase64Url(value);
2945
+ const body = xchacha20poly1305(knockMaterial(link, "knock key"), bytes.slice(0, NONCE_LENGTH), utf8Encode(link.g)).decrypt(bytes.slice(NONCE_LENGTH));
2946
+ const parsed = JSON.parse(utf8Decode(body));
2947
+ if (!Array.isArray(parsed)) return [];
2948
+ return parsed.slice(0, 6).flatMap((entry) => Array.isArray(entry) && typeof entry[0] === "string" && MEMBER_KEY.test(entry[0]) && Number.isSafeInteger(entry[1]) ? [{
2949
+ key: entry[0],
2950
+ ts: entry[1]
2951
+ }] : []);
2952
+ } catch {
2953
+ return [];
2954
+ }
2955
+ }
2956
+ /** The knocks to publish: mine refreshed, others' still fresh, newest last, at most `MAX_KNOCKS`. */
2957
+ function mergeKnocks(existing, mine, now = Date.now()) {
2958
+ return [...existing.filter((k) => k.key !== mine.key && now - k.ts < 18e4 && k.ts <= now + 6e4).sort((a, b) => a.ts - b.ts).slice(-5), mine];
2959
+ }
2960
+ /**
2961
+ * The entry session between the admin's entry key and a joiner's member key:
2962
+ * the same derivation as a group edge, under a salt of its own, so it can
2963
+ * never be confused with an edge of the same group.
2964
+ */
2965
+ function entryParams(link, mySeed, myZ32, peerZ32) {
2966
+ return edgeParams(`entry/${link.g}`, mySeed, myZ32, peerZ32);
2967
+ }
2968
+ // ../browser/src/engine/paymentAdapters/away.ts
13
2969
  var away = /* @__PURE__ */ new Map();
14
2970
  /** The wallets away from this device, by wallet id, with the name of their home device ("" when it has none here). */
15
2971
  function setAwayWallets(next) {
@@ -47,8 +3003,7 @@ function refuseAway(id, wallet) {
47
3003
  const device = awayFrom(id);
48
3004
  if (device !== void 0) throw new WalletAwayError(wallet, device);
49
3005
  }
50
- //#endregion
51
- //#region ../browser/src/engine/paymentAdapters/modeGate.ts
3006
+ // ../browser/src/engine/paymentAdapters/modeGate.ts
52
3007
  /** A wallet of the mode being left stopped opening: the switch goes ahead without waiting for its network. */
53
3008
  var ModeChanged = class extends Error {
54
3009
  constructor() {
@@ -133,8 +3088,7 @@ var ModeGate = class {
133
3088
  });
134
3089
  }
135
3090
  };
136
- //#endregion
137
- //#region ../browser/src/shared/ice.ts
3091
+ // ../browser/src/shared/ice.ts
138
3092
  /**
139
3093
  * What is wrong with a TURN/STUN server, or null. Browsers refuse to create any WebRTC connection when
140
3094
  * one server in the list is malformed, so a bad entry here would silently cut off calls and files.
@@ -170,8 +3124,7 @@ function iceServerSetting(server) {
170
3124
  urls: urls.join(", ")
171
3125
  };
172
3126
  }
173
- //#endregion
174
- //#region ../browser/src/engine/paymentAdapters/providers/breezDatabases.ts
3127
+ // ../browser/src/engine/paymentAdapters/providers/breezDatabases.ts
175
3128
  var netOf = (network) => network === "bitcoin" || network === "mainnet" ? "mainnet" : "regtest";
176
3129
  var hex$2 = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
177
3130
  var digest = (text) => hex$2(sha256(new TextEncoder().encode(text))).slice(0, 16);
@@ -315,13 +3268,12 @@ async function dropBreezDatabase(name, options = {}) {
315
3268
  store.delete(name);
316
3269
  }).catch(() => {});
317
3270
  }
318
- //#endregion
319
- //#region ../browser/src/engine/paymentAdapters/providers/breezSdk.ts
3271
+ // ../browser/src/engine/paymentAdapters/providers/breezSdk.ts
320
3272
  var loading$1;
321
3273
  /** Loads the WebAssembly once, on first use: profiles that never pick Breez never fetch its 12.8 MB. */
322
3274
  function loadBreezSdk() {
323
3275
  return loading$1 ??= (async () => {
324
- const breez = await import("./web-DwgdhfcY.js");
3276
+ const breez = await import("./web-68CYFCl9.js");
325
3277
  await breez.default();
326
3278
  return { async connect({ network, mnemonic, apiKey, storage }) {
327
3279
  const config = breez.defaultConfig(network);
@@ -340,20 +3292,19 @@ function loadBreezSdk() {
340
3292
  throw error;
341
3293
  });
342
3294
  }
343
- var hex$1 = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
344
3295
  var breezNetwork = (network) => network === "bitcoin" ? "mainnet" : "regtest";
345
3296
  var DISCONNECT_MS = 1e4;
346
3297
  /** One SDK instance per wallet storage: two over one database would each think the leaves are theirs. */
347
3298
  var open = /* @__PURE__ */ new Map();
348
3299
  /**
349
3300
  * Opens the Breez wallet of this seed on this network, or shares the one already open (the Spark rail and the
350
- * Breez Lightning source of the same seed are one wallet). `release` gives this user's share back; the last one
351
- * disconnects the SDK. `storage`: the database it opened, which `forgetBreez` deletes when the wallet is removed.
3301
+ * Breez Lightning source of the same seed are one wallet, even when they carry different API keys: the instance
3302
+ * open keeps the key it opened with). `release` gives this user's share back; the last one disconnects the SDK.
3303
+ * `storage`: the database it opened, which `forgetBreez` deletes when the wallet is removed.
352
3304
  */
353
3305
  async function openBreez(params, sdk = loadBreezSdk, storage = breezDatabase) {
354
3306
  const name = await storage(params.network, params.mnemonic);
355
- const key = `${name}|${params.apiKey ? hex$1(sha256(new TextEncoder().encode(params.apiKey))).slice(0, 8) : ""}`;
356
- let entry = open.get(key);
3307
+ let entry = open.get(name);
357
3308
  if (!entry) {
358
3309
  const wallet = sdk().then((module) => module.connect({
359
3310
  network: breezNetwork(params.network),
@@ -365,9 +3316,9 @@ async function openBreez(params, sdk = loadBreezSdk, storage = breezDatabase) {
365
3316
  wallet,
366
3317
  refs: 0
367
3318
  };
368
- open.set(key, entry);
3319
+ open.set(name, entry);
369
3320
  wallet.catch(() => {
370
- if (open.get(key) === entry) open.delete(key);
3321
+ if (open.get(name) === entry) open.delete(name);
371
3322
  });
372
3323
  }
373
3324
  entry.refs++;
@@ -387,13 +3338,13 @@ async function openBreez(params, sdk = loadBreezSdk, storage = breezDatabase) {
387
3338
  if (released) return;
388
3339
  released = true;
389
3340
  if (--held.refs > 0) return;
390
- if (open.get(key) === held) open.delete(key);
3341
+ if (open.get(name) === held) open.delete(name);
391
3342
  await Promise.race([wallet.disconnect(), new Promise((resolve) => setTimeout(resolve, DISCONNECT_MS))]);
392
3343
  }
393
3344
  };
394
3345
  }
395
3346
  /** Whether a wallet of this storage is open here (the Spark rail and a Breez card of one seed share it). */
396
- var breezOpen = (storage) => [...open.keys()].some((key) => key.startsWith(`${storage}|`));
3347
+ var breezOpen = (storage) => open.has(storage);
397
3348
  /**
398
3349
  * A wallet was removed: its Breez databases go, unless another user in this profile still has them open (a Breez
399
3350
  * Lightning card on the Spark wallet's own phrase). That one deletes them when it is removed in turn.
@@ -401,8 +3352,7 @@ var breezOpen = (storage) => [...open.keys()].some((key) => key.startsWith(`${st
401
3352
  async function forgetBreez(storage) {
402
3353
  if (!breezOpen(storage)) await dropBreezDatabase(storage);
403
3354
  }
404
- //#endregion
405
- //#region ../browser/src/engine/askBackoff.ts
3355
+ // ../browser/src/engine/askBackoff.ts
406
3356
  /**
407
3357
  * A growing wait with a cap, for whatever a wallet asks about again until it gets an answer: a Cashu melt or swap whose
408
3358
  * mint does not answer or keeps it pending, restored ecash at a mint that cannot say what is spent, a Lightning card's
@@ -452,8 +3402,7 @@ var AskBackoff = class {
452
3402
  for (const key of this.paces.keys()) if (!keys.has(key)) this.paces.delete(key);
453
3403
  }
454
3404
  };
455
- //#endregion
456
- //#region ../browser/src/engine/paymentAdapters/providers/cashuMint.ts
3405
+ // ../browser/src/engine/paymentAdapters/providers/cashuMint.ts
457
3406
  var CASHU_MINT_SOURCE = "cashu-mint";
458
3407
  var parseRef = (ref) => {
459
3408
  const parsed = JSON.parse(ref ?? "null");
@@ -597,8 +3546,7 @@ var cashuMint = {
597
3546
  return new CashuMintLightning(host.cashu, host.mode, host.cashuBalance);
598
3547
  }
599
3548
  };
600
- //#endregion
601
- //#region ../browser/src/engine/paymentAdapters/providers/sources.ts
3549
+ // ../browser/src/engine/paymentAdapters/providers/sources.ts
602
3550
  /** Where a source is stored: the mode's one, or one of several (`key`). */
603
3551
  var sourceKey = (kind, mode, key) => `${kind}Source-${mode}${key ? `-${key}` : ""}`;
604
3552
  var seenKey = (kind, mode, key) => `${kind}SourceSeen-${mode}${key ? `-${key}` : ""}`;
@@ -734,11 +3682,14 @@ var ProviderSources = class {
734
3682
  await this.load(this.mode);
735
3683
  this.view = this.idle();
736
3684
  }
737
- /** One saved secret of the source (a handoff asks whether an LND card pins its certificate, and a Breez phrase), or undefined. */
3685
+ /**
3686
+ * One saved secret of the source (a handoff asks whether an LND card pins its certificate, and a Breez phrase), or
3687
+ * undefined. A connected source reads the secrets it connected with, as `holds` does; one that is not unseals them.
3688
+ */
738
3689
  async secret(name) {
739
3690
  const stored = this.stored;
740
3691
  if (!stored?.secrets) return void 0;
741
- const value = JSON.parse(await unsealSeed(stored.secrets, stored.deviceKey ?? ""))[name];
3692
+ const value = (this.provider ? this.secrets : JSON.parse(await unsealSeed(stored.secrets, stored.deviceKey ?? "")))[name];
742
3693
  return typeof value === "string" && value ? value : void 0;
743
3694
  }
744
3695
  /** The list of providers changed (a plugin registered): the picker is told, nothing reconnects. */
@@ -934,12 +3885,14 @@ var ProviderSources = class {
934
3885
  /**
935
3886
  * Whether the saved source is this provider reaching the same wallet (the same wallet added twice): the provider's
936
3887
  * `wallet` says which one (an NWC URI spelled another way, or another app connection to it, is the same), else these
937
- * very settings. Its secrets are unsealed here to compare, and never leave.
3888
+ * very settings. A connected source compares the secrets it connected with; one that is not unseals them here (a
3889
+ * 600,000-iteration key: once per card of the kind, each new card took 320 ms more). They never leave.
938
3890
  */
939
3891
  async holds(providerId, settings) {
940
3892
  const stored = this.stored;
941
3893
  if (!stored || stored.providerId !== providerId) return false;
942
- const unseal = async () => stored.secrets ? JSON.parse(await unsealSeed(stored.secrets, stored.deviceKey ?? "")) : {};
3894
+ const connected = this.provider ? this.secrets : void 0;
3895
+ const unseal = async () => connected ?? (stored.secrets ? JSON.parse(await unsealSeed(stored.secrets, stored.deviceKey ?? "")) : {});
943
3896
  const wallet = this.find(providerId)?.wallet;
944
3897
  if (wallet) {
945
3898
  const secrets = await unseal();
@@ -1218,8 +4171,7 @@ var ProviderSources = class {
1218
4171
  await this.serial(() => this.disconnect());
1219
4172
  }
1220
4173
  };
1221
- //#endregion
1222
- //#region ../browser/src/engine/invoicePace.ts
4174
+ // ../browser/src/engine/invoicePace.ts
1223
4175
  /**
1224
4176
  * How often an open invoice of ours is asked about, at its Cashu mint or at a Lightning card's source (agents#2447).
1225
4177
  * Someone pays an invoice soon after it is shown, or not at all: it is asked about every few seconds at first, then
@@ -1264,8 +4216,7 @@ function nextInvoiceAsk(invoice, asked, now) {
1264
4216
  const age = now - invoice.createdAt;
1265
4217
  return asked + (fast || age < fastForMs ? fastMs : age < midForMs ? midMs : slowMs);
1266
4218
  }
1267
- //#endregion
1268
- //#region ../browser/src/engine/paymentAdapters/providers/lightningService.ts
4219
+ // ../browser/src/engine/paymentAdapters/providers/lightningService.ts
1269
4220
  var PREFIX = "lightningOp-";
1270
4221
  var opKey = (direction, hash) => `${PREFIX}${direction}-${hash}`;
1271
4222
  var RANGE = () => IDBKeyRange.bound(PREFIX, `${PREFIX}\uffff`);
@@ -1903,13 +4854,11 @@ var LightningService = class {
1903
4854
  function shownExpiredAt(op) {
1904
4855
  return op.direction === "in" && op.state === "open" && !op.selfSettled && op.expiresAt > 0 ? op.expiresAt + INVOICE_PACE.expiryGraceMs + 1 : Infinity;
1905
4856
  }
1906
- //#endregion
1907
- //#region ../browser/src/engine/paymentAdapters/providers/recoveryPhrase.ts
4857
+ // ../browser/src/engine/paymentAdapters/providers/recoveryPhrase.ts
1908
4858
  /** A phrase as BIP 39 wants it, however it was typed or pasted. */
1909
4859
  var normalizePhrase = (text = "") => text.trim().toLowerCase().split(/\s+/).join(" ");
1910
4860
  var isRecoveryPhrase = (text) => validateMnemonic(normalizePhrase(text), wordlist);
1911
- //#endregion
1912
- //#region ../browser/src/engine/paymentAdapters/providers/breez.ts
4861
+ // ../browser/src/engine/paymentAdapters/providers/breez.ts
1913
4862
  var BREEZ_SOURCE = "breez";
1914
4863
  /**
1915
4864
  * Where the Breez source is offered: Mainnet ("bitcoin", with the person's Breez API key, which the form requires
@@ -1932,7 +4881,7 @@ var PAGE = 100;
1932
4881
  var PAGES = 10;
1933
4882
  /** Without any record of a payment, it is called failed only this long after its invoice expired. */
1934
4883
  var LOST_AFTER_MS = 36e5;
1935
- var hex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
4884
+ var hex$1 = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1936
4885
  var sats = (value) => {
1937
4886
  const n = Number(value);
1938
4887
  if (!Number.isSafeInteger(n) || n < 0) throw new Error("Breez returned an invalid amount");
@@ -1947,7 +4896,7 @@ function idempotencyKey(paymentHash, attempt) {
1947
4896
  const b = sha256(new TextEncoder().encode(`ghostly-breez-pay:${paymentHash}:${attempt}`)).slice(0, 16);
1948
4897
  b[6] = b[6] & 15 | 64;
1949
4898
  b[8] = b[8] & 63 | 128;
1950
- const h = hex(b);
4899
+ const h = hex$1(b);
1951
4900
  return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
1952
4901
  }
1953
4902
  /** The payment hash a Breez payment is about, when it is one (Lightning, or a Spark HTLC). */
@@ -2180,8 +5129,7 @@ var breezDescriptor = (sdk = loadBreezSdk) => ({
2180
5129
  }
2181
5130
  });
2182
5131
  var breez = breezDescriptor();
2183
- //#endregion
2184
- //#region ../browser/src/engine/paymentAdapters/providers/lightningCards.ts
5132
+ // ../browser/src/engine/paymentAdapters/providers/lightningCards.ts
2185
5133
  /** The card of Lightning through the Cashu mints: at most one per network, shown while the network has mints. */
2186
5134
  var CASHU_CARD = "cashu";
2187
5135
  /** The card made from the one source a network had before it could have several. */
@@ -2332,10 +5280,13 @@ var LightningCards = class {
2332
5280
  shown() {
2333
5281
  return this.stored.cards.filter((c) => c.id !== "cashu" || this.options.hasMints());
2334
5282
  }
2335
- /** The default for receiving, or the first card shown when that one is not (the Cashu card of a network with no mints). */
5283
+ /**
5284
+ * The default for receiving, or the first card shown here when that one is not (the Cashu card of a network with no
5285
+ * mints): a card at home on another device cannot receive here.
5286
+ */
2336
5287
  get receivingId() {
2337
5288
  const shown = this.shown();
2338
- return shown.find((c) => c.id === this.stored.receive)?.id ?? shown[0]?.id ?? this.stored.receive;
5289
+ return shown.find((c) => c.id === this.stored.receive)?.id ?? shown.find((c) => this.isHere(c.id))?.id ?? shown[0]?.id ?? this.stored.receive;
2339
5290
  }
2340
5291
  get receiving() {
2341
5292
  return this.services.get(this.receivingId) ?? [...this.services.values()][0];
@@ -2463,7 +5414,8 @@ var LightningCards = class {
2463
5414
  }
2464
5415
  /**
2465
5416
  * Removes a card: its source and sealed secrets go (refused while a payment through it has not ended). The default
2466
- * for receiving moves to the first card of the person's own left, else the mints' card. A network left with no card gets the Cashu card back, as before cards.
5417
+ * for receiving moves to the first card of the person's own left on this device (one at home on another device
5418
+ * cannot receive here), else the mints' card. A network left with no card gets the Cashu card back, as before cards.
2467
5419
  */
2468
5420
  remove(id) {
2469
5421
  return this.serial(async () => {
@@ -2482,7 +5434,7 @@ var LightningCards = class {
2482
5434
  await added.start();
2483
5435
  }
2484
5436
  const shown = cards.filter((c) => c.id !== "cashu" || this.options.hasMints());
2485
- const next = shown.find((c) => c.id !== "cashu") ?? shown[0] ?? cards[0];
5437
+ const next = shown.find((c) => c.id !== "cashu" && this.isHere(c.id)) ?? shown.find((c) => c.id === "cashu") ?? shown[0] ?? cards[0];
2486
5438
  const receive = this.stored.receive === id || !cards.some((c) => c.id === this.stored.receive) ? next.id : this.stored.receive;
2487
5439
  await this.save({
2488
5440
  cards,
@@ -2572,7 +5524,10 @@ var LightningCards = class {
2572
5524
  }
2573
5525
  /** The cards whose source is opened on this device: not one at home on another device (WISP 06 § Wallets that stay home). */
2574
5526
  here() {
2575
- return [...this.services].filter(([id]) => awayFrom(`lightning:${this.network}:${id}`) === void 0).map(([, s]) => s);
5527
+ return [...this.services].filter(([id]) => this.isHere(id)).map(([, s]) => s);
5528
+ }
5529
+ isHere(id) {
5530
+ return awayFrom(`lightning:${this.network}:${id}`) === void 0;
2576
5531
  }
2577
5532
  async reconcile() {
2578
5533
  await Promise.all(this.here().map((s) => s.reconcile()));
@@ -2611,8 +5566,7 @@ var LightningCards = class {
2611
5566
  return this.stopped;
2612
5567
  }
2613
5568
  };
2614
- //#endregion
2615
- //#region ../browser/src/proofs/load.ts
5569
+ // ../browser/src/proofs/load.ts
2616
5570
  /**
2617
5571
  * The identity proof providers, loaded on first need and not with the app: they and their libraries (OpenPGP, the
2618
5572
  * Bitcoin signer, the DID, AT Protocol and OpenID Connect checks) are a large part of the code, and the first screen
@@ -2622,7 +5576,7 @@ var registry;
2622
5576
  var loading;
2623
5577
  var listeners = /* @__PURE__ */ new Set();
2624
5578
  function loadIdentityProviders() {
2625
- return loading ??= import("./registry-zUZBSHYv.js").then((m) => {
5579
+ return loading ??= import("./registry-B15Yg_1C.js").then((m) => {
2626
5580
  registry = m;
2627
5581
  for (const listener of listeners) listener();
2628
5582
  return m;
@@ -2633,8 +5587,7 @@ function loadIdentityProviders() {
2633
5587
  }
2634
5588
  /** The providers (built in, from plugins, the test ones when asked for), once loaded; none before. */
2635
5589
  var loadedIdentityProviders = () => registry?.identityProviders() ?? [];
2636
- //#endregion
2637
- //#region ../browser/src/engine/identities.ts
5590
+ // ../browser/src/engine/identities.ts
2638
5591
  /** Where a proof key's seed belongs: by proof id, so it still opens once the proof moved to the revocations. */
2639
5592
  var proofKeyAt = (id) => ({
2640
5593
  store: STORES.settings,
@@ -2649,6 +5602,8 @@ var REVOCATIONS_CHECKED_AT = "identityRevocationsCheckedAt";
2649
5602
  var REVOCATIONS_ROUND = "identityRevocationsRound";
2650
5603
  /** Relays and the DHT forget a record within hours: republish revocations this often while the app runs. */
2651
5604
  var REPUBLISH_MS = 36e5;
5605
+ /** The longest a timer waits; a redraw further off waits again from there. */
5606
+ var MAX_TIMER_MS = 2 ** 31 - 1;
2652
5607
  /**
2653
5608
  * A revocation is kept (with its sealed seed) this long past its expiry by this device's clock, which may be the one that
2654
5609
  * is wrong: the contacts decide expiry by theirs. Only a clock ahead by more than the longest a proof may last (400 days)
@@ -2768,6 +5723,8 @@ var IdentityProofs = class {
2768
5723
  recheckBackoff = /* @__PURE__ */ new Map();
2769
5724
  /** When the automatic re-check asked each provider with a `recheck.perHour` (ms), this last hour, by provider id. */
2770
5725
  recheckedAt = /* @__PURE__ */ new Map();
5726
+ /** Each chat's next change of its view by the time alone (s), and the timer that has it built again then: `linkView`. */
5727
+ redrawTimers = /* @__PURE__ */ new Map();
2771
5728
  fetch;
2772
5729
  constructor(host, providers = loadedIdentityProviders) {
2773
5730
  this.host = host;
@@ -2835,6 +5792,8 @@ var IdentityProofs = class {
2835
5792
  this.stops++;
2836
5793
  for (const t of this.timers) clearTimeout(t);
2837
5794
  this.timers = [];
5795
+ for (const { timer } of this.redrawTimers.values()) clearTimeout(timer);
5796
+ this.redrawTimers.clear();
2838
5797
  this.lookupTimer = void 0;
2839
5798
  this.saveRound();
2840
5799
  this.wakeLookup?.();
@@ -2892,7 +5851,7 @@ var IdentityProofs = class {
2892
5851
  let refused;
2893
5852
  let fetch = this.fetch;
2894
5853
  if (this.host.relayOnly?.()) {
2895
- const { fixedIdentityHosts } = await import("./fixedHosts-CbgqrIKs.js");
5854
+ const { fixedIdentityHosts } = await import("./fixedHosts-CPSsGOI2.js");
2896
5855
  const fixed = fixedIdentityHosts();
2897
5856
  fetch = async (url, options) => {
2898
5857
  const host = new URL(url).host;
@@ -3406,19 +6365,42 @@ var IdentityProofs = class {
3406
6365
  this.exchanges.get(linkId)?.stop();
3407
6366
  this.exchanges.delete(linkId);
3408
6367
  this.errors.delete(linkId);
6368
+ this.redrawAt(linkId, void 0);
6369
+ }
6370
+ /** Has the chat's view built again at `at` (s): nothing stored changes when a proof expires, so nothing else would. */
6371
+ redrawAt(linkId, at) {
6372
+ const armed = this.redrawTimers.get(linkId);
6373
+ if (armed?.at === at) return;
6374
+ if (armed) clearTimeout(armed.timer);
6375
+ this.redrawTimers.delete(linkId);
6376
+ if (at === void 0 || !this.host.redraw) return;
6377
+ const timer = setTimeout(() => {
6378
+ this.redrawTimers.delete(linkId);
6379
+ if (at * 1e3 > Date.now()) this.redrawAt(linkId, at);
6380
+ else this.host.redraw?.(linkId);
6381
+ }, Math.min(at * 1e3 - Date.now(), MAX_TIMER_MS));
6382
+ this.redrawTimers.set(linkId, {
6383
+ at,
6384
+ timer
6385
+ });
3409
6386
  }
3410
6387
  linkView(linkId, supported) {
3411
6388
  const ledger = this.host.ledger(linkId);
3412
6389
  if (!ledger) return void 0;
3413
6390
  const { mine, theirs } = this.host.keys(linkId);
3414
6391
  const t = now();
3415
- return {
6392
+ let next = Infinity;
6393
+ const view = {
3416
6394
  support: supported,
3417
6395
  contactProviders: supported ? this.exchanges.get(linkId)?.contactProviders?.slice() : void 0,
3418
6396
  shared: ledger.shared.map(ownRefusal),
3419
6397
  received: ledger.received.map((r) => {
3420
6398
  const provider = this.providers().find((p) => p.id === r.binding.provider);
3421
6399
  const status = receivedIdentityStatus(r, theirs, mine, t);
6400
+ const ends = Math.min(r.binding.expiresAt, r.verified.expiresAt ?? Infinity);
6401
+ if ((status === "verified" || status === "unconfirmed") && ends > t) next = Math.min(next, ends);
6402
+ const due = provider?.recheck && r.checkedAt <= t ? r.checkedAt + provider.recheck.afterSeconds : Infinity;
6403
+ if (due > t) next = Math.min(next, due);
3422
6404
  const publicProfile = status === "verified" ? this.host.publicProfile?.(r.binding.provider, r.verified.subject) : void 0;
3423
6405
  return {
3424
6406
  id: r.id,
@@ -3437,10 +6419,11 @@ var IdentityProofs = class {
3437
6419
  }),
3438
6420
  error: this.errors.get(linkId)
3439
6421
  };
6422
+ this.redrawAt(linkId, next === Infinity ? void 0 : next);
6423
+ return view;
3440
6424
  }
3441
6425
  };
3442
- //#endregion
3443
- //#region ../browser/src/shared/storedFiles.ts
6426
+ // ../browser/src/shared/storedFiles.ts
3444
6427
  /** The bytes a file holds: its metadata says, and a file stored before that says it with its Blob. */
3445
6428
  function storedSize(file) {
3446
6429
  return file.metadata?.size ?? file.blob?.size ?? 0;
@@ -3552,8 +6535,7 @@ var FileAppender = class {
3552
6535
  this.buffered = 0;
3553
6536
  }
3554
6537
  };
3555
- //#endregion
3556
- //#region ../browser/src/engine/forwards.ts
6538
+ // ../browser/src/engine/forwards.ts
3557
6539
  /**
3558
6540
  * Whether a message can be forwarded, and as what. Payments and payment requests (a bearer token or a request is for
3559
6541
  * the chat it was made in), a group's history lines and its payment notes cannot; neither can a message with nothing
@@ -3728,8 +6710,7 @@ async function copyFile(sourceId, target) {
3728
6710
  throw error;
3729
6711
  }
3730
6712
  }
3731
- //#endregion
3732
- //#region ../browser/src/shared/types.ts
6713
+ // ../browser/src/shared/types.ts
3733
6714
  var WALLET_TYPES = [
3734
6715
  "cashu",
3735
6716
  "lightning",
@@ -3742,8 +6723,7 @@ var WALLET_TYPES = [
3742
6723
  ];
3743
6724
  /** A details record larger than this (as JSON) is trimmed: its oldest sends go first. */
3744
6725
  var MESSAGE_DETAILS_MAX_BYTES = 2048;
3745
- //#endregion
3746
- //#region ../browser/src/engine/paymentAdapters/walletInstances.ts
6726
+ // ../browser/src/engine/paymentAdapters/walletInstances.ts
3747
6727
  var WALLET_NAMES = {
3748
6728
  cashu: "Cashu",
3749
6729
  lightning: "Lightning",
@@ -3865,8 +6845,7 @@ var REAL_MONEY_UNCONFIRMED = engineText("realMoneyUnconfirmed");
3865
6845
  function createFailure(label, error) {
3866
6846
  return `Could not create the ${label} wallet: ${(networkReason(error) ?? (error instanceof Error ? error.message : String(error))).replace(/\.$/, "")}. Nothing was saved; try again.`;
3867
6847
  }
3868
- //#endregion
3869
- //#region ../browser/src/shared/paymentIds.ts
6848
+ // ../browser/src/shared/paymentIds.ts
3870
6849
  /**
3871
6850
  * Payment ids are chosen by whoever sends them, and every member of a group sees the requests the others make to the
3872
6851
  * group. So a contact's request is kept under the id it came with, unless a record of another chat already holds that
@@ -3876,8 +6855,7 @@ function createFailure(label, error) {
3876
6855
  var paymentAlias = (wireId, linkId) => `${wireId}.${linkId}`;
3877
6856
  /** The id a payment record goes by on the wire, which is also the one its chat and its group's notes know it by. */
3878
6857
  var paymentWireId = (key) => key.split(".", 1)[0];
3879
- //#endregion
3880
- //#region ../browser/src/shared/replies.ts
6858
+ // ../browser/src/shared/replies.ts
3881
6859
  /** A paired chat's text (`me_`/`peer_` + its 22-character wire id), or a held file (`peer_` + its 16-character one). */
3882
6860
  var PAIRED_ROW = /^(?:me|peer)_([A-Za-z0-9_-]{22}|[A-Za-z0-9_-]{16})$/;
3883
6861
  var WIRE_ID = /^[A-Za-z0-9_-]{8,64}$/;
@@ -3942,8 +6920,7 @@ function groupReply(reply, myKey) {
3942
6920
  ...reply.b && { button: reply.b }
3943
6921
  };
3944
6922
  }
3945
- //#endregion
3946
- //#region ../browser/src/engine/groupFiles.ts
6923
+ // ../browser/src/engine/groupFiles.ts
3947
6924
  /** A group file's local id: its group's and a random part, never anything a member sends. */
3948
6925
  var groupFileId = (groupId, direction, random = toBase64Url(randomBytes(12))) => `group-${groupId}-${direction}-${random}`;
3949
6926
  /** The group a local file id names, among `groupIds`. */
@@ -5312,8 +8289,7 @@ function messageFile(kept) {
5312
8289
  ...image && { image }
5313
8290
  };
5314
8291
  }
5315
- //#endregion
5316
- //#region ../browser/src/shared/payLinks.ts
8292
+ // ../browser/src/shared/payLinks.ts
5317
8293
  /**
5318
8294
  * The desk's links to members of a community group (WISP 903 · Group Community § Payments): payments with a member
5319
8295
  * go through the group, sealed to them, over `cpay:<group>:<member>`; a request to everyone over `cpay:<group>`.
@@ -5328,8 +8304,7 @@ function parsePayLink(linkId) {
5328
8304
  ...m[2] ? { member: m[2] } : {}
5329
8305
  } : void 0;
5330
8306
  }
5331
- //#endregion
5332
- //#region ../browser/src/shared/groupPayNotes.ts
8307
+ // ../browser/src/shared/groupPayNotes.ts
5333
8308
  /** The id of a group payment note's line in the group's history (WISP 902 § Payments). */
5334
8309
  var groupPayLineId = (noteId) => `gpay:${noteId}`;
5335
8310
  /** The group note a payment of this device is part of: a request's own, or the request a payment answers (by its id on the wire). */
@@ -5368,8 +8343,7 @@ function groupPayTwin(message, payment, noteOf, myKey, memberOf = () => void 0)
5368
8343
  if (note?.kind !== "request" || !payer || !payee || note.to !== payee || note.from !== payer && note.from !== "*") return void 0;
5369
8344
  return note.id;
5370
8345
  }
5371
- //#endregion
5372
- //#region ../browser/src/platform/irohWeb.ts
8346
+ // ../browser/src/platform/irohWeb.ts
5373
8347
  /**
5374
8348
  * Iroh (WISP 102) in a browser: the same QUIC/TLS session and binding as the
5375
8349
  * Desktop's native Iroh, but relay only. A page cannot send UDP, so every
@@ -5430,13 +8404,15 @@ function irohRelayProblem(value) {
5430
8404
  "[::1]"
5431
8405
  ].includes(url.hostname);
5432
8406
  if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) return `Use an https:// relay address: ${value}`;
5433
- if (url.username || url.password || url.search || url.hash || value.length > 256) return `Not a relay address: ${value}`;
8407
+ if (url.username || url.password || url.search || url.hash) return `Not a relay address: ${value}`;
8408
+ const named = new URL(irohRelayUrl(value)).href;
8409
+ if (value.length > 256 || !relayUrl(named)) return relayUrlTooLong(named) ? `Use a shorter relay address: ${value}` : `Not a relay address: ${value}`;
5434
8410
  return null;
5435
8411
  }
5436
8412
  var loaded = null;
5437
8413
  /** Loads the wasm once per page. Tests pass their own `load` (Node reads the file). */
5438
8414
  function loadIrohWasm() {
5439
- loaded ??= import("./ghostly_iroh_web-BzAXJUYH.js").then(async (module) => {
8415
+ loaded ??= import("./ghostly_iroh_web-DIj5xGmR.js").then(async (module) => {
5440
8416
  await module.default();
5441
8417
  return module;
5442
8418
  }).catch((error) => {
@@ -5730,7 +8706,6 @@ async function createIrohWebEndpoint(seedB64, options = {}) {
5730
8706
  serve(node);
5731
8707
  return endpoint;
5732
8708
  }
5733
- //#endregion
5734
- export { lightningPaying as $, paymentNetworksOf as A, removeStored as B, paymentWireId as C, setSingleWriterGate as Ct, createTiming as D, createFailure as E, copyForForward as F, IdentityProofs as G, streamStored as H, forwardError as I, cardsKey as J, CASHU_CARD as K, forwardKind as L, MESSAGE_DETAILS_MAX_BYTES as M, WALLET_TYPES as N, crossNetwork as O, FORWARD_MESSAGE_GONE as P, journaledPayment as Q, FileAppender as R, paymentAlias as S, setAwayWallets as St, assertConfirmedReal as T, waitingGroupFile as U, storedSize as V, IDENTITY_DRAFT_TTL_MS as W, breez as X, BREEZ_SOURCE as Y, normalizePhrase as Z, groupReply as _, WrongNetworkError as _t, groupMemberOfLink as a, cashuMint as at, replyRef as b, refuseAway as bt, groupPayTwin as c, loadBreezSdk as ct, parsePayLink as d, breezDatabasesFor as dt, INVOICE_PACE as et, GroupFileDesk as f, iceServerProblem as ft, storedGroupFiles as g, ModeGate as gt, groupOfFile as h, ModeChanged as ht, onPublicIrohRelay as i, CASHU_MINT_SOURCE as it, walletInstances as j, paymentNetwork as k, groupLinkId as l, openBreez as lt, groupFileText as m, relayOnlyProblem as mt, createIrohWebEndpoint as n, ProviderSources as nt, groupPayLineId as o, AskBackoff as ot, groupFileId as p, iceServerSetting as pt, LightningCards as q, irohRelayProblem as r, sourceKey as rt, groupPayNoteId as s, forgetBreez as st, DEFAULT_IROH_RELAYS as t, nextInvoiceAsk as tt, pairLinkId as u, breezDatabaseInUse as ut, pairedWireReply as v, networkLabel as vt, WALLET_NAMES as w, replyTo as x, requireTurn as xt, receivedPairedReply as y, awayFrom as yt, readStored as z };
8709
+ export { lightningPaying as $, paymentNetworksOf as A, mergeKnocks as At, removeStored as B, validEditText as Bt, paymentWireId as C, setSingleWriterGate as Ct, createTiming as D, entryParams as Dt, createFailure as E, encodeGroupEntryLink as Et, copyForForward as F, carryMentions as Ft, IdentityProofs as G, wireMentions as Gt, streamStored as H, mentionsBytes as Ht, forwardError as I, communityEditFrame as It, cardsKey as J, NO_VIDEO_METADATA as Jt, CASHU_CARD as K, NO_AUDIO_METADATA as Kt, forwardKind as L, communityMessageAuthor as Lt, MESSAGE_DETAILS_MAX_BYTES as M, COMMUNITY_EDIT_FRAME as Mt, WALLET_TYPES as N, GROUP_EDIT_FRAME as Nt, crossNetwork as O, knockIdentity as Ot, FORWARD_MESSAGE_GONE as P, GROUP_EDIT_TEXT_BYTES as Pt, journaledPayment as Q, withoutPictureMetadata as Qt, FileAppender as R, meshMessageRef as Rt, paymentAlias as S, setAwayWallets as St, assertConfirmedReal as T, decodeGroupEntryLink as Tt, waitingGroupFile as U, mentionsMember as Ut, storedSize as V, MENTION_LIMITS as Vt, IDENTITY_DRAFT_TTL_MS as W, validMentions as Wt, breez as X, NO_PICTURE_METADATA as Xt, BREEZ_SOURCE as Y, withoutVideoMetadata as Yt, normalizePhrase as Z, stripPictureMetadata as Zt, groupReply as _, WrongNetworkError as _t, groupMemberOfLink as a, cashuMint as at, replyRef as b, refuseAway as bt, groupPayTwin as c, loadBreezSdk as ct, parsePayLink as d, breezDatabasesFor as dt, INVOICE_PACE as et, GroupFileDesk as f, iceServerProblem as ft, storedGroupFiles as g, ModeGate as gt, groupOfFile as h, ModeChanged as ht, onPublicIrohRelay as i, CASHU_MINT_SOURCE as it, walletInstances as j, readKnocks as jt, paymentNetwork as k, knockRecords as kt, groupLinkId as l, openBreez as lt, groupFileText as m, relayOnlyProblem as mt, createIrohWebEndpoint as n, ProviderSources as nt, groupPayLineId as o, AskBackoff as ot, groupFileId as p, iceServerSetting as pt, LightningCards as q, withoutAudioMetadata as qt, irohRelayProblem as r, sourceKey as rt, groupPayNoteId as s, forgetBreez as st, DEFAULT_IROH_RELAYS as t, nextInvoiceAsk as tt, pairLinkId as u, breezDatabaseInUse as ut, pairedWireReply as v, networkLabel as vt, WALLET_NAMES as w, KNOCK_TTL_MS as wt, replyTo as x, requireTurn as xt, receivedPairedReply as y, awayFrom as yt, readStored as z, parseCommunityEdit as zt };
5735
8710
 
5736
- //# sourceMappingURL=irohWeb-caAj4Dms.js.map
8711
+ //# sourceMappingURL=irohWeb-CLBx5MIv.js.map