matrix-js-sdk 41.5.0 → 41.6.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 (204) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/lib/ReEmitter.js +1 -1
  3. package/lib/ReEmitter.js.map +1 -1
  4. package/lib/ToDeviceMessageQueue.js +2 -2
  5. package/lib/ToDeviceMessageQueue.js.map +1 -1
  6. package/lib/autodiscovery.js +0 -1
  7. package/lib/autodiscovery.js.map +1 -1
  8. package/lib/client.js +112 -165
  9. package/lib/client.js.map +1 -1
  10. package/lib/common-crypto/CryptoBackend.js +0 -2
  11. package/lib/common-crypto/CryptoBackend.js.map +1 -1
  12. package/lib/content-helpers.js +3 -5
  13. package/lib/content-helpers.js.map +1 -1
  14. package/lib/content-repo.js +7 -1
  15. package/lib/content-repo.js.map +1 -1
  16. package/lib/crypto/store/indexeddb-crypto-store-backend.js +9 -11
  17. package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +1 -1
  18. package/lib/crypto/store/indexeddb-crypto-store.js +0 -2
  19. package/lib/crypto/store/indexeddb-crypto-store.js.map +1 -1
  20. package/lib/crypto/store/localStorage-crypto-store.js +11 -9
  21. package/lib/crypto/store/localStorage-crypto-store.js.map +1 -1
  22. package/lib/crypto/store/memory-crypto-store.js +11 -9
  23. package/lib/crypto/store/memory-crypto-store.js.map +1 -1
  24. package/lib/crypto-api/index.js +58 -58
  25. package/lib/crypto-api/index.js.map +1 -1
  26. package/lib/embedded.js +29 -45
  27. package/lib/embedded.js.map +1 -1
  28. package/lib/extensible_events_v1/MessageEvent.js +15 -15
  29. package/lib/extensible_events_v1/MessageEvent.js.map +1 -1
  30. package/lib/extensible_events_v1/PollEndEvent.js +8 -8
  31. package/lib/extensible_events_v1/PollEndEvent.js.map +1 -1
  32. package/lib/extensible_events_v1/PollResponseEvent.js +0 -1
  33. package/lib/extensible_events_v1/PollResponseEvent.js.map +1 -1
  34. package/lib/extensible_events_v1/PollStartEvent.js +28 -28
  35. package/lib/extensible_events_v1/PollStartEvent.js.map +1 -1
  36. package/lib/feature.js +5 -1
  37. package/lib/feature.js.map +1 -1
  38. package/lib/filter-component.js +4 -1
  39. package/lib/filter-component.js.map +1 -1
  40. package/lib/filter.js +1 -3
  41. package/lib/filter.js.map +1 -1
  42. package/lib/http-api/errors.js +20 -16
  43. package/lib/http-api/errors.js.map +1 -1
  44. package/lib/http-api/fetch.js +4 -6
  45. package/lib/http-api/fetch.js.map +1 -1
  46. package/lib/http-api/refresh.js +10 -12
  47. package/lib/http-api/refresh.js.map +1 -1
  48. package/lib/interactive-auth.js +1 -11
  49. package/lib/interactive-auth.js.map +1 -1
  50. package/lib/logger.js +0 -2
  51. package/lib/logger.js.map +1 -1
  52. package/lib/matrixrtc/CallMembership.js +43 -57
  53. package/lib/matrixrtc/CallMembership.js.map +1 -1
  54. package/lib/matrixrtc/MatrixRTCSession.js +19 -24
  55. package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
  56. package/lib/matrixrtc/MatrixRTCSessionManager.js +2 -3
  57. package/lib/matrixrtc/MatrixRTCSessionManager.js.map +1 -1
  58. package/lib/matrixrtc/MembershipManager.js +23 -30
  59. package/lib/matrixrtc/MembershipManager.js.map +1 -1
  60. package/lib/matrixrtc/MembershipManagerActionScheduler.js +1 -2
  61. package/lib/matrixrtc/MembershipManagerActionScheduler.js.map +1 -1
  62. package/lib/matrixrtc/RTCEncryptionManager.js +8 -11
  63. package/lib/matrixrtc/RTCEncryptionManager.js.map +1 -1
  64. package/lib/matrixrtc/ToDeviceKeyTransport.js +4 -4
  65. package/lib/matrixrtc/ToDeviceKeyTransport.js.map +1 -1
  66. package/lib/matrixrtc/utils.js +7 -1
  67. package/lib/matrixrtc/utils.js.map +1 -1
  68. package/lib/models/MSC3089TreeSpace.js +5 -7
  69. package/lib/models/MSC3089TreeSpace.js.map +1 -1
  70. package/lib/models/beacon.js +5 -11
  71. package/lib/models/beacon.js.map +1 -1
  72. package/lib/models/device.js +0 -7
  73. package/lib/models/device.js.map +1 -1
  74. package/lib/models/event-context.js +1 -2
  75. package/lib/models/event-context.js.map +1 -1
  76. package/lib/models/event-timeline-set.js +16 -26
  77. package/lib/models/event-timeline-set.js.map +1 -1
  78. package/lib/models/event-timeline.js +8 -15
  79. package/lib/models/event-timeline.js.map +1 -1
  80. package/lib/models/event.js +20 -37
  81. package/lib/models/event.js.map +1 -1
  82. package/lib/models/invites-ignorer.js +8 -12
  83. package/lib/models/invites-ignorer.js.map +1 -1
  84. package/lib/models/poll.js +7 -13
  85. package/lib/models/poll.js.map +1 -1
  86. package/lib/models/read-receipt.js +8 -4
  87. package/lib/models/read-receipt.js.map +1 -1
  88. package/lib/models/related-relations.js +0 -2
  89. package/lib/models/related-relations.js.map +1 -1
  90. package/lib/models/relations-container.js +4 -6
  91. package/lib/models/relations-container.js.map +1 -1
  92. package/lib/models/relations.js +7 -10
  93. package/lib/models/relations.js.map +1 -1
  94. package/lib/models/room-member.js +2 -24
  95. package/lib/models/room-member.js.map +1 -1
  96. package/lib/models/room-receipts.js +25 -22
  97. package/lib/models/room-receipts.js.map +1 -1
  98. package/lib/models/room-state.js +2 -2
  99. package/lib/models/room-state.js.map +1 -1
  100. package/lib/models/room-sticky-events.js +20 -5
  101. package/lib/models/room-sticky-events.js.map +1 -1
  102. package/lib/models/room.js +82 -105
  103. package/lib/models/room.js.map +1 -1
  104. package/lib/models/thread.js +12 -57
  105. package/lib/models/thread.js.map +1 -1
  106. package/lib/models/user.js +1 -20
  107. package/lib/models/user.js.map +1 -1
  108. package/lib/oidc/authorize.js +23 -32
  109. package/lib/oidc/authorize.js.map +1 -1
  110. package/lib/oidc/tokenRefresher.js +8 -11
  111. package/lib/oidc/tokenRefresher.js.map +1 -1
  112. package/lib/pushprocessor.js +8 -5
  113. package/lib/pushprocessor.js.map +1 -1
  114. package/lib/receipt-accumulator.js +12 -3
  115. package/lib/receipt-accumulator.js.map +1 -1
  116. package/lib/rendezvous/MSC4108SignInWithQR.d.ts.map +1 -1
  117. package/lib/rendezvous/MSC4108SignInWithQR.js +10 -23
  118. package/lib/rendezvous/MSC4108SignInWithQR.js.map +1 -1
  119. package/lib/rendezvous/channels/MSC4108SecureChannel.js +5 -10
  120. package/lib/rendezvous/channels/MSC4108SecureChannel.js.map +1 -1
  121. package/lib/rendezvous/transports/MSC4108RendezvousSession.js +5 -15
  122. package/lib/rendezvous/transports/MSC4108RendezvousSession.js.map +1 -1
  123. package/lib/room-hierarchy.js +7 -12
  124. package/lib/room-hierarchy.js.map +1 -1
  125. package/lib/rust-crypto/DehydratedDeviceManager.js +2 -3
  126. package/lib/rust-crypto/DehydratedDeviceManager.js.map +1 -1
  127. package/lib/rust-crypto/KeyClaimManager.js +1 -2
  128. package/lib/rust-crypto/KeyClaimManager.js.map +1 -1
  129. package/lib/rust-crypto/OutgoingRequestProcessor.js +11 -4
  130. package/lib/rust-crypto/OutgoingRequestProcessor.js.map +1 -1
  131. package/lib/rust-crypto/OutgoingRequestsManager.js +12 -12
  132. package/lib/rust-crypto/OutgoingRequestsManager.js.map +1 -1
  133. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js +3 -5
  134. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js.map +1 -1
  135. package/lib/rust-crypto/RoomEncryptor.js +6 -6
  136. package/lib/rust-crypto/RoomEncryptor.js.map +1 -1
  137. package/lib/rust-crypto/backup.js +22 -16
  138. package/lib/rust-crypto/backup.js.map +1 -1
  139. package/lib/rust-crypto/device-converter.js +13 -4
  140. package/lib/rust-crypto/device-converter.js.map +1 -1
  141. package/lib/rust-crypto/index.js +1 -3
  142. package/lib/rust-crypto/index.js.map +1 -1
  143. package/lib/rust-crypto/libolm_migration.js +13 -15
  144. package/lib/rust-crypto/libolm_migration.js.map +1 -1
  145. package/lib/rust-crypto/rust-crypto.js +52 -59
  146. package/lib/rust-crypto/rust-crypto.js.map +1 -1
  147. package/lib/rust-crypto/verification.js +10 -10
  148. package/lib/rust-crypto/verification.js.map +1 -1
  149. package/lib/scheduler.js +2 -2
  150. package/lib/scheduler.js.map +1 -1
  151. package/lib/secret-storage.js +16 -10
  152. package/lib/secret-storage.js.map +1 -1
  153. package/lib/serverCapabilities.js +2 -5
  154. package/lib/serverCapabilities.js.map +1 -1
  155. package/lib/sliding-sync-sdk.js +4 -9
  156. package/lib/sliding-sync-sdk.js.map +1 -1
  157. package/lib/sliding-sync.js +4 -9
  158. package/lib/sliding-sync.js.map +1 -1
  159. package/lib/store/indexeddb-local-backend.js +13 -8
  160. package/lib/store/indexeddb-local-backend.js.map +1 -1
  161. package/lib/store/indexeddb-remote-backend.js +6 -7
  162. package/lib/store/indexeddb-remote-backend.js.map +1 -1
  163. package/lib/store/indexeddb-store-worker.js +1 -2
  164. package/lib/store/indexeddb-store-worker.js.map +1 -1
  165. package/lib/store/indexeddb.js +4 -2
  166. package/lib/store/indexeddb.js.map +1 -1
  167. package/lib/store/memory.js +0 -4
  168. package/lib/store/memory.js.map +1 -1
  169. package/lib/sync-accumulator.js +2 -4
  170. package/lib/sync-accumulator.js.map +1 -1
  171. package/lib/sync.js +36 -43
  172. package/lib/sync.js.map +1 -1
  173. package/lib/timeline-window.js +2 -6
  174. package/lib/timeline-window.js.map +1 -1
  175. package/lib/utils/decryptAESSecretStorageItem.js +5 -1
  176. package/lib/utils/decryptAESSecretStorageItem.js.map +1 -1
  177. package/lib/utils/encryptAESSecretStorageItem.js +5 -1
  178. package/lib/utils/encryptAESSecretStorageItem.js.map +1 -1
  179. package/lib/utils.js +35 -20
  180. package/lib/utils.js.map +1 -1
  181. package/lib/webrtc/call.js +13 -45
  182. package/lib/webrtc/call.js.map +1 -1
  183. package/lib/webrtc/callEventHandler.js +0 -5
  184. package/lib/webrtc/callEventHandler.js.map +1 -1
  185. package/lib/webrtc/callFeed.js +0 -15
  186. package/lib/webrtc/callFeed.js.map +1 -1
  187. package/lib/webrtc/groupCall.js +82 -89
  188. package/lib/webrtc/groupCall.js.map +1 -1
  189. package/lib/webrtc/groupCallEventHandler.js +6 -7
  190. package/lib/webrtc/groupCallEventHandler.js.map +1 -1
  191. package/lib/webrtc/mediaHandler.js +8 -15
  192. package/lib/webrtc/mediaHandler.js.map +1 -1
  193. package/lib/webrtc/stats/callStatsReportGatherer.js +2 -5
  194. package/lib/webrtc/stats/callStatsReportGatherer.js.map +1 -1
  195. package/lib/webrtc/stats/connectionStatsReportBuilder.js +5 -1
  196. package/lib/webrtc/stats/connectionStatsReportBuilder.js.map +1 -1
  197. package/lib/webrtc/stats/groupCallStats.js +3 -4
  198. package/lib/webrtc/stats/groupCallStats.js.map +1 -1
  199. package/lib/webrtc/stats/media/mediaTrackStats.js +3 -3
  200. package/lib/webrtc/stats/media/mediaTrackStats.js.map +1 -1
  201. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js +1 -1
  202. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js.map +1 -1
  203. package/package.json +3 -3
  204. package/src/rendezvous/MSC4108SignInWithQR.ts +2 -1
@@ -30,12 +30,12 @@ import { ExtensibleEvent } from "./ExtensibleEvent.js";
30
30
  * within the PollStartEvent parsing.
31
31
  */
32
32
  export class PollAnswerSubevent extends MessageEvent {
33
+ /**
34
+ * The answer ID.
35
+ */
36
+
33
37
  constructor(wireFormat) {
34
38
  super(wireFormat);
35
- /**
36
- * The answer ID.
37
- */
38
- _defineProperty(this, "id", void 0);
39
39
  var id = wireFormat.content.id;
40
40
  if (!id || typeof id !== "string") {
41
41
  throw new InvalidEventError("Answer ID must be a non-empty string");
@@ -72,6 +72,30 @@ export class PollAnswerSubevent extends MessageEvent {
72
72
  * Represents a poll start event.
73
73
  */
74
74
  export class PollStartEvent extends ExtensibleEvent {
75
+ /**
76
+ * The question being asked, as a MessageEvent node.
77
+ */
78
+
79
+ /**
80
+ * The interpreted kind of poll. Note that this will infer a value that is known to the
81
+ * SDK rather than verbatim - this means unknown types will be represented as undisclosed
82
+ * polls.
83
+ *
84
+ * To get the raw kind, use rawKind.
85
+ */
86
+
87
+ /**
88
+ * The true kind as provided by the event sender. Might not be valid.
89
+ */
90
+
91
+ /**
92
+ * The maximum number of selections a user is allowed to make.
93
+ */
94
+
95
+ /**
96
+ * The possible answers for the poll.
97
+ */
98
+
75
99
  /**
76
100
  * Creates a new PollStartEvent from a pure format. Note that the event is *not*
77
101
  * parsed here: it will be treated as a literal m.poll.start primary typed event.
@@ -79,30 +103,6 @@ export class PollStartEvent extends ExtensibleEvent {
79
103
  */
80
104
  constructor(wireFormat) {
81
105
  super(wireFormat);
82
- /**
83
- * The question being asked, as a MessageEvent node.
84
- */
85
- _defineProperty(this, "question", void 0);
86
- /**
87
- * The interpreted kind of poll. Note that this will infer a value that is known to the
88
- * SDK rather than verbatim - this means unknown types will be represented as undisclosed
89
- * polls.
90
- *
91
- * To get the raw kind, use rawKind.
92
- */
93
- _defineProperty(this, "kind", void 0);
94
- /**
95
- * The true kind as provided by the event sender. Might not be valid.
96
- */
97
- _defineProperty(this, "rawKind", void 0);
98
- /**
99
- * The maximum number of selections a user is allowed to make.
100
- */
101
- _defineProperty(this, "maxSelections", void 0);
102
- /**
103
- * The possible answers for the poll.
104
- */
105
- _defineProperty(this, "answers", void 0);
106
106
  var poll = M_POLL_START.findIn(this.wireContent);
107
107
  if (!(poll !== null && poll !== void 0 && poll.question)) {
108
108
  throw new InvalidEventError("A question is required");
@@ -1 +1 @@
1
- {"version":3,"file":"PollStartEvent.js","names":["NamespacedValue","MessageEvent","isEventTypeSame","M_TEXT","M_POLL_KIND_DISCLOSED","M_POLL_KIND_UNDISCLOSED","M_POLL_START","InvalidEventError","ExtensibleEvent","PollAnswerSubevent","constructor","wireFormat","_defineProperty","id","content","serialize","type","_objectSpread","serializeMMessageOnly","from","text","name","PollStartEvent","poll","findIn","wireContent","question","rawKind","kind","matches","maxSelections","Number","isFinite","max_selections","Array","isArray","answers","slice","map","a","length","isEquivalentTo","primaryEventType","concat","i","join","arguments","undefined","makeId","LETTERS","charAt","Math","floor","random"],"sources":["../../src/extensible_events_v1/PollStartEvent.ts"],"sourcesContent":["/*\nCopyright 2022 - 2023 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 { NamespacedValue } from \"matrix-events-sdk\";\n\nimport { MessageEvent } from \"./MessageEvent.ts\";\nimport { type ExtensibleEventType, type IPartialEvent, isEventTypeSame, M_TEXT } from \"../@types/extensible_events.ts\";\nimport {\n type KnownPollKind,\n M_POLL_KIND_DISCLOSED,\n M_POLL_KIND_UNDISCLOSED,\n M_POLL_START,\n type PollStartEventContent,\n type PollStartSubtype,\n type PollAnswer,\n} from \"../@types/polls.ts\";\nimport { InvalidEventError } from \"./InvalidEventError.ts\";\nimport { ExtensibleEvent } from \"./ExtensibleEvent.ts\";\n\n/**\n * Represents a poll answer. Note that this is represented as a subtype and is\n * not registered as a parsable event - it is implied for usage exclusively\n * within the PollStartEvent parsing.\n */\nexport class PollAnswerSubevent extends MessageEvent {\n /**\n * The answer ID.\n */\n public readonly id: string;\n\n public constructor(wireFormat: IPartialEvent<PollAnswer>) {\n super(wireFormat);\n\n const id = wireFormat.content.id;\n if (!id || typeof id !== \"string\") {\n throw new InvalidEventError(\"Answer ID must be a non-empty string\");\n }\n this.id = id;\n }\n\n public serialize(): IPartialEvent<object> {\n return {\n type: \"org.matrix.sdk.poll.answer\",\n content: {\n id: this.id,\n ...this.serializeMMessageOnly(),\n },\n };\n }\n\n /**\n * Creates a new PollAnswerSubevent from ID and text.\n * @param id - The answer ID (unique within the poll).\n * @param text - The text.\n * @returns The representative answer.\n */\n public static from(id: string, text: string): PollAnswerSubevent {\n return new PollAnswerSubevent({\n type: \"org.matrix.sdk.poll.answer\",\n content: {\n id: id,\n [M_TEXT.name]: text,\n },\n });\n }\n}\n\n/**\n * Represents a poll start event.\n */\nexport class PollStartEvent extends ExtensibleEvent<PollStartEventContent> {\n /**\n * The question being asked, as a MessageEvent node.\n */\n public readonly question: MessageEvent;\n\n /**\n * The interpreted kind of poll. Note that this will infer a value that is known to the\n * SDK rather than verbatim - this means unknown types will be represented as undisclosed\n * polls.\n *\n * To get the raw kind, use rawKind.\n */\n public readonly kind: KnownPollKind;\n\n /**\n * The true kind as provided by the event sender. Might not be valid.\n */\n public readonly rawKind: string;\n\n /**\n * The maximum number of selections a user is allowed to make.\n */\n public readonly maxSelections: number;\n\n /**\n * The possible answers for the poll.\n */\n public readonly answers: PollAnswerSubevent[];\n\n /**\n * Creates a new PollStartEvent from a pure format. Note that the event is *not*\n * parsed here: it will be treated as a literal m.poll.start primary typed event.\n * @param wireFormat - The event.\n */\n public constructor(wireFormat: IPartialEvent<PollStartEventContent>) {\n super(wireFormat);\n\n const poll = M_POLL_START.findIn<PollStartSubtype>(this.wireContent);\n\n if (!poll?.question) {\n throw new InvalidEventError(\"A question is required\");\n }\n\n this.question = new MessageEvent({ type: \"org.matrix.sdk.poll.question\", content: poll.question });\n\n this.rawKind = poll.kind;\n if (M_POLL_KIND_DISCLOSED.matches(this.rawKind)) {\n this.kind = M_POLL_KIND_DISCLOSED;\n } else {\n this.kind = M_POLL_KIND_UNDISCLOSED; // default & assumed value\n }\n\n this.maxSelections =\n Number.isFinite(poll.max_selections) && poll.max_selections! > 0 ? poll.max_selections! : 1;\n\n if (!Array.isArray(poll.answers)) {\n throw new InvalidEventError(\"Poll answers must be an array\");\n }\n const answers = poll.answers.slice(0, 20).map(\n (a) =>\n new PollAnswerSubevent({\n type: \"org.matrix.sdk.poll.answer\",\n content: a,\n }),\n );\n if (answers.length <= 0) {\n throw new InvalidEventError(\"No answers available\");\n }\n this.answers = answers;\n }\n\n public isEquivalentTo(primaryEventType: ExtensibleEventType): boolean {\n return isEventTypeSame(primaryEventType, M_POLL_START);\n }\n\n public serialize(): IPartialEvent<object> {\n return {\n type: M_POLL_START.name,\n content: {\n [M_POLL_START.name]: {\n question: this.question.serialize().content,\n kind: this.rawKind,\n max_selections: this.maxSelections,\n answers: this.answers.map((a) => a.serialize().content),\n },\n [M_TEXT.name]: `${this.question.text}\\n${this.answers.map((a, i) => `${i + 1}. ${a.text}`).join(\"\\n\")}`,\n },\n };\n }\n\n /**\n * Creates a new PollStartEvent from question, answers, and metadata.\n * @param question - The question to ask.\n * @param answers - The answers. Should be unique within each other.\n * @param kind - The kind of poll.\n * @param maxSelections - The maximum number of selections. Must be 1 or higher.\n * @returns The representative poll start event.\n */\n public static from(\n question: string,\n answers: string[],\n kind: KnownPollKind | string,\n maxSelections = 1,\n ): PollStartEvent {\n return new PollStartEvent({\n type: M_POLL_START.name,\n content: {\n [M_TEXT.name]: question, // unused by parsing\n [M_POLL_START.name]: {\n question: { [M_TEXT.name]: question },\n kind: kind instanceof NamespacedValue ? kind.name : kind,\n max_selections: maxSelections,\n answers: answers.map((a) => ({ id: makeId(), [M_TEXT.name]: a })),\n },\n },\n });\n }\n}\n\nconst LETTERS = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\nfunction makeId(): string {\n return [...Array(16)].map(() => LETTERS.charAt(Math.floor(Math.random() * LETTERS.length))).join(\"\");\n}\n"],"mappings":";;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,eAAe,QAAQ,mBAAmB;AAEnD,SAASC,YAAY,QAAQ,mBAAmB;AAChD,SAAuDC,eAAe,EAAEC,MAAM,QAAQ,gCAAgC;AACtH,SAEIC,qBAAqB,EACrBC,uBAAuB,EACvBC,YAAY,QAIT,oBAAoB;AAC3B,SAASC,iBAAiB,QAAQ,wBAAwB;AAC1D,SAASC,eAAe,QAAQ,sBAAsB;;A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4B,IAAI,CAACP,IAAI,GAAGO,IAAI;UACxDK,cAAc,EAAEH,aAAa;UAC7BM,OAAO,EAAEA,OAAO,CAACE,GAAG,CAAEC,CAAC,KAAM;YAAE1B,EAAE,EAAEmC,MAAM,CAAC,CAAC;YAAE,CAAC7C,MAAM,CAACkB,IAAI,GAAGkB;UAAE,CAAC,CAAC;QACpE;MACJ;IACJ,CAAC,CAAC;EACN;AACJ;AAEA,IAAMU,OAAO,GAAG,gEAAgE;AAChF,SAASD,MAAMA,CAAA,EAAW;EACtB,OAAO,CAAC,GAAGd,KAAK,CAAC,EAAE,CAAC,CAAC,CAACI,GAAG,CAAC,MAAMW,OAAO,CAACC,MAAM,CAACC,IAAI,CAACC,KAAK,CAACD,IAAI,CAACE,MAAM,CAAC,CAAC,GAAGJ,OAAO,CAACT,MAAM,CAAC,CAAC,CAAC,CAACK,IAAI,CAAC,EAAE,CAAC;AACxG","ignoreList":[]}
1
+ {"version":3,"file":"PollStartEvent.js","names":["NamespacedValue","MessageEvent","isEventTypeSame","M_TEXT","M_POLL_KIND_DISCLOSED","M_POLL_KIND_UNDISCLOSED","M_POLL_START","InvalidEventError","ExtensibleEvent","PollAnswerSubevent","constructor","wireFormat","id","content","serialize","type","_objectSpread","serializeMMessageOnly","from","text","name","PollStartEvent","poll","findIn","wireContent","question","rawKind","kind","matches","maxSelections","Number","isFinite","max_selections","Array","isArray","answers","slice","map","a","length","isEquivalentTo","primaryEventType","concat","i","join","arguments","undefined","makeId","LETTERS","charAt","Math","floor","random"],"sources":["../../src/extensible_events_v1/PollStartEvent.ts"],"sourcesContent":["/*\nCopyright 2022 - 2023 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 { NamespacedValue } from \"matrix-events-sdk\";\n\nimport { MessageEvent } from \"./MessageEvent.ts\";\nimport { type ExtensibleEventType, type IPartialEvent, isEventTypeSame, M_TEXT } from \"../@types/extensible_events.ts\";\nimport {\n type KnownPollKind,\n M_POLL_KIND_DISCLOSED,\n M_POLL_KIND_UNDISCLOSED,\n M_POLL_START,\n type PollStartEventContent,\n type PollStartSubtype,\n type PollAnswer,\n} from \"../@types/polls.ts\";\nimport { InvalidEventError } from \"./InvalidEventError.ts\";\nimport { ExtensibleEvent } from \"./ExtensibleEvent.ts\";\n\n/**\n * Represents a poll answer. Note that this is represented as a subtype and is\n * not registered as a parsable event - it is implied for usage exclusively\n * within the PollStartEvent parsing.\n */\nexport class PollAnswerSubevent extends MessageEvent {\n /**\n * The answer ID.\n */\n public readonly id: string;\n\n public constructor(wireFormat: IPartialEvent<PollAnswer>) {\n super(wireFormat);\n\n const id = wireFormat.content.id;\n if (!id || typeof id !== \"string\") {\n throw new InvalidEventError(\"Answer ID must be a non-empty string\");\n }\n this.id = id;\n }\n\n public serialize(): IPartialEvent<object> {\n return {\n type: \"org.matrix.sdk.poll.answer\",\n content: {\n id: this.id,\n ...this.serializeMMessageOnly(),\n },\n };\n }\n\n /**\n * Creates a new PollAnswerSubevent from ID and text.\n * @param id - The answer ID (unique within the poll).\n * @param text - The text.\n * @returns The representative answer.\n */\n public static from(id: string, text: string): PollAnswerSubevent {\n return new PollAnswerSubevent({\n type: \"org.matrix.sdk.poll.answer\",\n content: {\n id: id,\n [M_TEXT.name]: text,\n },\n });\n }\n}\n\n/**\n * Represents a poll start event.\n */\nexport class PollStartEvent extends ExtensibleEvent<PollStartEventContent> {\n /**\n * The question being asked, as a MessageEvent node.\n */\n public readonly question: MessageEvent;\n\n /**\n * The interpreted kind of poll. Note that this will infer a value that is known to the\n * SDK rather than verbatim - this means unknown types will be represented as undisclosed\n * polls.\n *\n * To get the raw kind, use rawKind.\n */\n public readonly kind: KnownPollKind;\n\n /**\n * The true kind as provided by the event sender. Might not be valid.\n */\n public readonly rawKind: string;\n\n /**\n * The maximum number of selections a user is allowed to make.\n */\n public readonly maxSelections: number;\n\n /**\n * The possible answers for the poll.\n */\n public readonly answers: PollAnswerSubevent[];\n\n /**\n * Creates a new PollStartEvent from a pure format. Note that the event is *not*\n * parsed here: it will be treated as a literal m.poll.start primary typed event.\n * @param wireFormat - The event.\n */\n public constructor(wireFormat: IPartialEvent<PollStartEventContent>) {\n super(wireFormat);\n\n const poll = M_POLL_START.findIn<PollStartSubtype>(this.wireContent);\n\n if (!poll?.question) {\n throw new InvalidEventError(\"A question is required\");\n }\n\n this.question = new MessageEvent({ type: \"org.matrix.sdk.poll.question\", content: poll.question });\n\n this.rawKind = poll.kind;\n if (M_POLL_KIND_DISCLOSED.matches(this.rawKind)) {\n this.kind = M_POLL_KIND_DISCLOSED;\n } else {\n this.kind = M_POLL_KIND_UNDISCLOSED; // default & assumed value\n }\n\n this.maxSelections =\n Number.isFinite(poll.max_selections) && poll.max_selections! > 0 ? poll.max_selections! : 1;\n\n if (!Array.isArray(poll.answers)) {\n throw new InvalidEventError(\"Poll answers must be an array\");\n }\n const answers = poll.answers.slice(0, 20).map(\n (a) =>\n new PollAnswerSubevent({\n type: \"org.matrix.sdk.poll.answer\",\n content: a,\n }),\n );\n if (answers.length <= 0) {\n throw new InvalidEventError(\"No answers available\");\n }\n this.answers = answers;\n }\n\n public isEquivalentTo(primaryEventType: ExtensibleEventType): boolean {\n return isEventTypeSame(primaryEventType, M_POLL_START);\n }\n\n public serialize(): IPartialEvent<object> {\n return {\n type: M_POLL_START.name,\n content: {\n [M_POLL_START.name]: {\n question: this.question.serialize().content,\n kind: this.rawKind,\n max_selections: this.maxSelections,\n answers: this.answers.map((a) => a.serialize().content),\n },\n [M_TEXT.name]: `${this.question.text}\\n${this.answers.map((a, i) => `${i + 1}. ${a.text}`).join(\"\\n\")}`,\n },\n };\n }\n\n /**\n * Creates a new PollStartEvent from question, answers, and metadata.\n * @param question - The question to ask.\n * @param answers - The answers. Should be unique within each other.\n * @param kind - The kind of poll.\n * @param maxSelections - The maximum number of selections. Must be 1 or higher.\n * @returns The representative poll start event.\n */\n public static from(\n question: string,\n answers: string[],\n kind: KnownPollKind | string,\n maxSelections = 1,\n ): PollStartEvent {\n return new PollStartEvent({\n type: M_POLL_START.name,\n content: {\n [M_TEXT.name]: question, // unused by parsing\n [M_POLL_START.name]: {\n question: { [M_TEXT.name]: question },\n kind: kind instanceof NamespacedValue ? kind.name : kind,\n max_selections: maxSelections,\n answers: answers.map((a) => ({ id: makeId(), [M_TEXT.name]: a })),\n },\n },\n });\n }\n}\n\nconst LETTERS = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\nfunction makeId(): string {\n return [...Array(16)].map(() => LETTERS.charAt(Math.floor(Math.random() * LETTERS.length))).join(\"\");\n}\n"],"mappings":";;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,eAAe,QAAQ,mBAAmB;AAEnD,SAASC,YAAY,QAAQ,mBAAmB;AAChD,SAAuDC,eAAe,EAAEC,MAAM,QAAQ,gCAAgC;AACtH,SAEIC,qBAAqB,EACrBC,uBAAuB,EACvBC,YAAY,QAIT,oBAAoB;AAC3B,SAASC,iBAAiB,QAAQ,wBAAwB;AAC1D,SAASC,eAAe,QAAQ,sBAAsB;;AAEtD;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,kBAAkB,SAASR,YAAY,CAAC;EACjD;AACJ;AACA;;EAGWS,WAAWA,CAACC,UAAqC,EAAE;IACtD,KAAK,CAACA,UAAU,CAAC;IAEjB,IAAMC,EAAE,GAAGD,UAAU,CAACE,OAAO,CAACD,EAAE;IAChC,IAAI,CAACA,EAAE,IAAI,OAAOA,EAAE,KAAK,QAAQ,EAAE;MAC/B,MAAM,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CAAC,EAAE,CAAC,CAAC,CAACI,GAAG,CAAC,MAAMW,OAAO,CAACC,MAAM,CAACC,IAAI,CAACC,KAAK,CAACD,IAAI,CAACE,MAAM,CAAC,CAAC,GAAGJ,OAAO,CAACT,MAAM,CAAC,CAAC,CAAC,CAACK,IAAI,CAAC,EAAE,CAAC;AACxG","ignoreList":[]}
package/lib/feature.js CHANGED
@@ -1,3 +1,4 @@
1
+ import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
1
2
  import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
2
3
  /*
3
4
  Copyright 2022 The Matrix.org Foundation C.I.C.
@@ -67,8 +68,11 @@ export function buildFeatureSupportMap(_x) {
67
68
  function _buildFeatureSupportMap() {
68
69
  _buildFeatureSupportMap = _asyncToGenerator(function* (versions) {
69
70
  var supportMap = new Map();
70
- for (var [feature, supportCondition] of Object.entries(featureSupportResolver)) {
71
+ for (var _ref3 of Object.entries(featureSupportResolver)) {
71
72
  var _versions$versions$in, _versions$versions, _supportCondition$uns, _supportCondition$uns2;
73
+ var _ref2 = _slicedToArray(_ref3, 2);
74
+ var feature = _ref2[0];
75
+ var supportCondition = _ref2[1];
72
76
  var supportMatrixVersion = (_versions$versions$in = (_versions$versions = versions.versions) === null || _versions$versions === void 0 ? void 0 : _versions$versions.includes(supportCondition.matrixVersion || "")) !== null && _versions$versions$in !== void 0 ? _versions$versions$in : false;
73
77
  var supportUnstablePrefixes = (_supportCondition$uns = (_supportCondition$uns2 = supportCondition.unstablePrefixes) === null || _supportCondition$uns2 === void 0 ? void 0 : _supportCondition$uns2.every(unstablePrefix => {
74
78
  var _versions$unstable_fe;
@@ -1 +1 @@
1
- {"version":3,"file":"feature.js","names":["ServerSupport","Feature","featureSupportResolver","Thread","unstablePrefixes","matrixVersion","ThreadUnreadNotifications","LoginTokenRequest","RelationBasedRedactions","AccountDataDeletion","RelationsRecursion","IntentionalMentions","buildFeatureSupportMap","_x","_buildFeatureSupportMap","apply","arguments","_asyncToGenerator","versions","supportMap","Map","feature","supportCondition","Object","entries","_versions$versions$in","_versions$versions","_supportCondition$uns","_supportCondition$uns2","supportMatrixVersion","includes","supportUnstablePrefixes","every","unstablePrefix","_versions$unstable_fe","unstable_features","set","Stable","Unstable","Unsupported"],"sources":["../src/feature.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 IServerVersions } from \"./client.ts\";\n\nexport enum ServerSupport {\n Stable,\n Unstable,\n Unsupported,\n}\n\nexport enum Feature {\n Thread = \"Thread\",\n ThreadUnreadNotifications = \"ThreadUnreadNotifications\",\n /**\n * @deprecated this is now exposed as a capability not a feature\n */\n LoginTokenRequest = \"LoginTokenRequest\",\n RelationBasedRedactions = \"RelationBasedRedactions\",\n AccountDataDeletion = \"AccountDataDeletion\",\n RelationsRecursion = \"RelationsRecursion\",\n IntentionalMentions = \"IntentionalMentions\",\n}\n\ntype FeatureSupportCondition = {\n unstablePrefixes?: string[];\n matrixVersion?: string;\n};\n\nconst featureSupportResolver: Record<string, FeatureSupportCondition> = {\n [Feature.Thread]: {\n unstablePrefixes: [\"org.matrix.msc3440\"],\n matrixVersion: \"v1.3\",\n },\n [Feature.ThreadUnreadNotifications]: {\n unstablePrefixes: [\"org.matrix.msc3771\", \"org.matrix.msc3773\"],\n matrixVersion: \"v1.4\",\n },\n [Feature.LoginTokenRequest]: {\n unstablePrefixes: [\"org.matrix.msc3882\"],\n },\n [Feature.RelationBasedRedactions]: {\n unstablePrefixes: [\"org.matrix.msc3912\"],\n },\n [Feature.AccountDataDeletion]: {\n unstablePrefixes: [\"org.matrix.msc3391\"],\n },\n [Feature.RelationsRecursion]: {\n unstablePrefixes: [\"org.matrix.msc3981\"],\n matrixVersion: \"v1.10\",\n },\n [Feature.IntentionalMentions]: {\n unstablePrefixes: [\"org.matrix.msc3952_intentional_mentions\"],\n matrixVersion: \"v1.7\",\n },\n};\n\nexport async function buildFeatureSupportMap(versions: IServerVersions): Promise<Map<Feature, ServerSupport>> {\n const supportMap = new Map<Feature, ServerSupport>();\n for (const [feature, supportCondition] of Object.entries(featureSupportResolver)) {\n const supportMatrixVersion = versions.versions?.includes(supportCondition.matrixVersion || \"\") ?? false;\n const supportUnstablePrefixes =\n supportCondition.unstablePrefixes?.every((unstablePrefix) => {\n return versions.unstable_features?.[unstablePrefix] === true;\n }) ?? false;\n if (supportMatrixVersion) {\n supportMap.set(feature as Feature, ServerSupport.Stable);\n } else if (supportUnstablePrefixes) {\n supportMap.set(feature as Feature, ServerSupport.Unstable);\n } else {\n supportMap.set(feature as Feature, ServerSupport.Unsupported);\n }\n }\n return supportMap;\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAIA,WAAYA,aAAa,0BAAbA,aAAa;EAAbA,aAAa,CAAbA,aAAa;EAAbA,aAAa,CAAbA,aAAa;EAAbA,aAAa,CAAbA,aAAa;EAAA,OAAbA,aAAa;AAAA;AAMzB,WAAYC,OAAO,0BAAPA,OAAO;EAAPA,OAAO;EAAPA,OAAO;EAGf;AACJ;AACA;EALYA,OAAO;EAAPA,OAAO;EAAPA,OAAO;EAAPA,OAAO;EAAPA,OAAO;EAAA,OAAPA,OAAO;AAAA;AAkBnB,IAAMC,sBAA+D,GAAG;EACpE,CAACD,OAAO,CAACE,MAAM,GAAG;IACdC,gBAAgB,EAAE,CAAC,oBAAoB,CAAC;IACxCC,aAAa,EAAE;EACnB,CAAC;EACD,CAACJ,OAAO,CAACK,yBAAyB,GAAG;IACjCF,gBAAgB,E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,GACzBN,gBAAgB,CAAClB,gBAAgB,cAAAwB,sBAAA,uBAAjCA,sBAAA,CAAmCI,KAAK,CAAEC,cAAc,IAAK;QAAA,IAAAC,qBAAA;QACzD,OAAO,EAAAA,qBAAA,GAAAhB,QAAQ,CAACiB,iBAAiB,cAAAD,qBAAA,uBAA1BA,qBAAA,CAA6BD,cAAc,CAAC,MAAK,IAAI;MAChE,CAAC,CAAC,cAAAN,qBAAA,cAAAA,qBAAA,GAAI,KAAK;MACf,IAAIE,oBAAoB,EAAE;QACtBV,UAAU,CAACiB,GAAG,CAACf,OAAO,EAAarB,aAAa,CAACqC,MAAM,CAAC;MAC5D,CAAC,MAAM,IAAIN,uBAAuB,EAAE;QAChCZ,UAAU,CAACiB,GAAG,CAACf,OAAO,EAAarB,aAAa,CAACsC,QAAQ,CAAC;MAC9D,CAAC,MAAM;QACHnB,UAAU,CAACiB,GAAG,CAACf,OAAO,EAAarB,aAAa,CAACuC,WAAW,CAAC;MACjE;IACJ;IACA,OAAOpB,UAAU;EACrB,CAAC;EAAA,OAAAL,uBAAA,CAAAC,KAAA,OAAAC,SAAA;AAAA","ignoreList":[]}
1
+ {"version":3,"file":"feature.js","names":["ServerSupport","Feature","featureSupportResolver","Thread","unstablePrefixes","matrixVersion","ThreadUnreadNotifications","LoginTokenRequest","RelationBasedRedactions","AccountDataDeletion","RelationsRecursion","IntentionalMentions","buildFeatureSupportMap","_x","_buildFeatureSupportMap","apply","arguments","_asyncToGenerator","versions","supportMap","Map","_ref3","Object","entries","_versions$versions$in","_versions$versions","_supportCondition$uns","_supportCondition$uns2","_ref2","_slicedToArray","feature","supportCondition","supportMatrixVersion","includes","supportUnstablePrefixes","every","unstablePrefix","_versions$unstable_fe","unstable_features","set","Stable","Unstable","Unsupported"],"sources":["../src/feature.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 IServerVersions } from \"./client.ts\";\n\nexport enum ServerSupport {\n Stable,\n Unstable,\n Unsupported,\n}\n\nexport enum Feature {\n Thread = \"Thread\",\n ThreadUnreadNotifications = \"ThreadUnreadNotifications\",\n /**\n * @deprecated this is now exposed as a capability not a feature\n */\n LoginTokenRequest = \"LoginTokenRequest\",\n RelationBasedRedactions = \"RelationBasedRedactions\",\n AccountDataDeletion = \"AccountDataDeletion\",\n RelationsRecursion = \"RelationsRecursion\",\n IntentionalMentions = \"IntentionalMentions\",\n}\n\ntype FeatureSupportCondition = {\n unstablePrefixes?: string[];\n matrixVersion?: string;\n};\n\nconst featureSupportResolver: Record<string, FeatureSupportCondition> = {\n [Feature.Thread]: {\n unstablePrefixes: [\"org.matrix.msc3440\"],\n matrixVersion: \"v1.3\",\n },\n [Feature.ThreadUnreadNotifications]: {\n unstablePrefixes: [\"org.matrix.msc3771\", \"org.matrix.msc3773\"],\n matrixVersion: \"v1.4\",\n },\n [Feature.LoginTokenRequest]: {\n unstablePrefixes: [\"org.matrix.msc3882\"],\n },\n [Feature.RelationBasedRedactions]: {\n unstablePrefixes: [\"org.matrix.msc3912\"],\n },\n [Feature.AccountDataDeletion]: {\n unstablePrefixes: [\"org.matrix.msc3391\"],\n },\n [Feature.RelationsRecursion]: {\n unstablePrefixes: [\"org.matrix.msc3981\"],\n matrixVersion: \"v1.10\",\n },\n [Feature.IntentionalMentions]: {\n unstablePrefixes: [\"org.matrix.msc3952_intentional_mentions\"],\n matrixVersion: \"v1.7\",\n },\n};\n\nexport async function buildFeatureSupportMap(versions: IServerVersions): Promise<Map<Feature, ServerSupport>> {\n const supportMap = new Map<Feature, ServerSupport>();\n for (const [feature, supportCondition] of Object.entries(featureSupportResolver)) {\n const supportMatrixVersion = versions.versions?.includes(supportCondition.matrixVersion || \"\") ?? false;\n const supportUnstablePrefixes =\n supportCondition.unstablePrefixes?.every((unstablePrefix) => {\n return versions.unstable_features?.[unstablePrefix] === true;\n }) ?? false;\n if (supportMatrixVersion) {\n supportMap.set(feature as Feature, ServerSupport.Stable);\n } else if (supportUnstablePrefixes) {\n supportMap.set(feature as Feature, ServerSupport.Unstable);\n } else {\n supportMap.set(feature as Feature, ServerSupport.Unsupported);\n }\n }\n return supportMap;\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAIA,WAAYA,aAAa,0BAAbA,aAAa;EAAbA,aAAa,CAAbA,aAAa;EAAbA,aAAa,CAAbA,aAAa;EAAbA,aAAa,CAAbA,aAAa;EAAA,OAAbA,aAAa;AAAA;AAMzB,WAAYC,OAAO,0BAAPA,OAAO;EAAPA,OAAO;EAAPA,OAAO;EAGf;AACJ;AACA;EALYA,OAAO;EAAPA,OAAO;EAAPA,OAAO;EAAPA,OAAO;EAAPA,OAAO;EAAA,OAAPA,OAAO;AAAA;AAkBnB,IAAMC,sBAA+D,GAAG;EACpE,CAACD,OAAO,CAACE,MAAM,GAAG;IACdC,gBAAgB,EAAE,CAAC,oBAAoB,CAAC;IACxCC,aAAa,EAAE;EACnB,CAAC;EACD,CAACJ,OAAO,CAACK,yBAAyB,GAAG;IACjCF,gBAAgB,EAAE,CAAC,oBAAoB,EAAE,oBAAoB,CAAC;IAC9DC,aAAa,EAAE;EACnB,CAAC;EACD,CAACJ,OAAO,CAACM,iBAAiB,GAAG;IACzBH,gBAAgB,EAAE,CAAC,oBAAoB;EAC3C,CAAC;EACD,CAACH,OAAO,CAACO,uBAAuB,GAAG;IAC/BJ,gBAAgB,EAAE,CAAC,oBAAoB;EAC3C,CAAC;EACD,CAACH,OAAO,CAACQ,mBAAmB,GAAG;IAC3BL,gBAAgB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,CAAC,MAAK,IAAI;MAChE,CAAC,CAAC,cAAAV,qBAAA,cAAAA,qBAAA,GAAI,KAAK;MACf,IAAIM,oBAAoB,EAAE;QACtBb,UAAU,CAACoB,GAAG,CAACT,OAAO,EAAa9B,aAAa,CAACwC,MAAM,CAAC;MAC5D,CAAC,MAAM,IAAIN,uBAAuB,EAAE;QAChCf,UAAU,CAACoB,GAAG,CAACT,OAAO,EAAa9B,aAAa,CAACyC,QAAQ,CAAC;MAC9D,CAAC,MAAM;QACHtB,UAAU,CAACoB,GAAG,CAACT,OAAO,EAAa9B,aAAa,CAAC0C,WAAW,CAAC;MACjE;IACJ;IACA,OAAOvB,UAAU;EACrB,CAAC;EAAA,OAAAL,uBAAA,CAAAC,KAAA,OAAAC,SAAA;AAAA","ignoreList":[]}
@@ -1,3 +1,4 @@
1
+ import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
1
2
  /*
2
3
  Copyright 2016 - 2021 The Matrix.org Foundation C.I.C.
3
4
 
@@ -86,7 +87,9 @@ export class FilterComponent {
86
87
  [FILTER_RELATED_BY_SENDERS.name]: this.filterJson[FILTER_RELATED_BY_SENDERS.name],
87
88
  [FILTER_RELATED_BY_REL_TYPES.name]: this.filterJson[FILTER_RELATED_BY_REL_TYPES.name]
88
89
  }).filter(_ref => {
89
- var [_key, value] = _ref;
90
+ var _ref2 = _slicedToArray(_ref, 2),
91
+ _key = _ref2[0],
92
+ value = _ref2[1];
90
93
  return value;
91
94
  }));
92
95
  }
@@ -1 +1 @@
1
- {"version":3,"file":"filter-component.js","names":["FILTER_RELATED_BY_REL_TYPES","FILTER_RELATED_BY_SENDERS","THREAD_RELATION_TYPE","matchesWildcard","actualValue","filterValue","endsWith","typePrefix","slice","length","FilterComponent","constructor","filterJson","userId","check","event","_event$getUnsigned","_bundledRelationships","bundledRelationships","getUnsigned","relations","Object","keys","relationSenders","name","current_user_participated","push","checkFields","getRoomId","getSender","getType","getContent","url","undefined","toJSON","fromEntries","entries","types","not_types","rooms","not_rooms","senders","not_senders","contains_url","filter","_ref","_key","value","roomId","sender","eventType","containsUrl","relationTypes","literalKeys","v","matchFunc","notName","disallowedValues","some","allowedValues","containsUrlFilter","relationTypesFilter","arrayMatchesFilter","relationSendersFilter","values","every","includes","events","limit"],"sources":["../src/filter-component.ts"],"sourcesContent":["/*\nCopyright 2016 - 2021 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 RelationType } from \"./@types/event.ts\";\nimport { type MatrixEvent } from \"./models/event.ts\";\nimport { FILTER_RELATED_BY_REL_TYPES, FILTER_RELATED_BY_SENDERS, THREAD_RELATION_TYPE } from \"./models/thread.ts\";\n\n/**\n * Checks if a value matches a given field value, which may be a * terminated\n * wildcard pattern.\n * @param actualValue - The value to be compared\n * @param filterValue - The filter pattern to be compared\n * @returns true if the actualValue matches the filterValue\n */\nfunction matchesWildcard(actualValue: string, filterValue: string): boolean {\n if (filterValue.endsWith(\"*\")) {\n const typePrefix = filterValue.slice(0, -1);\n return actualValue.slice(0, typePrefix.length) === typePrefix;\n } else {\n return actualValue === filterValue;\n }\n}\n\n/* eslint-disable camelcase */\nexport interface IFilterComponent {\n \"types\"?: string[];\n \"not_types\"?: string[];\n \"rooms\"?: string[];\n \"not_rooms\"?: string[];\n \"senders\"?: string[];\n \"not_senders\"?: string[];\n \"contains_url\"?: boolean;\n \"limit\"?: number;\n \"related_by_senders\"?: Array<RelationType | string>;\n \"related_by_rel_types\"?: string[];\n\n // Unstable values\n \"io.element.relation_senders\"?: Array<RelationType | string>;\n \"io.element.relation_types\"?: string[];\n}\n/* eslint-enable camelcase */\n\n/**\n * FilterComponent is a section of a Filter definition which defines the\n * types, rooms, senders filters etc to be applied to a particular type of resource.\n * This is all ported over from synapse's Filter object.\n *\n * N.B. that synapse refers to these as 'Filters', and what js-sdk refers to as\n * 'Filters' are referred to as 'FilterCollections'.\n */\nexport class FilterComponent {\n public constructor(\n private filterJson: IFilterComponent,\n public readonly userId?: string | undefined | null,\n ) {}\n\n /**\n * Checks with the filter component matches the given event\n * @param event - event to be checked against the filter\n * @returns true if the event matches the filter\n */\n public check(event: MatrixEvent): boolean {\n const bundledRelationships = event.getUnsigned()?.[\"m.relations\"] || {};\n const relations: Array<string | RelationType> = Object.keys(bundledRelationships);\n // Relation senders allows in theory a look-up of any senders\n // however clients can only know about the current user participation status\n // as sending a whole list of participants could be proven problematic in terms\n // of performance\n // This should be improved when bundled relationships solve that problem\n const relationSenders: string[] = [];\n if (this.userId && bundledRelationships?.[THREAD_RELATION_TYPE.name]?.current_user_participated) {\n relationSenders.push(this.userId);\n }\n\n return this.checkFields(\n event.getRoomId(),\n event.getSender(),\n event.getType(),\n event.getContent() ? event.getContent().url !== undefined : false,\n relations,\n relationSenders,\n );\n }\n\n /**\n * Converts the filter component into the form expected over the wire\n */\n public toJSON(): object {\n return Object.fromEntries(\n Object.entries({\n types: this.filterJson.types,\n not_types: this.filterJson.not_types,\n rooms: this.filterJson.rooms,\n not_rooms: this.filterJson.not_rooms,\n senders: this.filterJson.senders,\n not_senders: this.filterJson.not_senders,\n contains_url: this.filterJson.contains_url,\n [FILTER_RELATED_BY_SENDERS.name]: this.filterJson[FILTER_RELATED_BY_SENDERS.name],\n [FILTER_RELATED_BY_REL_TYPES.name]: this.filterJson[FILTER_RELATED_BY_REL_TYPES.name],\n }).filter(([_key, value]) => value),\n );\n }\n\n /**\n * Checks whether the filter component matches the given event fields.\n * @param roomId - the roomId for the event being checked\n * @param sender - the sender of the event being checked\n * @param eventType - the type of the event being checked\n * @param containsUrl - whether the event contains a content.url field\n * @param relationTypes - whether has aggregated relation of the given type\n * @param relationSenders - whether one of the relation is sent by the user listed\n * @returns true if the event fields match the filter\n */\n private checkFields(\n roomId: string | undefined,\n sender: string | undefined,\n eventType: string,\n containsUrl: boolean,\n relationTypes: Array<RelationType | string>,\n relationSenders: string[],\n ): boolean {\n const literalKeys = {\n rooms: function (v: string): boolean {\n return roomId === v;\n },\n senders: function (v: string): boolean {\n return sender === v;\n },\n types: function (v: string): boolean {\n return matchesWildcard(eventType, v);\n },\n } as const;\n\n for (const name in literalKeys) {\n const matchFunc = literalKeys[<keyof typeof literalKeys>name];\n const notName = \"not_\" + name;\n const disallowedValues = this.filterJson[<`not_${keyof typeof literalKeys}`>notName];\n if (disallowedValues?.some(matchFunc)) {\n return false;\n }\n\n const allowedValues = this.filterJson[name as keyof typeof literalKeys];\n if (allowedValues && !allowedValues.some(matchFunc)) {\n return false;\n }\n }\n\n const containsUrlFilter = this.filterJson.contains_url;\n if (containsUrlFilter !== undefined && containsUrlFilter !== containsUrl) {\n return false;\n }\n\n const relationTypesFilter = this.filterJson[FILTER_RELATED_BY_REL_TYPES.name];\n if (relationTypesFilter !== undefined) {\n if (!this.arrayMatchesFilter(relationTypesFilter, relationTypes)) {\n return false;\n }\n }\n\n const relationSendersFilter = this.filterJson[FILTER_RELATED_BY_SENDERS.name];\n if (relationSendersFilter !== undefined) {\n if (!this.arrayMatchesFilter(relationSendersFilter, relationSenders)) {\n return false;\n }\n }\n\n return true;\n }\n\n private arrayMatchesFilter(filter: any[], values: any[]): boolean {\n return (\n values.length > 0 &&\n filter.every((value) => {\n return values.includes(value);\n })\n );\n }\n\n /**\n * Filters a list of events down to those which match this filter component\n * @param events - Events to be checked against the filter component\n * @returns events which matched the filter component\n */\n public filter(events: MatrixEvent[]): MatrixEvent[] {\n return events.filter(this.check, this);\n }\n\n /**\n * Returns the limit field for a given filter component, providing a default of\n * 10 if none is otherwise specified. Cargo-culted from Synapse.\n * @returns the limit for this filter component.\n */\n public limit(): number {\n return this.filterJson.limit !== undefined ? this.filterJson.limit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,2BAA2B,CAACwB,IAAI,CAAC;IAC7E,IAAIqC,mBAAmB,KAAK5B,SAAS,EAAE;MACnC,IAAI,CAAC,IAAI,CAAC6B,kBAAkB,CAACD,mBAAmB,EAAET,aAAa,CAAC,EAAE;QAC9D,OAAO,KAAK;MAChB;IACJ;IAEA,IAAMW,qBAAqB,GAAG,IAAI,CAACnD,UAAU,CAACX,yBAAyB,CAACuB,IAAI,CAAC;IAC7E,IAAIuC,qBAAqB,KAAK9B,SAAS,EAAE;MACrC,IAAI,CAAC,IAAI,CAAC6B,kBAAkB,CAACC,qBAAqB,EAAExC,eAAe,CAAC,EAAE;QAClE,OAAO,KAAK;MAChB;IACJ;IAEA,OAAO,IAAI;EACf;EAEQuC,kBAAkBA,CAAClB,MAAa,EAAEoB,MAAa,EAAW;IAC9D,OACIA,MAAM,CAACvD,MAAM,GAAG,CAAC,IACjBmC,MAAM,CAACqB,KAAK,CAAElB,KAAK,IAAK;MACpB,OAAOiB,MAAM,CAACE,QAAQ,CAACnB,KAAK,CAAC;IACjC,CAAC,CAAC;EAEV;;EAEA;AACJ;AACA;AACA;AACA;EACWH,MAAMA,CAACuB,MAAqB,EAAiB;IAChD,OAAOA,MAAM,CAACvB,MAAM,CAAC,IAAI,CAAC9B,KAAK,EAAE,IAAI,CAAC;EAC1C;;EAEA;AACJ;AACA;AACA;AACA;EACWsD,KAAKA,CAAA,EAAW;IACnB,OAAO,IAAI,CAACxD,UAAU,CAACwD,KAAK,KAAKnC,SAAS,GAAG,IAAI,CAACrB,UAAU,CAACwD,KAAK,GAAG,EAAE;EAC3E;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"filter-component.js","names":["FILTER_RELATED_BY_REL_TYPES","FILTER_RELATED_BY_SENDERS","THREAD_RELATION_TYPE","matchesWildcard","actualValue","filterValue","endsWith","typePrefix","slice","length","FilterComponent","constructor","filterJson","userId","check","event","_event$getUnsigned","_bundledRelationships","bundledRelationships","getUnsigned","relations","Object","keys","relationSenders","name","current_user_participated","push","checkFields","getRoomId","getSender","getType","getContent","url","undefined","toJSON","fromEntries","entries","types","not_types","rooms","not_rooms","senders","not_senders","contains_url","filter","_ref","_ref2","_slicedToArray","_key","value","roomId","sender","eventType","containsUrl","relationTypes","literalKeys","v","matchFunc","notName","disallowedValues","some","allowedValues","containsUrlFilter","relationTypesFilter","arrayMatchesFilter","relationSendersFilter","values","every","includes","events","limit"],"sources":["../src/filter-component.ts"],"sourcesContent":["/*\nCopyright 2016 - 2021 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 RelationType } from \"./@types/event.ts\";\nimport { type MatrixEvent } from \"./models/event.ts\";\nimport { FILTER_RELATED_BY_REL_TYPES, FILTER_RELATED_BY_SENDERS, THREAD_RELATION_TYPE } from \"./models/thread.ts\";\n\n/**\n * Checks if a value matches a given field value, which may be a * terminated\n * wildcard pattern.\n * @param actualValue - The value to be compared\n * @param filterValue - The filter pattern to be compared\n * @returns true if the actualValue matches the filterValue\n */\nfunction matchesWildcard(actualValue: string, filterValue: string): boolean {\n if (filterValue.endsWith(\"*\")) {\n const typePrefix = filterValue.slice(0, -1);\n return actualValue.slice(0, typePrefix.length) === typePrefix;\n } else {\n return actualValue === filterValue;\n }\n}\n\n/* eslint-disable camelcase */\nexport interface IFilterComponent {\n \"types\"?: string[];\n \"not_types\"?: string[];\n \"rooms\"?: string[];\n \"not_rooms\"?: string[];\n \"senders\"?: string[];\n \"not_senders\"?: string[];\n \"contains_url\"?: boolean;\n \"limit\"?: number;\n \"related_by_senders\"?: Array<RelationType | string>;\n \"related_by_rel_types\"?: string[];\n\n // Unstable values\n \"io.element.relation_senders\"?: Array<RelationType | string>;\n \"io.element.relation_types\"?: string[];\n}\n/* eslint-enable camelcase */\n\n/**\n * FilterComponent is a section of a Filter definition which defines the\n * types, rooms, senders filters etc to be applied to a particular type of resource.\n * This is all ported over from synapse's Filter object.\n *\n * N.B. that synapse refers to these as 'Filters', and what js-sdk refers to as\n * 'Filters' are referred to as 'FilterCollections'.\n */\nexport class FilterComponent {\n public constructor(\n private filterJson: IFilterComponent,\n public readonly userId?: string | undefined | null,\n ) {}\n\n /**\n * Checks with the filter component matches the given event\n * @param event - event to be checked against the filter\n * @returns true if the event matches the filter\n */\n public check(event: MatrixEvent): boolean {\n const bundledRelationships = event.getUnsigned()?.[\"m.relations\"] || {};\n const relations: Array<string | RelationType> = Object.keys(bundledRelationships);\n // Relation senders allows in theory a look-up of any senders\n // however clients can only know about the current user participation status\n // as sending a whole list of participants could be proven problematic in terms\n // of performance\n // This should be improved when bundled relationships solve that problem\n const relationSenders: string[] = [];\n if (this.userId && bundledRelationships?.[THREAD_RELATION_TYPE.name]?.current_user_participated) {\n relationSenders.push(this.userId);\n }\n\n return this.checkFields(\n event.getRoomId(),\n event.getSender(),\n event.getType(),\n event.getContent() ? event.getContent().url !== undefined : false,\n relations,\n relationSenders,\n );\n }\n\n /**\n * Converts the filter component into the form expected over the wire\n */\n public toJSON(): object {\n return Object.fromEntries(\n Object.entries({\n types: this.filterJson.types,\n not_types: this.filterJson.not_types,\n rooms: this.filterJson.rooms,\n not_rooms: this.filterJson.not_rooms,\n senders: this.filterJson.senders,\n not_senders: this.filterJson.not_senders,\n contains_url: this.filterJson.contains_url,\n [FILTER_RELATED_BY_SENDERS.name]: this.filterJson[FILTER_RELATED_BY_SENDERS.name],\n [FILTER_RELATED_BY_REL_TYPES.name]: this.filterJson[FILTER_RELATED_BY_REL_TYPES.name],\n }).filter(([_key, value]) => value),\n );\n }\n\n /**\n * Checks whether the filter component matches the given event fields.\n * @param roomId - the roomId for the event being checked\n * @param sender - the sender of the event being checked\n * @param eventType - the type of the event being checked\n * @param containsUrl - whether the event contains a content.url field\n * @param relationTypes - whether has aggregated relation of the given type\n * @param relationSenders - whether one of the relation is sent by the user listed\n * @returns true if the event fields match the filter\n */\n private checkFields(\n roomId: string | undefined,\n sender: string | undefined,\n eventType: string,\n containsUrl: boolean,\n relationTypes: Array<RelationType | string>,\n relationSenders: string[],\n ): boolean {\n const literalKeys = {\n rooms: function (v: string): boolean {\n return roomId === v;\n },\n senders: function (v: string): boolean {\n return sender === v;\n },\n types: function (v: string): boolean {\n return matchesWildcard(eventType, v);\n },\n } as const;\n\n for (const name in literalKeys) {\n const matchFunc = literalKeys[<keyof typeof literalKeys>name];\n const notName = \"not_\" + name;\n const disallowedValues = this.filterJson[<`not_${keyof typeof literalKeys}`>notName];\n if (disallowedValues?.some(matchFunc)) {\n return false;\n }\n\n const allowedValues = this.filterJson[name as keyof typeof literalKeys];\n if (allowedValues && !allowedValues.some(matchFunc)) {\n return false;\n }\n }\n\n const containsUrlFilter = this.filterJson.contains_url;\n if (containsUrlFilter !== undefined && containsUrlFilter !== containsUrl) {\n return false;\n }\n\n const relationTypesFilter = this.filterJson[FILTER_RELATED_BY_REL_TYPES.name];\n if (relationTypesFilter !== undefined) {\n if (!this.arrayMatchesFilter(relationTypesFilter, relationTypes)) {\n return false;\n }\n }\n\n const relationSendersFilter = this.filterJson[FILTER_RELATED_BY_SENDERS.name];\n if (relationSendersFilter !== undefined) {\n if (!this.arrayMatchesFilter(relationSendersFilter, relationSenders)) {\n return false;\n }\n }\n\n return true;\n }\n\n private arrayMatchesFilter(filter: any[], values: any[]): boolean {\n return (\n values.length > 0 &&\n filter.every((value) => {\n return values.includes(value);\n })\n );\n }\n\n /**\n * Filters a list of events down to those which match this filter component\n * @param events - Events to be checked against the filter component\n * @returns events which matched the filter component\n */\n public filter(events: MatrixEvent[]): MatrixEvent[] {\n return events.filter(this.check, this);\n }\n\n /**\n * Returns the limit field for a given filter component, providing a default of\n * 10 if none is otherwise specified. Cargo-culted from Synapse.\n * @returns the limit for this filter component.\n */\n public limit(): number {\n return this.filterJson.limit !== undefined ? this.filterJson.limit : 10;\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAIA,SAASA,2BAA2B,EAAEC,yBAAyB,EAAEC,oBAAoB,QAAQ,oBAAoB;;AAEjH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,eAAeA,CAACC,WAAmB,EAAEC,WAAmB,EAAW;EACxE,IAAIA,WAAW,CAACC,QAAQ,CAAC,GAAG,CAAC,EAAE;IAC3B,IAAMC,UAAU,GAAGF,WAAW,CAACG,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IAC3C,OAAOJ,WAAW,CAACI,KAAK,CAAC,CAAC,EAAED,UAAU,CAACE,MAAM,CAAC,KAAKF,UAAU;EACjE,CAAC,MAAM;IACH,OAAOH,WAAW,KAAKC,WAAW;EACtC;AACJ;;AAEA;;AAiBA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMK,eAAe,CAAC;EAClBC,WAAWA,CACNC,UAA4B,EACpBC,MAAkC,EACpD;IAAA,KAFUD,UAA4B,GAA5BA,UAA4B;IAAA,KACpBC,MAAkC,GAAlCA,MAAkC;EACnD;;EAEH;AACJ;AACA;AACA;AACA;EACWC,KAAKA,CAACC,KAAkB,EAAW;IAAA,IAAAC,kBAAA,EAAAC,qBAAA;IACtC,IAAMC,oBAAoB,GAAG,EAAAF,kBAAA,GAAAD,KAAK,CAACI,WAAW,CAAC,CAAC,cAAAH,kBAAA,uBAAnBA,kBAAA,CAAsB,aAAa,CAAC,KAAI,CAAC,CAAC;IACvE,IAAMI,SAAuC,GAAGC,MAAM,CAACC,IAAI,CAACJ,oBAAoB,CAAC;IACjF;IACA;IACA;IACA;IACA;IACA,IAAMK,eAAyB,GAAG,EAAE;IACpC,IAAI,IAAI,CAACV,MA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AK7B,SAAS,IAAI6B,iBAAiB,KAAKT,WAAW,EAAE;MACtE,OAAO,KAAK;IAChB;IAEA,IAAMU,mBAAmB,GAAG,IAAI,CAACnD,UAAU,CAACZ,2BAA2B,CAACwB,IAAI,CAAC;IAC7E,IAAIuC,mBAAmB,KAAK9B,SAAS,EAAE;MACnC,IAAI,CAAC,IAAI,CAAC+B,kBAAkB,CAACD,mBAAmB,EAAET,aAAa,CAAC,EAAE;QAC9D,OAAO,KAAK;MAChB;IACJ;IAEA,IAAMW,qBAAqB,GAAG,IAAI,CAACrD,UAAU,CAACX,yBAAyB,CAACuB,IAAI,CAAC;IAC7E,IAAIyC,qBAAqB,KAAKhC,SAAS,EAAE;MACrC,IAAI,CAAC,IAAI,CAAC+B,kBAAkB,CAACC,qBAAqB,EAAE1C,eAAe,CAAC,EAAE;QAClE,OAAO,KAAK;MAChB;IACJ;IAEA,OAAO,IAAI;EACf;EAEQyC,kBAAkBA,CAACpB,MAAa,EAAEsB,MAAa,EAAW;IAC9D,OACIA,MAAM,CAACzD,MAAM,GAAG,CAAC,IACjBmC,MAAM,CAACuB,KAAK,CAAElB,KAAK,IAAK;MACpB,OAAOiB,MAAM,CAACE,QAAQ,CAACnB,KAAK,CAAC;IACjC,CAAC,CAAC;EAEV;;EAEA;AACJ;AACA;AACA;AACA;EACWL,MAAMA,CAACyB,MAAqB,EAAiB;IAChD,OAAOA,MAAM,CAACzB,MAAM,CAAC,IAAI,CAAC9B,KAAK,EAAE,IAAI,CAAC;EAC1C;;EAEA;AACJ;AACA;AACA;AACA;EACWwD,KAAKA,CAAA,EAAW;IACnB,OAAO,IAAI,CAAC1D,UAAU,CAAC0D,KAAK,KAAKrC,SAAS,GAAG,IAAI,CAACrB,UAAU,CAAC0D,KAAK,GAAG,EAAE;EAC3E;AACJ","ignoreList":[]}
package/lib/filter.js CHANGED
@@ -59,11 +59,9 @@ export class Filter {
59
59
  * @param filterId - The filter ID if known.
60
60
  */
61
61
  constructor(userId, filterId) {
62
+ _defineProperty(this, "definition", {});
62
63
  this.userId = userId;
63
64
  this.filterId = filterId;
64
- _defineProperty(this, "definition", {});
65
- _defineProperty(this, "roomFilter", void 0);
66
- _defineProperty(this, "roomTimelineFilter", void 0);
67
65
  }
68
66
 
69
67
  /**
package/lib/filter.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"filter.js","names":["UNREAD_THREAD_NOTIFICATIONS","FilterComponent","NamespacedValue","profileFieldsFilterName","setProp","obj","keyNesting","val","nestedKeys","split","currentObj","i","length","Filter","fromJson","userId","filterId","jsonObj","filter","setDefinition","constructor","_defineProperty","getFilterId","getDefinition","definition","roomFilterJson","room","roomFilterFields","rooms","not_rooms","roomFilter","roomTimelineFilter","timeline","getRoomTimelineFilterComponent","filterRoomTimeline","events","setTimelineLimit","limit","setUnreadThreadNotifications","enabled","_this$definition","_this$definition2","_objectSpread","name","setLazyLoadMembers","setIncludeLeaveRooms","includeLeave","setUnstableMSC4429SyncUserProfiles","ids","stable","_profileFieldsFilterN","field","unstable","lazy_load_members"],"sources":["../src/filter.ts"],"sourcesContent":["/*\nCopyright 2015 - 2021 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 EventType, type RelationType } from \"./@types/event.ts\";\nimport { UNREAD_THREAD_NOTIFICATIONS } from \"./@types/sync.ts\";\nimport { FilterComponent, type IFilterComponent } from \"./filter-component.ts\";\nimport { type MatrixEvent } from \"./models/event.ts\";\nimport { NamespacedValue } from \"./NamespacedValue.ts\";\n\nconst profileFieldsFilterName = new NamespacedValue(\"profile_fields\", \"org.matrix.msc4429.profile_fields\");\n\n/**\n */\nfunction setProp(obj: Record<string, any>, keyNesting: string, val: any): void {\n const nestedKeys = keyNesting.split(\".\") as [keyof typeof obj];\n let currentObj = obj;\n for (let i = 0; i < nestedKeys.length - 1; i++) {\n if (!currentObj[nestedKeys[i]]) {\n currentObj[nestedKeys[i]] = {};\n }\n currentObj = currentObj[nestedKeys[i]];\n }\n currentObj[nestedKeys[nestedKeys.length - 1]] = val;\n}\n\n/* eslint-disable camelcase */\nexport interface IFilterDefinition {\n \"event_fields\"?: string[];\n \"event_format\"?: \"client\" | \"federation\";\n \"presence\"?: IFilterComponent;\n \"account_data\"?: IFilterComponent;\n \"room\"?: IRoomFilter;\n \"profile_fields\"?: ProfileFieldsFilter;\n \"org.matrix.msc4429.profile_fields\"?: ProfileFieldsFilter;\n}\n\nexport interface IRoomEventFilter extends IFilterComponent {\n \"lazy_load_members\"?: boolean;\n \"include_redundant_members\"?: boolean;\n \"types\"?: Array<EventType | string>;\n \"related_by_senders\"?: Array<RelationType | string>;\n \"related_by_rel_types\"?: string[];\n \"unread_thread_notifications\"?: boolean;\n \"org.matrix.msc3773.unread_thread_notifications\"?: boolean;\n\n // Unstable values\n \"io.element.relation_senders\"?: Array<RelationType | string>;\n \"io.element.relation_types\"?: string[];\n}\n\ninterface IStateFilter extends IRoomEventFilter {}\n\ninterface IRoomFilter {\n not_rooms?: string[];\n rooms?: string[];\n ephemeral?: IRoomEventFilter;\n include_leave?: boolean;\n state?: IStateFilter;\n timeline?: IRoomEventFilter;\n account_data?: IRoomEventFilter;\n}\n\n/**\n * Filter section used for requesting a set of extended profile fields that will be sent down the sync stream.\n */\ninterface ProfileFieldsFilter {\n ids: string[];\n}\n\n/* eslint-enable camelcase */\n\nexport class Filter {\n public static LAZY_LOADING_MESSAGES_FILTER = {\n lazy_load_members: true,\n };\n\n /**\n * Create a filter from existing data.\n */\n public static fromJson(userId: string | undefined | null, filterId: string, jsonObj: IFilterDefinition): Filter {\n const filter = new Filter(userId, filterId);\n filter.setDefinition(jsonObj);\n return filter;\n }\n\n private definition: IFilterDefinition = {};\n private roomFilter?: FilterComponent;\n private roomTimelineFilter?: FilterComponent;\n\n /**\n * Construct a new Filter.\n * @param userId - The user ID for this filter.\n * @param filterId - The filter ID if known.\n */\n public constructor(\n public readonly userId: string | undefined | null,\n public filterId?: string,\n ) {}\n\n /**\n * Get the ID of this filter on your homeserver (if known)\n * @returns The filter ID\n */\n public getFilterId(): string | undefined {\n return this.filterId;\n }\n\n /**\n * Get the JSON body of the filter.\n * @returns The filter definition\n */\n public getDefinition(): IFilterDefinition {\n return this.definition;\n }\n\n /**\n * Set the JSON body of the filter\n * @param definition - The filter definition\n */\n public setDefinition(definition: IFilterDefinition): void {\n this.definition = definition;\n\n // This is all ported from synapse's FilterCollection()\n\n // definitions look something like:\n // {\n // \"room\": {\n // \"rooms\": [\"!abcde:example.com\"],\n // \"not_rooms\": [\"!123456:example.com\"],\n // \"state\": {\n // \"types\": [\"m.room.*\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"lazy_load_members\": true,\n // },\n // \"timeline\": {\n // \"limit\": 10,\n // \"types\": [\"m.room.message\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"not_senders\": [\"@spam:example.com\"]\n // \"contains_url\": true\n // },\n // \"ephemeral\": {\n // \"types\": [\"m.receipt\", \"m.typing\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"not_senders\": [\"@spam:example.com\"]\n // }\n // },\n // \"presence\": {\n // \"types\": [\"m.presence\"],\n // \"not_senders\": [\"@alice:example.com\"]\n // },\n // \"event_format\": \"client\",\n // \"event_fields\": [\"type\", \"content\", \"sender\"]\n // }\n\n const roomFilterJson = definition.room;\n\n // consider the top level rooms/not_rooms filter\n const roomFilterFields: IRoomFilter = {};\n if (roomFilterJson) {\n if (roomFilterJson.rooms) {\n roomFilterFields.rooms = roomFilterJson.rooms;\n }\n if (roomFilterJson.rooms) {\n roomFilterFields.not_rooms = roomFilterJson.not_rooms;\n }\n }\n\n this.roomFilter = new FilterComponent(roomFilterFields, this.userId);\n this.roomTimelineFilter = new FilterComponent(roomFilterJson?.timeline || {}, this.userId);\n\n // don't bother porting this from synapse yet:\n // this._room_state_filter =\n // new FilterComponent(roomFilterJson.state || {});\n // this._room_ephemeral_filter =\n // new FilterComponent(roomFilterJson.ephemeral || {});\n // this._room_account_data_filter =\n // new FilterComponent(roomFilterJson.account_data || {});\n // this._presence_filter =\n // new FilterComponent(definition.presence || {});\n // this._account_data_filter =\n // new FilterComponent(definition.account_data || {});\n }\n\n /**\n * Get the room.timeline filter component of the filter\n * @returns room timeline filter component\n */\n public getRoomTimelineFilterComponent(): FilterComponent | undefined {\n return this.roomTimelineFilter;\n }\n\n /**\n * Filter the list of events based on whether they are allowed in a timeline\n * based on this filter\n * @param events - the list of events being filtered\n * @returns the list of events which match the filter\n */\n public filterRoomTimeline(events: MatrixEvent[]): MatrixEvent[] {\n if (this.roomFilter) {\n events = this.roomFilter.filter(events);\n }\n if (this.roomTimelineFilter) {\n events = this.roomTimelineFilter.filter(events);\n }\n return events;\n }\n\n /**\n * Set the max number of events to return for each room's timeline.\n * @param limit - The max number of events to return for each room.\n */\n public setTimelineLimit(limit: number): void {\n setProp(this.definition, \"room.timeline.limit\", limit);\n }\n\n /**\n * Enable threads unread notification\n */\n public setUnreadThreadNotifications(enabled: boolean): void {\n this.definition = {\n ...this.definition,\n room: {\n ...this.definition?.room,\n timeline: {\n ...this.definition?.room?.timeline,\n [UNREAD_THREAD_NOTIFICATIONS.name]: enabled,\n },\n },\n };\n }\n\n public setLazyLoadMembers(enabled: boolean): void {\n setProp(this.definition, \"room.state.lazy_load_members\", enabled);\n }\n\n /**\n * Control whether left rooms should be included in responses.\n * @param includeLeave - True to make rooms the user has left appear\n * in responses.\n */\n public setIncludeLeaveRooms(includeLeave: boolean): void {\n setProp(this.definition, \"room.include_leave\", includeLeave);\n }\n\n /**\n * Set the list of fields to be included in the profile information sent down the sync stream.\n * @param ids The field IDs to sync.\n * @param stable Whether to use the stable or unstable versions of this filter.\n * @experimental\n */\n public setUnstableMSC4429SyncUserProfiles(ids: string[], stable: boolean): void {\n const field = stable\n ? profileFieldsFilterName.name\n : (profileFieldsFilterName.unstable ?? profileFieldsFilterName.name);\n this.definition[field] = { ids };\n }\n}\n"],"mappings":";;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SAASA,2BAA2B,QAAQ,kBAAkB;AAC9D,SAASC,eAAe,QAA+B,uBAAuB;AAE9E,SAASC,eAAe,QAAQ,sBAAsB;AAEtD,IAAMC,uBAAuB,GAAG,IAAID,eAAe,CAAC,gBAAgB,EAAE,mCAAmC,CAAC;;AAE1G;AACA;AACA,SAASE,OAAOA,CAACC,GAAwB,EAAEC,UAAkB,EAAEC,GAAQ,EAAQ;EAC3E,IAAMC,UAAU,GAAGF,UAAU,CAACG,KAAK,CAAC,GAAG,CAAuB;EAC9D,IAAIC,UAAU,GAAGL,GAAG;EACpB,KAAK,IAAIM,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGH,UAAU,CAACI,MAAM,GAAG,CAAC,EAAED,CAAC,EAAE,EAAE;IAC5C,IAAI,CAACD,UAAU,CAACF,UAAU,CAACG,CAAC,CAAC,CAAC,EAAE;MAC5BD,UAAU,CAACF,UAAU,CAACG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IAClC;IACAD,UAAU,GAAGA,UAAU,CAACF,UAAU,CAACG,CAAC,CAAC,CAAC;EAC1C;EACAD,UAAU,CAACF,UAAU,CAACA,UAAU,CAACI,MAAM,GAAG,CAAC,CAAC,CAAC,GAAGL,GAAG;AACvD;;AAEA;;AAqCA;AACA;AACA;;AAKA;;AAEA,OAAO,MAAMM,MAAM,CAAC;EAKhB;AACJ;AACA;EACI,OAAcC,QAAQA,CAACC,MAAiC,EAAEC,QAAgB,EAAEC,OAA0B,EAAU;IAC5G,IAAMC,MAAM,GAAG,IAAIL,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9C;IACJ,EACJ;EACL;EAEOK,kBAAkBA,CAACL,OAAgB,EAAQ;IAC9CnC,OAAO,CAAC,IAAI,CAACoB,UAAU,EAAE,8BAA8B,EAAEe,OAAO,CAAC;EACrE;;EAEA;AACJ;AACA;AACA;AACA;EACWM,oBAAoBA,CAACC,YAAqB,EAAQ;IACrD1C,OAAO,CAAC,IAAI,CAACoB,UAAU,EAAE,oBAAoB,EAAEsB,YAAY,CAAC;EAChE;;EAEA;AACJ;AACA;AACA;AACA;AACA;EACWC,kCAAkCA,CAACC,GAAa,EAAEC,MAAe,EAAQ;IAAA,IAAAC,qBAAA;IAC5E,IAAMC,KAAK,GAAGF,MAAM,GACd9C,uBAAuB,CAACwC,IAAI,IAAAO,qBAAA,GAC3B/C,uBAAuB,CAACiD,QAAQ,cAAAF,qBAAA,cAAAA,qBAAA,GAAI/C,uBAAuB,CAACwC,IAAK;IACxE,IAAI,CAACnB,UAAU,CAAC2B,KAAK,CAAC,GAAG;MAAEH;IAAI,CAAC;EACpC;AACJ;AAAC3B,eAAA,CA1LYR,MAAM,kCAC8B;EACzCwC,iBAAiB,EAAE;AACvB,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"filter.js","names":["UNREAD_THREAD_NOTIFICATIONS","FilterComponent","NamespacedValue","profileFieldsFilterName","setProp","obj","keyNesting","val","nestedKeys","split","currentObj","i","length","Filter","fromJson","userId","filterId","jsonObj","filter","setDefinition","constructor","_defineProperty","getFilterId","getDefinition","definition","roomFilterJson","room","roomFilterFields","rooms","not_rooms","roomFilter","roomTimelineFilter","timeline","getRoomTimelineFilterComponent","filterRoomTimeline","events","setTimelineLimit","limit","setUnreadThreadNotifications","enabled","_this$definition","_this$definition2","_objectSpread","name","setLazyLoadMembers","setIncludeLeaveRooms","includeLeave","setUnstableMSC4429SyncUserProfiles","ids","stable","_profileFieldsFilterN","field","unstable","lazy_load_members"],"sources":["../src/filter.ts"],"sourcesContent":["/*\nCopyright 2015 - 2021 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 EventType, type RelationType } from \"./@types/event.ts\";\nimport { UNREAD_THREAD_NOTIFICATIONS } from \"./@types/sync.ts\";\nimport { FilterComponent, type IFilterComponent } from \"./filter-component.ts\";\nimport { type MatrixEvent } from \"./models/event.ts\";\nimport { NamespacedValue } from \"./NamespacedValue.ts\";\n\nconst profileFieldsFilterName = new NamespacedValue(\"profile_fields\", \"org.matrix.msc4429.profile_fields\");\n\n/**\n */\nfunction setProp(obj: Record<string, any>, keyNesting: string, val: any): void {\n const nestedKeys = keyNesting.split(\".\") as [keyof typeof obj];\n let currentObj = obj;\n for (let i = 0; i < nestedKeys.length - 1; i++) {\n if (!currentObj[nestedKeys[i]]) {\n currentObj[nestedKeys[i]] = {};\n }\n currentObj = currentObj[nestedKeys[i]];\n }\n currentObj[nestedKeys[nestedKeys.length - 1]] = val;\n}\n\n/* eslint-disable camelcase */\nexport interface IFilterDefinition {\n \"event_fields\"?: string[];\n \"event_format\"?: \"client\" | \"federation\";\n \"presence\"?: IFilterComponent;\n \"account_data\"?: IFilterComponent;\n \"room\"?: IRoomFilter;\n \"profile_fields\"?: ProfileFieldsFilter;\n \"org.matrix.msc4429.profile_fields\"?: ProfileFieldsFilter;\n}\n\nexport interface IRoomEventFilter extends IFilterComponent {\n \"lazy_load_members\"?: boolean;\n \"include_redundant_members\"?: boolean;\n \"types\"?: Array<EventType | string>;\n \"related_by_senders\"?: Array<RelationType | string>;\n \"related_by_rel_types\"?: string[];\n \"unread_thread_notifications\"?: boolean;\n \"org.matrix.msc3773.unread_thread_notifications\"?: boolean;\n\n // Unstable values\n \"io.element.relation_senders\"?: Array<RelationType | string>;\n \"io.element.relation_types\"?: string[];\n}\n\ninterface IStateFilter extends IRoomEventFilter {}\n\ninterface IRoomFilter {\n not_rooms?: string[];\n rooms?: string[];\n ephemeral?: IRoomEventFilter;\n include_leave?: boolean;\n state?: IStateFilter;\n timeline?: IRoomEventFilter;\n account_data?: IRoomEventFilter;\n}\n\n/**\n * Filter section used for requesting a set of extended profile fields that will be sent down the sync stream.\n */\ninterface ProfileFieldsFilter {\n ids: string[];\n}\n\n/* eslint-enable camelcase */\n\nexport class Filter {\n public static LAZY_LOADING_MESSAGES_FILTER = {\n lazy_load_members: true,\n };\n\n /**\n * Create a filter from existing data.\n */\n public static fromJson(userId: string | undefined | null, filterId: string, jsonObj: IFilterDefinition): Filter {\n const filter = new Filter(userId, filterId);\n filter.setDefinition(jsonObj);\n return filter;\n }\n\n private definition: IFilterDefinition = {};\n private roomFilter?: FilterComponent;\n private roomTimelineFilter?: FilterComponent;\n\n /**\n * Construct a new Filter.\n * @param userId - The user ID for this filter.\n * @param filterId - The filter ID if known.\n */\n public constructor(\n public readonly userId: string | undefined | null,\n public filterId?: string,\n ) {}\n\n /**\n * Get the ID of this filter on your homeserver (if known)\n * @returns The filter ID\n */\n public getFilterId(): string | undefined {\n return this.filterId;\n }\n\n /**\n * Get the JSON body of the filter.\n * @returns The filter definition\n */\n public getDefinition(): IFilterDefinition {\n return this.definition;\n }\n\n /**\n * Set the JSON body of the filter\n * @param definition - The filter definition\n */\n public setDefinition(definition: IFilterDefinition): void {\n this.definition = definition;\n\n // This is all ported from synapse's FilterCollection()\n\n // definitions look something like:\n // {\n // \"room\": {\n // \"rooms\": [\"!abcde:example.com\"],\n // \"not_rooms\": [\"!123456:example.com\"],\n // \"state\": {\n // \"types\": [\"m.room.*\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"lazy_load_members\": true,\n // },\n // \"timeline\": {\n // \"limit\": 10,\n // \"types\": [\"m.room.message\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"not_senders\": [\"@spam:example.com\"]\n // \"contains_url\": true\n // },\n // \"ephemeral\": {\n // \"types\": [\"m.receipt\", \"m.typing\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"not_senders\": [\"@spam:example.com\"]\n // }\n // },\n // \"presence\": {\n // \"types\": [\"m.presence\"],\n // \"not_senders\": [\"@alice:example.com\"]\n // },\n // \"event_format\": \"client\",\n // \"event_fields\": [\"type\", \"content\", \"sender\"]\n // }\n\n const roomFilterJson = definition.room;\n\n // consider the top level rooms/not_rooms filter\n const roomFilterFields: IRoomFilter = {};\n if (roomFilterJson) {\n if (roomFilterJson.rooms) {\n roomFilterFields.rooms = roomFilterJson.rooms;\n }\n if (roomFilterJson.rooms) {\n roomFilterFields.not_rooms = roomFilterJson.not_rooms;\n }\n }\n\n this.roomFilter = new FilterComponent(roomFilterFields, this.userId);\n this.roomTimelineFilter = new FilterComponent(roomFilterJson?.timeline || {}, this.userId);\n\n // don't bother porting this from synapse yet:\n // this._room_state_filter =\n // new FilterComponent(roomFilterJson.state || {});\n // this._room_ephemeral_filter =\n // new FilterComponent(roomFilterJson.ephemeral || {});\n // this._room_account_data_filter =\n // new FilterComponent(roomFilterJson.account_data || {});\n // this._presence_filter =\n // new FilterComponent(definition.presence || {});\n // this._account_data_filter =\n // new FilterComponent(definition.account_data || {});\n }\n\n /**\n * Get the room.timeline filter component of the filter\n * @returns room timeline filter component\n */\n public getRoomTimelineFilterComponent(): FilterComponent | undefined {\n return this.roomTimelineFilter;\n }\n\n /**\n * Filter the list of events based on whether they are allowed in a timeline\n * based on this filter\n * @param events - the list of events being filtered\n * @returns the list of events which match the filter\n */\n public filterRoomTimeline(events: MatrixEvent[]): MatrixEvent[] {\n if (this.roomFilter) {\n events = this.roomFilter.filter(events);\n }\n if (this.roomTimelineFilter) {\n events = this.roomTimelineFilter.filter(events);\n }\n return events;\n }\n\n /**\n * Set the max number of events to return for each room's timeline.\n * @param limit - The max number of events to return for each room.\n */\n public setTimelineLimit(limit: number): void {\n setProp(this.definition, \"room.timeline.limit\", limit);\n }\n\n /**\n * Enable threads unread notification\n */\n public setUnreadThreadNotifications(enabled: boolean): void {\n this.definition = {\n ...this.definition,\n room: {\n ...this.definition?.room,\n timeline: {\n ...this.definition?.room?.timeline,\n [UNREAD_THREAD_NOTIFICATIONS.name]: enabled,\n },\n },\n };\n }\n\n public setLazyLoadMembers(enabled: boolean): void {\n setProp(this.definition, \"room.state.lazy_load_members\", enabled);\n }\n\n /**\n * Control whether left rooms should be included in responses.\n * @param includeLeave - True to make rooms the user has left appear\n * in responses.\n */\n public setIncludeLeaveRooms(includeLeave: boolean): void {\n setProp(this.definition, \"room.include_leave\", includeLeave);\n }\n\n /**\n * Set the list of fields to be included in the profile information sent down the sync stream.\n * @param ids The field IDs to sync.\n * @param stable Whether to use the stable or unstable versions of this filter.\n * @experimental\n */\n public setUnstableMSC4429SyncUserProfiles(ids: string[], stable: boolean): void {\n const field = stable\n ? profileFieldsFilterName.name\n : (profileFieldsFilterName.unstable ?? profileFieldsFilterName.name);\n this.definition[field] = { ids };\n }\n}\n"],"mappings":";;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SAASA,2BAA2B,QAAQ,kBAAkB;AAC9D,SAASC,eAAe,QAA+B,uBAAuB;AAE9E,SAASC,eAAe,QAAQ,sBAAsB;AAEtD,IAAMC,uBAAuB,GAAG,IAAID,eAAe,CAAC,gBAAgB,EAAE,mCAAmC,CAAC;;AAE1G;AACA;AACA,SAASE,OAAOA,CAACC,GAAwB,EAAEC,UAAkB,EAAEC,GAAQ,EAAQ;EAC3E,IAAMC,UAAU,GAAGF,UAAU,CAACG,KAAK,CAAC,GAAG,CAAuB;EAC9D,IAAIC,UAAU,GAAGL,GAAG;EACpB,KAAK,IAAIM,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGH,UAAU,CAACI,MAAM,GAAG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1
  import _defineProperty from "@babel/runtime/helpers/defineProperty";
2
+ import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
2
3
  function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
3
4
  function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
4
5
  /*
@@ -71,6 +72,12 @@ export class HTTPError extends Error {
71
72
  }
72
73
  }
73
74
  export class MatrixError extends HTTPError {
75
+ // The Matrix 'errcode' value, e.g. "M_FORBIDDEN".
76
+
77
+ // The Matrix 'error' value.
78
+
79
+ // The raw Matrix error JSON used to construct this object.
80
+
74
81
  /**
75
82
  * Construct a Matrix error. This is a JavaScript Error with additional
76
83
  * information specific to the standard Matrix error response.
@@ -94,12 +101,6 @@ export class MatrixError extends HTTPError {
94
101
  super("MatrixError: ".concat(message), httpStatus, httpHeaders);
95
102
  this.url = url;
96
103
  this.event = event;
97
- // The Matrix 'errcode' value, e.g. "M_FORBIDDEN".
98
- _defineProperty(this, "errcode", void 0);
99
- // The Matrix 'error' value.
100
- _defineProperty(this, "error", void 0);
101
- // The raw Matrix error JSON used to construct this object.
102
- _defineProperty(this, "data", void 0);
103
104
  this.errcode = errorJson.errcode;
104
105
  this.error = errorJson.error;
105
106
  this.name = errorJson.errcode || "Unknown error code";
@@ -131,7 +132,10 @@ export class MatrixError extends HTTPError {
131
132
  var _this$httpStatus, _this$url, _this$errcode, _this$data$error;
132
133
  var headers = {};
133
134
  if (this.httpHeaders) {
134
- for (var [name, value] of this.httpHeaders) {
135
+ for (var _ref3 of this.httpHeaders) {
136
+ var _ref2 = _slicedToArray(_ref3, 2);
137
+ var name = _ref2[0];
138
+ var value = _ref2[1];
135
139
  headers[name] = value;
136
140
  }
137
141
  }
@@ -223,17 +227,17 @@ export var MatrixSafetyErrorCode = new NamespacedValue(null, "ORG.MATRIX.MSC4387
223
227
  * @see https://github.com/matrix-org/matrix-spec-proposals/pull/4387
224
228
  */
225
229
  export class MatrixSafetyError extends MatrixError {
230
+ /**
231
+ * The kinds of harms detected by the server.
232
+ * @see https://github.com/matrix-org/matrix-spec-proposals/pull/4387 for a list of spec defined harms.
233
+ */
234
+
235
+ /**
236
+ * The date at which a request can be reattempted.
237
+ */
238
+
226
239
  constructor() {
227
240
  super(...arguments);
228
- /**
229
- * The kinds of harms detected by the server.
230
- * @see https://github.com/matrix-org/matrix-spec-proposals/pull/4387 for a list of spec defined harms.
231
- */
232
- _defineProperty(this, "harms", void 0);
233
- /**
234
- * The date at which a request can be reattempted.
235
- */
236
- _defineProperty(this, "expiry", void 0);
237
241
  var body = arguments.length <= 0 ? undefined : arguments[0];
238
242
  this.harms = new Set(body && "harms" in body && Array.isArray(body.harms) ? body.harms : []);
239
243
  this.message = "".concat(super.message, " (").concat([...this.harms].join(", "), ")");
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","names":["NamespacedValue","HTTPError","Error","constructor","msg","httpStatus","httpHeaders","isRateLimitError","getRetryAfterMs","_this$httpHeaders","retryAfter","get","test","ms","Number","parseInt","isFinite","date","Date","toUTCString","getTime","now","MatrixError","errorJson","arguments","length","undefined","url","event","message","error","concat","_defineProperty","errcode","name","data","headerValue","isInteger","retry_after_ms","asWidgetApiErrorData","_this$httpStatus","_this$url","_this$errcode","_this$data$error","headers","value","http_status","http_headers","response","_objectSpread","fromWidgetApiErrorData","Headers","safeGetRetryAfterMs","defaultMs","_error$getRetryAfterM","_unused","ConnectionError","cause","TokenRefreshError","_cause$message","TokenRefreshLogoutError","_cause$message2","MatrixSafetyErrorCode","MatrixSafetyError","body","harms","Set","Array","isArray","join","expiry"],"sources":["../../src/http-api/errors.ts"],"sourcesContent":["/*\nCopyright 2022 - 2024 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 IMatrixApiError as IWidgetMatrixError } from \"matrix-widget-api\";\n\nimport { type IUsageLimit } from \"../@types/partials.ts\";\nimport { type MatrixEvent } from \"../models/event.ts\";\nimport { NamespacedValue } from \"../NamespacedValue.ts\";\n\ninterface IErrorJson extends Partial<IUsageLimit> {\n [key: string]: any; // extensible\n errcode?: string;\n error?: string;\n}\n\n/**\n * Construct a generic HTTP error. This is a JavaScript Error with additional information\n * specific to HTTP responses.\n * @param msg - The error message to include.\n * @param httpStatus - The HTTP response status code.\n * @param httpHeaders - The HTTP response headers.\n */\nexport class HTTPError extends Error {\n public constructor(\n msg: string,\n public readonly httpStatus?: number,\n public readonly httpHeaders?: Headers,\n ) {\n super(msg);\n }\n\n /**\n * Check if this error was due to rate-limiting on the server side (and should therefore be retried after a delay).\n *\n * If this returns `true`, {@link getRetryAfterMs} can be called to retrieve the server-side\n * recommendation for the retry period.\n *\n * @returns Whether this error is due to rate-limiting.\n */\n public isRateLimitError(): boolean {\n return this.httpStatus === 429;\n }\n\n /**\n * @returns The recommended delay in milliseconds to wait before retrying\n * the request that triggered this error, or null if no delay is recommended.\n * @throws Error if the recommended delay is an invalid value.\n * @see {@link safeGetRetryAfterMs} for a version of this check that doesn't throw.\n */\n public getRetryAfterMs(): number | null {\n const retryAfter = this.httpHeaders?.get(\"Retry-After\");\n if (retryAfter != null) {\n if (/^\\d+$/.test(retryAfter)) {\n const ms = Number.parseInt(retryAfter) * 1000;\n if (!Number.isFinite(ms)) {\n throw new Error(\"Retry-After header integer value is too large\");\n }\n return ms;\n }\n const date = new Date(retryAfter);\n if (date.toUTCString() !== retryAfter) {\n throw new Error(\"Retry-After header value is not a valid HTTP-date or non-negative decimal integer\");\n }\n return date.getTime() - Date.now();\n }\n return null;\n }\n}\n\nexport class MatrixError extends HTTPError {\n // The Matrix 'errcode' value, e.g. \"M_FORBIDDEN\".\n public readonly errcode?: string;\n // The Matrix 'error' value.\n public readonly error?: string;\n // The raw Matrix error JSON used to construct this object.\n public data: IErrorJson;\n\n /**\n * Construct a Matrix error. This is a JavaScript Error with additional\n * information specific to the standard Matrix error response.\n * @param errorJson - The Matrix error JSON returned from the homeserver.\n * @param httpStatus - The numeric HTTP status code given\n * @param httpHeaders - The HTTP response headers given\n */\n public constructor(\n errorJson: IErrorJson = {},\n httpStatus?: number,\n public url?: string,\n public event?: MatrixEvent,\n httpHeaders?: Headers,\n ) {\n let message = errorJson.error || \"Unknown message\";\n if (httpStatus) {\n message = `[${httpStatus}] ${message}`;\n }\n if (url) {\n message = `${message} (${url})`;\n }\n super(`MatrixError: ${message}`, httpStatus, httpHeaders);\n this.errcode = errorJson.errcode;\n this.error = errorJson.error;\n this.name = errorJson.errcode || \"Unknown error code\";\n this.data = errorJson;\n }\n\n public isRateLimitError(): boolean {\n return (\n this.errcode === \"M_LIMIT_EXCEEDED\" ||\n ((this.errcode === \"M_UNKNOWN\" || this.errcode === undefined) && super.isRateLimitError())\n );\n }\n\n public getRetryAfterMs(): number | null {\n const headerValue = super.getRetryAfterMs();\n if (headerValue !== null) {\n return headerValue;\n }\n // Note: retry_after_ms is deprecated as of spec version v1.10\n if (this.errcode === \"M_LIMIT_EXCEEDED\" && \"retry_after_ms\" in this.data) {\n if (!Number.isInteger(this.data.retry_after_ms)) {\n throw new Error(\"retry_after_ms is not an integer\");\n }\n return this.data.retry_after_ms;\n }\n return null;\n }\n\n /**\n * @returns this error expressed as a JSON payload\n * for use by Widget API error responses.\n */\n public asWidgetApiErrorData(): IWidgetMatrixError {\n const headers: Record<string, string> = {};\n if (this.httpHeaders) {\n for (const [name, value] of this.httpHeaders) {\n headers[name] = value;\n }\n }\n return {\n http_status: this.httpStatus ?? 400,\n http_headers: headers,\n url: this.url ?? \"\",\n response: {\n errcode: this.errcode ?? \"M_UNKNOWN\",\n error: this.data.error ?? \"Unknown message\",\n ...this.data,\n },\n };\n }\n\n /**\n * @returns a new {@link MatrixError} from a JSON payload\n * received from Widget API error responses.\n */\n public static fromWidgetApiErrorData(data: IWidgetMatrixError): MatrixError {\n return new MatrixError(data.response, data.http_status, data.url, undefined, new Headers(data.http_headers));\n }\n}\n\n/**\n * @returns The recommended delay in milliseconds to wait before retrying the request.\n * @param error - The error to check for a retry delay.\n * @param defaultMs - The delay to use if the error was not due to rate-limiting or if no valid delay is recommended.\n */\nexport function safeGetRetryAfterMs(error: unknown, defaultMs: number): number {\n if (!(error instanceof HTTPError) || !error.isRateLimitError()) {\n return defaultMs;\n }\n try {\n return error.getRetryAfterMs() ?? defaultMs;\n } catch {\n return defaultMs;\n }\n}\n\n/**\n * Construct a ConnectionError. This is a JavaScript Error indicating\n * that a request failed because of some error with the connection, either\n * CORS was not correctly configured on the server, the server didn't response,\n * the request timed out, or the internet connection on the client side went down.\n */\nexport class ConnectionError extends Error {\n public constructor(message: string, cause?: Error) {\n super(message + (cause ? `: ${cause.message}` : \"\"));\n }\n\n public get name(): string {\n return \"ConnectionError\";\n }\n}\n\n/**\n * Construct a TokenRefreshError. This indicates that a request failed due to the token being expired,\n * and attempting to refresh said token also failed but in a way which was not indicative of token invalidation.\n * Assumed to be a temporary failure.\n */\nexport class TokenRefreshError extends Error {\n public constructor(cause?: Error) {\n super(cause?.message ?? \"\");\n }\n\n public get name(): string {\n return \"TokenRefreshError\";\n }\n}\n\n/**\n * Construct a TokenRefreshError. This indicates that a request failed due to the token being expired,\n * and attempting to refresh said token failed in a way indicative of token invalidation.\n */\nexport class TokenRefreshLogoutError extends Error {\n public constructor(cause?: Error) {\n super(cause?.message ?? \"\");\n }\n\n public get name(): string {\n return \"TokenRefreshLogoutError\";\n }\n}\n\nexport const MatrixSafetyErrorCode = new NamespacedValue(null, \"ORG.MATRIX.MSC4387_SAFETY\");\n\n/***\n * This error is thrown when the homeserver refuses to handle an action due to a\n * safety concern.\n * @see https://github.com/matrix-org/matrix-spec-proposals/pull/4387\n */\nexport class MatrixSafetyError extends MatrixError {\n /**\n * The kinds of harms detected by the server.\n * @see https://github.com/matrix-org/matrix-spec-proposals/pull/4387 for a list of spec defined harms.\n */\n public readonly harms: Set<string>;\n /**\n * The date at which a request can be reattempted.\n */\n public readonly expiry?: Date;\n public constructor(...props: ConstructorParameters<typeof MatrixError>) {\n super(...props);\n const body = props[0];\n\n this.harms = new Set(body && \"harms\" in body && Array.isArray(body.harms) ? body.harms : []);\n this.message = `${super.message} (${[...this.harms].join(\", \")})`;\n if (body && \"expiry\" in body && typeof body.expiry === \"number\") {\n this.expiry = new Date(body.expiry);\n }\n }\n}\n"],"mappings":";;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA,SAASA,eAAe,QAAQ,uBAAuB;AAQvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,SAAS,SAASC,KAAK,CAAC;EAC1BC,WAAWA,CACdC,GAAW,EACKC,UAAmB,EACnBC,WAAqB,EACvC;IACE,KAAK,CAACF,GAAG,CAAC;IAAC,KAHKC,UAAmB,GAAnBA,UAAmB;IAAA,KACnBC,WAAqB,GAArBA,WAAqB;EAGzC;;EAEA;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;EACWC,gBAAgBA,CAAA,EAAY;IAC/B,OAAO,IAAI,CAACF,UAAU,KAAK,GAAG;EAClC;;EAEA;AACJ;AACA;AACA;AACA;AACA;EACWG,eAAeA,CAAA,EAAkB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GAAI,EAAE,CAAC;EAC/B;EAEA,IAAW3B,IAAIA,CAAA,EAAW;IACtB,OAAO,yBAAyB;EACpC;AACJ;AAEA,OAAO,IAAM4B,qBAAqB,GAAG,IAAI9D,eAAe,CAAC,IAAI,EAAE,2BAA2B,CAAC;;AAE3F;AACA;AACA;AACA;AACA;AACA,OAAO,MAAM+D,iBAAiB,SAASzC,WAAW,CAAC;EAUxCnB,WAAWA,CAAA,EAAsD;IACpE,KAAK,CAAC,GAAAqB,SAAQ,CAAC;IAVnB;AACJ;AACA;AACA;IAHIQ,eAAA;IAKA;AACJ;AACA;IAFIA,eAAA;IAMI,IAAMgC,IAAI,GAAAxC,SAAA,CAAAC,MAAA,QAAAC,SAAA,GAAAF,SAAA,GAAW;IAErB,IAAI,CAACyC,KAAK,GAAG,IAAIC,GAAG,CAACF,IAAI,IAAI,OAAO,IAAIA,IAAI,IAAIG,KAAK,CAACC,OAAO,CAACJ,IAAI,CAACC,KAAK,CAAC,GAAGD,IAAI,CAACC,KAAK,GAAG,EAAE,CAAC;IAC5F,IAAI,CAACpC,OAAO,MAAAE,MAAA,CAAM,KAAK,CAACF,OAAO,QAAAE,MAAA,CAAK,CAAC,GAAG,IAAI,CAACkC,KAAK,CAAC,CAACI,IAAI,CAAC,IAAI,CAAC,MAAG;IACjE,IAAIL,IAAI,IAAI,QAAQ,IAAIA,IAAI,IAAI,OAAOA,IAAI,CAACM,MAAM,KAAK,QAAQ,EAAE;MAC7D,IAAI,CAACA,MAAM,GAAG,IAAIpD,IAAI,CAAC8C,IAAI,CAACM,MAAM,CAAC;IACvC;EACJ;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"errors.js","names":["NamespacedValue","HTTPError","Error","constructor","msg","httpStatus","httpHeaders","isRateLimitError","getRetryAfterMs","_this$httpHeaders","retryAfter","get","test","ms","Number","parseInt","isFinite","date","Date","toUTCString","getTime","now","MatrixError","errorJson","arguments","length","undefined","url","event","message","error","concat","errcode","name","data","headerValue","isInteger","retry_after_ms","asWidgetApiErrorData","_this$httpStatus","_this$url","_this$errcode","_this$data$error","headers","_ref3","_ref2","_slicedToArray","value","http_status","http_headers","response","_objectSpread","fromWidgetApiErrorData","Headers","safeGetRetryAfterMs","defaultMs","_error$getRetryAfterM","_unused","ConnectionError","cause","TokenRefreshError","_cause$message","TokenRefreshLogoutError","_cause$message2","MatrixSafetyErrorCode","MatrixSafetyError","body","harms","Set","Array","isArray","join","expiry"],"sources":["../../src/http-api/errors.ts"],"sourcesContent":["/*\nCopyright 2022 - 2024 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 IMatrixApiError as IWidgetMatrixError } from \"matrix-widget-api\";\n\nimport { type IUsageLimit } from \"../@types/partials.ts\";\nimport { type MatrixEvent } from \"../models/event.ts\";\nimport { NamespacedValue } from \"../NamespacedValue.ts\";\n\ninterface IErrorJson extends Partial<IUsageLimit> {\n [key: string]: any; // extensible\n errcode?: string;\n error?: string;\n}\n\n/**\n * Construct a generic HTTP error. This is a JavaScript Error with additional information\n * specific to HTTP responses.\n * @param msg - The error message to include.\n * @param httpStatus - The HTTP response status code.\n * @param httpHeaders - The HTTP response headers.\n */\nexport class HTTPError extends Error {\n public constructor(\n msg: string,\n public readonly httpStatus?: number,\n public readonly httpHeaders?: Headers,\n ) {\n super(msg);\n }\n\n /**\n * Check if this error was due to rate-limiting on the server side (and should therefore be retried after a delay).\n *\n * If this returns `true`, {@link getRetryAfterMs} can be called to retrieve the server-side\n * recommendation for the retry period.\n *\n * @returns Whether this error is due to rate-limiting.\n */\n public isRateLimitError(): boolean {\n return this.httpStatus === 429;\n }\n\n /**\n * @returns The recommended delay in milliseconds to wait before retrying\n * the request that triggered this error, or null if no delay is recommended.\n * @throws Error if the recommended delay is an invalid value.\n * @see {@link safeGetRetryAfterMs} for a version of this check that doesn't throw.\n */\n public getRetryAfterMs(): number | null {\n const retryAfter = this.httpHeaders?.get(\"Retry-After\");\n if (retryAfter != null) {\n if (/^\\d+$/.test(retryAfter)) {\n const ms = Number.parseInt(retryAfter) * 1000;\n if (!Number.isFinite(ms)) {\n throw new Error(\"Retry-After header integer value is too large\");\n }\n return ms;\n }\n const date = new Date(retryAfter);\n if (date.toUTCString() !== retryAfter) {\n throw new Error(\"Retry-After header value is not a valid HTTP-date or non-negative decimal integer\");\n }\n return date.getTime() - Date.now();\n }\n return null;\n }\n}\n\nexport class MatrixError extends HTTPError {\n // The Matrix 'errcode' value, e.g. \"M_FORBIDDEN\".\n public readonly errcode?: string;\n // The Matrix 'error' value.\n public readonly error?: string;\n // The raw Matrix error JSON used to construct this object.\n public data: IErrorJson;\n\n /**\n * Construct a Matrix error. This is a JavaScript Error with additional\n * information specific to the standard Matrix error response.\n * @param errorJson - The Matrix error JSON returned from the homeserver.\n * @param httpStatus - The numeric HTTP status code given\n * @param httpHeaders - The HTTP response headers given\n */\n public constructor(\n errorJson: IErrorJson = {},\n httpStatus?: number,\n public url?: string,\n public event?: MatrixEvent,\n httpHeaders?: Headers,\n ) {\n let message = errorJson.error || \"Unknown message\";\n if (httpStatus) {\n message = `[${httpStatus}] ${message}`;\n }\n if (url) {\n message = `${message} (${url})`;\n }\n super(`MatrixError: ${message}`, httpStatus, httpHeaders);\n this.errcode = errorJson.errcode;\n this.error = errorJson.error;\n this.name = errorJson.errcode || \"Unknown error code\";\n this.data = errorJson;\n }\n\n public isRateLimitError(): boolean {\n return (\n this.errcode === \"M_LIMIT_EXCEEDED\" ||\n ((this.errcode === \"M_UNKNOWN\" || this.errcode === undefined) && super.isRateLimitError())\n );\n }\n\n public getRetryAfterMs(): number | null {\n const headerValue = super.getRetryAfterMs();\n if (headerValue !== null) {\n return headerValue;\n }\n // Note: retry_after_ms is deprecated as of spec version v1.10\n if (this.errcode === \"M_LIMIT_EXCEEDED\" && \"retry_after_ms\" in this.data) {\n if (!Number.isInteger(this.data.retry_after_ms)) {\n throw new Error(\"retry_after_ms is not an integer\");\n }\n return this.data.retry_after_ms;\n }\n return null;\n }\n\n /**\n * @returns this error expressed as a JSON payload\n * for use by Widget API error responses.\n */\n public asWidgetApiErrorData(): IWidgetMatrixError {\n const headers: Record<string, string> = {};\n if (this.httpHeaders) {\n for (const [name, value] of this.httpHeaders) {\n headers[name] = value;\n }\n }\n return {\n http_status: this.httpStatus ?? 400,\n http_headers: headers,\n url: this.url ?? \"\",\n response: {\n errcode: this.errcode ?? \"M_UNKNOWN\",\n error: this.data.error ?? \"Unknown message\",\n ...this.data,\n },\n };\n }\n\n /**\n * @returns a new {@link MatrixError} from a JSON payload\n * received from Widget API error responses.\n */\n public static fromWidgetApiErrorData(data: IWidgetMatrixError): MatrixError {\n return new MatrixError(data.response, data.http_status, data.url, undefined, new Headers(data.http_headers));\n }\n}\n\n/**\n * @returns The recommended delay in milliseconds to wait before retrying the request.\n * @param error - The error to check for a retry delay.\n * @param defaultMs - The delay to use if the error was not due to rate-limiting or if no valid delay is recommended.\n */\nexport function safeGetRetryAfterMs(error: unknown, defaultMs: number): number {\n if (!(error instanceof HTTPError) || !error.isRateLimitError()) {\n return defaultMs;\n }\n try {\n return error.getRetryAfterMs() ?? defaultMs;\n } catch {\n return defaultMs;\n }\n}\n\n/**\n * Construct a ConnectionError. This is a JavaScript Error indicating\n * that a request failed because of some error with the connection, either\n * CORS was not correctly configured on the server, the server didn't response,\n * the request timed out, or the internet connection on the client side went down.\n */\nexport class ConnectionError extends Error {\n public constructor(message: string, cause?: Error) {\n super(message + (cause ? `: ${cause.message}` : \"\"));\n }\n\n public get name(): string {\n return \"ConnectionError\";\n }\n}\n\n/**\n * Construct a TokenRefreshError. This indicates that a request failed due to the token being expired,\n * and attempting to refresh said token also failed but in a way which was not indicative of token invalidation.\n * Assumed to be a temporary failure.\n */\nexport class TokenRefreshError extends Error {\n public constructor(cause?: Error) {\n super(cause?.message ?? \"\");\n }\n\n public get name(): string {\n return \"TokenRefreshError\";\n }\n}\n\n/**\n * Construct a TokenRefreshError. This indicates that a request failed due to the token being expired,\n * and attempting to refresh said token failed in a way indicative of token invalidation.\n */\nexport class TokenRefreshLogoutError extends Error {\n public constructor(cause?: Error) {\n super(cause?.message ?? \"\");\n }\n\n public get name(): string {\n return \"TokenRefreshLogoutError\";\n }\n}\n\nexport const MatrixSafetyErrorCode = new NamespacedValue(null, \"ORG.MATRIX.MSC4387_SAFETY\");\n\n/***\n * This error is thrown when the homeserver refuses to handle an action due to a\n * safety concern.\n * @see https://github.com/matrix-org/matrix-spec-proposals/pull/4387\n */\nexport class MatrixSafetyError extends MatrixError {\n /**\n * The kinds of harms detected by the server.\n * @see https://github.com/matrix-org/matrix-spec-proposals/pull/4387 for a list of spec defined harms.\n */\n public readonly harms: Set<string>;\n /**\n * The date at which a request can be reattempted.\n */\n public readonly expiry?: Date;\n public constructor(...props: ConstructorParameters<typeof MatrixError>) {\n super(...props);\n const body = props[0];\n\n this.harms = new Set(body && \"harms\" in body && Array.isArray(body.harms) ? body.harms : []);\n this.message = `${super.message} (${[...this.harms].join(\", \")})`;\n if (body && \"expiry\" in body && typeof body.expiry === \"number\") {\n this.expiry = new Date(body.expiry);\n }\n }\n}\n"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA,SAASA,eAAe,QAAQ,uBAAuB;AAQvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,SAAS,SAASC,KAAK,CAAC;EAC1BC,WAAWA,CACdC,GAAW,EACKC,UAAmB,EACnBC,WAAqB,EACvC;IACE,KAAK,CAACF,GAAG,CAAC;IAAC,KAHKC,UAAmB,GAAnBA,UAAmB;IAAA,KACn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}
@@ -31,10 +31,9 @@ import { TokenRefresher, TokenRefreshOutcome } from "./refresh.js";
31
31
  export class FetchHttpApi {
32
32
  constructor(eventEmitter, opts) {
33
33
  var _opts$useAuthorizatio;
34
+ _defineProperty(this, "abortController", new AbortController());
34
35
  this.eventEmitter = eventEmitter;
35
36
  this.opts = opts;
36
- _defineProperty(this, "abortController", new AbortController());
37
- _defineProperty(this, "tokenRefresher", void 0);
38
37
  checkObjectHasKeys(opts, ["baseUrl", "prefix"]);
39
38
  if (!opts.onlyData) {
40
39
  throw new Error("Constructing FetchHttpApi without `onlyData=true` is no longer supported.");
@@ -235,10 +234,9 @@ export class FetchHttpApi {
235
234
  } else {
236
235
  data = body;
237
236
  }
238
- var {
239
- signal,
240
- cleanup
241
- } = anySignal(signals);
237
+ var _anySignal = anySignal(signals),
238
+ signal = _anySignal.signal,
239
+ cleanup = _anySignal.cleanup;
242
240
 
243
241
  // Set cache mode based on presence of Authorization header.
244
242
  // Browsers/proxies do not cache responses to requests with Authorization headers.