matrix-js-sdk 41.8.0 → 41.9.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 (458) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +1 -1
  3. package/lib/@types/AESEncryptedSecretStoragePayload.js +3 -1
  4. package/lib/@types/IIdentityServerProvider.js +3 -1
  5. package/lib/@types/PushRules.js +7 -7
  6. package/lib/@types/PushRules.js.map +1 -1
  7. package/lib/@types/auth.js +4 -4
  8. package/lib/@types/auth.js.map +1 -1
  9. package/lib/@types/beacon.js +2 -2
  10. package/lib/@types/beacon.js.map +1 -1
  11. package/lib/@types/common.js +3 -1
  12. package/lib/@types/crypto.js +3 -1
  13. package/lib/@types/event.js +20 -20
  14. package/lib/@types/event.js.map +1 -1
  15. package/lib/@types/events.js +3 -1
  16. package/lib/@types/extensible_events.js +6 -6
  17. package/lib/@types/extensible_events.js.map +1 -1
  18. package/lib/@types/global.d.js.map +1 -1
  19. package/lib/@types/json.js +3 -1
  20. package/lib/@types/local_notifications.js +3 -1
  21. package/lib/@types/location.js +4 -4
  22. package/lib/@types/location.js.map +1 -1
  23. package/lib/@types/matrix-sdk-crypto-wasm.d.js +3 -1
  24. package/lib/@types/media.js +3 -1
  25. package/lib/@types/membership.js +1 -1
  26. package/lib/@types/membership.js.map +1 -1
  27. package/lib/@types/partials.js +6 -6
  28. package/lib/@types/partials.js.map +1 -1
  29. package/lib/@types/polls.js +5 -5
  30. package/lib/@types/polls.js.map +1 -1
  31. package/lib/@types/read_receipts.js +2 -2
  32. package/lib/@types/read_receipts.js.map +1 -1
  33. package/lib/@types/registration.js +3 -1
  34. package/lib/@types/requests.js +1 -1
  35. package/lib/@types/requests.js.map +1 -1
  36. package/lib/@types/retention.js +1 -1
  37. package/lib/@types/retention.js.map +1 -1
  38. package/lib/@types/search.js +1 -1
  39. package/lib/@types/search.js.map +1 -1
  40. package/lib/@types/signed.js +3 -1
  41. package/lib/@types/spaces.js +3 -1
  42. package/lib/@types/state_events.js +3 -1
  43. package/lib/@types/synapse.js +3 -1
  44. package/lib/@types/sync.js +1 -1
  45. package/lib/@types/sync.js.map +1 -1
  46. package/lib/@types/threepids.js +1 -1
  47. package/lib/@types/threepids.js.map +1 -1
  48. package/lib/@types/topic.js +1 -1
  49. package/lib/@types/topic.js.map +1 -1
  50. package/lib/@types/uia.js +3 -1
  51. package/lib/NamespacedValue.js +8 -8
  52. package/lib/NamespacedValue.js.map +1 -1
  53. package/lib/ReEmitter.js +9 -16
  54. package/lib/ReEmitter.js.map +1 -1
  55. package/lib/ToDeviceMessageQueue.js +49 -57
  56. package/lib/ToDeviceMessageQueue.js.map +1 -1
  57. package/lib/autodiscovery.js +232 -247
  58. package/lib/autodiscovery.js.map +1 -1
  59. package/lib/base64.js +1 -1
  60. package/lib/base64.js.map +1 -1
  61. package/lib/browser-index.d.ts +2 -2
  62. package/lib/browser-index.d.ts.map +1 -1
  63. package/lib/browser-index.js +5 -5
  64. package/lib/browser-index.js.map +1 -1
  65. package/lib/capabilityPoller.js +19 -22
  66. package/lib/capabilityPoller.js.map +1 -1
  67. package/lib/client.d.ts +2 -8
  68. package/lib/client.d.ts.map +1 -1
  69. package/lib/client.js +2043 -2487
  70. package/lib/client.js.map +1 -1
  71. package/lib/common-crypto/CryptoBackend.js +2 -2
  72. package/lib/common-crypto/CryptoBackend.js.map +1 -1
  73. package/lib/common-crypto/key-passphrase.js.map +1 -1
  74. package/lib/content-helpers.js +43 -48
  75. package/lib/content-helpers.js.map +1 -1
  76. package/lib/content-repo.js +14 -24
  77. package/lib/content-repo.js.map +1 -1
  78. package/lib/crypto/store/base.js +6 -6
  79. package/lib/crypto/store/base.js.map +1 -1
  80. package/lib/crypto/store/indexeddb-crypto-store-backend.js +190 -238
  81. package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +1 -1
  82. package/lib/crypto/store/indexeddb-crypto-store.js +25 -30
  83. package/lib/crypto/store/indexeddb-crypto-store.js.map +1 -1
  84. package/lib/crypto/store/localStorage-crypto-store.js +113 -145
  85. package/lib/crypto/store/localStorage-crypto-store.js.map +1 -1
  86. package/lib/crypto/store/memory-crypto-store.js +74 -105
  87. package/lib/crypto/store/memory-crypto-store.js.map +1 -1
  88. package/lib/crypto-api/CryptoEvent.js +1 -1
  89. package/lib/crypto-api/CryptoEvent.js.map +1 -1
  90. package/lib/crypto-api/CryptoEventHandlerMap.js +3 -1
  91. package/lib/crypto-api/index.d.ts +15 -6
  92. package/lib/crypto-api/index.d.ts.map +1 -1
  93. package/lib/crypto-api/index.js +22 -22
  94. package/lib/crypto-api/index.js.map +1 -1
  95. package/lib/crypto-api/key-passphrase.js +15 -23
  96. package/lib/crypto-api/key-passphrase.js.map +1 -1
  97. package/lib/crypto-api/keybackup.js +3 -1
  98. package/lib/crypto-api/recovery-key.js +11 -12
  99. package/lib/crypto-api/recovery-key.js.map +1 -1
  100. package/lib/crypto-api/verification.js +3 -3
  101. package/lib/crypto-api/verification.js.map +1 -1
  102. package/lib/digest.js +7 -14
  103. package/lib/digest.js.map +1 -1
  104. package/lib/embedded.d.ts.map +1 -1
  105. package/lib/embedded.js +380 -505
  106. package/lib/embedded.js.map +1 -1
  107. package/lib/errors.js +2 -2
  108. package/lib/errors.js.map +1 -1
  109. package/lib/event-mapper.js +10 -12
  110. package/lib/event-mapper.js.map +1 -1
  111. package/lib/extensible_events_v1/ExtensibleEvent.js.map +1 -1
  112. package/lib/extensible_events_v1/InvalidEventError.js.map +1 -1
  113. package/lib/extensible_events_v1/MessageEvent.js +11 -13
  114. package/lib/extensible_events_v1/MessageEvent.js.map +1 -1
  115. package/lib/extensible_events_v1/PollEndEvent.js +3 -4
  116. package/lib/extensible_events_v1/PollEndEvent.js.map +1 -1
  117. package/lib/extensible_events_v1/PollResponseEvent.js +5 -6
  118. package/lib/extensible_events_v1/PollResponseEvent.js.map +1 -1
  119. package/lib/extensible_events_v1/PollStartEvent.js +8 -10
  120. package/lib/extensible_events_v1/PollStartEvent.js.map +1 -1
  121. package/lib/extensible_events_v1/utilities.js.map +1 -1
  122. package/lib/feature.js +18 -31
  123. package/lib/feature.js.map +1 -1
  124. package/lib/filter-component.d.ts.map +1 -1
  125. package/lib/filter-component.js +20 -26
  126. package/lib/filter-component.js.map +1 -1
  127. package/lib/filter.js +14 -17
  128. package/lib/filter.js.map +1 -1
  129. package/lib/http-api/errors.js +28 -43
  130. package/lib/http-api/errors.js.map +1 -1
  131. package/lib/http-api/fetch.js +141 -159
  132. package/lib/http-api/fetch.js.map +1 -1
  133. package/lib/http-api/index.js +17 -20
  134. package/lib/http-api/index.js.map +1 -1
  135. package/lib/http-api/interface.js +1 -1
  136. package/lib/http-api/interface.js.map +1 -1
  137. package/lib/http-api/method.js +1 -1
  138. package/lib/http-api/method.js.map +1 -1
  139. package/lib/http-api/prefix.js +3 -3
  140. package/lib/http-api/prefix.js.map +1 -1
  141. package/lib/http-api/refresh.js +74 -94
  142. package/lib/http-api/refresh.js.map +1 -1
  143. package/lib/http-api/utils.d.ts +1 -1
  144. package/lib/http-api/utils.d.ts.map +1 -1
  145. package/lib/http-api/utils.js +34 -42
  146. package/lib/http-api/utils.js.map +1 -1
  147. package/lib/index.js.map +1 -1
  148. package/lib/indexeddb-helpers.js +3 -3
  149. package/lib/indexeddb-helpers.js.map +1 -1
  150. package/lib/indexeddb-worker.js.map +1 -1
  151. package/lib/interactive-auth.d.ts +5 -5
  152. package/lib/interactive-auth.d.ts.map +1 -1
  153. package/lib/interactive-auth.js +172 -204
  154. package/lib/interactive-auth.js.map +1 -1
  155. package/lib/logger.js +21 -57
  156. package/lib/logger.js.map +1 -1
  157. package/lib/matrix.js +7 -11
  158. package/lib/matrix.js.map +1 -1
  159. package/lib/matrixrtc/CallMembership.js +80 -74
  160. package/lib/matrixrtc/CallMembership.js.map +1 -1
  161. package/lib/matrixrtc/EncryptionManager.js +1 -1
  162. package/lib/matrixrtc/EncryptionManager.js.map +1 -1
  163. package/lib/matrixrtc/IKeyTransport.js +1 -1
  164. package/lib/matrixrtc/IKeyTransport.js.map +1 -1
  165. package/lib/matrixrtc/IMembershipManager.js +1 -1
  166. package/lib/matrixrtc/IMembershipManager.js.map +1 -1
  167. package/lib/matrixrtc/LivekitTransport.d.ts +1 -1
  168. package/lib/matrixrtc/LivekitTransport.js +4 -4
  169. package/lib/matrixrtc/LivekitTransport.js.map +1 -1
  170. package/lib/matrixrtc/MatrixRTCSession.js +137 -187
  171. package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
  172. package/lib/matrixrtc/MatrixRTCSessionManager.js +36 -41
  173. package/lib/matrixrtc/MatrixRTCSessionManager.js.map +1 -1
  174. package/lib/matrixrtc/MembershipManager.js +332 -378
  175. package/lib/matrixrtc/MembershipManager.js.map +1 -1
  176. package/lib/matrixrtc/MembershipManagerActionScheduler.js +54 -63
  177. package/lib/matrixrtc/MembershipManagerActionScheduler.js.map +1 -1
  178. package/lib/matrixrtc/RTCEncryptionManager.js +119 -143
  179. package/lib/matrixrtc/RTCEncryptionManager.js.map +1 -1
  180. package/lib/matrixrtc/ToDeviceKeyTransport.js +53 -58
  181. package/lib/matrixrtc/ToDeviceKeyTransport.js.map +1 -1
  182. package/lib/matrixrtc/index.js.map +1 -1
  183. package/lib/matrixrtc/membershipData/common.js +1 -1
  184. package/lib/matrixrtc/membershipData/common.js.map +1 -1
  185. package/lib/matrixrtc/membershipData/index.js.map +1 -1
  186. package/lib/matrixrtc/membershipData/rtc.js +15 -23
  187. package/lib/matrixrtc/membershipData/rtc.js.map +1 -1
  188. package/lib/matrixrtc/membershipData/session.js +4 -5
  189. package/lib/matrixrtc/membershipData/session.js.map +1 -1
  190. package/lib/matrixrtc/types.js +4 -6
  191. package/lib/matrixrtc/types.js.map +1 -1
  192. package/lib/matrixrtc/utils.js +4 -11
  193. package/lib/matrixrtc/utils.js.map +1 -1
  194. package/lib/models/MSC3089Branch.js +91 -116
  195. package/lib/models/MSC3089Branch.js.map +1 -1
  196. package/lib/models/MSC3089TreeSpace.js +209 -245
  197. package/lib/models/MSC3089TreeSpace.js.map +1 -1
  198. package/lib/models/ToDeviceMessage.js +3 -1
  199. package/lib/models/beacon.js +14 -13
  200. package/lib/models/beacon.js.map +1 -1
  201. package/lib/models/compare-event-ordering.js +13 -13
  202. package/lib/models/compare-event-ordering.js.map +1 -1
  203. package/lib/models/device.js +3 -3
  204. package/lib/models/device.js.map +1 -1
  205. package/lib/models/event-context.js +5 -8
  206. package/lib/models/event-context.js.map +1 -1
  207. package/lib/models/event-status.js +1 -1
  208. package/lib/models/event-status.js.map +1 -1
  209. package/lib/models/event-timeline-set.js +88 -94
  210. package/lib/models/event-timeline-set.js.map +1 -1
  211. package/lib/models/event-timeline.js +28 -30
  212. package/lib/models/event-timeline.js.map +1 -1
  213. package/lib/models/event.js +182 -226
  214. package/lib/models/event.js.map +1 -1
  215. package/lib/models/invites-ignorer-types.js +4 -4
  216. package/lib/models/invites-ignorer-types.js.map +1 -1
  217. package/lib/models/invites-ignorer.js +159 -179
  218. package/lib/models/invites-ignorer.js.map +1 -1
  219. package/lib/models/poll.js +71 -81
  220. package/lib/models/poll.js.map +1 -1
  221. package/lib/models/profile-keys.js +2 -2
  222. package/lib/models/profile-keys.js.map +1 -1
  223. package/lib/models/read-receipt.js +40 -56
  224. package/lib/models/read-receipt.js.map +1 -1
  225. package/lib/models/related-relations.js.map +1 -1
  226. package/lib/models/relations-container.js +22 -23
  227. package/lib/models/relations-container.js.map +1 -1
  228. package/lib/models/relations.js +133 -159
  229. package/lib/models/relations.js.map +1 -1
  230. package/lib/models/room-member.js +24 -29
  231. package/lib/models/room-member.js.map +1 -1
  232. package/lib/models/room-receipts.js +29 -43
  233. package/lib/models/room-receipts.js.map +1 -1
  234. package/lib/models/room-retention.js +74 -83
  235. package/lib/models/room-retention.js.map +1 -1
  236. package/lib/models/room-state.js +143 -172
  237. package/lib/models/room-state.js.map +1 -1
  238. package/lib/models/room-sticky-events.d.ts +1 -0
  239. package/lib/models/room-sticky-events.d.ts.map +1 -1
  240. package/lib/models/room-sticky-events.js +45 -65
  241. package/lib/models/room-sticky-events.js.map +1 -1
  242. package/lib/models/room-summary.js.map +1 -1
  243. package/lib/models/room.d.ts.map +1 -1
  244. package/lib/models/room.js +765 -909
  245. package/lib/models/room.js.map +1 -1
  246. package/lib/models/search-result.js +5 -5
  247. package/lib/models/search-result.js.map +1 -1
  248. package/lib/models/thread.js +225 -285
  249. package/lib/models/thread.js.map +1 -1
  250. package/lib/models/typed-event-emitter.js +7 -18
  251. package/lib/models/typed-event-emitter.js.map +1 -1
  252. package/lib/models/user.js +8 -8
  253. package/lib/models/user.js.map +1 -1
  254. package/lib/oidc/authorize.js +208 -241
  255. package/lib/oidc/authorize.js.map +1 -1
  256. package/lib/oidc/discovery.js +23 -36
  257. package/lib/oidc/discovery.js.map +1 -1
  258. package/lib/oidc/error.js +1 -1
  259. package/lib/oidc/error.js.map +1 -1
  260. package/lib/oidc/index.js +1 -0
  261. package/lib/oidc/index.js.map +1 -1
  262. package/lib/oidc/register.js +60 -66
  263. package/lib/oidc/register.js.map +1 -1
  264. package/lib/oidc/tokenRefresher.js +77 -91
  265. package/lib/oidc/tokenRefresher.js.map +1 -1
  266. package/lib/oidc/validate.js +18 -18
  267. package/lib/oidc/validate.js.map +1 -1
  268. package/lib/pushprocessor.js +71 -82
  269. package/lib/pushprocessor.js.map +1 -1
  270. package/lib/randomstring.js +9 -9
  271. package/lib/randomstring.js.map +1 -1
  272. package/lib/realtime-callbacks.js +25 -28
  273. package/lib/realtime-callbacks.js.map +1 -1
  274. package/lib/receipt-accumulator.d.ts +2 -0
  275. package/lib/receipt-accumulator.d.ts.map +1 -1
  276. package/lib/receipt-accumulator.js +14 -22
  277. package/lib/receipt-accumulator.js.map +1 -1
  278. package/lib/rendezvous/MSC4108SignInWithQR.js +271 -302
  279. package/lib/rendezvous/MSC4108SignInWithQR.js.map +1 -1
  280. package/lib/rendezvous/RendezvousChannel.js +3 -1
  281. package/lib/rendezvous/RendezvousCode.js +3 -1
  282. package/lib/rendezvous/RendezvousError.js.map +1 -1
  283. package/lib/rendezvous/RendezvousFailureReason.js +2 -2
  284. package/lib/rendezvous/RendezvousFailureReason.js.map +1 -1
  285. package/lib/rendezvous/RendezvousIntent.js +1 -1
  286. package/lib/rendezvous/RendezvousIntent.js.map +1 -1
  287. package/lib/rendezvous/RendezvousTransport.js +3 -1
  288. package/lib/rendezvous/channels/MSC4108SecureChannel.js +123 -147
  289. package/lib/rendezvous/channels/MSC4108SecureChannel.js.map +1 -1
  290. package/lib/rendezvous/index.js +44 -69
  291. package/lib/rendezvous/index.js.map +1 -1
  292. package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts +1 -1
  293. package/lib/rendezvous/transports/MSC4108RendezvousSession.js +134 -152
  294. package/lib/rendezvous/transports/MSC4108RendezvousSession.js.map +1 -1
  295. package/lib/retentionPolicy.js +6 -9
  296. package/lib/retentionPolicy.js.map +1 -1
  297. package/lib/room-hierarchy.js +52 -60
  298. package/lib/room-hierarchy.js.map +1 -1
  299. package/lib/rust-crypto/CrossSigningIdentity.js +94 -104
  300. package/lib/rust-crypto/CrossSigningIdentity.js.map +1 -1
  301. package/lib/rust-crypto/DehydratedDeviceManager.js +157 -190
  302. package/lib/rust-crypto/DehydratedDeviceManager.js.map +1 -1
  303. package/lib/rust-crypto/KeyClaimManager.js +18 -22
  304. package/lib/rust-crypto/KeyClaimManager.js.map +1 -1
  305. package/lib/rust-crypto/OutgoingRequestProcessor.js +109 -139
  306. package/lib/rust-crypto/OutgoingRequestProcessor.js.map +1 -1
  307. package/lib/rust-crypto/OutgoingRequestsManager.js +66 -80
  308. package/lib/rust-crypto/OutgoingRequestsManager.js.map +1 -1
  309. package/lib/rust-crypto/PerSessionKeyBackupDownloader.d.ts +1 -1
  310. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js +196 -224
  311. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js.map +1 -1
  312. package/lib/rust-crypto/RoomEncryptor.js +127 -143
  313. package/lib/rust-crypto/RoomEncryptor.js.map +1 -1
  314. package/lib/rust-crypto/backup.js +453 -549
  315. package/lib/rust-crypto/backup.js.map +1 -1
  316. package/lib/rust-crypto/constants.js +1 -1
  317. package/lib/rust-crypto/constants.js.map +1 -1
  318. package/lib/rust-crypto/device-converter.js +15 -28
  319. package/lib/rust-crypto/device-converter.js.map +1 -1
  320. package/lib/rust-crypto/index.js +103 -116
  321. package/lib/rust-crypto/index.js.map +1 -1
  322. package/lib/rust-crypto/libolm_migration.js +303 -365
  323. package/lib/rust-crypto/libolm_migration.js.map +1 -1
  324. package/lib/rust-crypto/rust-crypto.d.ts +5 -1
  325. package/lib/rust-crypto/rust-crypto.d.ts.map +1 -1
  326. package/lib/rust-crypto/rust-crypto.js +1067 -1332
  327. package/lib/rust-crypto/rust-crypto.js.map +1 -1
  328. package/lib/rust-crypto/secret-storage.js +12 -25
  329. package/lib/rust-crypto/secret-storage.js.map +1 -1
  330. package/lib/rust-crypto/verification.js +137 -189
  331. package/lib/rust-crypto/verification.js.map +1 -1
  332. package/lib/scheduler.js +44 -19
  333. package/lib/scheduler.js.map +1 -1
  334. package/lib/secret-storage.js +179 -213
  335. package/lib/secret-storage.js.map +1 -1
  336. package/lib/serverCapabilities.js +6 -9
  337. package/lib/serverCapabilities.js.map +1 -1
  338. package/lib/service-types.js +1 -1
  339. package/lib/service-types.js.map +1 -1
  340. package/lib/sliding-sync-sdk.d.ts.map +1 -1
  341. package/lib/sliding-sync-sdk.js +368 -424
  342. package/lib/sliding-sync-sdk.js.map +1 -1
  343. package/lib/sliding-sync.js +135 -171
  344. package/lib/sliding-sync.js.map +1 -1
  345. package/lib/store/index.js +3 -1
  346. package/lib/store/indexeddb-backend.js +3 -1
  347. package/lib/store/indexeddb-local-backend.js +194 -253
  348. package/lib/store/indexeddb-local-backend.js.map +1 -1
  349. package/lib/store/indexeddb-remote-backend.js +33 -63
  350. package/lib/store/indexeddb-remote-backend.js.map +1 -1
  351. package/lib/store/indexeddb-store-worker.js +22 -23
  352. package/lib/store/indexeddb-store-worker.js.map +1 -1
  353. package/lib/store/indexeddb.js +44 -71
  354. package/lib/store/indexeddb.js.map +1 -1
  355. package/lib/store/local-storage-events-emitter.js +2 -2
  356. package/lib/store/local-storage-events-emitter.js.map +1 -1
  357. package/lib/store/memory.js +34 -57
  358. package/lib/store/memory.js.map +1 -1
  359. package/lib/store/stub.js +22 -35
  360. package/lib/store/stub.js.map +1 -1
  361. package/lib/sync-accumulator.js +54 -66
  362. package/lib/sync-accumulator.js.map +1 -1
  363. package/lib/sync.d.ts.map +1 -1
  364. package/lib/sync.js +905 -998
  365. package/lib/sync.js.map +1 -1
  366. package/lib/testing.js +63 -105
  367. package/lib/testing.js.map +1 -1
  368. package/lib/thread-utils.js +1 -4
  369. package/lib/thread-utils.js.map +1 -1
  370. package/lib/timeline-window.js +89 -102
  371. package/lib/timeline-window.js.map +1 -1
  372. package/lib/types.js +1 -1
  373. package/lib/types.js.map +1 -1
  374. package/lib/utils/decryptAESSecretStorageItem.js +14 -25
  375. package/lib/utils/decryptAESSecretStorageItem.js.map +1 -1
  376. package/lib/utils/encryptAESSecretStorageItem.js +27 -38
  377. package/lib/utils/encryptAESSecretStorageItem.js.map +1 -1
  378. package/lib/utils/internal/deriveKeys.js +25 -32
  379. package/lib/utils/internal/deriveKeys.js.map +1 -1
  380. package/lib/utils/roomVersion.js +1 -1
  381. package/lib/utils/roomVersion.js.map +1 -1
  382. package/lib/utils.js +83 -135
  383. package/lib/utils.js.map +1 -1
  384. package/lib/version-support.js +3 -3
  385. package/lib/version-support.js.map +1 -1
  386. package/lib/webrtc/audioContext.js +5 -6
  387. package/lib/webrtc/audioContext.js.map +1 -1
  388. package/lib/webrtc/call.js +1081 -1250
  389. package/lib/webrtc/call.js.map +1 -1
  390. package/lib/webrtc/callEventHandler.js +202 -214
  391. package/lib/webrtc/callEventHandler.js.map +1 -1
  392. package/lib/webrtc/callEventTypes.js +2 -2
  393. package/lib/webrtc/callEventTypes.js.map +1 -1
  394. package/lib/webrtc/callFeed.js +18 -20
  395. package/lib/webrtc/callFeed.js.map +1 -1
  396. package/lib/webrtc/groupCall.js +513 -602
  397. package/lib/webrtc/groupCall.js.map +1 -1
  398. package/lib/webrtc/groupCallEventHandler.js +59 -62
  399. package/lib/webrtc/groupCallEventHandler.js.map +1 -1
  400. package/lib/webrtc/mediaHandler.js +198 -232
  401. package/lib/webrtc/mediaHandler.js.map +1 -1
  402. package/lib/webrtc/stats/callFeedStatsReporter.js +16 -20
  403. package/lib/webrtc/stats/callFeedStatsReporter.js.map +1 -1
  404. package/lib/webrtc/stats/callStatsReportGatherer.js +67 -75
  405. package/lib/webrtc/stats/callStatsReportGatherer.js.map +1 -1
  406. package/lib/webrtc/stats/callStatsReportSummary.js +3 -1
  407. package/lib/webrtc/stats/connectionStats.js.map +1 -1
  408. package/lib/webrtc/stats/connectionStatsBuilder.js +2 -2
  409. package/lib/webrtc/stats/connectionStatsBuilder.js.map +1 -1
  410. package/lib/webrtc/stats/connectionStatsReportBuilder.js +20 -24
  411. package/lib/webrtc/stats/connectionStatsReportBuilder.js.map +1 -1
  412. package/lib/webrtc/stats/groupCallStats.js +6 -8
  413. package/lib/webrtc/stats/groupCallStats.js.map +1 -1
  414. package/lib/webrtc/stats/media/mediaSsrcHandler.js +7 -8
  415. package/lib/webrtc/stats/media/mediaSsrcHandler.js.map +1 -1
  416. package/lib/webrtc/stats/media/mediaTrackHandler.js +7 -9
  417. package/lib/webrtc/stats/media/mediaTrackHandler.js.map +1 -1
  418. package/lib/webrtc/stats/media/mediaTrackStats.js +3 -3
  419. package/lib/webrtc/stats/media/mediaTrackStats.js.map +1 -1
  420. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js +7 -7
  421. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js.map +1 -1
  422. package/lib/webrtc/stats/statsReport.js +1 -1
  423. package/lib/webrtc/stats/statsReport.js.map +1 -1
  424. package/lib/webrtc/stats/statsReportEmitter.js.map +1 -1
  425. package/lib/webrtc/stats/summaryStatsReportGatherer.js +14 -14
  426. package/lib/webrtc/stats/summaryStatsReportGatherer.js.map +1 -1
  427. package/lib/webrtc/stats/trackStatsBuilder.js +32 -34
  428. package/lib/webrtc/stats/trackStatsBuilder.js.map +1 -1
  429. package/lib/webrtc/stats/transportStats.js +3 -1
  430. package/lib/webrtc/stats/transportStatsBuilder.js +9 -9
  431. package/lib/webrtc/stats/transportStatsBuilder.js.map +1 -1
  432. package/lib/webrtc/stats/valueFormatter.js +1 -1
  433. package/lib/webrtc/stats/valueFormatter.js.map +1 -1
  434. package/package.json +18 -33
  435. package/src/@types/global.d.ts +2 -2
  436. package/src/ToDeviceMessageQueue.ts +2 -2
  437. package/src/browser-index.ts +4 -4
  438. package/src/client.ts +15 -20
  439. package/src/crypto-api/index.ts +17 -6
  440. package/src/embedded.ts +4 -6
  441. package/src/filter-component.ts +1 -0
  442. package/src/http-api/utils.ts +1 -1
  443. package/src/interactive-auth.ts +11 -5
  444. package/src/matrixrtc/LivekitTransport.ts +1 -1
  445. package/src/matrixrtc/MatrixRTCSession.ts +1 -1
  446. package/src/models/MSC3089Branch.ts +1 -1
  447. package/src/models/room-sticky-events.ts +1 -0
  448. package/src/models/room.ts +9 -11
  449. package/src/receipt-accumulator.ts +2 -0
  450. package/src/rendezvous/index.ts +1 -1
  451. package/src/rendezvous/transports/MSC4108RendezvousSession.ts +2 -2
  452. package/src/rust-crypto/PerSessionKeyBackupDownloader.ts +1 -1
  453. package/src/rust-crypto/index.ts +6 -6
  454. package/src/rust-crypto/rust-crypto.ts +31 -7
  455. package/src/rust-crypto/verification.ts +1 -1
  456. package/src/sliding-sync-sdk.ts +5 -7
  457. package/src/store/indexeddb-local-backend.ts +3 -3
  458. package/src/sync.ts +6 -8
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["FetchHttpApi","MediaPrefix","removeElement","callbacks","Method","ConnectionError","parseErrorResponse","MatrixHttpApi","constructor","arguments","_defineProperty","uploadContent","file","_opts$includeFilename","_opts$abortController","_opts$type","_opts$name","opts","length","undefined","includeFilename","abortController","AbortController","contentType","type","fileName","name","upload","loaded","total","uploadResolvers","Promise","withResolvers","globalThis","XMLHttpRequest","xhr","timeoutFn","abort","reject","Error","timeoutTimer","setTimeout","onreadystatechange","readyState","DONE","clearTimeout","status","DOMException","statusText","responseText","resolve","JSON","parse","err","onprogress","ev","_opts$progressHandler","progressHandler","call","url","getUrl","V3","searchParams","set","encodeURIComponent","useAuthorizationHeader","accessToken","open","Post","href","setRequestHeader","send","signal","addEventListener","queryParams","filename","headers","authedRequest","prefix","abortSignal","then","promise","finally","uploads","elem","push","cancelUpload","find","u","getCurrentUploads","getContentUri","base","baseUrl","path","params","access_token"],"sources":["../../src/http-api/index.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { FetchHttpApi } from \"./fetch.ts\";\nimport {\n type FileType,\n type IContentUri,\n type IHttpOpts,\n type Upload,\n type UploadOpts,\n type UploadResponse,\n} from \"./interface.ts\";\nimport { MediaPrefix } from \"./prefix.ts\";\nimport { type QueryDict, removeElement } from \"../utils.ts\";\nimport * as callbacks from \"../realtime-callbacks.ts\";\nimport { Method } from \"./method.ts\";\nimport { ConnectionError } from \"./errors.ts\";\nimport { parseErrorResponse } from \"./utils.ts\";\n\nexport * from \"./interface.ts\";\nexport * from \"./prefix.ts\";\nexport * from \"./errors.ts\";\nexport * from \"./method.ts\";\nexport * from \"./utils.ts\";\n\nexport class MatrixHttpApi<O extends IHttpOpts> extends FetchHttpApi<O> {\n private uploads: Upload[] = [];\n\n /**\n * Upload content to the homeserver\n *\n * @param file - The object to upload. On a browser, something that\n * can be sent to XMLHttpRequest.send (typically a File). Under node.js,\n * a Buffer, String or ReadStream.\n *\n * @param opts - options object\n *\n * @returns Promise which resolves to response object, or rejects with an error (usually a MatrixError).\n * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n * @see MatrixSafetyError\n */\n public uploadContent(file: FileType, opts: UploadOpts = {}): Promise<UploadResponse> {\n const includeFilename = opts.includeFilename ?? true;\n const abortController = opts.abortController ?? new AbortController();\n\n // If the file doesn't have a mime type, use a default since the HS errors if we don't supply one.\n const contentType = (opts.type ?? (file as File).type) || \"application/octet-stream\";\n const fileName = opts.name ?? (file as File).name;\n\n const upload = {\n loaded: 0,\n total: 0,\n abortController,\n } as Upload;\n const uploadResolvers = Promise.withResolvers<UploadResponse>();\n\n if (globalThis.XMLHttpRequest) {\n const xhr = new globalThis.XMLHttpRequest();\n\n const timeoutFn = function (): void {\n xhr.abort();\n uploadResolvers.reject(new Error(\"Timeout\"));\n };\n\n // set an initial timeout of 30s; we'll advance it each time we get a progress notification\n let timeoutTimer = callbacks.setTimeout(timeoutFn, 30000);\n\n xhr.onreadystatechange = function (): void {\n switch (xhr.readyState) {\n case globalThis.XMLHttpRequest.DONE:\n callbacks.clearTimeout(timeoutTimer);\n try {\n if (xhr.status === 0) {\n throw new DOMException(xhr.statusText, \"AbortError\"); // mimic fetch API\n }\n if (!xhr.responseText) {\n throw new Error(\"No response body.\");\n }\n\n if (xhr.status >= 400) {\n uploadResolvers.reject(parseErrorResponse(xhr, xhr.responseText));\n } else {\n uploadResolvers.resolve(JSON.parse(xhr.responseText));\n }\n } catch (err) {\n if ((<Error>err).name === \"AbortError\") {\n uploadResolvers.reject(err);\n return;\n }\n uploadResolvers.reject(new ConnectionError(\"request failed\", <Error>err));\n }\n break;\n }\n };\n\n xhr.upload.onprogress = (ev: ProgressEvent): void => {\n callbacks.clearTimeout(timeoutTimer);\n upload.loaded = ev.loaded;\n upload.total = ev.total;\n timeoutTimer = callbacks.setTimeout(timeoutFn, 30000);\n opts.progressHandler?.({\n loaded: ev.loaded,\n total: ev.total,\n });\n };\n\n const url = this.getUrl(\"/upload\", undefined, MediaPrefix.V3);\n\n if (includeFilename && fileName) {\n url.searchParams.set(\"filename\", encodeURIComponent(fileName));\n }\n\n if (!this.opts.useAuthorizationHeader && this.opts.accessToken) {\n url.searchParams.set(\"access_token\", encodeURIComponent(this.opts.accessToken));\n }\n\n xhr.open(Method.Post, url.href);\n if (this.opts.useAuthorizationHeader && this.opts.accessToken) {\n xhr.setRequestHeader(\"Authorization\", \"Bearer \" + this.opts.accessToken);\n }\n xhr.setRequestHeader(\"Content-Type\", contentType);\n xhr.send(file);\n\n abortController.signal.addEventListener(\"abort\", () => {\n xhr.abort();\n });\n } else {\n const queryParams: QueryDict = {};\n if (includeFilename && fileName) {\n queryParams.filename = fileName;\n }\n\n const headers: Record<string, string> = { \"Content-Type\": contentType };\n\n this.authedRequest<UploadResponse>(Method.Post, \"/upload\", queryParams, file, {\n prefix: MediaPrefix.V3,\n headers,\n abortSignal: abortController.signal,\n }).then(uploadResolvers.resolve, uploadResolvers.reject);\n }\n\n // remove the upload from the list on completion\n upload.promise = uploadResolvers.promise.finally(() => {\n removeElement(this.uploads, (elem) => elem === upload);\n });\n abortController.signal.addEventListener(\"abort\", () => {\n removeElement(this.uploads, (elem) => elem === upload);\n uploadResolvers.reject(new DOMException(\"Aborted\", \"AbortError\"));\n });\n this.uploads.push(upload);\n return upload.promise;\n }\n\n public cancelUpload(promise: Promise<UploadResponse>): boolean {\n const upload = this.uploads.find((u) => u.promise === promise);\n if (upload) {\n upload.abortController.abort();\n return true;\n }\n return false;\n }\n\n public getCurrentUploads(): Upload[] {\n return this.uploads;\n }\n\n /**\n * Get the content repository url with query parameters.\n * @returns An object with a 'base', 'path' and 'params' for base URL,\n * path and query parameters respectively.\n */\n public getContentUri(): IContentUri {\n return {\n base: this.opts.baseUrl,\n path: MediaP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M,CAAC;IAC1D,CAAC,CAAC;IACFN,eAAe,CAACmD,MAAM,CAACC,gBAAgB,CAAC,OAAO,EAAE,MAAM;MACnDvE,aAAa,CAAC,IAAI,CAACiF,OAAO,EAAGC,IAAI,IAAKA,IAAI,KAAKzD,MAAM,CAAC;MACtDG,eAAe,CAACQ,MAAM,CAAC,IAAIS,YAAY,CAAC,SAAS,EAAE,YAAY,CAAC,CAAC;IACrE,CAAC,CAAC;IACF,IAAI,CAACoC,OAAO,CAACE,IAAI,CAAC1D,MAAM,CAAC;IACzB,OAAOA,MAAM,CAACsD,OAAO;EACzB;EAEOK,YAAYA,CAACL,OAAgC,EAAW;IAC3D,IAAMtD,MAAM,GAAG,IAAI,CAACwD,OAAO,CAACI,IAAI,CAAEC,CAAC,IAAKA,CAAC,CAACP,OAAO,KAAKA,OAAO,CAAC;IAC9D,IAAItD,MAAM,EAAE;MACRA,MAAM,CAACN,eAAe,CAACgB,KAAK,CAAC,CAAC;MAC9B,OAAO,IAAI;IACf;IACA,OAAO,KAAK;EAChB;EAEOoD,iBAAiBA,CAAA,EAAa;IACjC,OAAO,IAAI,CAACN,OAAO;EACvB;;EAEA;AACJ;AACA;AACA;AACA;EACWO,aAAaA,CAAA,EAAgB;IAChC,OAAO;MACHC,IAAI,EAAE,IAAI,CAAC1E,IAAI,CAAC2E,OAAO;MACvBC,IAAI,EAAE5F,WAAW,CAAC4D,EAAE,GAAG,SAAS;MAChCiC,MAAM,EAAE;QACJC,YAAY,EAAE,IAAI,CAAC9E,IAAI,CAACiD;MAC5B;IACJ,CAAC;EACL;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/http-api/index.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { FetchHttpApi } from \"./fetch.ts\";\nimport {\n type FileType,\n type IContentUri,\n type IHttpOpts,\n type Upload,\n type UploadOpts,\n type UploadResponse,\n} from \"./interface.ts\";\nimport { MediaPrefix } from \"./prefix.ts\";\nimport { type QueryDict, removeElement } from \"../utils.ts\";\nimport * as callbacks from \"../realtime-callbacks.ts\";\nimport { Method } from \"./method.ts\";\nimport { ConnectionError } from \"./errors.ts\";\nimport { parseErrorResponse } from \"./utils.ts\";\n\nexport * from \"./interface.ts\";\nexport * from \"./prefix.ts\";\nexport * from \"./errors.ts\";\nexport * from \"./method.ts\";\nexport * from \"./utils.ts\";\n\nexport class MatrixHttpApi<O extends IHttpOpts> extends FetchHttpApi<O> {\n private uploads: Upload[] = [];\n\n /**\n * Upload content to the homeserver\n *\n * @param file - The object to upload. On a browser, something that\n * can be sent to XMLHttpRequest.send (typically a File). Under node.js,\n * a Buffer, String or ReadStream.\n *\n * @param opts - options object\n *\n * @returns Promise which resolves to response object, or rejects with an error (usually a MatrixError).\n * @throws May throw a `MatrixSafetyError` if content is deemed unsafe.\n * @see MatrixSafetyError\n */\n public uploadContent(file: FileType, opts: UploadOpts = {}): Promise<UploadResponse> {\n const includeFilename = opts.includeFilename ?? true;\n const abortController = opts.abortController ?? new AbortController();\n\n // If the file doesn't have a mime type, use a default since the HS errors if we don't supply one.\n const contentType = (opts.type ?? (file as File).type) || \"application/octet-stream\";\n const fileName = opts.name ?? (file as File).name;\n\n const upload = {\n loaded: 0,\n total: 0,\n abortController,\n } as Upload;\n const uploadResolvers = Promise.withResolvers<UploadResponse>();\n\n if (globalThis.XMLHttpRequest) {\n const xhr = new globalThis.XMLHttpRequest();\n\n const timeoutFn = function (): void {\n xhr.abort();\n uploadResolvers.reject(new Error(\"Timeout\"));\n };\n\n // set an initial timeout of 30s; we'll advance it each time we get a progress notification\n let timeoutTimer = callbacks.setTimeout(timeoutFn, 30000);\n\n xhr.onreadystatechange = function (): void {\n switch (xhr.readyState) {\n case globalThis.XMLHttpRequest.DONE:\n callbacks.clearTimeout(timeoutTimer);\n try {\n if (xhr.status === 0) {\n throw new DOMException(xhr.statusText, \"AbortError\"); // mimic fetch API\n }\n if (!xhr.responseText) {\n throw new Error(\"No response body.\");\n }\n\n if (xhr.status >= 400) {\n uploadResolvers.reject(parseErrorResponse(xhr, xhr.responseText));\n } else {\n uploadResolvers.resolve(JSON.parse(xhr.responseText));\n }\n } catch (err) {\n if ((<Error>err).name === \"AbortError\") {\n uploadResolvers.reject(err);\n return;\n }\n uploadResolvers.reject(new ConnectionError(\"request failed\", <Error>err));\n }\n break;\n }\n };\n\n xhr.upload.onprogress = (ev: ProgressEvent): void => {\n callbacks.clearTimeout(timeoutTimer);\n upload.loaded = ev.loaded;\n upload.total = ev.total;\n timeoutTimer = callbacks.setTimeout(timeoutFn, 30000);\n opts.progressHandler?.({\n loaded: ev.loaded,\n total: ev.total,\n });\n };\n\n const url = this.getUrl(\"/upload\", undefined, MediaPrefix.V3);\n\n if (includeFilename && fileName) {\n url.searchParams.set(\"filename\", encodeURIComponent(fileName));\n }\n\n if (!this.opts.useAuthorizationHeader && this.opts.accessToken) {\n url.searchParams.set(\"access_token\", encodeURIComponent(this.opts.accessToken));\n }\n\n xhr.open(Method.Post, url.href);\n if (this.opts.useAuthorizationHeader && this.opts.accessToken) {\n xhr.setRequestHeader(\"Authorization\", \"Bearer \" + this.opts.accessToken);\n }\n xhr.setRequestHeader(\"Content-Type\", contentType);\n xhr.send(file);\n\n abortController.signal.addEventListener(\"abort\", () => {\n xhr.abort();\n });\n } else {\n const queryParams: QueryDict = {};\n if (includeFilename && fileName) {\n queryParams.filename = fileName;\n }\n\n const headers: Record<string, string> = { \"Content-Type\": contentType };\n\n this.authedRequest<UploadResponse>(Method.Post, \"/upload\", queryParams, file, {\n prefix: MediaPrefix.V3,\n headers,\n abortSignal: abortController.signal,\n }).then(uploadResolvers.resolve, uploadResolvers.reject);\n }\n\n // remove the upload from the list on completion\n upload.promise = uploadResolvers.promise.finally(() => {\n removeElement(this.uploads, (elem) => elem === upload);\n });\n abortController.signal.addEventListener(\"abort\", () => {\n removeElement(this.uploads, (elem) => elem === upload);\n uploadResolvers.reject(new DOMException(\"Aborted\", \"AbortError\"));\n });\n this.uploads.push(upload);\n return upload.promise;\n }\n\n public cancelUpload(promise: Promise<UploadResponse>): boolean {\n const upload = this.uploads.find((u) => u.promise === promise);\n if (upload) {\n upload.abortController.abort();\n return true;\n }\n return false;\n }\n\n public getCurrentUploads(): Upload[] {\n return this.uploads;\n }\n\n /**\n * Get the content repository url with query parameters.\n * @returns An object with a 'base', 'path' and 'params' for base URL,\n * path and query parameters respectively.\n */\n public getContentUri(): IContentUri {\n return {\n base: this.opts.baseUrl,\n path: MediaPrefix.V3 + \"/upload\",\n params: {\n access_token: this.opts.accessToken!,\n },\n };\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,YAAY,QAAQ,YAAY;AASzC,SAAS,WAAW,QAAQ,aAAa;AACzC,SAAyB,aAAa,QAAQ,aAAa;AAC3D,OAAO,KAAK,SAAS,MAAM,0BAA0B;AACrD,SAAS,MAAM,QAAQ,aAAa;AACpC,SAAS,eAAe,QAAQ,aAAa;AAC7C,SAAS,kBAAkB,QAAQ,YAAY;AAE/C,cAAc,gBAAgB;AAC9B,cAAc,aAAa;AAC3B,cAAc,aAAa;AAC3B,cAAc,aAAa;AAC3B,cAAc,YAAY;AAE1B,OAAO,MAAM,aAAa,SAA8B,YAAY,CAAI;EAAA;IAAA;IAAA,iCACxC,EAAE;EAAA;EAE9B;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACW,aAAa,CAAC,IAAc,EAAE,IAAgB,GAAG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AI,IAAK,IAAI,KAAK,MAAM,CAAC;MACtD,eAAe,CAAC,MAAM,CAAC,IAAI,YAAY,CAAC,SAAS,EAAE,YAAY,CAAC,CAAC;IACrE,CAAC,CAAC;IACF,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC;IACzB,OAAO,MAAM,CAAC,OAAO;EACzB;EAEO,YAAY,CAAC,OAAgC,EAAW;IAC3D,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAE,CAAC,IAAK,CAAC,CAAC,OAAO,KAAK,OAAO,CAAC;IAC9D,IAAI,MAAM,EAAE;MACR,MAAM,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;MAC9B,OAAO,IAAI;IACf;IACA,OAAO,KAAK;EAChB;EAEO,iBAAiB,GAAa;IACjC,OAAO,IAAI,CAAC,OAAO;EACvB;;EAEA;AACJ;AACA;AACA;AACA;EACW,aAAa,GAAgB;IAChC,OAAO;MACH,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,OAAO;MACvB,IAAI,EAAE,WAAW,CAAC,EAAE,GAAG,SAAS;MAChC,MAAM,EAAE;QACJ,YAAY,EAAE,IAAI,CAAC,IAAI,CAAC;MAC5B;IACJ,CAAC;EACL;AACJ","ignoreList":[]}
@@ -31,7 +31,7 @@ limitations under the License.
31
31
 
32
32
  /** Options object for `FetchHttpApi.requestOtherUrl`. */
33
33
 
34
- export var HttpApiEvent = /*#__PURE__*/function (HttpApiEvent) {
34
+ export let HttpApiEvent = /*#__PURE__*/function (HttpApiEvent) {
35
35
  HttpApiEvent["SessionLoggedOut"] = "Session.logged_out";
36
36
  HttpApiEvent["NoConsent"] = "no_consent";
37
37
  return HttpApiEvent;
@@ -1 +1 @@
1
- {"version":3,"file":"interface.js","names":["HttpApiEvent"],"sources":["../../src/http-api/interface.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type MatrixError } from \"./errors.ts\";\nimport { type Logger } from \"../logger.ts\";\nimport { type QueryDict } from \"../utils.ts\";\n\nexport type Body = Record<string, any> | BodyInit;\n\n/**\n * @experimental\n * Unencrypted access and (optional) refresh token\n */\nexport type AccessTokens = {\n /**\n * The new access token to use for authenticated requests\n */\n accessToken: string;\n /**\n * The new refresh token to use for refreshing tokens, optional\n */\n refreshToken?: string;\n /**\n * Approximate date when the access token will expire, optional\n */\n expiry?: Date;\n};\n\n/**\n * @experimental\n * Function that performs token refresh using the given refreshToken.\n * Returns a promise that resolves to the refreshed access and (optional) refresh tokens.\n *\n * Can be passed to HttpApi instance as {@link IHttpOpts.tokenRefreshFunction} during client creation {@link ICreateClientOpts}\n */\nexport type TokenRefreshFunction = (refreshToken: string) => Promise<AccessTokens>;\n\n/** Options object for `FetchHttpApi` and {@link MatrixHttpApi}. */\nexport interface IHttpOpts {\n fetchFn?: typeof globalThis.fetch;\n\n baseUrl: string;\n idBaseUrl?: string;\n prefix: string;\n extraParams?: QueryDict;\n\n accessToken?: string;\n /**\n * Used in conjunction with tokenRefreshFunction to attempt token refresh\n */\n refreshToken?: string;\n /**\n * Function to attempt token refresh when a possibly expired token is encountered\n * Optional, only called when a refreshToken is present\n */\n tokenRefreshFunction?: TokenRefreshFunction;\n\n /**\n * Whether to use the HTTP Authorization header over the `access_token` query parameter\n * @deprecated as of v1.11 in https://spec.matrix.org/v1.17/client-server-api/#using-access-tokens\n */\n useAuthorizationHeader?: boolean; // defaults to true\n\n /** For historical reasons, must be set to `true`. Will eventually be removed. */\n onlyData?: boolean;\n\n localTimeoutMs?: number;\n\n /** Optional logger instance. If provided, requests and responses will be logged. */\n logger?: Logger;\n}\n\n/** Options object for `FetchHttpApi.requestOtherUrl`. */\nexport interface BaseRequestOpts extends Pick<RequestInit, \"priority\"> {\n /**\n * map of additional request headers\n */\n headers?: Record<string, string>;\n abortSignal?: AbortSignal;\n /**\n * The maximum amount of time to wait before\n * timing out the request. If not specified, there is no timeout.\n */\n localTimeoutMs?: number;\n keepAlive?: boolean; // defaults to false\n\n /**\n * By default, we will:\n *\n * * If the `body` is an object, JSON-encode it and set `Content-Type: application/json` in the\n * request headers (unless overridden by {@link headers}).\n *\n * * Set `Accept: application/json` in the request headers (again, unless overridden by {@link headers}).\n *\n * * Parse the response as JSON and return the parsed response.\n *\n * Setting this to `false` inhibits all three behaviors, and the response is instead parsed as a UTF-8 string. It\n * defaults to `true`, unless {@link rawResponseBody} is set.\n *\n * @deprecated Instead of setting this to `false`, set {@link rawResponseBody} to `true`.\n */\n json?: boolean;\n\n /**\n * Setting this to `true` does two things:\n *\n * * Inhibits the automatic addition of `Accept: application/json` in the request headers.\n *\n * * Causes the raw response to be returned as a {@link https://developer.mozilla.org/en-US/docs/Web/API/Blob|Blob}\n * instead of parsing it as JSON.\n */\n rawResponseBody?: boolean;\n}\n\nexport interface IRequestOpts extends BaseRequestOpts {\n /**\n * The alternative base url to use.\n * If not specified, uses this.opts.baseUrl\n */\n baseUrl?: string;\n /**\n * The full prefix to use e.g.\n * \"/_matrix/client/v2_alpha\". If not specified, uses this.opts.prefix.\n */\n prefix?: string;\n\n // Set to true to prevent the request function from emitting a Session.logged_out event.\n // This is intended for use on endpoints where M_UNKNOWN_TOKEN is a valid/notable error response,\n // such as with token refreshes.\n inhibitLogoutEmit?: boolean;\n}\n\nexport interface IContentUri {\n base: string;\n path: string;\n params: {\n // eslint-disable-next-line camelcase\n access_token: string;\n };\n}\n\nexport enum HttpApiEvent {\n SessionLoggedOut = \"Session.logged_out\",\n NoConsent = \"no_consent\",\n}\n\nexport type HttpApiEventHandlerMap = {\n /**\n * Fires whenever the login session the JS SDK is using is no\n * longer valid and the user must log in again.\n * NB. This only fires when action is required from the user, not\n * when then login session can be renewed by using a refresh token.\n * @example\n * ```\n * matrixClient.on(\"Session.logged_out\", function(errorObj){\n * // show the login screen\n * });\n * ```\n */\n [HttpApiEvent.SessionLoggedOut]: (err: MatrixError) => void;\n /**\n * Fires when the JS SDK receives a M_CONSENT_NOT_GIVEN error in response\n * to a HTTP request.\n * @example\n * ```\n * matrixClient.on(\"no_consent\", function(message, contentUri) {\n * console.info(message + ' Go to ' + contentUri);\n * });\n * ```\n */\n [HttpApiEvent.NoConsent]: (message: string, consentUri: string) => void;\n};\n\nexport interface UploadProgress {\n loaded: number;\n total: number;\n}\n\nexport interface UploadOpts {\n /**\n * Name to give the file on the server. Defaults to <tt>file.name</tt>.\n */\n name?: string;\n /**\n * Content-type for the upload. Defaults to\n * <tt>file.type</tt>, or <tt>applicaton/octet-stream</tt>.\n */\n type?: string;\n /**\n * if false will not send the filename,\n * e.g for encrypted file uploads where filename leaks are undesirable.\n * Defaults to true.\n */\n includeFilename?: boolean;\n /**\n * Optional. Called when a chunk of\n * data has been uploaded, with an object containing the fields `loaded`\n * (number of bytes transferred) and `total` (total size, if known).\n */\n progressHandler?(progress: UploadProgress): void;\n abortController?: AbortController;\n}\n\nexport interface Upload {\n loaded: number;\n total: number;\n promise: Promise<UploadResponse>;\n abortController: AbortController;\n}\n\nexport interface UploadResponse {\n // eslint-disable-next-line camelcase\n content_uri: string;\n}\n\nexport type FileType = XMLHttpRequestBodyInit;\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAQA;AACA;AACA;AACA;;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;;AAmCA;;AAqEA,WAAYA,YAAY,0BAAZA,YAAY;EAAZA,YAAY;EAAZA,YAAY;EAAA,OAAZA,YAAY;AAAA","ignoreList":[]}
1
+ {"version":3,"file":"interface.js","names":[],"sources":["../../src/http-api/interface.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type MatrixError } from \"./errors.ts\";\nimport { type Logger } from \"../logger.ts\";\nimport { type QueryDict } from \"../utils.ts\";\n\nexport type Body = Record<string, any> | BodyInit;\n\n/**\n * @experimental\n * Unencrypted access and (optional) refresh token\n */\nexport type AccessTokens = {\n /**\n * The new access token to use for authenticated requests\n */\n accessToken: string;\n /**\n * The new refresh token to use for refreshing tokens, optional\n */\n refreshToken?: string;\n /**\n * Approximate date when the access token will expire, optional\n */\n expiry?: Date;\n};\n\n/**\n * @experimental\n * Function that performs token refresh using the given refreshToken.\n * Returns a promise that resolves to the refreshed access and (optional) refresh tokens.\n *\n * Can be passed to HttpApi instance as {@link IHttpOpts.tokenRefreshFunction} during client creation {@link ICreateClientOpts}\n */\nexport type TokenRefreshFunction = (refreshToken: string) => Promise<AccessTokens>;\n\n/** Options object for `FetchHttpApi` and {@link MatrixHttpApi}. */\nexport interface IHttpOpts {\n fetchFn?: typeof globalThis.fetch;\n\n baseUrl: string;\n idBaseUrl?: string;\n prefix: string;\n extraParams?: QueryDict;\n\n accessToken?: string;\n /**\n * Used in conjunction with tokenRefreshFunction to attempt token refresh\n */\n refreshToken?: string;\n /**\n * Function to attempt token refresh when a possibly expired token is encountered\n * Optional, only called when a refreshToken is present\n */\n tokenRefreshFunction?: TokenRefreshFunction;\n\n /**\n * Whether to use the HTTP Authorization header over the `access_token` query parameter\n * @deprecated as of v1.11 in https://spec.matrix.org/v1.17/client-server-api/#using-access-tokens\n */\n useAuthorizationHeader?: boolean; // defaults to true\n\n /** For historical reasons, must be set to `true`. Will eventually be removed. */\n onlyData?: boolean;\n\n localTimeoutMs?: number;\n\n /** Optional logger instance. If provided, requests and responses will be logged. */\n logger?: Logger;\n}\n\n/** Options object for `FetchHttpApi.requestOtherUrl`. */\nexport interface BaseRequestOpts extends Pick<RequestInit, \"priority\"> {\n /**\n * map of additional request headers\n */\n headers?: Record<string, string>;\n abortSignal?: AbortSignal;\n /**\n * The maximum amount of time to wait before\n * timing out the request. If not specified, there is no timeout.\n */\n localTimeoutMs?: number;\n keepAlive?: boolean; // defaults to false\n\n /**\n * By default, we will:\n *\n * * If the `body` is an object, JSON-encode it and set `Content-Type: application/json` in the\n * request headers (unless overridden by {@link headers}).\n *\n * * Set `Accept: application/json` in the request headers (again, unless overridden by {@link headers}).\n *\n * * Parse the response as JSON and return the parsed response.\n *\n * Setting this to `false` inhibits all three behaviors, and the response is instead parsed as a UTF-8 string. It\n * defaults to `true`, unless {@link rawResponseBody} is set.\n *\n * @deprecated Instead of setting this to `false`, set {@link rawResponseBody} to `true`.\n */\n json?: boolean;\n\n /**\n * Setting this to `true` does two things:\n *\n * * Inhibits the automatic addition of `Accept: application/json` in the request headers.\n *\n * * Causes the raw response to be returned as a {@link https://developer.mozilla.org/en-US/docs/Web/API/Blob|Blob}\n * instead of parsing it as JSON.\n */\n rawResponseBody?: boolean;\n}\n\nexport interface IRequestOpts extends BaseRequestOpts {\n /**\n * The alternative base url to use.\n * If not specified, uses this.opts.baseUrl\n */\n baseUrl?: string;\n /**\n * The full prefix to use e.g.\n * \"/_matrix/client/v2_alpha\". If not specified, uses this.opts.prefix.\n */\n prefix?: string;\n\n // Set to true to prevent the request function from emitting a Session.logged_out event.\n // This is intended for use on endpoints where M_UNKNOWN_TOKEN is a valid/notable error response,\n // such as with token refreshes.\n inhibitLogoutEmit?: boolean;\n}\n\nexport interface IContentUri {\n base: string;\n path: string;\n params: {\n // eslint-disable-next-line camelcase\n access_token: string;\n };\n}\n\nexport enum HttpApiEvent {\n SessionLoggedOut = \"Session.logged_out\",\n NoConsent = \"no_consent\",\n}\n\nexport type HttpApiEventHandlerMap = {\n /**\n * Fires whenever the login session the JS SDK is using is no\n * longer valid and the user must log in again.\n * NB. This only fires when action is required from the user, not\n * when then login session can be renewed by using a refresh token.\n * @example\n * ```\n * matrixClient.on(\"Session.logged_out\", function(errorObj){\n * // show the login screen\n * });\n * ```\n */\n [HttpApiEvent.SessionLoggedOut]: (err: MatrixError) => void;\n /**\n * Fires when the JS SDK receives a M_CONSENT_NOT_GIVEN error in response\n * to a HTTP request.\n * @example\n * ```\n * matrixClient.on(\"no_consent\", function(message, contentUri) {\n * console.info(message + ' Go to ' + contentUri);\n * });\n * ```\n */\n [HttpApiEvent.NoConsent]: (message: string, consentUri: string) => void;\n};\n\nexport interface UploadProgress {\n loaded: number;\n total: number;\n}\n\nexport interface UploadOpts {\n /**\n * Name to give the file on the server. Defaults to <tt>file.name</tt>.\n */\n name?: string;\n /**\n * Content-type for the upload. Defaults to\n * <tt>file.type</tt>, or <tt>applicaton/octet-stream</tt>.\n */\n type?: string;\n /**\n * if false will not send the filename,\n * e.g for encrypted file uploads where filename leaks are undesirable.\n * Defaults to true.\n */\n includeFilename?: boolean;\n /**\n * Optional. Called when a chunk of\n * data has been uploaded, with an object containing the fields `loaded`\n * (number of bytes transferred) and `total` (total size, if known).\n */\n progressHandler?(progress: UploadProgress): void;\n abortController?: AbortController;\n}\n\nexport interface Upload {\n loaded: number;\n total: number;\n promise: Promise<UploadResponse>;\n abortController: AbortController;\n}\n\nexport interface UploadResponse {\n // eslint-disable-next-line camelcase\n content_uri: string;\n}\n\nexport type FileType = XMLHttpRequestBodyInit;\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAQA;AACA;AACA;AACA;;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;;AAmCA;;AAqEA,WAAY,YAAY,0BAAZ,YAAY;EAAZ,YAAY;EAAZ,YAAY;EAAA,OAAZ,YAAY;AAAA","ignoreList":[]}
@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- export var Method = /*#__PURE__*/function (Method) {
17
+ export let Method = /*#__PURE__*/function (Method) {
18
18
  Method["Get"] = "GET";
19
19
  Method["Put"] = "PUT";
20
20
  Method["Post"] = "POST";
@@ -1 +1 @@
1
- {"version":3,"file":"method.js","names":["Method"],"sources":["../../src/http-api/method.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport enum Method {\n Get = \"GET\",\n Put = \"PUT\",\n Post = \"POST\",\n Delete = \"DELETE\",\n Options = \"OPTIONS\",\n Head = \"HEAD\",\n Patch = \"PATCH\",\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,WAAYA,MAAM,0BAANA,MAAM;EAANA,MAAM;EAANA,MAAM;EAANA,MAAM;EAANA,MAAM;EAANA,MAAM;EAANA,MAAM;EAANA,MAAM;EAAA,OAANA,MAAM;AAAA","ignoreList":[]}
1
+ {"version":3,"file":"method.js","names":[],"sources":["../../src/http-api/method.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport enum Method {\n Get = \"GET\",\n Put = \"PUT\",\n Post = \"POST\",\n Delete = \"DELETE\",\n Options = \"OPTIONS\",\n Head = \"HEAD\",\n Patch = \"PATCH\",\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,WAAY,MAAM,0BAAN,MAAM;EAAN,MAAM;EAAN,MAAM;EAAN,MAAM;EAAN,MAAM;EAAN,MAAM;EAAN,MAAM;EAAN,MAAM;EAAA,OAAN,MAAM;AAAA","ignoreList":[]}
@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- export var ClientPrefix = /*#__PURE__*/function (ClientPrefix) {
17
+ export let ClientPrefix = /*#__PURE__*/function (ClientPrefix) {
18
18
  /**
19
19
  * A constant representing the URI path for Client-Server API endpoints versioned at v1.
20
20
  */
@@ -29,14 +29,14 @@ export var ClientPrefix = /*#__PURE__*/function (ClientPrefix) {
29
29
  ClientPrefix["Unstable"] = "/_matrix/client/unstable";
30
30
  return ClientPrefix;
31
31
  }({});
32
- export var IdentityPrefix = /*#__PURE__*/function (IdentityPrefix) {
32
+ export let IdentityPrefix = /*#__PURE__*/function (IdentityPrefix) {
33
33
  /**
34
34
  * URI path for the v2 identity API
35
35
  */
36
36
  IdentityPrefix["V2"] = "/_matrix/identity/v2";
37
37
  return IdentityPrefix;
38
38
  }({});
39
- export var MediaPrefix = /*#__PURE__*/function (MediaPrefix) {
39
+ export let MediaPrefix = /*#__PURE__*/function (MediaPrefix) {
40
40
  /**
41
41
  * A constant representing the URI path for Client-Server API Media endpoints versioned at v1.
42
42
  */
@@ -1 +1 @@
1
- {"version":3,"file":"prefix.js","names":["ClientPrefix","IdentityPrefix","MediaPrefix"],"sources":["../../src/http-api/prefix.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport enum ClientPrefix {\n /**\n * A constant representing the URI path for Client-Server API endpoints versioned at v1.\n */\n V1 = \"/_matrix/client/v1\",\n /**\n * A constant representing the URI path for Client-Server API endpoints versioned at v3.\n */\n V3 = \"/_matrix/client/v3\",\n /**\n * A constant representing the URI path for as-yet unspecified Client-Server HTTP APIs.\n */\n Unstable = \"/_matrix/client/unstable\",\n}\n\nexport enum IdentityPrefix {\n /**\n * URI path for the v2 identity API\n */\n V2 = \"/_matrix/identity/v2\",\n}\n\nexport enum MediaPrefix {\n /**\n * A constant representing the URI path for Client-Server API Media endpoints versioned at v1.\n */\n V1 = \"/_matrix/media/v1\",\n /**\n * A constant representing the URI path for Client-Server API Media endpoints versioned at v3.\n */\n V3 = \"/_matrix/media/v3\",\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,WAAYA,YAAY,0BAAZA,YAAY;EACpB;AACJ;AACA;EAHYA,YAAY;EAKpB;AACJ;AACA;EAPYA,YAAY;EASpB;AACJ;AACA;EAXYA,YAAY;EAAA,OAAZA,YAAY;AAAA;AAexB,WAAYC,cAAc,0BAAdA,cAAc;EACtB;AACJ;AACA;EAHYA,cAAc;EAAA,OAAdA,cAAc;AAAA;AAO1B,WAAYC,WAAW,0BAAXA,WAAW;EACnB;AACJ;AACA;EAHYA,WAAW;EAKnB;AACJ;AACA;EAPYA,WAAW;EAAA,OAAXA,WAAW;AAAA","ignoreList":[]}
1
+ {"version":3,"file":"prefix.js","names":[],"sources":["../../src/http-api/prefix.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport enum ClientPrefix {\n /**\n * A constant representing the URI path for Client-Server API endpoints versioned at v1.\n */\n V1 = \"/_matrix/client/v1\",\n /**\n * A constant representing the URI path for Client-Server API endpoints versioned at v3.\n */\n V3 = \"/_matrix/client/v3\",\n /**\n * A constant representing the URI path for as-yet unspecified Client-Server HTTP APIs.\n */\n Unstable = \"/_matrix/client/unstable\",\n}\n\nexport enum IdentityPrefix {\n /**\n * URI path for the v2 identity API\n */\n V2 = \"/_matrix/identity/v2\",\n}\n\nexport enum MediaPrefix {\n /**\n * A constant representing the URI path for Client-Server API Media endpoints versioned at v1.\n */\n V1 = \"/_matrix/media/v1\",\n /**\n * A constant representing the URI path for Client-Server API Media endpoints versioned at v3.\n */\n V3 = \"/_matrix/media/v3\",\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,WAAY,YAAY,0BAAZ,YAAY;EACpB;AACJ;AACA;EAHY,YAAY;EAKpB;AACJ;AACA;EAPY,YAAY;EASpB;AACJ;AACA;EAXY,YAAY;EAAA,OAAZ,YAAY;AAAA;AAexB,WAAY,cAAc,0BAAd,cAAc;EACtB;AACJ;AACA;EAHY,cAAc;EAAA,OAAd,cAAc;AAAA;AAO1B,WAAY,WAAW,0BAAX,WAAW;EACnB;AACJ;AACA;EAHY,WAAW;EAKnB;AACJ;AACA;EAPY,WAAW;EAAA,OAAX,WAAW;AAAA","ignoreList":[]}
@@ -1,4 +1,3 @@
1
- import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
2
1
  import _defineProperty from "@babel/runtime/helpers/defineProperty";
3
2
  /*
4
3
  Copyright 2025 The Matrix.org Foundation C.I.C.
@@ -23,61 +22,55 @@ import { sleep } from "../utils.js";
23
22
  * This is an internal module. See {@link MatrixHttpApi} for the public class.
24
23
  */
25
24
 
26
- export var TokenRefreshOutcome = /*#__PURE__*/function (TokenRefreshOutcome) {
25
+ export let TokenRefreshOutcome = /*#__PURE__*/function (TokenRefreshOutcome) {
27
26
  TokenRefreshOutcome["Success"] = "success";
28
27
  TokenRefreshOutcome["Failure"] = "failure";
29
28
  TokenRefreshOutcome["Logout"] = "logout";
30
29
  return TokenRefreshOutcome;
31
30
  }({});
32
31
  // If the token expires in less than this time amount of time, we will eagerly refresh it before making the intended request.
33
- var REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS = 500;
32
+ const REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS = 500;
34
33
  // If we get an unknown token error and the token expires in less than this time amount of time, we will refresh it before making the intended request.
35
34
  // Otherwise, we will error as the token should not have expired yet and we need to avoid retrying indefinitely.
36
- var REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS = 60 * 1000;
35
+ const REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS = 60 * 1000;
37
36
  /**
38
37
  * This class is responsible for managing the access token and refresh token for authenticated requests.
39
38
  * It will automatically refresh the access token when it is about to expire, and will handle unknown token errors.
40
39
  */
41
40
  export class TokenRefresher {
42
41
  constructor(opts) {
43
- this.opts = opts;
44
42
  /**
45
43
  * Promise used to block authenticated requests during a token refresh to avoid repeated expected errors.
46
44
  * @private
47
45
  */
48
46
  _defineProperty(this, "tokenRefreshPromise", void 0);
49
47
  _defineProperty(this, "latestTokenRefreshExpiry", void 0);
48
+ this.opts = opts;
50
49
  }
51
50
  /**
52
51
  * This function is called before every request to ensure that the access token is valid.
53
52
  * @returns a snapshot containing the access token and other properties which must be passed to the handleUnknownToken
54
53
  * handler if an M_UNKNOWN_TOKEN error is encountered.
55
54
  */
56
- prepareForRequest() {
57
- var _this = this;
58
- return _asyncToGenerator(function* () {
59
- // Ensure our token is refreshed before we build the headers/params
60
- yield _this.refreshIfNeeded();
61
- return {
62
- accessToken: _this.opts.accessToken,
63
- refreshToken: _this.opts.refreshToken,
64
- expiry: _this.latestTokenRefreshExpiry
65
- };
66
- })();
55
+ async prepareForRequest() {
56
+ // Ensure our token is refreshed before we build the headers/params
57
+ await this.refreshIfNeeded();
58
+ return {
59
+ accessToken: this.opts.accessToken,
60
+ refreshToken: this.opts.refreshToken,
61
+ expiry: this.latestTokenRefreshExpiry
62
+ };
67
63
  }
68
- refreshIfNeeded() {
69
- var _this2 = this;
70
- return _asyncToGenerator(function* () {
71
- if (_this2.tokenRefreshPromise) {
72
- return _this2.tokenRefreshPromise;
73
- }
74
- // If we don't know the token expiry, we can't eagerly refresh
75
- if (!_this2.latestTokenRefreshExpiry) return;
76
- var expiresIn = _this2.latestTokenRefreshExpiry.getTime() - Date.now();
77
- if (expiresIn <= REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS) {
78
- yield _this2._handleUnknownToken();
79
- }
80
- })();
64
+ async refreshIfNeeded() {
65
+ if (this.tokenRefreshPromise) {
66
+ return this.tokenRefreshPromise;
67
+ }
68
+ // If we don't know the token expiry, we can't eagerly refresh
69
+ if (!this.latestTokenRefreshExpiry) return;
70
+ const expiresIn = this.latestTokenRefreshExpiry.getTime() - Date.now();
71
+ if (expiresIn <= REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS) {
72
+ await this._handleUnknownToken();
73
+ }
81
74
  }
82
75
 
83
76
  /**
@@ -87,42 +80,35 @@ export class TokenRefresher {
87
80
  * @param attempt - the number of attempts made for this request so far
88
81
  * @returns a TokenRefreshOutcome indicating the result of the refresh attempt
89
82
  */
90
- handleUnknownToken(snapshot, attempt) {
91
- var _this3 = this;
92
- return _asyncToGenerator(function* () {
93
- return _this3._handleUnknownToken(snapshot, attempt);
94
- })();
83
+ async handleUnknownToken(snapshot, attempt) {
84
+ return this._handleUnknownToken(snapshot, attempt);
95
85
  }
96
86
 
97
87
  /* eslint-disable @typescript-eslint/naming-convention */
98
88
 
99
- _handleUnknownToken(snapshot, attempt) {
100
- var _this4 = this;
101
- return _asyncToGenerator(function* () {
102
- if (snapshot !== null && snapshot !== void 0 && snapshot.expiry) {
103
- // If our token is unknown, but it should not have expired yet, then we should not refresh
104
- var expiresIn = snapshot.expiry.getTime() - Date.now();
105
- // If it still has plenty of time left on the clock, we assume something else must be wrong and
106
- // do not refresh. Otherwise if it's expired, or will soon, we try refreshing.
107
- if (expiresIn >= REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS) {
108
- return TokenRefreshOutcome.Logout;
109
- }
89
+ async _handleUnknownToken(snapshot, attempt) {
90
+ if (snapshot?.expiry) {
91
+ // If our token is unknown, but it should not have expired yet, then we should not refresh
92
+ const expiresIn = snapshot.expiry.getTime() - Date.now();
93
+ // If it still has plenty of time left on the clock, we assume something else must be wrong and
94
+ // do not refresh. Otherwise if it's expired, or will soon, we try refreshing.
95
+ if (expiresIn >= REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS) {
96
+ return TokenRefreshOutcome.Logout;
110
97
  }
111
- if (!snapshot || (snapshot === null || snapshot === void 0 ? void 0 : snapshot.accessToken) === _this4.opts.accessToken) {
112
- var _this4$tokenRefreshPr;
113
- // If we have a snapshot, but the access token is the same as the current one then a refresh
114
- // did not happen behind us but one may be ongoing anyway
115
- (_this4$tokenRefreshPr = _this4.tokenRefreshPromise) !== null && _this4$tokenRefreshPr !== void 0 ? _this4$tokenRefreshPr : _this4.tokenRefreshPromise = _this4.doTokenRefresh(attempt);
116
- try {
117
- return yield _this4.tokenRefreshPromise;
118
- } finally {
119
- _this4.tokenRefreshPromise = undefined;
120
- }
98
+ }
99
+ if (!snapshot || snapshot?.accessToken === this.opts.accessToken) {
100
+ // If we have a snapshot, but the access token is the same as the current one then a refresh
101
+ // did not happen behind us but one may be ongoing anyway
102
+ this.tokenRefreshPromise ??= this.doTokenRefresh(attempt);
103
+ try {
104
+ return await this.tokenRefreshPromise;
105
+ } finally {
106
+ this.tokenRefreshPromise = undefined;
121
107
  }
108
+ }
122
109
 
123
- // We may end up here if the token was refreshed in the background due to another request
124
- return TokenRefreshOutcome.Success;
125
- })();
110
+ // We may end up here if the token was refreshed in the background due to another request
111
+ return TokenRefreshOutcome.Success;
126
112
  }
127
113
 
128
114
  /**
@@ -130,44 +116,38 @@ export class TokenRefresher {
130
116
  * On success, sets new access and refresh tokens in opts.
131
117
  * @returns Promise that resolves to a boolean - true when token was refreshed successfully
132
118
  */
133
- doTokenRefresh(attempt) {
134
- var _this5 = this;
135
- return _asyncToGenerator(function* () {
136
- if (!_this5.opts.refreshToken || !_this5.opts.tokenRefreshFunction) {
137
- var _this5$opts$logger;
138
- (_this5$opts$logger = _this5.opts.logger) === null || _this5$opts$logger === void 0 || _this5$opts$logger.error("Unable to refresh token - no refresh token or refresh function");
139
- return TokenRefreshOutcome.Logout;
140
- }
141
- if (attempt && attempt > 1) {
142
- // Exponential backoff to ensure we don't trash the server, up to 2^5 seconds
143
- yield sleep(1000 * Math.min(32, 2 ** attempt));
144
- }
145
- try {
146
- var _this5$opts$logger2, _this5$opts$logger3;
147
- (_this5$opts$logger2 = _this5.opts.logger) === null || _this5$opts$logger2 === void 0 || _this5$opts$logger2.debug("Attempting to refresh token");
148
- var _yield$_this5$opts$to = yield _this5.opts.tokenRefreshFunction(_this5.opts.refreshToken),
149
- accessToken = _yield$_this5$opts$to.accessToken,
150
- refreshToken = _yield$_this5$opts$to.refreshToken,
151
- expiry = _yield$_this5$opts$to.expiry;
152
- _this5.opts.accessToken = accessToken;
153
- _this5.opts.refreshToken = refreshToken;
154
- _this5.latestTokenRefreshExpiry = expiry;
155
- (_this5$opts$logger3 = _this5.opts.logger) === null || _this5$opts$logger3 === void 0 || _this5$opts$logger3.debug("... token refresh complete, new token expiry:", expiry);
119
+ async doTokenRefresh(attempt) {
120
+ if (!this.opts.refreshToken || !this.opts.tokenRefreshFunction) {
121
+ this.opts.logger?.error("Unable to refresh token - no refresh token or refresh function");
122
+ return TokenRefreshOutcome.Logout;
123
+ }
124
+ if (attempt && attempt > 1) {
125
+ // Exponential backoff to ensure we don't trash the server, up to 2^5 seconds
126
+ await sleep(1000 * Math.min(32, 2 ** attempt));
127
+ }
128
+ try {
129
+ this.opts.logger?.debug("Attempting to refresh token");
130
+ const {
131
+ accessToken,
132
+ refreshToken,
133
+ expiry
134
+ } = await this.opts.tokenRefreshFunction(this.opts.refreshToken);
135
+ this.opts.accessToken = accessToken;
136
+ this.opts.refreshToken = refreshToken;
137
+ this.latestTokenRefreshExpiry = expiry;
138
+ this.opts.logger?.debug("... token refresh complete, new token expiry:", expiry);
156
139
 
157
- // successfully got new tokens
158
- return TokenRefreshOutcome.Success;
159
- } catch (error) {
160
- var _this5$opts$logger5;
161
- // If we get a TokenError or MatrixError, we should log out, otherwise assume transient
162
- if (error instanceof TokenRefreshLogoutError || error instanceof MatrixError) {
163
- var _this5$opts$logger4;
164
- (_this5$opts$logger4 = _this5.opts.logger) === null || _this5$opts$logger4 === void 0 || _this5$opts$logger4.error("Failed to refresh token", error);
165
- return TokenRefreshOutcome.Logout;
166
- }
167
- (_this5$opts$logger5 = _this5.opts.logger) === null || _this5$opts$logger5 === void 0 || _this5$opts$logger5.warn("Failed to refresh token", error);
168
- return TokenRefreshOutcome.Failure;
140
+ // successfully got new tokens
141
+ return TokenRefreshOutcome.Success;
142
+ } catch (error) {
143
+ // If we get a TokenError or MatrixError, we should log out, otherwise assume transient
144
+ if (error instanceof TokenRefreshLogoutError || error instanceof MatrixError) {
145
+ this.opts.logger?.error("Failed to refresh token", error);
146
+ return TokenRefreshOutcome.Logout;
169
147
  }
170
- })();
148
+ this.opts.logger?.warn("Failed to refresh token", error);
149
+ return TokenRefreshOutcome.Failure;
150
+ }
171
151
  }
172
152
  }
173
153
  //# sourceMappingURL=refresh.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"refresh.js","names":["MatrixError","TokenRefreshLogoutError","sleep","TokenRefreshOutcome","REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS","REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS","TokenRefresher","constructor","opts","_defineProperty","prepareForRequest","_this","_asyncToGenerator","refreshIfNeeded","accessToken","refreshToken","expiry","latestTokenRefreshExpiry","_this2","tokenRefreshPromise","expiresIn","getTime","Date","now","_handleUnknownToken","handleUnknownToken","snapshot","attempt","_this3","_this4","Logout","_this4$tokenRefreshPr","doTokenRefresh","undefined","Success","_this5","tokenRefreshFunction","_this5$opts$logger","logger","error","Math","min","_this5$opts$logger2","_this5$opts$logger3","debug","_yield$_this5$opts$to","_this5$opts$logger5","_this5$opts$logger4","warn","Failure"],"sources":["../../src/http-api/refresh.ts"],"sourcesContent":["/*\nCopyright 2025 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixError, TokenRefreshLogoutError } from \"./errors.ts\";\nimport { type IHttpOpts } from \"./interface.ts\";\nimport { sleep } from \"../utils.ts\";\n\n/**\n * This is an internal module. See {@link MatrixHttpApi} for the public class.\n */\n\nexport const enum TokenRefreshOutcome {\n Success = \"success\",\n Failure = \"failure\",\n Logout = \"logout\",\n}\n\ninterface Snapshot {\n accessToken: string;\n refreshToken?: string;\n expiry?: Date;\n}\n\n// If the token expires in less than this time amount of time, we will eagerly refresh it before making the intended request.\nconst REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS = 500;\n// If we get an unknown token error and the token expires in less than this time amount of time, we will refresh it before making the intended request.\n// Otherwise, we will error as the token should not have expired yet and we need to avoid retrying indefinitely.\nconst REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS = 60 * 1000;\n\ntype Opts = Pick<IHttpOpts, \"tokenRefreshFunction\" | \"logger\" | \"refreshToken\" | \"accessToken\">;\n\n/**\n * This class is responsible for managing the access token and refresh token for authenticated requests.\n * It will automatically refresh the access token when it is about to expire, and will handle unknown token errors.\n */\nexport class TokenRefresher {\n public constructor(private readonly opts: Opts) {}\n\n /**\n * Promise used to block authenticated requests during a token refresh to avoid repeated expected errors.\n * @private\n */\n private tokenRefreshPromise?: Promise<TokenRefreshOutcome>;\n\n private latestTokenRefreshExpiry?: Date;\n\n /**\n * This function is called before every request to ensure that the access token is valid.\n * @returns a snapshot containing the access token and other properties which must be passed to the handleUnknownToken\n * handler if an M_UNKNOWN_TOKEN error is encountered.\n */\n public async prepareForRequest(): Promise<Snapshot> {\n // Ensure our token is refreshed before we build the headers/params\n await this.refreshIfNeeded();\n\n return {\n accessToken: this.opts.accessToken!,\n refreshToken: this.opts.refreshToken,\n expiry: this.latestTokenRefreshExpiry,\n };\n }\n\n private async refreshIfNeeded(): Promise<unknown> {\n if (this.tokenRefreshPromise) {\n return this.tokenRefreshPromise;\n }\n // If we don't know the token expiry, we can't eagerly refresh\n if (!this.latestTokenRefreshExpiry) return;\n\n const expiresIn = this.latestTokenRefreshExpiry.getTime() - Date.now();\n if (expiresIn <= REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS) {\n await this._handleUnknownToken();\n }\n }\n\n /**\n * This function is called when an M_UNKNOWN_TOKEN error is encountered.\n * It will attempt to refresh the access token if it is unknown, and will return a TokenRefreshOutcome.\n * @param snapshot - the snapshot returned by prepareForRequest\n * @param attempt - the number of attempts made for this request so far\n * @returns a TokenRefreshOutcome indicating the result of the refresh attempt\n */\n public async handleUnknownToken(snapshot: Snapshot, attempt: number): Promise<TokenRefreshOutcome> {\n return this._handleUnknownToken(snapshot, attempt);\n }\n\n /* eslint-disable @typescript-eslint/naming-convention */\n private async _handleUnknownToken(): Promise<TokenRefreshOutcome>;\n private async _handleUnknownToken(snapshot: Snapshot, attempt: number): Promise<TokenRefreshOutcome>;\n private async _handleUnknownToken(snapshot?: Snapshot, attempt?: number): Promise<TokenRefreshOutcome> {\n if (snapshot?.expiry) {\n // If our token is unknown, but it should not have expired yet, then we should not refresh\n const expiresIn = snapshot.expiry.getTime() - Date.now();\n // If it still has plenty of time left on the clock, we assume something else must be wrong and\n // do not refresh. Otherwise if it's expired, or will soon, we try refreshing.\n if (expiresIn >= REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS) {\n return TokenRefreshOutcome.Logout;\n }\n }\n\n if (!snapshot || snapshot?.accessToken === this.opts.accessToken) {\n // If we have a snapshot, but the access token is the same as the current one then a refresh\n // did not happen behind us but one may be ongoing anyway\n this.tokenRefreshPromise ??= this.doTokenRefresh(attempt);\n\n try {\n return await this.tokenRefreshPromise;\n } finally {\n this.tokenRefreshPromise = undefined;\n }\n }\n\n // We may end up here if the token was refreshed in the background due to another request\n return TokenRefreshOutcome.Success;\n }\n\n /**\n * Attempt to refresh access tokens.\n * On success, sets new access and refresh tokens in opts.\n * @returns Promise that resolves to a boolean - true when token was refreshed successfully\n */\n private async doTokenRefresh(attempt?: number): Promise<TokenRefreshOutcome> {\n if (!this.opts.refreshToken || !this.opts.tokenRefreshFunction) {\n this.opts.logger?.error(\"Unable to refresh token - no refresh token or refresh function\");\n return TokenRefreshOutcome.Logout;\n }\n\n if (attempt && attempt > 1) {\n // Exponential backoff to ensure we don't trash the server, up to 2^5 seconds\n await sleep(1000 * Math.min(32, 2 ** attempt));\n }\n\n try {\n this.opts.logger?.debug(\"Attempting to refresh token\");\n const { accessToken, refreshToken, expiry } = await this.opts.tokenRefreshFunction(this.opts.refreshToken);\n this.opts.accessToken = accessToken;\n this.opts.refreshToken = refreshToken;\n this.latestTokenRefreshExpiry = expiry;\n this.opts.logger?.debug(\"... token refresh complete, new token expiry:\", expiry);\n\n // successfully got new tokens\n return TokenRefreshOutcome.Success;\n } catch (error) {\n // If we get a TokenError or MatrixError, we should log out, otherwise assume transient\n if (error instanceof TokenRefreshLogoutError || error instanceof MatrixError) {\n this.opts.logger?.error(\"Failed to refresh token\", error);\n return TokenRefreshOutcome.Logout;\n }\n\n this.opts.logger?.warn(\"Failed to refresh token\", error);\n return TokenRefreshOutcome.Failure;\n }\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,WAAW,EAAEC,uBAAuB,QAAQ,aAAa;AAElE,SAASC,KAAK,QAAQ,aAAa;;AAEnC;AACA;AACA;;AAEA,WAAkBC,mBAAmB,0BAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAA,OAAnBA,mBAAmB;AAAA;AAYrC;AACA,IAAMC,kCAAkC,GAAG,GAAG;AAC9C;AACA;AACA,IAAMC,2CAA2C,GAAG,EAAE,GAAG,IAAI;AAI7D;AACA;AACA;AACA;AACA,OAAO,MAAMC,cAAc,CAAC;EACjBC,WAAWA,CAAkBC,IAAU,EAAE;IAAA,KAAZA,IAAU,GAAVA,IAAU;IAE9C;AACJ;AACA;AACA;IAHIC,eAAA;IAAAA,eAAA;EAFiD;EAUjD;AACJ;AACA;AACA;AACA;EACiBC,iBAAiBA,CAAA,EAAsB;IAAA,IAAAC,KAAA;IAAA,OAAAC,iBAAA;MAChD;MACA,MAAMD,KAAI,CAACE,eAAe,CAAC,CAAC;MAE5B,OAAO;QACHC,WAAW,EAAEH,KAAI,CAACH,IAAI,CAACM,WAAY;QACnCC,YAAY,EAAEJ,KAAI,CAACH,IAAI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C,YAAY,GAAA8B,qBAAA,CAAZ9B,YAAY;UAAEC,MAAM,GAAA6B,qBAAA,CAAN7B,MAAM;QACzCmB,MAAI,CAAC3B,IAAI,CAACM,WAAW,GAAGA,WAAW;QACnCqB,MAAI,CAAC3B,IAAI,CAACO,YAAY,GAAGA,YAAY;QACrCoB,MAAI,CAAClB,wBAAwB,GAAGD,MAAM;QACtC,CAAA2B,mBAAA,GAAAR,MAAI,CAAC3B,IAAI,CAAC8B,MAAM,cAAAK,mBAAA,eAAhBA,mBAAA,CAAkBC,KAAK,CAAC,+CAA+C,EAAE5B,MAAM,CAAC;;QAEhF;QACA,OAAOb,mBAAmB,CAAC+B,OAAO;MACtC,CAAC,CAAC,OAAOK,KAAK,EAAE;QAAA,IAAAO,mBAAA;QACZ;QACA,IAAIP,KAAK,YAAYtC,uBAAuB,IAAIsC,KAAK,YAAYvC,WAAW,EAAE;UAAA,IAAA+C,mBAAA;UAC1E,CAAAA,mBAAA,GAAAZ,MAAI,CAAC3B,IAAI,CAAC8B,MAAM,cAAAS,mBAAA,eAAhBA,mBAAA,CAAkBR,KAAK,CAAC,yBAAyB,EAAEA,KAAK,CAAC;UACzD,OAAOpC,mBAAmB,CAAC2B,MAAM;QACrC;QAEA,CAAAgB,mBAAA,GAAAX,MAAI,CAAC3B,IAAI,CAAC8B,MAAM,cAAAQ,mBAAA,eAAhBA,mBAAA,CAAkBE,IAAI,CAAC,yBAAyB,EAAET,KAAK,CAAC;QACxD,OAAOpC,mBAAmB,CAAC8C,OAAO;MACtC;IAAC;EACL;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"refresh.js","names":[],"sources":["../../src/http-api/refresh.ts"],"sourcesContent":["/*\nCopyright 2025 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixError, TokenRefreshLogoutError } from \"./errors.ts\";\nimport { type IHttpOpts } from \"./interface.ts\";\nimport { sleep } from \"../utils.ts\";\n\n/**\n * This is an internal module. See {@link MatrixHttpApi} for the public class.\n */\n\nexport const enum TokenRefreshOutcome {\n Success = \"success\",\n Failure = \"failure\",\n Logout = \"logout\",\n}\n\ninterface Snapshot {\n accessToken: string;\n refreshToken?: string;\n expiry?: Date;\n}\n\n// If the token expires in less than this time amount of time, we will eagerly refresh it before making the intended request.\nconst REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS = 500;\n// If we get an unknown token error and the token expires in less than this time amount of time, we will refresh it before making the intended request.\n// Otherwise, we will error as the token should not have expired yet and we need to avoid retrying indefinitely.\nconst REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS = 60 * 1000;\n\ntype Opts = Pick<IHttpOpts, \"tokenRefreshFunction\" | \"logger\" | \"refreshToken\" | \"accessToken\">;\n\n/**\n * This class is responsible for managing the access token and refresh token for authenticated requests.\n * It will automatically refresh the access token when it is about to expire, and will handle unknown token errors.\n */\nexport class TokenRefresher {\n public constructor(private readonly opts: Opts) {}\n\n /**\n * Promise used to block authenticated requests during a token refresh to avoid repeated expected errors.\n * @private\n */\n private tokenRefreshPromise?: Promise<TokenRefreshOutcome>;\n\n private latestTokenRefreshExpiry?: Date;\n\n /**\n * This function is called before every request to ensure that the access token is valid.\n * @returns a snapshot containing the access token and other properties which must be passed to the handleUnknownToken\n * handler if an M_UNKNOWN_TOKEN error is encountered.\n */\n public async prepareForRequest(): Promise<Snapshot> {\n // Ensure our token is refreshed before we build the headers/params\n await this.refreshIfNeeded();\n\n return {\n accessToken: this.opts.accessToken!,\n refreshToken: this.opts.refreshToken,\n expiry: this.latestTokenRefreshExpiry,\n };\n }\n\n private async refreshIfNeeded(): Promise<unknown> {\n if (this.tokenRefreshPromise) {\n return this.tokenRefreshPromise;\n }\n // If we don't know the token expiry, we can't eagerly refresh\n if (!this.latestTokenRefreshExpiry) return;\n\n const expiresIn = this.latestTokenRefreshExpiry.getTime() - Date.now();\n if (expiresIn <= REFRESH_IF_TOKEN_EXPIRES_WITHIN_MS) {\n await this._handleUnknownToken();\n }\n }\n\n /**\n * This function is called when an M_UNKNOWN_TOKEN error is encountered.\n * It will attempt to refresh the access token if it is unknown, and will return a TokenRefreshOutcome.\n * @param snapshot - the snapshot returned by prepareForRequest\n * @param attempt - the number of attempts made for this request so far\n * @returns a TokenRefreshOutcome indicating the result of the refresh attempt\n */\n public async handleUnknownToken(snapshot: Snapshot, attempt: number): Promise<TokenRefreshOutcome> {\n return this._handleUnknownToken(snapshot, attempt);\n }\n\n /* eslint-disable @typescript-eslint/naming-convention */\n private async _handleUnknownToken(): Promise<TokenRefreshOutcome>;\n private async _handleUnknownToken(snapshot: Snapshot, attempt: number): Promise<TokenRefreshOutcome>;\n private async _handleUnknownToken(snapshot?: Snapshot, attempt?: number): Promise<TokenRefreshOutcome> {\n if (snapshot?.expiry) {\n // If our token is unknown, but it should not have expired yet, then we should not refresh\n const expiresIn = snapshot.expiry.getTime() - Date.now();\n // If it still has plenty of time left on the clock, we assume something else must be wrong and\n // do not refresh. Otherwise if it's expired, or will soon, we try refreshing.\n if (expiresIn >= REFRESH_ON_ERROR_IF_TOKEN_EXPIRES_WITHIN_MS) {\n return TokenRefreshOutcome.Logout;\n }\n }\n\n if (!snapshot || snapshot?.accessToken === this.opts.accessToken) {\n // If we have a snapshot, but the access token is the same as the current one then a refresh\n // did not happen behind us but one may be ongoing anyway\n this.tokenRefreshPromise ??= this.doTokenRefresh(attempt);\n\n try {\n return await this.tokenRefreshPromise;\n } finally {\n this.tokenRefreshPromise = undefined;\n }\n }\n\n // We may end up here if the token was refreshed in the background due to another request\n return TokenRefreshOutcome.Success;\n }\n\n /**\n * Attempt to refresh access tokens.\n * On success, sets new access and refresh tokens in opts.\n * @returns Promise that resolves to a boolean - true when token was refreshed successfully\n */\n private async doTokenRefresh(attempt?: number): Promise<TokenRefreshOutcome> {\n if (!this.opts.refreshToken || !this.opts.tokenRefreshFunction) {\n this.opts.logger?.error(\"Unable to refresh token - no refresh token or refresh function\");\n return TokenRefreshOutcome.Logout;\n }\n\n if (attempt && attempt > 1) {\n // Exponential backoff to ensure we don't trash the server, up to 2^5 seconds\n await sleep(1000 * Math.min(32, 2 ** attempt));\n }\n\n try {\n this.opts.logger?.debug(\"Attempting to refresh token\");\n const { accessToken, refreshToken, expiry } = await this.opts.tokenRefreshFunction(this.opts.refreshToken);\n this.opts.accessToken = accessToken;\n this.opts.refreshToken = refreshToken;\n this.latestTokenRefreshExpiry = expiry;\n this.opts.logger?.debug(\"... token refresh complete, new token expiry:\", expiry);\n\n // successfully got new tokens\n return TokenRefreshOutcome.Success;\n } catch (error) {\n // If we get a TokenError or MatrixError, we should log out, otherwise assume transient\n if (error instanceof TokenRefreshLogoutError || error instanceof MatrixError) {\n this.opts.logger?.error(\"Failed to refresh token\", error);\n return TokenRefreshOutcome.Logout;\n }\n\n this.opts.logger?.warn(\"Failed to refresh token\", error);\n return TokenRefreshOutcome.Failure;\n }\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,WAAW,EAAE,uBAAuB,QAAQ,aAAa;AAElE,SAAS,KAAK,QAAQ,aAAa;;AAEnC;AACA;AACA;;AAEA,WAAkB,mBAAmB,0BAAnB,mBAAmB;EAAnB,mBAAmB;EAAnB,mBAAmB;EAAnB,mBAAmB;EAAA,OAAnB,mBAAmB;AAAA;AAYrC;AACA,MAAM,kCAAkC,GAAG,GAAG;AAC9C;AACA;AACA,MAAM,2CAA2C,GAAG,EAAE,GAAG,IAAI;AAI7D;AACA;AACA;AACA;AACA,OAAO,MAAM,cAAc,CAAC;EACjB,WAAW,CAAkB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Y,uBAAuB,IAAI,KAAK,YAAY,WAAW,EAAE;QAC1E,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC;QACzD,OAAO,mBAAmB,CAAC,MAAM;MACrC;MAEA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,yBAAyB,EAAE,KAAK,CAAC;MACxD,OAAO,mBAAmB,CAAC,OAAO;IACtC;EACJ;AACJ","ignoreList":[]}
@@ -1,7 +1,7 @@
1
1
  export declare function timeoutSignal(ms: number): AbortSignal;
2
2
  export declare function anySignal(signals: AbortSignal[]): {
3
3
  signal: AbortSignal;
4
- cleanup(): void;
4
+ cleanup(this: void): void;
5
5
  };
6
6
  /**
7
7
  * Attempt to turn an HTTP error response into a Javascript Error.
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/http-api/utils.ts"],"names":[],"mappings":"AA8BA,wBAAgB,aAAa,CAAC,EAAE,EAAE,MAAM,GAAG,WAAW,CAOrD;AAED,wBAAgB,SAAS,CAAC,OAAO,EAAE,WAAW,EAAE,GAAG;IAC/C,MAAM,EAAE,WAAW,CAAC;IACpB,OAAO,IAAI,IAAI,CAAC;CACnB,CA0BA;AAED;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,cAAc,GAAG,QAAQ,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,KAAK,CA2C5F;AAqBD;;;;;;GAMG;AACH,wBAAsB,qBAAqB,CAAC,CAAC,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAqB1G;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,oBAAoB,EAAE,OAAO,GAAG,MAAM,CA0BvG"}
1
+ {"version":3,"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