@matrix-widget-toolkit/api 3.3.0 → 3.3.2

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.
@@ -1,6 +1,6 @@
1
- import { WidgetEventCapability, EventDirection, Symbols, WidgetApi, WidgetApiToWidgetAction, MatrixCapabilities } from 'matrix-widget-api';
2
- import { fromEvent, firstValueFrom, map, first, throwError, from, mergeAll, filter, concat, ReplaySubject, share } from 'rxjs';
3
- import { parse, stringify } from 'qs';
1
+ import { Symbols, WidgetEventCapability, EventDirection, WidgetApi, WidgetApiToWidgetAction, MatrixCapabilities } from 'matrix-widget-api';
2
+ import { stringify, parse } from 'qs';
3
+ import { filter, fromEvent, firstValueFrom, map, first, throwError, from, mergeAll, concat, ReplaySubject, share } from 'rxjs';
4
4
 
5
5
  /*
6
6
  * Copyright 2022 Nordeck IT + Consulting GmbH
@@ -17,92 +17,112 @@ import { parse, stringify } from 'qs';
17
17
  * See the License for the specific language governing permissions and
18
18
  * limitations under the License.
19
19
  */
20
- var __assign$1 = (undefined && undefined.__assign) || function () {
21
- __assign$1 = Object.assign || function(t) {
22
- for (var s, i = 1, n = arguments.length; i < n; i++) {
23
- s = arguments[i];
24
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
25
- t[p] = s[p];
26
- }
27
- return t;
28
- };
29
- return __assign$1.apply(this, arguments);
30
- };
31
20
  /**
32
- * Extract the parameters used to initialize the widget API from the current
33
- * `window.location`.
34
- * @returns The parameters required for initializing the widget API.
21
+ * Generate a list of capabilities to access the timeline of other rooms.
22
+ * If enabled, all previously or future capabilities will apply to _all_
23
+ * selected rooms.
24
+ * If `Symbols.AnyRoom` is passed, this is expanded to all joined
25
+ * or invited rooms the client is able to see, current and future.
26
+ *
27
+ * @param roomIds - a list of room ids or `@link Symbols.AnyRoom`.
28
+ * @returns the generated capabilities.
35
29
  */
36
- function extractWidgetApiParameters() {
37
- var query = parse(window.location.search, { ignoreQueryPrefix: true });
38
- // If either parentUrl or widgetId is missing, we have no element context and
39
- // want to inform the user that the widget only works inside of element.
40
- if (typeof query.parentUrl !== 'string') {
41
- throw Error('Missing parameter "parentUrl"');
30
+ function generateRoomTimelineCapabilities(roomIds) {
31
+ if (roomIds === Symbols.AnyRoom) {
32
+ return ['org.matrix.msc2762.timeline:*'];
42
33
  }
43
- var clientOrigin = new URL(query.parentUrl).origin;
44
- if (typeof query.widgetId !== 'string') {
45
- throw Error('Missing parameter "widgetId"');
34
+ if (Array.isArray(roomIds)) {
35
+ return roomIds.map(function (id) { return "org.matrix.msc2762.timeline:".concat(id); });
46
36
  }
47
- var widgetId = query.widgetId;
48
- return { widgetId: widgetId, clientOrigin: clientOrigin };
37
+ return [];
49
38
  }
39
+
40
+ /*
41
+ * Copyright 2022 Nordeck IT + Consulting GmbH
42
+ *
43
+ * Licensed under the Apache License, Version 2.0 (the "License");
44
+ * you may not use this file except in compliance with the License.
45
+ * You may obtain a copy of the License at
46
+ *
47
+ * http://www.apache.org/licenses/LICENSE-2.0
48
+ *
49
+ * Unless required by applicable law or agreed to in writing, software
50
+ * distributed under the License is distributed on an "AS IS" BASIS,
51
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
52
+ * See the License for the specific language governing permissions and
53
+ * limitations under the License.
54
+ */
50
55
  /**
51
- * Extract the widget parameters from the current `window.location`.
52
- * @returns The all unprocessed raw widget parameters.
56
+ * Generate a unique displayname of a user that is consistent across Matrix clients.
57
+ *
58
+ * @remarks The algorithm is based on https://spec.matrix.org/v1.1/client-server-api/#calculating-the-display-name-for-a-user
59
+ *
60
+ * @param member - the member to generate a name for.
61
+ * @param allRoomMembers - a list of all members of the same room.
62
+ * @returns the displayname that is unique in given the set of all room members.
53
63
  */
54
- function extractRawWidgetParameters() {
55
- var hash = window.location.hash.substring(window.location.hash.indexOf('?') + 1);
56
- var params = __assign$1(__assign$1({}, parse(window.location.search, { ignoreQueryPrefix: true })), parse(hash));
57
- return Object.fromEntries(Object.entries(params).filter(
58
- // For now only use simple values, don't allow them to be specified more
59
- // than once.
60
- function (e) { return typeof e[1] === 'string'; }));
64
+ function getRoomMemberDisplayName(member, allRoomMembers) {
65
+ if (allRoomMembers === void 0) { allRoomMembers = []; }
66
+ // If the m.room.member state event has no displayname field, or if that field
67
+ // has a null value, use the raw user id as the display name.
68
+ if (typeof member.content.displayname !== 'string') {
69
+ return member.state_key;
70
+ }
71
+ // If the m.room.member event has a displayname which is unique among members of
72
+ // the room with membership: join or membership: invite, ...
73
+ var hasDuplicateDisplayName = allRoomMembers.some(function (m) {
74
+ // same room
75
+ return m.room_id === member.room_id &&
76
+ // not the own event
77
+ m.state_key !== member.state_key &&
78
+ // only join or invite state
79
+ ['join', 'invite'].includes(m.content.membership) &&
80
+ // same displayname
81
+ m.content.displayname === member.content.displayname;
82
+ });
83
+ if (!hasDuplicateDisplayName) {
84
+ // ... use the given displayname as the user-visible display name.
85
+ return member.content.displayname;
86
+ }
87
+ else {
88
+ // The m.room.member event has a non-unique displayname. This should be
89
+ // disambiguated using the user id, for example “display name (@id:homeserver.org)”.
90
+ return "".concat(member.content.displayname, " (").concat(member.state_key, ")");
91
+ }
61
92
  }
93
+
94
+ /*
95
+ * Copyright 2022 Nordeck IT + Consulting GmbH
96
+ *
97
+ * Licensed under the Apache License, Version 2.0 (the "License");
98
+ * you may not use this file except in compliance with the License.
99
+ * You may obtain a copy of the License at
100
+ *
101
+ * http://www.apache.org/licenses/LICENSE-2.0
102
+ *
103
+ * Unless required by applicable law or agreed to in writing, software
104
+ * distributed under the License is distributed on an "AS IS" BASIS,
105
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
106
+ * See the License for the specific language governing permissions and
107
+ * limitations under the License.
108
+ */
62
109
  /**
63
- * Extract the widget parameters from the current `window.location`.
64
- * @returns The widget parameters.
110
+ * Check if the given event is a {@link StateEvent}.
111
+ *
112
+ * @param event - An event that is either a {@link RoomEvent} or a {@link StateEvent}.
113
+ * @returns True, if the event is a {@link StateEvent}.
65
114
  */
66
- function extractWidgetParameters() {
67
- var params = extractRawWidgetParameters();
68
- // This is a hack to detect whether we are in a mobile client that supports widgets,
69
- // but not the widget API. Mobile clients are not passing the parameters required for
70
- // the widget API (like widgetId), but are passing the replaced placeholder values for
71
- // the widget parameters.
72
- var roomId = params['matrix_room_id'];
73
- var isOpenedByClient = typeof roomId === 'string' && roomId !== '$matrix_room_id';
74
- return {
75
- userId: params['matrix_user_id'],
76
- displayName: params['matrix_display_name'],
77
- avatarUrl: params['matrix_avatar_url'],
78
- roomId: roomId,
79
- theme: params['theme'],
80
- clientId: params['matrix_client_id'],
81
- clientLanguage: params['matrix_client_language'],
82
- isOpenedByClient: isOpenedByClient,
83
- };
115
+ function isStateEvent(event) {
116
+ return 'state_key' in event && typeof event.state_key === 'string';
84
117
  }
85
118
  /**
86
- * Parse a widget id into the individual fields.
87
- * @param widgetId - The widget id to parse.
88
- * @returns The individual fields encoded inside a widget id.
119
+ * Check if the given event is a {@link RoomEvent}.
120
+ *
121
+ * @param event - An event that is either a {@link RoomEvent} or a {@link StateEvent}.
122
+ * @returns True, if the event is a {@link RoomEvent}.
89
123
  */
90
- function parseWidgetId(widgetId) {
91
- // TODO: Is this whole parsing still working for user widgets?
92
- var mainWidgetId = decodeURIComponent(widgetId).replace(/^modal_/, '');
93
- var roomId = mainWidgetId.indexOf('_')
94
- ? decodeURIComponent(mainWidgetId.split('_')[0])
95
- : undefined;
96
- var creator = (mainWidgetId.match(/_/g) || []).length > 1
97
- ? decodeURIComponent(mainWidgetId.split('_')[1])
98
- : undefined;
99
- var isModal = decodeURIComponent(widgetId).startsWith('modal_');
100
- return {
101
- mainWidgetId: mainWidgetId,
102
- roomId: roomId,
103
- creator: creator,
104
- isModal: isModal,
105
- };
124
+ function isRoomEvent(event) {
125
+ return !('state_key' in event);
106
126
  }
107
127
 
108
128
  /*
@@ -120,17 +140,6 @@ function parseWidgetId(widgetId) {
120
140
  * See the License for the specific language governing permissions and
121
141
  * limitations under the License.
122
142
  */
123
- var __assign = (undefined && undefined.__assign) || function () {
124
- __assign = Object.assign || function(t) {
125
- for (var s, i = 1, n = arguments.length; i < n; i++) {
126
- s = arguments[i];
127
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
128
- t[p] = s[p];
129
- }
130
- return t;
131
- };
132
- return __assign.apply(this, arguments);
133
- };
134
143
  var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
135
144
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
136
145
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -167,124 +176,63 @@ var __generator$3 = (undefined && undefined.__generator) || function (thisArg, b
167
176
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
168
177
  }
169
178
  };
170
- var __rest = (undefined && undefined.__rest) || function (s, e) {
171
- var t = {};
172
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
173
- t[p] = s[p];
174
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
175
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
176
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
177
- t[p[i]] = s[p[i]];
178
- }
179
- return t;
180
- };
181
179
  /**
182
- * Checks whether all widget parameters were provided to the widget.
183
- *
184
- * @param widgetApi - The widget api to read the parameters from
185
- * @returns True, if all parameters were provided.
180
+ * The capability that needs to be requested in order to navigate to another room.
186
181
  */
187
- function hasRequiredWidgetParameters(widgetApi) {
188
- return (typeof widgetApi.widgetParameters.userId === 'string' &&
189
- typeof widgetApi.widgetParameters.displayName === 'string' &&
190
- typeof widgetApi.widgetParameters.avatarUrl === 'string' &&
191
- typeof widgetApi.widgetParameters.roomId === 'string' &&
192
- typeof widgetApi.widgetParameters.theme === 'string' &&
193
- typeof widgetApi.widgetParameters.clientId === 'string' &&
194
- typeof widgetApi.widgetParameters.clientLanguage === 'string');
195
- }
182
+ var WIDGET_CAPABILITY_NAVIGATE = 'org.matrix.msc2931.navigate';
196
183
  /**
197
- * Generate a registration URL for the widget based on the current URL and
198
- * include all widget parameters (and their placeholders).
199
- * @param options - Options for generating the URL.
200
- * Use `pathName` to include an optional sub path in the URL.
201
- * Use `includeParameters` to append the widget parameters to
202
- * the URL, defaults to `true`.
203
- * @returns The generated URL.
184
+ * Navigate the client to another matrix room.
185
+ *
186
+ * @remarks This requires the {@link WIDGET_CAPABILITY_NAVIGATE} capability.
187
+ *
188
+ * @param widgetApi - the {@link WidgetApi} instance.
189
+ * @param roomId - the room ID.
190
+ * @param opts - {@link NavigateToRoomOptions}
204
191
  */
205
- function generateWidgetRegistrationUrl(options) {
206
- var _a, _b, _c, _d, _e, _f, _g;
207
- if (options === void 0) { options = {}; }
208
- var pathName = options.pathName, _h = options.includeParameters, includeParameters = _h === void 0 ? true : _h, widgetParameters = options.widgetParameters;
209
- // don't forward widgetId and parentUrl as they will be generated by the client
210
- var _j = extractRawWidgetParameters(); _j.widgetId; _j.parentUrl; var rawWidgetParameters = __rest(_j, ["widgetId", "parentUrl"]);
211
- var parameters = Object.entries(__assign(__assign({}, rawWidgetParameters), { theme: (_a = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.theme) !== null && _a !== void 0 ? _a : '$org.matrix.msc2873.client_theme', matrix_user_id: (_b = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.userId) !== null && _b !== void 0 ? _b : '$matrix_user_id', matrix_display_name: (_c = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.displayName) !== null && _c !== void 0 ? _c : '$matrix_display_name', matrix_avatar_url: (_d = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.avatarUrl) !== null && _d !== void 0 ? _d : '$matrix_avatar_url', matrix_room_id: (_e = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.roomId) !== null && _e !== void 0 ? _e : '$matrix_room_id', matrix_client_id: (_f = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.clientId) !== null && _f !== void 0 ? _f : '$org.matrix.msc2873.client_id', matrix_client_language: (_g = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.clientLanguage) !== null && _g !== void 0 ? _g : '$org.matrix.msc2873.client_language' }))
212
- .map(function (_a) {
213
- var k = _a[0], v = _a[1];
214
- return "".concat(k, "=").concat(v);
215
- })
216
- .join('&');
217
- var url = new URL(window.location.href);
218
- if (pathName) {
219
- url.pathname = pathName;
220
- }
221
- else {
222
- // ensure trailing '/'
223
- url.pathname = url.pathname.replace(/\/?$/, '/');
224
- }
225
- url.search = '';
226
- url.hash = includeParameters ? "#/?".concat(parameters) : '';
227
- return url.toString();
192
+ function navigateToRoom(widgetApi_1, roomId_1) {
193
+ return __awaiter$3(this, arguments, void 0, function (widgetApi, roomId, opts) {
194
+ var _a, via, params, url;
195
+ if (opts === void 0) { opts = {}; }
196
+ return __generator$3(this, function (_b) {
197
+ switch (_b.label) {
198
+ case 0:
199
+ _a = opts.via, via = _a === void 0 ? [] : _a;
200
+ params = stringify({ via: via }, { addQueryPrefix: true, arrayFormat: 'repeat' });
201
+ url = "https://matrix.to/#/".concat(encodeURIComponent(roomId)).concat(params);
202
+ return [4 /*yield*/, widgetApi.navigateTo(url)];
203
+ case 1:
204
+ _b.sent();
205
+ return [2 /*return*/];
206
+ }
207
+ });
208
+ });
228
209
  }
229
- var STATE_EVENT_WIDGETS = 'im.vector.modular.widgets';
230
- /**
231
- * Repair/configure the registration of the current widget.
232
- * This steps make sure to include all the required widget parameters in the
233
- * URL. Support setting a widget name and additional parameters.
210
+
211
+ /*
212
+ * Copyright 2022 Nordeck IT + Consulting GmbH
234
213
  *
235
- * @param widgetApi - The widget api of the current widget.
236
- * @param registration - Optional configuration options for the widget
237
- * registration, like the display name of the widget.
214
+ * Licensed under the Apache License, Version 2.0 (the "License");
215
+ * you may not use this file except in compliance with the License.
216
+ * You may obtain a copy of the License at
217
+ *
218
+ * http://www.apache.org/licenses/LICENSE-2.0
219
+ *
220
+ * Unless required by applicable law or agreed to in writing, software
221
+ * distributed under the License is distributed on an "AS IS" BASIS,
222
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
223
+ * See the License for the specific language governing permissions and
224
+ * limitations under the License.
238
225
  */
239
- function repairWidgetRegistration(widgetApi, registration) {
240
- if (registration === void 0) { registration = {}; }
241
- return __awaiter$3(this, void 0, void 0, function () {
242
- var readResult, url, name, type, data;
243
- return __generator$3(this, function (_a) {
244
- switch (_a.label) {
245
- case 0: return [4 /*yield*/, widgetApi.requestCapabilities([
246
- WidgetEventCapability.forStateEvent(EventDirection.Send, STATE_EVENT_WIDGETS, widgetApi.widgetId),
247
- WidgetEventCapability.forStateEvent(EventDirection.Receive, STATE_EVENT_WIDGETS, widgetApi.widgetId),
248
- ])];
249
- case 1:
250
- _a.sent();
251
- return [4 /*yield*/, widgetApi.receiveSingleStateEvent(STATE_EVENT_WIDGETS, widgetApi.widgetId)];
252
- case 2:
253
- readResult = _a.sent();
254
- if (!readResult) {
255
- throw new Error("Error while repairing registration, can't find existing registration.");
256
- }
257
- url = generateWidgetRegistrationUrl();
258
- name = registration.name &&
259
- (!readResult.content.name ||
260
- readResult.content.name === 'Custom Widget' ||
261
- readResult.content.name === 'Custom')
262
- ? registration.name
263
- : readResult.content.name;
264
- type = registration.type &&
265
- (!readResult.content.type || readResult.content.type === 'm.custom')
266
- ? registration.type
267
- : readResult.content.type;
268
- data = registration.data
269
- ? __assign(__assign({}, readResult.content.data), registration.data) : readResult.content.data;
270
- // This is a workaround because changing the widget config is breaking the
271
- // widget API communication. However we need to fail in case the power level
272
- // for this change is missing. As the error happens quite fast, we just wait
273
- // a moment and then consider the operation as succeeded.
274
- return [4 /*yield*/, Promise.race([
275
- widgetApi.sendStateEvent(STATE_EVENT_WIDGETS, __assign(__assign({}, readResult.content), { url: url.toString(), name: name, type: type, data: data }), { stateKey: widgetApi.widgetId }),
276
- new Promise(function (resolve) { return setTimeout(resolve, 1000); }),
277
- ])];
278
- case 3:
279
- // This is a workaround because changing the widget config is breaking the
280
- // widget API communication. However we need to fail in case the power level
281
- // for this change is missing. As the error happens quite fast, we just wait
282
- // a moment and then consider the operation as succeeded.
283
- _a.sent();
284
- return [2 /*return*/];
285
- }
286
- });
287
- });
226
+ /**
227
+ * Compares two room events by their origin server timestamp.
228
+ *
229
+ * @param a - A room event
230
+ * @param b - A room event
231
+ * @returns Either zero if the timestamp is equal, \>0 if a is newer, or \<0 if
232
+ * b is newer.
233
+ */
234
+ function compareOriginServerTS(a, b) {
235
+ return a.origin_server_ts - b.origin_server_ts;
288
236
  }
289
237
 
290
238
  /*
@@ -302,31 +250,176 @@ function repairWidgetRegistration(widgetApi, registration) {
302
250
  * See the License for the specific language governing permissions and
303
251
  * limitations under the License.
304
252
  */
305
- function convertToRawCapabilities(rawCapabilities) {
306
- return rawCapabilities.map(function (c) { return (typeof c === 'string' ? c : c.raw); });
253
+ /**
254
+ * The name of the power levels state event.
255
+ */
256
+ var STATE_EVENT_POWER_LEVELS = 'm.room.power_levels';
257
+ function isNumberOrUndefined(value) {
258
+ return value === undefined || typeof value === 'number';
307
259
  }
308
- function isDefined(arg) {
309
- return arg !== null && arg !== undefined;
260
+ function isStringToNumberMapOrUndefined(value) {
261
+ return (value === undefined ||
262
+ (value !== null &&
263
+ typeof value === 'object' &&
264
+ Object.entries(value).every(function (_a) {
265
+ var k = _a[0], v = _a[1];
266
+ return typeof k === 'string' && typeof v === 'number';
267
+ })));
310
268
  }
311
- function unique(items) {
312
- return Array.from(new Set(items));
269
+ /**
270
+ * Validates that `event` is has a valid structure for a
271
+ * {@link PowerLevelsStateEvent}.
272
+ * @param event - The event to validate.
273
+ * @returns True, if the event is valid.
274
+ */
275
+ function isValidPowerLevelStateEvent(event) {
276
+ if (event.type !== STATE_EVENT_POWER_LEVELS ||
277
+ typeof event.content !== 'object') {
278
+ return false;
279
+ }
280
+ var content = event.content;
281
+ if (!isStringToNumberMapOrUndefined(content.events)) {
282
+ return false;
283
+ }
284
+ if (!isNumberOrUndefined(content.state_default)) {
285
+ return false;
286
+ }
287
+ if (!isNumberOrUndefined(content.events_default)) {
288
+ return false;
289
+ }
290
+ if (!isStringToNumberMapOrUndefined(content.users)) {
291
+ return false;
292
+ }
293
+ if (!isNumberOrUndefined(content.users_default)) {
294
+ return false;
295
+ }
296
+ if (!isNumberOrUndefined(content.ban)) {
297
+ return false;
298
+ }
299
+ if (!isNumberOrUndefined(content.invite)) {
300
+ return false;
301
+ }
302
+ if (!isNumberOrUndefined(content.kick)) {
303
+ return false;
304
+ }
305
+ if (!isNumberOrUndefined(content.redact)) {
306
+ return false;
307
+ }
308
+ return true;
313
309
  }
314
- function subtractSet(as, bs) {
315
- var result = new Set(as);
316
- bs.forEach(function (v) { return result.delete(v); });
317
- return result;
310
+ /**
311
+ * Check if a user has the power to send a specific room event.
312
+ *
313
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
314
+ * @param userId - the id of the user
315
+ * @param eventType - the type of room event
316
+ * @returns if true, the user has the power
317
+ */
318
+ function hasRoomEventPower(powerLevelStateEvent, userId, eventType) {
319
+ if (!powerLevelStateEvent) {
320
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L36-L43
321
+ return true;
322
+ }
323
+ var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
324
+ var eventLevel = calculateRoomEventPowerLevel(powerLevelStateEvent, eventType);
325
+ return userLevel >= eventLevel;
318
326
  }
319
- function isInRoom(matrixEvent, currentRoomId, roomIds) {
320
- if (!roomIds) {
321
- return matrixEvent.room_id === currentRoomId;
327
+ /**
328
+ * Check if a user has the power to send a specific state event.
329
+ *
330
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
331
+ * @param userId - the id of the user
332
+ * @param eventType - the type of state event
333
+ * @returns if true, the user has the power
334
+ */
335
+ function hasStateEventPower(powerLevelStateEvent, userId, eventType) {
336
+ if (!powerLevelStateEvent) {
337
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L36-L43
338
+ return true;
322
339
  }
323
- if (typeof roomIds === 'string') {
324
- if (roomIds !== Symbols.AnyRoom) {
325
- throw Error("Unknown room id symbol: ".concat(roomIds));
326
- }
340
+ var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
341
+ var eventLevel = calculateStateEventPowerLevel(powerLevelStateEvent, eventType);
342
+ return userLevel >= eventLevel;
343
+ }
344
+ /**
345
+ * Check if a user has the power to perform a specific action.
346
+ *
347
+ * Supported actions:
348
+ * * invite: Invite a new user into the room
349
+ * * kick: Kick a user from the room
350
+ * * ban: Ban a user from the room
351
+ * * redact: Redact a message from another user
352
+ *
353
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
354
+ * @param userId - the id of the user
355
+ * @param action - the action
356
+ * @returns if true, the user has the power
357
+ */
358
+ function hasActionPower(powerLevelStateEvent, userId, action) {
359
+ if (!powerLevelStateEvent) {
360
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L36-L43
327
361
  return true;
328
362
  }
329
- return roomIds.includes(matrixEvent.room_id);
363
+ var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
364
+ var eventLevel = calculateActionPowerLevel(powerLevelStateEvent, action);
365
+ return userLevel >= eventLevel;
366
+ }
367
+ /**
368
+ * Calculate the power level of the user based on a `m.room.power_levels` event.
369
+ *
370
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event.
371
+ * @param userId - the ID of the user.
372
+ * @returns the power level of the user.
373
+ */
374
+ function calculateUserPowerLevel(powerLevelStateEvent, userId) {
375
+ var _a, _b, _c;
376
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L8-L12
377
+ return ((_c = (_b = (userId ? (_a = powerLevelStateEvent.users) === null || _a === void 0 ? void 0 : _a[userId] : undefined)) !== null && _b !== void 0 ? _b : powerLevelStateEvent.users_default) !== null && _c !== void 0 ? _c : 0);
378
+ }
379
+ /**
380
+ * Calculate the power level that a user needs send a specific room event.
381
+ *
382
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
383
+ * @param eventType - the type of room event
384
+ * @returns the power level that is needed
385
+ */
386
+ function calculateRoomEventPowerLevel(powerLevelStateEvent, eventType) {
387
+ var _a, _b, _c;
388
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L14-L19
389
+ return ((_c = (_b = (_a = powerLevelStateEvent.events) === null || _a === void 0 ? void 0 : _a[eventType]) !== null && _b !== void 0 ? _b : powerLevelStateEvent.events_default) !== null && _c !== void 0 ? _c : 0);
390
+ }
391
+ /**
392
+ * Calculate the power level that a user needs send a specific state event.
393
+ *
394
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
395
+ * @param eventType - the type of state event
396
+ * @returns the power level that is needed
397
+ */
398
+ function calculateStateEventPowerLevel(powerLevelStateEvent, eventType) {
399
+ var _a, _b, _c;
400
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L14-L19
401
+ return ((_c = (_b = (_a = powerLevelStateEvent.events) === null || _a === void 0 ? void 0 : _a[eventType]) !== null && _b !== void 0 ? _b : powerLevelStateEvent.state_default) !== null && _c !== void 0 ? _c : 50);
402
+ }
403
+ /**
404
+ * Calculate the power level that a user needs to perform an action.
405
+ *
406
+ * Supported actions:
407
+ * * invite: Invite a new user into the room
408
+ * * kick: Kick a user from the room
409
+ * * ban: Ban a user from the room
410
+ * * redact: Redact a message from another user
411
+ *
412
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
413
+ * @param action - the action
414
+ * @returns the power level that is needed
415
+ */
416
+ function calculateActionPowerLevel(powerLevelStateEvent, action) {
417
+ var _a, _b;
418
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L27-L32
419
+ if (action === 'invite') {
420
+ return (_a = powerLevelStateEvent === null || powerLevelStateEvent === void 0 ? void 0 : powerLevelStateEvent[action]) !== null && _a !== void 0 ? _a : 0;
421
+ }
422
+ return (_b = powerLevelStateEvent === null || powerLevelStateEvent === void 0 ? void 0 : powerLevelStateEvent[action]) !== null && _b !== void 0 ? _b : 50;
330
423
  }
331
424
 
332
425
  /*
@@ -380,672 +473,452 @@ var __generator$2 = (undefined && undefined.__generator) || function (thisArg, b
380
473
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
381
474
  }
382
475
  };
383
- var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
384
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
385
- if (ar || !(i in from)) {
386
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
387
- ar[i] = from[i];
388
- }
476
+ /**
477
+ * The name of the redaction room event.
478
+ */
479
+ var ROOM_EVENT_REDACTION = 'm.room.redaction';
480
+ /**
481
+ * Check whether the format of a redaction event is valid.
482
+ * @param event - The event to check.
483
+ * @returns True if the event format is valid, otherwise false.
484
+ */
485
+ function isValidRedactionEvent(event) {
486
+ if (event.type === ROOM_EVENT_REDACTION &&
487
+ typeof event.redacts === 'string') {
488
+ return true;
389
489
  }
390
- return to.concat(ar || Array.prototype.slice.call(from));
391
- };
490
+ return false;
491
+ }
392
492
  /**
393
- * Implementation of the API from the widget to the client.
394
- *
395
- * @remarks Widget API is specified here:
396
- * https://docs.google.com/document/d/1uPF7XWY_dXTKVKV7jZQ2KmsI19wn9-kFRgQ1tFQP7wQ/edit#heading=h.9rn9lt6ctkgi
493
+ * Redacts an event in the current room.
494
+ * @param widgetApi - An instance of the widget API.
495
+ * @param eventId - The id of the event to redact.
496
+ * @returns The redaction event that was send to the room.
397
497
  */
398
- var WidgetApiImpl = /** @class */ (function () {
399
- function WidgetApiImpl(
400
- /**
401
- * Provide access to the underlying widget API from `matrix-widget-sdk`.
402
- *
403
- * @remarks Normally there is no need to use it, however if features are
404
- * missing from `WidgetApi` it can be handy to work with the
405
- * original API.
406
- */
407
- matrixWidgetApi,
408
- /** {@inheritDoc WidgetApi.widgetId} */
409
- widgetId,
410
- /** {@inheritDoc WidgetApi.widgetParameters} */
411
- widgetParameters, _a) {
412
- var _this = this;
413
- var _b = _a === void 0 ? {} : _a, _c = _b.capabilities, capabilities = _c === void 0 ? [] : _c, _d = _b.supportStandalone, supportStandalone = _d === void 0 ? false : _d;
414
- this.matrixWidgetApi = matrixWidgetApi;
415
- this.widgetId = widgetId;
416
- this.widgetParameters = widgetParameters;
417
- this.events$ = fromEvent(this.matrixWidgetApi, "action:".concat(WidgetApiToWidgetAction.SendEvent), function (event) {
418
- event.preventDefault();
419
- try {
420
- _this.matrixWidgetApi.transport.reply(event.detail, {});
421
- }
422
- catch (_) {
423
- // Ignore errors while replying
424
- }
425
- return event;
426
- }).pipe(share());
427
- this.toDeviceMessages$ = fromEvent(this.matrixWidgetApi, 'action:send_to_device', function (event) {
428
- event.preventDefault();
429
- try {
430
- matrixWidgetApi.transport.reply(event.detail, {});
431
- }
432
- catch (_) {
433
- // Ignore errors while replying
498
+ function redactEvent(widgetApi, eventId) {
499
+ return __awaiter$2(this, void 0, void 0, function () {
500
+ var result;
501
+ return __generator$2(this, function (_a) {
502
+ switch (_a.label) {
503
+ case 0: return [4 /*yield*/, widgetApi.sendRoomEvent(ROOM_EVENT_REDACTION, { redacts: eventId })];
504
+ case 1:
505
+ result = _a.sent();
506
+ // The redaction event is special and needs to be casted, as the widget
507
+ // toolkit assumes that the content of an event is returned as we send it.
508
+ // However for redactions the content is copied directly into the event to
509
+ // make it available without decrypting the content.
510
+ return [2 /*return*/, result];
434
511
  }
435
- return event;
436
- }).pipe(share());
437
- this.initialCapabilities = __spreadArray(__spreadArray([], capabilities, true), (supportStandalone ? [] : [MatrixCapabilities.RequiresClient]), true);
438
- }
439
- /**
440
- * Initialize a new widget API instance and wait till it is ready.
441
- * There should only be one instance of the widget API. The widget API should
442
- * be created as early as possible when starting the application. This is
443
- * required to match the timing of the API connection establishment with the
444
- * client, especially in Safari. Therefore it is recommended to create it
445
- * inside the entrypoint, before initializing rendering engines like react.
446
- *
447
- * @param param0 - {@link WidgetApiOptions}
448
- *
449
- * @returns A widget API instance ready to use.
450
- */
451
- WidgetApiImpl.create = function (_a) {
452
- var _b = _a === void 0 ? {} : _a, _c = _b.capabilities, capabilities = _c === void 0 ? [] : _c, _d = _b.supportStandalone, supportStandalone = _d === void 0 ? false : _d;
453
- return __awaiter$2(this, void 0, void 0, function () {
454
- var _e, clientOrigin, widgetId, widgetParameters, matrixWidgetApi, widgetApi;
455
- return __generator$2(this, function (_f) {
456
- switch (_f.label) {
457
- case 0:
458
- _e = extractWidgetApiParameters(), clientOrigin = _e.clientOrigin, widgetId = _e.widgetId;
459
- widgetParameters = extractWidgetParameters();
460
- matrixWidgetApi = new WidgetApi(widgetId, clientOrigin);
461
- widgetApi = new WidgetApiImpl(matrixWidgetApi, widgetId, widgetParameters, { capabilities: capabilities, supportStandalone: supportStandalone });
462
- return [4 /*yield*/, widgetApi.initialize()];
463
- case 1:
464
- _f.sent();
465
- return [2 /*return*/, widgetApi];
466
- }
467
- });
468
512
  });
513
+ });
514
+ }
515
+ /**
516
+ * Observes redaction events in the current room.
517
+ * @param widgetApi - An instance of the widget API.
518
+ * @returns An observable of validated redaction events.
519
+ */
520
+ function observeRedactionEvents(widgetApi) {
521
+ return widgetApi
522
+ .observeRoomEvents(ROOM_EVENT_REDACTION)
523
+ .pipe(filter(isValidRedactionEvent));
524
+ }
525
+
526
+ /*
527
+ * Copyright 2022 Nordeck IT + Consulting GmbH
528
+ *
529
+ * Licensed under the Apache License, Version 2.0 (the "License");
530
+ * you may not use this file except in compliance with the License.
531
+ * You may obtain a copy of the License at
532
+ *
533
+ * http://www.apache.org/licenses/LICENSE-2.0
534
+ *
535
+ * Unless required by applicable law or agreed to in writing, software
536
+ * distributed under the License is distributed on an "AS IS" BASIS,
537
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
538
+ * See the License for the specific language governing permissions and
539
+ * limitations under the License.
540
+ */
541
+ /**
542
+ * Get the original event id, or the event id of the current event if it
543
+ * doesn't relates to another event.
544
+ * @param event - The room event.
545
+ * @returns The event id of the original event, or the current event id.
546
+ */
547
+ function getOriginalEventId(event) {
548
+ var _a, _b, _c;
549
+ var newContentRelatesTo = event.content;
550
+ if (((_a = newContentRelatesTo['m.relates_to']) === null || _a === void 0 ? void 0 : _a.rel_type) === 'm.replace') {
551
+ return (_c = (_b = newContentRelatesTo['m.relates_to']) === null || _b === void 0 ? void 0 : _b.event_id) !== null && _c !== void 0 ? _c : event.event_id;
552
+ }
553
+ return event.event_id;
554
+ }
555
+ /**
556
+ * Get the content of the event, independent from whether it contains the
557
+ * content directly or contains a "m.new_content" key.
558
+ * @param event - The room event.
559
+ * @returns Only the content of the room event.
560
+ */
561
+ function getContent(event) {
562
+ var _a;
563
+ var newContentRelatesTo = event.content;
564
+ return (_a = newContentRelatesTo['m.new_content']) !== null && _a !== void 0 ? _a : event.content;
565
+ }
566
+ /**
567
+ * Validates that `event` has a valid structure for a
568
+ * {@link EventWithRelatesTo}.
569
+ * @param event - The event to validate.
570
+ * @returns True, if the event is valid.
571
+ */
572
+ function isValidEventWithRelatesTo(event) {
573
+ if (!event.content || typeof event.content !== 'object') {
574
+ return false;
575
+ }
576
+ var relatedEvent = event;
577
+ if (!relatedEvent.content['m.relates_to'] ||
578
+ typeof relatedEvent.content['m.relates_to'] !== 'object') {
579
+ return false;
580
+ }
581
+ if (typeof relatedEvent.content['m.relates_to'].rel_type !== 'string' ||
582
+ typeof relatedEvent.content['m.relates_to'].event_id !== 'string') {
583
+ return false;
584
+ }
585
+ return true;
586
+ }
587
+
588
+ /*
589
+ * Copyright 2022 Nordeck IT + Consulting GmbH
590
+ *
591
+ * Licensed under the Apache License, Version 2.0 (the "License");
592
+ * you may not use this file except in compliance with the License.
593
+ * You may obtain a copy of the License at
594
+ *
595
+ * http://www.apache.org/licenses/LICENSE-2.0
596
+ *
597
+ * Unless required by applicable law or agreed to in writing, software
598
+ * distributed under the License is distributed on an "AS IS" BASIS,
599
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
600
+ * See the License for the specific language governing permissions and
601
+ * limitations under the License.
602
+ */
603
+ /**
604
+ * The name of the room member state event.
605
+ */
606
+ var STATE_EVENT_ROOM_MEMBER = 'm.room.member';
607
+ function isStringUndefinedOrNull(value) {
608
+ return value === undefined || value === null || typeof value === 'string';
609
+ }
610
+ /**
611
+ * Validates that `event` is has a valid structure for a
612
+ * {@link RoomMemberStateEventContent}.
613
+ * @param event - The event to validate.
614
+ * @returns True, if the event is valid.
615
+ */
616
+ function isValidRoomMemberStateEvent(event) {
617
+ if (event.type !== STATE_EVENT_ROOM_MEMBER ||
618
+ typeof event.content !== 'object') {
619
+ return false;
620
+ }
621
+ var content = event.content;
622
+ if (typeof content.membership !== 'string') {
623
+ return false;
624
+ }
625
+ if (!isStringUndefinedOrNull(content.displayname)) {
626
+ return false;
627
+ }
628
+ // the avatar_url shouldn't be null, but some implementations
629
+ // set it as a valid value
630
+ if (!isStringUndefinedOrNull(content.avatar_url)) {
631
+ return false;
632
+ }
633
+ return true;
634
+ }
635
+
636
+ /*
637
+ * Copyright 2022 Nordeck IT + Consulting GmbH
638
+ *
639
+ * Licensed under the Apache License, Version 2.0 (the "License");
640
+ * you may not use this file except in compliance with the License.
641
+ * You may obtain a copy of the License at
642
+ *
643
+ * http://www.apache.org/licenses/LICENSE-2.0
644
+ *
645
+ * Unless required by applicable law or agreed to in writing, software
646
+ * distributed under the License is distributed on an "AS IS" BASIS,
647
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
648
+ * See the License for the specific language governing permissions and
649
+ * limitations under the License.
650
+ */
651
+ var __assign$1 = (undefined && undefined.__assign) || function () {
652
+ __assign$1 = Object.assign || function(t) {
653
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
654
+ s = arguments[i];
655
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
656
+ t[p] = s[p];
657
+ }
658
+ return t;
469
659
  };
470
- /**
471
- * Initialize the widget API and wait till a connection with the client is
472
- * fully established.
473
- *
474
- * Waits till the user has approved the initial set of capabilities. The
475
- * method doesn't fail if the user doesn't approve all of them. It is
476
- * required to check manually afterwards.
477
- * In case of modal widgets it waits till the `widgetConfig` is received.
478
- *
479
- * @remarks Should only be called once during startup.
480
- */
481
- WidgetApiImpl.prototype.initialize = function () {
482
- return __awaiter$2(this, void 0, void 0, function () {
483
- var ready, isModal, configReady, rawCapabilities;
484
- var _this = this;
485
- return __generator$2(this, function (_a) {
486
- switch (_a.label) {
487
- case 0:
488
- ready = new Promise(function (resolve) {
489
- _this.matrixWidgetApi.once('ready', function () { return resolve(); });
490
- });
491
- isModal = parseWidgetId(this.widgetId).isModal;
492
- configReady = isModal
493
- ? (function () { return __awaiter$2(_this, void 0, void 0, function () {
494
- var widgetConfig$, _a;
495
- var _this = this;
496
- return __generator$2(this, function (_b) {
497
- switch (_b.label) {
498
- case 0:
499
- widgetConfig$ = fromEvent(this.matrixWidgetApi, "action:".concat(WidgetApiToWidgetAction.WidgetConfig), function (ev) {
500
- ev.preventDefault();
501
- _this.matrixWidgetApi.transport.reply(ev.detail, {});
502
- return ev.detail.data;
503
- });
504
- _a = this;
505
- return [4 /*yield*/, firstValueFrom(widgetConfig$)];
506
- case 1:
507
- _a.widgetConfig = _b.sent();
508
- return [2 /*return*/];
509
- }
510
- });
511
- }); })()
512
- : undefined;
513
- rawCapabilities = unique(convertToRawCapabilities(this.initialCapabilities));
514
- this.matrixWidgetApi.requestCapabilities(rawCapabilities);
515
- this.matrixWidgetApi.start();
516
- return [4 /*yield*/, ready];
517
- case 1:
518
- _a.sent();
519
- if (!configReady) return [3 /*break*/, 3];
520
- return [4 /*yield*/, configReady];
521
- case 2:
522
- _a.sent();
523
- _a.label = 3;
524
- case 3: return [2 /*return*/];
525
- }
526
- });
527
- });
528
- };
529
- /** {@inheritDoc WidgetApi.getWidgetConfig} */
530
- WidgetApiImpl.prototype.getWidgetConfig = function () {
531
- return this.widgetConfig;
532
- };
533
- /** {@inheritDoc WidgetApi.rerequestInitialCapabilities} */
534
- WidgetApiImpl.prototype.rerequestInitialCapabilities = function () {
535
- return __awaiter$2(this, void 0, void 0, function () {
536
- return __generator$2(this, function (_a) {
537
- switch (_a.label) {
538
- case 0: return [4 /*yield*/, this.requestCapabilities(this.initialCapabilities)];
539
- case 1: return [2 /*return*/, _a.sent()];
540
- }
541
- });
542
- });
543
- };
544
- /** {@inheritDoc WidgetApi.hasInitialCapabilities} */
545
- WidgetApiImpl.prototype.hasInitialCapabilities = function () {
546
- return this.hasCapabilities(this.initialCapabilities);
547
- };
548
- /** {@inheritDoc WidgetApi.requestCapabilities} */
549
- WidgetApiImpl.prototype.requestCapabilities = function (capabilities) {
550
- return __awaiter$2(this, void 0, void 0, function () {
551
- return __generator$2(this, function (_b) {
552
- switch (_b.label) {
553
- case 0:
554
- if (!this.outstandingCapabilitiesRequest) return [3 /*break*/, 4];
555
- _b.label = 1;
556
- case 1:
557
- _b.trys.push([1, 3, , 4]);
558
- return [4 /*yield*/, this.outstandingCapabilitiesRequest];
559
- case 2:
560
- _b.sent();
561
- return [3 /*break*/, 4];
562
- case 3:
563
- _b.sent();
564
- return [3 /*break*/, 4];
565
- case 4:
566
- _b.trys.push([4, , 6, 7]);
567
- this.outstandingCapabilitiesRequest =
568
- this.requestCapabilitiesInternal(capabilities);
569
- return [4 /*yield*/, this.outstandingCapabilitiesRequest];
570
- case 5:
571
- _b.sent();
572
- return [3 /*break*/, 7];
573
- case 6:
574
- this.outstandingCapabilitiesRequest = undefined;
575
- return [7 /*endfinally*/];
576
- case 7: return [2 /*return*/];
577
- }
578
- });
579
- });
660
+ return __assign$1.apply(this, arguments);
661
+ };
662
+ /**
663
+ * Extract the parameters used to initialize the widget API from the current
664
+ * `window.location`.
665
+ * @returns The parameters required for initializing the widget API.
666
+ */
667
+ function extractWidgetApiParameters() {
668
+ var query = parse(window.location.search, { ignoreQueryPrefix: true });
669
+ // If either parentUrl or widgetId is missing, we have no element context and
670
+ // want to inform the user that the widget only works inside of element.
671
+ if (typeof query.parentUrl !== 'string') {
672
+ throw Error('Missing parameter "parentUrl"');
673
+ }
674
+ var clientOrigin = new URL(query.parentUrl).origin;
675
+ if (typeof query.widgetId !== 'string') {
676
+ throw Error('Missing parameter "widgetId"');
677
+ }
678
+ var widgetId = query.widgetId;
679
+ return { widgetId: widgetId, clientOrigin: clientOrigin };
680
+ }
681
+ /**
682
+ * Extract the widget parameters from the current `window.location`.
683
+ * @returns The all unprocessed raw widget parameters.
684
+ */
685
+ function extractRawWidgetParameters() {
686
+ var hash = window.location.hash.substring(window.location.hash.indexOf('?') + 1);
687
+ var params = __assign$1(__assign$1({}, parse(window.location.search, { ignoreQueryPrefix: true })), parse(hash));
688
+ return Object.fromEntries(Object.entries(params).filter(
689
+ // For now only use simple values, don't allow them to be specified more
690
+ // than once.
691
+ function (e) { return typeof e[1] === 'string'; }));
692
+ }
693
+ /**
694
+ * Extract the widget parameters from the current `window.location`.
695
+ * @returns The widget parameters.
696
+ */
697
+ function extractWidgetParameters() {
698
+ var params = extractRawWidgetParameters();
699
+ // This is a hack to detect whether we are in a mobile client that supports widgets,
700
+ // but not the widget API. Mobile clients are not passing the parameters required for
701
+ // the widget API (like widgetId), but are passing the replaced placeholder values for
702
+ // the widget parameters.
703
+ var roomId = params['matrix_room_id'];
704
+ var isOpenedByClient = typeof roomId === 'string' && roomId !== '$matrix_room_id';
705
+ return {
706
+ userId: params['matrix_user_id'],
707
+ displayName: params['matrix_display_name'],
708
+ avatarUrl: params['matrix_avatar_url'],
709
+ roomId: roomId,
710
+ theme: params['theme'],
711
+ clientId: params['matrix_client_id'],
712
+ clientLanguage: params['matrix_client_language'],
713
+ baseUrl: params['matrix_base_url'],
714
+ isOpenedByClient: isOpenedByClient,
580
715
  };
581
- WidgetApiImpl.prototype.requestCapabilitiesInternal = function (capabilities) {
582
- return __awaiter$2(this, void 0, void 0, function () {
583
- var rawCapabilities, requestedSet, capabilities$;
584
- var _this = this;
585
- return __generator$2(this, function (_a) {
586
- switch (_a.label) {
587
- case 0:
588
- rawCapabilities = unique(convertToRawCapabilities(capabilities));
589
- // Take shortcut if possible, that avoid extra roundtrips over the API.
590
- if (this.hasCapabilities(rawCapabilities)) {
591
- return [2 /*return*/];
592
- }
593
- requestedSet = new Set(rawCapabilities);
594
- capabilities$ = fromEvent(this.matrixWidgetApi, "action:".concat(WidgetApiToWidgetAction.NotifyCapabilities), function (ev) { return ev; }).pipe(
595
- // TODO: `hasCapability` in the matrix-widget-api isn't consistent when capability
596
- // upgrades happened. But `updateRequestedCapabilities` will deduplicate already
597
- // approved capabilities, so the the `requested` field will be inconsistent.
598
- // If we would enable this check, the function will never resolve. This should
599
- // be reactivated once the capability upgrade is working correctly. See also:
600
- // https://github.com/matrix-org/matrix-widget-api/issues/52
601
- // Ignore events from other parallel capability requests
602
- //filter((ev) =>
603
- // equalsSet(new Set(ev.detail.data.requested), requestedSet)
604
- //),
605
- map(function (ev) {
606
- var approvedSet = new Set(ev.detail.data.approved);
607
- var missingSet = subtractSet(requestedSet, approvedSet);
608
- if (missingSet.size > 0) {
609
- throw new Error("Capabilities rejected: ".concat(Array.from(missingSet).join(', ')));
610
- }
611
- }), first());
612
- return [4 /*yield*/, new Promise(function (resolve, reject) { return __awaiter$2(_this, void 0, void 0, function () {
613
- var subscription, err_1;
614
- return __generator$2(this, function (_a) {
615
- switch (_a.label) {
616
- case 0:
617
- subscription = capabilities$.subscribe({
618
- next: resolve,
619
- error: reject,
620
- });
621
- _a.label = 1;
622
- case 1:
623
- _a.trys.push([1, 3, , 4]);
624
- this.matrixWidgetApi.requestCapabilities(rawCapabilities);
625
- return [4 /*yield*/, this.matrixWidgetApi.updateRequestedCapabilities()];
626
- case 2:
627
- _a.sent();
628
- return [3 /*break*/, 4];
629
- case 3:
630
- err_1 = _a.sent();
631
- subscription.unsubscribe();
632
- reject(err_1);
633
- return [3 /*break*/, 4];
634
- case 4: return [2 /*return*/];
635
- }
636
- });
637
- }); })];
638
- case 1:
639
- _a.sent();
640
- return [2 /*return*/];
641
- }
642
- });
643
- });
716
+ }
717
+ /**
718
+ * Parse a widget id into the individual fields.
719
+ * @param widgetId - The widget id to parse.
720
+ * @returns The individual fields encoded inside a widget id.
721
+ */
722
+ function parseWidgetId(widgetId) {
723
+ // TODO: Is this whole parsing still working for user widgets?
724
+ var mainWidgetId = decodeURIComponent(widgetId).replace(/^modal_/, '');
725
+ var roomId = mainWidgetId.indexOf('_')
726
+ ? decodeURIComponent(mainWidgetId.split('_')[0])
727
+ : undefined;
728
+ var creator = (mainWidgetId.match(/_/g) || []).length > 1
729
+ ? decodeURIComponent(mainWidgetId.split('_')[1])
730
+ : undefined;
731
+ var isModal = decodeURIComponent(widgetId).startsWith('modal_');
732
+ return {
733
+ mainWidgetId: mainWidgetId,
734
+ roomId: roomId,
735
+ creator: creator,
736
+ isModal: isModal,
644
737
  };
645
- /** {@inheritDoc WidgetApi.hasCapabilities} */
646
- WidgetApiImpl.prototype.hasCapabilities = function (capabilities) {
647
- var _this = this;
648
- var rawCapabilities = convertToRawCapabilities(capabilities);
649
- return rawCapabilities.every(function (c) { return _this.matrixWidgetApi.hasCapability(c); });
738
+ }
739
+
740
+ /*
741
+ * Copyright 2022 Nordeck IT + Consulting GmbH
742
+ *
743
+ * Licensed under the Apache License, Version 2.0 (the "License");
744
+ * you may not use this file except in compliance with the License.
745
+ * You may obtain a copy of the License at
746
+ *
747
+ * http://www.apache.org/licenses/LICENSE-2.0
748
+ *
749
+ * Unless required by applicable law or agreed to in writing, software
750
+ * distributed under the License is distributed on an "AS IS" BASIS,
751
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
752
+ * See the License for the specific language governing permissions and
753
+ * limitations under the License.
754
+ */
755
+ var __assign = (undefined && undefined.__assign) || function () {
756
+ __assign = Object.assign || function(t) {
757
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
758
+ s = arguments[i];
759
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
760
+ t[p] = s[p];
761
+ }
762
+ return t;
650
763
  };
651
- /** {@inheritDoc WidgetApi.receiveSingleStateEvent} */
652
- WidgetApiImpl.prototype.receiveSingleStateEvent = function (eventType, stateKey) {
653
- if (stateKey === void 0) { stateKey = ''; }
654
- return __awaiter$2(this, void 0, void 0, function () {
655
- var events;
656
- return __generator$2(this, function (_a) {
657
- switch (_a.label) {
658
- case 0: return [4 /*yield*/, this.receiveStateEvents(eventType, { stateKey: stateKey })];
659
- case 1:
660
- events = _a.sent();
661
- return [2 /*return*/, events && events[0]];
662
- }
663
- });
664
- });
665
- };
666
- /** {@inheritDoc WidgetApi.receiveStateEvents} */
667
- WidgetApiImpl.prototype.receiveStateEvents = function (eventType, _a) {
668
- var _b = _a === void 0 ? {} : _a, stateKey = _b.stateKey, roomIds = _b.roomIds;
669
- return __awaiter$2(this, void 0, void 0, function () {
670
- return __generator$2(this, function (_c) {
671
- switch (_c.label) {
672
- case 0: return [4 /*yield*/, this.matrixWidgetApi.readStateEvents(eventType, Number.MAX_SAFE_INTEGER, stateKey, typeof roomIds === 'string' ? [Symbols.AnyRoom] : roomIds)];
673
- case 1: return [2 /*return*/, (_c.sent())];
674
- }
675
- });
676
- });
677
- };
678
- /** {@inheritDoc WidgetApi.observeStateEvents} */
679
- WidgetApiImpl.prototype.observeStateEvents = function (eventType, _a) {
680
- var _b = _a === void 0 ? {} : _a, stateKey = _b.stateKey, roomIds = _b.roomIds;
681
- var currentRoomId = this.widgetParameters.roomId;
682
- if (!currentRoomId) {
683
- return throwError(function () { return new Error('Current room id is unknown'); });
684
- }
685
- var historyEvent$ = from(this.receiveStateEvents(eventType, { stateKey: stateKey, roomIds: roomIds })).pipe(mergeAll());
686
- var futureEvent$ = this.events$.pipe(map(function (event) {
687
- var matrixEvent = event.detail.data;
688
- if (matrixEvent.type === eventType &&
689
- matrixEvent.state_key !== undefined &&
690
- (stateKey === undefined || matrixEvent.state_key === stateKey) &&
691
- isInRoom(matrixEvent, currentRoomId, roomIds)) {
692
- return event.detail.data;
764
+ return __assign.apply(this, arguments);
765
+ };
766
+ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
767
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
768
+ return new (P || (P = Promise))(function (resolve, reject) {
769
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
770
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
771
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
772
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
773
+ });
774
+ };
775
+ var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) {
776
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
777
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
778
+ function verb(n) { return function (v) { return step([n, v]); }; }
779
+ function step(op) {
780
+ if (f) throw new TypeError("Generator is already executing.");
781
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
782
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
783
+ if (y = 0, t) op = [op[0] & 2, t.value];
784
+ switch (op[0]) {
785
+ case 0: case 1: t = op; break;
786
+ case 4: _.label++; return { value: op[1], done: false };
787
+ case 5: _.label++; y = op[1]; op = [0]; continue;
788
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
789
+ default:
790
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
791
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
792
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
793
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
794
+ if (t[2]) _.ops.pop();
795
+ _.trys.pop(); continue;
693
796
  }
694
- return undefined;
695
- }), filter(isDefined));
696
- return concat(historyEvent$, futureEvent$);
697
- };
698
- /** {@inheritDoc WidgetApi.sendStateEvent} */
699
- WidgetApiImpl.prototype.sendStateEvent = function (eventType, content, _a) {
700
- var _b = _a === void 0 ? {} : _a, roomId = _b.roomId, _c = _b.stateKey, stateKey = _c === void 0 ? '' : _c;
701
- return __awaiter$2(this, void 0, void 0, function () {
702
- var subject, subscription, _d, event_id_1, room_id_1, event_1;
703
- return __generator$2(this, function (_e) {
704
- switch (_e.label) {
705
- case 0:
706
- subject = new ReplaySubject();
707
- subscription = this.events$.subscribe(function (e) { return subject.next(e); });
708
- _e.label = 1;
709
- case 1:
710
- _e.trys.push([1, , 4, 5]);
711
- return [4 /*yield*/, this.matrixWidgetApi.sendStateEvent(eventType, stateKey, content, roomId)];
712
- case 2:
713
- _d = _e.sent(), event_id_1 = _d.event_id, room_id_1 = _d.room_id;
714
- return [4 /*yield*/, firstValueFrom(subject.pipe(filter(function (event) {
715
- var matrixEvent = event.detail.data;
716
- return (matrixEvent.event_id === event_id_1 &&
717
- matrixEvent.room_id === room_id_1);
718
- }), map(function (event) { return event.detail.data; })))];
719
- case 3:
720
- event_1 = _e.sent();
721
- return [2 /*return*/, event_1];
722
- case 4:
723
- subscription.unsubscribe();
724
- return [7 /*endfinally*/];
725
- case 5: return [2 /*return*/];
726
- }
727
- });
728
- });
729
- };
730
- /** {@inheritDoc WidgetApi.receiveRoomEvents} */
731
- WidgetApiImpl.prototype.receiveRoomEvents = function (eventType, _a) {
732
- var _b = _a === void 0 ? {} : _a, messageType = _b.messageType, roomIds = _b.roomIds;
733
- return __awaiter$2(this, void 0, void 0, function () {
734
- return __generator$2(this, function (_c) {
735
- switch (_c.label) {
736
- case 0: return [4 /*yield*/, this.matrixWidgetApi.readRoomEvents(eventType, Number.MAX_SAFE_INTEGER, messageType, typeof roomIds === 'string' ? [Symbols.AnyRoom] : roomIds)];
737
- case 1: return [2 /*return*/, (_c.sent())];
738
- }
739
- });
740
- });
741
- };
742
- /** {@inheritDoc WidgetApi.observeRoomEvents} */
743
- WidgetApiImpl.prototype.observeRoomEvents = function (eventType, _a) {
744
- var _b = _a === void 0 ? {} : _a, messageType = _b.messageType, roomIds = _b.roomIds;
745
- var currentRoomId = this.widgetParameters.roomId;
746
- if (!currentRoomId) {
747
- return throwError(function () { return new Error('Current room id is unknown'); });
797
+ op = body.call(thisArg, _);
798
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
799
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
800
+ }
801
+ };
802
+ var __rest = (undefined && undefined.__rest) || function (s, e) {
803
+ var t = {};
804
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
805
+ t[p] = s[p];
806
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
807
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
808
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
809
+ t[p[i]] = s[p[i]];
748
810
  }
749
- var historyEvent$ = from(this.receiveRoomEvents(eventType, { messageType: messageType, roomIds: roomIds })).pipe(mergeAll());
750
- var futureEvent$ = this.events$.pipe(map(function (event) {
751
- var matrixEvent = event.detail.data;
752
- if (matrixEvent.type === eventType &&
753
- matrixEvent.state_key === undefined &&
754
- (!messageType || matrixEvent.content.msgtype === messageType) &&
755
- isInRoom(matrixEvent, currentRoomId, roomIds)) {
756
- return event.detail.data;
811
+ return t;
812
+ };
813
+ /**
814
+ * Checks whether all widget parameters were provided to the widget.
815
+ *
816
+ * @param widgetApi - The widget api to read the parameters from
817
+ * @returns True, if all parameters were provided.
818
+ */
819
+ function hasRequiredWidgetParameters(widgetApi) {
820
+ return (typeof widgetApi.widgetParameters.userId === 'string' &&
821
+ typeof widgetApi.widgetParameters.displayName === 'string' &&
822
+ typeof widgetApi.widgetParameters.avatarUrl === 'string' &&
823
+ typeof widgetApi.widgetParameters.roomId === 'string' &&
824
+ typeof widgetApi.widgetParameters.theme === 'string' &&
825
+ typeof widgetApi.widgetParameters.clientId === 'string' &&
826
+ typeof widgetApi.widgetParameters.clientLanguage === 'string' &&
827
+ typeof widgetApi.widgetParameters.baseUrl === 'string');
828
+ }
829
+ /**
830
+ * Generate a registration URL for the widget based on the current URL and
831
+ * include all widget parameters (and their placeholders).
832
+ * @param options - Options for generating the URL.
833
+ * Use `pathName` to include an optional sub path in the URL.
834
+ * Use `includeParameters` to append the widget parameters to
835
+ * the URL, defaults to `true`.
836
+ * @returns The generated URL.
837
+ */
838
+ function generateWidgetRegistrationUrl(options) {
839
+ var _a, _b, _c, _d, _e, _f, _g, _h;
840
+ if (options === void 0) { options = {}; }
841
+ var pathName = options.pathName, _j = options.includeParameters, includeParameters = _j === void 0 ? true : _j, widgetParameters = options.widgetParameters;
842
+ // don't forward widgetId and parentUrl as they will be generated by the client
843
+ var _k = extractRawWidgetParameters(); _k.widgetId; _k.parentUrl; var rawWidgetParameters = __rest(_k, ["widgetId", "parentUrl"]);
844
+ var parameters = Object.entries(__assign(__assign({}, rawWidgetParameters), { theme: (_a = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.theme) !== null && _a !== void 0 ? _a : '$org.matrix.msc2873.client_theme', matrix_user_id: (_b = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.userId) !== null && _b !== void 0 ? _b : '$matrix_user_id', matrix_display_name: (_c = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.displayName) !== null && _c !== void 0 ? _c : '$matrix_display_name', matrix_avatar_url: (_d = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.avatarUrl) !== null && _d !== void 0 ? _d : '$matrix_avatar_url', matrix_room_id: (_e = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.roomId) !== null && _e !== void 0 ? _e : '$matrix_room_id', matrix_client_id: (_f = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.clientId) !== null && _f !== void 0 ? _f : '$org.matrix.msc2873.client_id', matrix_client_language: (_g = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.clientLanguage) !== null && _g !== void 0 ? _g : '$org.matrix.msc2873.client_language', matrix_base_url: (_h = widgetParameters === null || widgetParameters === void 0 ? void 0 : widgetParameters.baseUrl) !== null && _h !== void 0 ? _h : '$org.matrix.msc4039.matrix_base_url' }))
845
+ .map(function (_a) {
846
+ var k = _a[0], v = _a[1];
847
+ return "".concat(k, "=").concat(v);
848
+ })
849
+ .join('&');
850
+ var url = new URL(window.location.href);
851
+ if (pathName) {
852
+ url.pathname = pathName;
853
+ }
854
+ else {
855
+ // ensure trailing '/'
856
+ url.pathname = url.pathname.replace(/\/?$/, '/');
857
+ }
858
+ url.search = '';
859
+ url.hash = includeParameters ? "#/?".concat(parameters) : '';
860
+ return url.toString();
861
+ }
862
+ var STATE_EVENT_WIDGETS = 'im.vector.modular.widgets';
863
+ /**
864
+ * Repair/configure the registration of the current widget.
865
+ * This steps make sure to include all the required widget parameters in the
866
+ * URL. Support setting a widget name and additional parameters.
867
+ *
868
+ * @param widgetApi - The widget api of the current widget.
869
+ * @param registration - Optional configuration options for the widget
870
+ * registration, like the display name of the widget.
871
+ */
872
+ function repairWidgetRegistration(widgetApi_1) {
873
+ return __awaiter$1(this, arguments, void 0, function (widgetApi, registration) {
874
+ var readResult, url, name, type, data;
875
+ if (registration === void 0) { registration = {}; }
876
+ return __generator$1(this, function (_a) {
877
+ switch (_a.label) {
878
+ case 0: return [4 /*yield*/, widgetApi.requestCapabilities([
879
+ WidgetEventCapability.forStateEvent(EventDirection.Send, STATE_EVENT_WIDGETS, widgetApi.widgetId),
880
+ WidgetEventCapability.forStateEvent(EventDirection.Receive, STATE_EVENT_WIDGETS, widgetApi.widgetId),
881
+ ])];
882
+ case 1:
883
+ _a.sent();
884
+ return [4 /*yield*/, widgetApi.receiveSingleStateEvent(STATE_EVENT_WIDGETS, widgetApi.widgetId)];
885
+ case 2:
886
+ readResult = _a.sent();
887
+ if (!readResult) {
888
+ throw new Error("Error while repairing registration, can't find existing registration.");
889
+ }
890
+ url = generateWidgetRegistrationUrl();
891
+ name = registration.name &&
892
+ (!readResult.content.name ||
893
+ readResult.content.name === 'Custom Widget' ||
894
+ readResult.content.name === 'Custom')
895
+ ? registration.name
896
+ : readResult.content.name;
897
+ type = registration.type &&
898
+ (!readResult.content.type || readResult.content.type === 'm.custom')
899
+ ? registration.type
900
+ : readResult.content.type;
901
+ data = registration.data
902
+ ? __assign(__assign({}, readResult.content.data), registration.data) : readResult.content.data;
903
+ // This is a workaround because changing the widget config is breaking the
904
+ // widget API communication. However we need to fail in case the power level
905
+ // for this change is missing. As the error happens quite fast, we just wait
906
+ // a moment and then consider the operation as succeeded.
907
+ return [4 /*yield*/, Promise.race([
908
+ widgetApi.sendStateEvent(STATE_EVENT_WIDGETS, __assign(__assign({}, readResult.content), { url: url.toString(), name: name, type: type, data: data }), { stateKey: widgetApi.widgetId }),
909
+ new Promise(function (resolve) { return setTimeout(resolve, 1000); }),
910
+ ])];
911
+ case 3:
912
+ // This is a workaround because changing the widget config is breaking the
913
+ // widget API communication. However we need to fail in case the power level
914
+ // for this change is missing. As the error happens quite fast, we just wait
915
+ // a moment and then consider the operation as succeeded.
916
+ _a.sent();
917
+ return [2 /*return*/];
757
918
  }
758
- return undefined;
759
- }), filter(isDefined));
760
- return concat(historyEvent$, futureEvent$);
761
- };
762
- /** {@inheritDoc WidgetApi.sendRoomEvent} */
763
- WidgetApiImpl.prototype.sendRoomEvent = function (eventType, content, _a) {
764
- var _b = _a === void 0 ? {} : _a, roomId = _b.roomId;
765
- return __awaiter$2(this, void 0, void 0, function () {
766
- var subject, subscription, _c, event_id_2, room_id_2, event_2;
767
- return __generator$2(this, function (_d) {
768
- switch (_d.label) {
769
- case 0:
770
- subject = new ReplaySubject();
771
- subscription = this.events$.subscribe(function (e) { return subject.next(e); });
772
- _d.label = 1;
773
- case 1:
774
- _d.trys.push([1, , 4, 5]);
775
- return [4 /*yield*/, this.matrixWidgetApi.sendRoomEvent(eventType, content, roomId)];
776
- case 2:
777
- _c = _d.sent(), event_id_2 = _c.event_id, room_id_2 = _c.room_id;
778
- return [4 /*yield*/, firstValueFrom(subject.pipe(filter(function (event) {
779
- var matrixEvent = event.detail.data;
780
- return (matrixEvent.event_id === event_id_2 &&
781
- matrixEvent.room_id === room_id_2);
782
- }), map(function (event) { return event.detail.data; })))];
783
- case 3:
784
- event_2 = _d.sent();
785
- return [2 /*return*/, event_2];
786
- case 4:
787
- subscription.unsubscribe();
788
- return [7 /*endfinally*/];
789
- case 5: return [2 /*return*/];
790
- }
791
- });
792
- });
793
- };
794
- /** {@inheritDoc WidgetApi.readEventRelations} */
795
- WidgetApiImpl.prototype.readEventRelations = function (eventId, options) {
796
- return __awaiter$2(this, void 0, void 0, function () {
797
- var _a, chunk, next_batch;
798
- return __generator$2(this, function (_b) {
799
- switch (_b.label) {
800
- case 0: return [4 /*yield*/, this.matrixWidgetApi.readEventRelations(eventId, options === null || options === void 0 ? void 0 : options.roomId, options === null || options === void 0 ? void 0 : options.relationType, options === null || options === void 0 ? void 0 : options.eventType, options === null || options === void 0 ? void 0 : options.limit, options === null || options === void 0 ? void 0 : options.from, undefined, options === null || options === void 0 ? void 0 : options.direction)];
801
- case 1:
802
- _a = _b.sent(), chunk = _a.chunk, next_batch = _a.next_batch;
803
- return [2 /*return*/, {
804
- chunk: chunk,
805
- nextToken: next_batch !== null && next_batch !== void 0 ? next_batch : undefined,
806
- }];
807
- }
808
- });
809
- });
810
- };
811
- /** {@inheritDoc WidgetApi.sendToDeviceMessage} */
812
- WidgetApiImpl.prototype.sendToDeviceMessage = function (eventType, encrypted, content) {
813
- return __awaiter$2(this, void 0, void 0, function () {
814
- return __generator$2(this, function (_a) {
815
- switch (_a.label) {
816
- case 0: return [4 /*yield*/, this.matrixWidgetApi.sendToDevice(eventType, encrypted, content)];
817
- case 1:
818
- _a.sent();
819
- return [2 /*return*/];
820
- }
821
- });
822
- });
823
- };
824
- /** {@inheritDoc WidgetApi.observeToDeviceMessages} */
825
- WidgetApiImpl.prototype.observeToDeviceMessages = function (eventType) {
826
- return this.toDeviceMessages$.pipe(map(function (e) { return e.detail.data; }), filter(function (e) { return e.type === eventType; }));
827
- };
828
- /** {@inheritDoc WidgetApi.openModal} */
829
- WidgetApiImpl.prototype.openModal = function (pathName, name, options) {
830
- return __awaiter$2(this, void 0, void 0, function () {
831
- var isModal, url, closeModalWidget$;
832
- var _this = this;
833
- return __generator$2(this, function (_a) {
834
- switch (_a.label) {
835
- case 0:
836
- isModal = parseWidgetId(this.widgetId).isModal;
837
- if (isModal) {
838
- throw new Error("Modals can't be opened from another modal widget");
839
- }
840
- url = generateWidgetRegistrationUrl({
841
- pathName: pathName,
842
- widgetParameters: this.widgetParameters,
843
- });
844
- return [4 /*yield*/, this.matrixWidgetApi.openModalWidget(url, name, options === null || options === void 0 ? void 0 : options.buttons, options === null || options === void 0 ? void 0 : options.data)];
845
- case 1:
846
- _a.sent();
847
- closeModalWidget$ = fromEvent(this.matrixWidgetApi, "action:".concat(WidgetApiToWidgetAction.CloseModalWidget), function (event) {
848
- var _a;
849
- event.preventDefault();
850
- _this.matrixWidgetApi.transport.reply(event.detail, {});
851
- if (((_a = event.detail.data) === null || _a === void 0 ? void 0 : _a['m.exited']) === true) {
852
- return undefined;
853
- }
854
- return event.detail.data;
855
- });
856
- return [2 /*return*/, firstValueFrom(closeModalWidget$)];
857
- }
858
- });
859
- });
860
- };
861
- /** {@inheritDoc WidgetApi.setModalButtonEnabled} */
862
- WidgetApiImpl.prototype.setModalButtonEnabled = function (buttonId, isEnabled) {
863
- return __awaiter$2(this, void 0, void 0, function () {
864
- var isModal;
865
- return __generator$2(this, function (_a) {
866
- switch (_a.label) {
867
- case 0:
868
- isModal = parseWidgetId(this.widgetId).isModal;
869
- if (!isModal) {
870
- throw new Error('Modal buttons can only be enabled from a modal widget');
871
- }
872
- return [4 /*yield*/, this.matrixWidgetApi.setModalButtonEnabled(buttonId, isEnabled)];
873
- case 1:
874
- _a.sent();
875
- return [2 /*return*/];
876
- }
877
- });
878
- });
879
- };
880
- /** {@inheritDoc WidgetApi.observeModalButtons} */
881
- WidgetApiImpl.prototype.observeModalButtons = function () {
882
- var _this = this;
883
- var isModal = parseWidgetId(this.widgetId).isModal;
884
- if (!isModal) {
885
- throw new Error('Modal buttons can only be observed from a modal widget');
886
- }
887
- return fromEvent(this.matrixWidgetApi, "action:".concat(WidgetApiToWidgetAction.ButtonClicked), function (event) {
888
- event.preventDefault();
889
- _this.matrixWidgetApi.transport.reply(event.detail, {});
890
- return event.detail.data.id;
891
- });
892
- };
893
- /** {@inheritDoc WidgetApi.closeModal} */
894
- WidgetApiImpl.prototype.closeModal = function (data) {
895
- return __awaiter$2(this, void 0, void 0, function () {
896
- var isModal;
897
- return __generator$2(this, function (_a) {
898
- switch (_a.label) {
899
- case 0:
900
- isModal = parseWidgetId(this.widgetId).isModal;
901
- if (!isModal) {
902
- throw new Error('Modals can only be closed from a modal widget');
903
- }
904
- return [4 /*yield*/, this.matrixWidgetApi.closeModalWidget(data ? data : { 'm.exited': true })];
905
- case 1:
906
- _a.sent();
907
- return [2 /*return*/];
908
- }
909
- });
910
- });
911
- };
912
- /** {@inheritdoc WidgetApi.navigateTo} */
913
- WidgetApiImpl.prototype.navigateTo = function (uri) {
914
- return __awaiter$2(this, void 0, void 0, function () {
915
- return __generator$2(this, function (_a) {
916
- switch (_a.label) {
917
- case 0: return [4 /*yield*/, this.matrixWidgetApi.navigateTo(uri)];
918
- case 1:
919
- _a.sent();
920
- return [2 /*return*/];
921
- }
922
- });
923
- });
924
- };
925
- /** {@inheritdoc WidgetApi.requestOpenIDConnectToken} */
926
- WidgetApiImpl.prototype.requestOpenIDConnectToken = function () {
927
- return __awaiter$2(this, void 0, void 0, function () {
928
- return __generator$2(this, function (_b) {
929
- switch (_b.label) {
930
- case 0:
931
- if (!this.outstandingOpenIDConnectTokenRequest) return [3 /*break*/, 4];
932
- _b.label = 1;
933
- case 1:
934
- _b.trys.push([1, 3, , 4]);
935
- return [4 /*yield*/, this.outstandingOpenIDConnectTokenRequest];
936
- case 2:
937
- _b.sent();
938
- return [3 /*break*/, 4];
939
- case 3:
940
- _b.sent();
941
- return [3 /*break*/, 4];
942
- case 4:
943
- _b.trys.push([4, , 6, 7]);
944
- this.outstandingOpenIDConnectTokenRequest =
945
- this.requestOpenIDConnectTokenInternal();
946
- return [4 /*yield*/, this.outstandingOpenIDConnectTokenRequest];
947
- case 5: return [2 /*return*/, _b.sent()];
948
- case 6:
949
- this.outstandingOpenIDConnectTokenRequest = undefined;
950
- return [7 /*endfinally*/];
951
- case 7: return [2 /*return*/];
952
- }
953
- });
954
- });
955
- };
956
- WidgetApiImpl.prototype.requestOpenIDConnectTokenInternal = function () {
957
- var _a;
958
- return __awaiter$2(this, void 0, void 0, function () {
959
- var leywayMilliseconds, openIdToken, err_2;
960
- return __generator$2(this, function (_b) {
961
- switch (_b.label) {
962
- case 0:
963
- leywayMilliseconds = 30 * 1000;
964
- if (this.cachedOpenIdToken &&
965
- this.cachedOpenIdToken.expiresAt - leywayMilliseconds > Date.now()) {
966
- return [2 /*return*/, this.cachedOpenIdToken.openIdToken];
967
- }
968
- _b.label = 1;
969
- case 1:
970
- _b.trys.push([1, 3, , 4]);
971
- return [4 /*yield*/, this.matrixWidgetApi.requestOpenIDConnectToken()];
972
- case 2:
973
- openIdToken = _b.sent();
974
- this.cachedOpenIdToken = {
975
- openIdToken: openIdToken,
976
- expiresAt: Date.now() + ((_a = openIdToken.expires_in) !== null && _a !== void 0 ? _a : 0) * 1000,
977
- };
978
- return [2 /*return*/, openIdToken];
979
- case 3:
980
- err_2 = _b.sent();
981
- this.cachedOpenIdToken = undefined;
982
- throw err_2;
983
- case 4: return [2 /*return*/];
984
- }
985
- });
986
- });
987
- };
988
- /** {@inheritdoc WidgetApi.observeTurnServers} */
989
- WidgetApiImpl.prototype.observeTurnServers = function () {
990
- return from(this.matrixWidgetApi.getTurnServers()).pipe(
991
- // For some reason a different naming was chosen for the API, but
992
- // we already convert them to the right type for WebRTC consumers.
993
- map(function (_a) {
994
- var uris = _a.uris, username = _a.username, password = _a.password;
995
- return ({
996
- urls: uris,
997
- username: username,
998
- credential: password,
999
- });
1000
- }));
1001
- };
1002
- /** {@inheritdoc WidgetApi.searchUserDirectory} */
1003
- WidgetApiImpl.prototype.searchUserDirectory = function (searchTerm, options) {
1004
- return __awaiter$2(this, void 0, void 0, function () {
1005
- var results;
1006
- return __generator$2(this, function (_a) {
1007
- switch (_a.label) {
1008
- case 0: return [4 /*yield*/, this.matrixWidgetApi.searchUserDirectory(searchTerm, options === null || options === void 0 ? void 0 : options.limit)];
1009
- case 1:
1010
- results = (_a.sent()).results;
1011
- return [2 /*return*/, {
1012
- results: results.map(function (_a) {
1013
- var user_id = _a.user_id, display_name = _a.display_name, avatar_url = _a.avatar_url;
1014
- return ({
1015
- userId: user_id,
1016
- displayName: display_name,
1017
- avatarUrl: avatar_url,
1018
- });
1019
- }),
1020
- }];
1021
- }
1022
- });
1023
- });
1024
- };
1025
- /** {@inheritdoc WidgetApi.getMediaConfig} */
1026
- WidgetApiImpl.prototype.getMediaConfig = function () {
1027
- return __awaiter$2(this, void 0, void 0, function () {
1028
- return __generator$2(this, function (_a) {
1029
- switch (_a.label) {
1030
- case 0: return [4 /*yield*/, this.matrixWidgetApi.getMediaConfig()];
1031
- case 1: return [2 /*return*/, _a.sent()];
1032
- }
1033
- });
1034
- });
1035
- };
1036
- /** {@inheritdoc WidgetApi.uploadFile} */
1037
- WidgetApiImpl.prototype.uploadFile = function (file) {
1038
- return __awaiter$2(this, void 0, void 0, function () {
1039
- return __generator$2(this, function (_a) {
1040
- switch (_a.label) {
1041
- case 0: return [4 /*yield*/, this.matrixWidgetApi.uploadFile(file)];
1042
- case 1: return [2 /*return*/, _a.sent()];
1043
- }
1044
- });
1045
919
  });
1046
- };
1047
- return WidgetApiImpl;
1048
- }());
920
+ });
921
+ }
1049
922
 
1050
923
  /*
1051
924
  * Copyright 2022 Nordeck IT + Consulting GmbH
@@ -1062,112 +935,31 @@ var WidgetApiImpl = /** @class */ (function () {
1062
935
  * See the License for the specific language governing permissions and
1063
936
  * limitations under the License.
1064
937
  */
1065
- /**
1066
- * Generate a list of capabilities to access the timeline of other rooms.
1067
- * If enabled, all previously or future capabilities will apply to _all_
1068
- * selected rooms.
1069
- * If `Symbols.AnyRoom` is passed, this is expanded to all joined
1070
- * or invited rooms the client is able to see, current and future.
1071
- *
1072
- * @param roomIds - a list of room ids or `@link Symbols.AnyRoom`.
1073
- * @returns the generated capabilities.
1074
- */
1075
- function generateRoomTimelineCapabilities(roomIds) {
1076
- if (roomIds === Symbols.AnyRoom) {
1077
- return ['org.matrix.msc2762.timeline:*'];
1078
- }
1079
- if (Array.isArray(roomIds)) {
1080
- return roomIds.map(function (id) { return "org.matrix.msc2762.timeline:".concat(id); });
1081
- }
1082
- return [];
1083
- }
1084
-
1085
- /*
1086
- * Copyright 2022 Nordeck IT + Consulting GmbH
1087
- *
1088
- * Licensed under the Apache License, Version 2.0 (the "License");
1089
- * you may not use this file except in compliance with the License.
1090
- * You may obtain a copy of the License at
1091
- *
1092
- * http://www.apache.org/licenses/LICENSE-2.0
1093
- *
1094
- * Unless required by applicable law or agreed to in writing, software
1095
- * distributed under the License is distributed on an "AS IS" BASIS,
1096
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1097
- * See the License for the specific language governing permissions and
1098
- * limitations under the License.
1099
- */
1100
- /**
1101
- * Generate a unique displayname of a user that is consistent across Matrix clients.
1102
- *
1103
- * @remarks The algorithm is based on https://spec.matrix.org/v1.1/client-server-api/#calculating-the-display-name-for-a-user
1104
- *
1105
- * @param member - the member to generate a name for.
1106
- * @param allRoomMembers - a list of all members of the same room.
1107
- * @returns the displayname that is unique in given the set of all room members.
1108
- */
1109
- function getRoomMemberDisplayName(member, allRoomMembers) {
1110
- if (allRoomMembers === void 0) { allRoomMembers = []; }
1111
- // If the m.room.member state event has no displayname field, or if that field
1112
- // has a null value, use the raw user id as the display name.
1113
- if (typeof member.content.displayname !== 'string') {
1114
- return member.state_key;
1115
- }
1116
- // If the m.room.member event has a displayname which is unique among members of
1117
- // the room with membership: join or membership: invite, ...
1118
- var hasDuplicateDisplayName = allRoomMembers.some(function (m) {
1119
- // same room
1120
- return m.room_id === member.room_id &&
1121
- // not the own event
1122
- m.state_key !== member.state_key &&
1123
- // only join or invite state
1124
- ['join', 'invite'].includes(m.content.membership) &&
1125
- // same displayname
1126
- m.content.displayname === member.content.displayname;
1127
- });
1128
- if (!hasDuplicateDisplayName) {
1129
- // ... use the given displayname as the user-visible display name.
1130
- return member.content.displayname;
1131
- }
1132
- else {
1133
- // The m.room.member event has a non-unique displayname. This should be
1134
- // disambiguated using the user id, for example “display name (@id:homeserver.org)”.
1135
- return "".concat(member.content.displayname, " (").concat(member.state_key, ")");
1136
- }
938
+ function convertToRawCapabilities(rawCapabilities) {
939
+ return rawCapabilities.map(function (c) { return (typeof c === 'string' ? c : c.raw); });
1137
940
  }
1138
-
1139
- /*
1140
- * Copyright 2022 Nordeck IT + Consulting GmbH
1141
- *
1142
- * Licensed under the Apache License, Version 2.0 (the "License");
1143
- * you may not use this file except in compliance with the License.
1144
- * You may obtain a copy of the License at
1145
- *
1146
- * http://www.apache.org/licenses/LICENSE-2.0
1147
- *
1148
- * Unless required by applicable law or agreed to in writing, software
1149
- * distributed under the License is distributed on an "AS IS" BASIS,
1150
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1151
- * See the License for the specific language governing permissions and
1152
- * limitations under the License.
1153
- */
1154
- /**
1155
- * Check if the given event is a {@link StateEvent}.
1156
- *
1157
- * @param event - An event that is either a {@link RoomEvent} or a {@link StateEvent}.
1158
- * @returns True, if the event is a {@link StateEvent}.
1159
- */
1160
- function isStateEvent(event) {
1161
- return 'state_key' in event && typeof event.state_key === 'string';
941
+ function isDefined(arg) {
942
+ return arg !== null && arg !== undefined;
1162
943
  }
1163
- /**
1164
- * Check if the given event is a {@link RoomEvent}.
1165
- *
1166
- * @param event - An event that is either a {@link RoomEvent} or a {@link StateEvent}.
1167
- * @returns True, if the event is a {@link RoomEvent}.
1168
- */
1169
- function isRoomEvent(event) {
1170
- return !('state_key' in event);
944
+ function unique(items) {
945
+ return Array.from(new Set(items));
946
+ }
947
+ function subtractSet(as, bs) {
948
+ var result = new Set(as);
949
+ bs.forEach(function (v) { return result.delete(v); });
950
+ return result;
951
+ }
952
+ function isInRoom(matrixEvent, currentRoomId, roomIds) {
953
+ if (!roomIds) {
954
+ return matrixEvent.room_id === currentRoomId;
955
+ }
956
+ if (typeof roomIds === 'string') {
957
+ if (roomIds !== Symbols.AnyRoom) {
958
+ throw Error("Unknown room id symbol: ".concat(roomIds));
959
+ }
960
+ return true;
961
+ }
962
+ return roomIds.includes(matrixEvent.room_id);
1171
963
  }
1172
964
 
1173
965
  /*
@@ -1185,7 +977,7 @@ function isRoomEvent(event) {
1185
977
  * See the License for the specific language governing permissions and
1186
978
  * limitations under the License.
1187
979
  */
1188
- var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
980
+ var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1189
981
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1190
982
  return new (P || (P = Promise))(function (resolve, reject) {
1191
983
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
@@ -1194,7 +986,7 @@ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _argu
1194
986
  step((generator = generator.apply(thisArg, _arguments || [])).next());
1195
987
  });
1196
988
  };
1197
- var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) {
989
+ var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
1198
990
  var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
1199
991
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
1200
992
  function verb(n) { return function (v) { return step([n, v]); }; }
@@ -1221,461 +1013,671 @@ var __generator$1 = (undefined && undefined.__generator) || function (thisArg, b
1221
1013
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1222
1014
  }
1223
1015
  };
1016
+ var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
1017
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
1018
+ if (ar || !(i in from)) {
1019
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
1020
+ ar[i] = from[i];
1021
+ }
1022
+ }
1023
+ return to.concat(ar || Array.prototype.slice.call(from));
1024
+ };
1224
1025
  /**
1225
- * The capability that needs to be requested in order to navigate to another room.
1226
- */
1227
- var WIDGET_CAPABILITY_NAVIGATE = 'org.matrix.msc2931.navigate';
1228
- /**
1229
- * Navigate the client to another matrix room.
1230
- *
1231
- * @remarks This requires the {@link WIDGET_CAPABILITY_NAVIGATE} capability.
1026
+ * Implementation of the API from the widget to the client.
1232
1027
  *
1233
- * @param widgetApi - the {@link WidgetApi} instance.
1234
- * @param roomId - the room ID.
1235
- * @param opts - {@link NavigateToRoomOptions}
1028
+ * @remarks Widget API is specified here:
1029
+ * https://docs.google.com/document/d/1uPF7XWY_dXTKVKV7jZQ2KmsI19wn9-kFRgQ1tFQP7wQ/edit#heading=h.9rn9lt6ctkgi
1236
1030
  */
1237
- function navigateToRoom(widgetApi, roomId, opts) {
1238
- if (opts === void 0) { opts = {}; }
1239
- return __awaiter$1(this, void 0, void 0, function () {
1240
- var _a, via, params, url;
1241
- return __generator$1(this, function (_b) {
1242
- switch (_b.label) {
1243
- case 0:
1244
- _a = opts.via, via = _a === void 0 ? [] : _a;
1245
- params = stringify({ via: via }, { addQueryPrefix: true, arrayFormat: 'repeat' });
1246
- url = "https://matrix.to/#/".concat(encodeURIComponent(roomId)).concat(params);
1247
- return [4 /*yield*/, widgetApi.navigateTo(url)];
1248
- case 1:
1249
- _b.sent();
1250
- return [2 /*return*/];
1031
+ var WidgetApiImpl = /** @class */ (function () {
1032
+ function WidgetApiImpl(
1033
+ /**
1034
+ * Provide access to the underlying widget API from `matrix-widget-sdk`.
1035
+ *
1036
+ * @remarks Normally there is no need to use it, however if features are
1037
+ * missing from `WidgetApi` it can be handy to work with the
1038
+ * original API.
1039
+ */
1040
+ matrixWidgetApi,
1041
+ /** {@inheritDoc WidgetApi.widgetId} */
1042
+ widgetId,
1043
+ /** {@inheritDoc WidgetApi.widgetParameters} */
1044
+ widgetParameters, _a) {
1045
+ var _b = _a === void 0 ? {} : _a, _c = _b.capabilities, capabilities = _c === void 0 ? [] : _c, _d = _b.supportStandalone, supportStandalone = _d === void 0 ? false : _d;
1046
+ var _this = this;
1047
+ this.matrixWidgetApi = matrixWidgetApi;
1048
+ this.widgetId = widgetId;
1049
+ this.widgetParameters = widgetParameters;
1050
+ this.events$ = fromEvent(this.matrixWidgetApi, "action:".concat(WidgetApiToWidgetAction.SendEvent), function (event) {
1051
+ event.preventDefault();
1052
+ try {
1053
+ _this.matrixWidgetApi.transport.reply(event.detail, {});
1251
1054
  }
1252
- });
1253
- });
1254
- }
1255
-
1256
- /*
1257
- * Copyright 2022 Nordeck IT + Consulting GmbH
1258
- *
1259
- * Licensed under the Apache License, Version 2.0 (the "License");
1260
- * you may not use this file except in compliance with the License.
1261
- * You may obtain a copy of the License at
1262
- *
1263
- * http://www.apache.org/licenses/LICENSE-2.0
1264
- *
1265
- * Unless required by applicable law or agreed to in writing, software
1266
- * distributed under the License is distributed on an "AS IS" BASIS,
1267
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1268
- * See the License for the specific language governing permissions and
1269
- * limitations under the License.
1270
- */
1271
- /**
1272
- * Compares two room events by their origin server timestamp.
1273
- *
1274
- * @param a - A room event
1275
- * @param b - A room event
1276
- * @returns Either zero if the timestamp is equal, \>0 if a is newer, or \<0 if
1277
- * b is newer.
1278
- */
1279
- function compareOriginServerTS(a, b) {
1280
- return a.origin_server_ts - b.origin_server_ts;
1281
- }
1282
-
1283
- /*
1284
- * Copyright 2022 Nordeck IT + Consulting GmbH
1285
- *
1286
- * Licensed under the Apache License, Version 2.0 (the "License");
1287
- * you may not use this file except in compliance with the License.
1288
- * You may obtain a copy of the License at
1289
- *
1290
- * http://www.apache.org/licenses/LICENSE-2.0
1291
- *
1292
- * Unless required by applicable law or agreed to in writing, software
1293
- * distributed under the License is distributed on an "AS IS" BASIS,
1294
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1295
- * See the License for the specific language governing permissions and
1296
- * limitations under the License.
1297
- */
1298
- /**
1299
- * The name of the power levels state event.
1300
- */
1301
- var STATE_EVENT_POWER_LEVELS = 'm.room.power_levels';
1302
- function isNumberOrUndefined(value) {
1303
- return value === undefined || typeof value === 'number';
1304
- }
1305
- function isStringToNumberMapOrUndefined(value) {
1306
- return (value === undefined ||
1307
- (value !== null &&
1308
- typeof value === 'object' &&
1309
- Object.entries(value).every(function (_a) {
1310
- var k = _a[0], v = _a[1];
1311
- return typeof k === 'string' && typeof v === 'number';
1312
- })));
1313
- }
1314
- /**
1315
- * Validates that `event` is has a valid structure for a
1316
- * {@link PowerLevelsStateEvent}.
1317
- * @param event - The event to validate.
1318
- * @returns True, if the event is valid.
1319
- */
1320
- function isValidPowerLevelStateEvent(event) {
1321
- if (event.type !== STATE_EVENT_POWER_LEVELS ||
1322
- typeof event.content !== 'object') {
1323
- return false;
1055
+ catch (_) {
1056
+ // Ignore errors while replying
1057
+ }
1058
+ return event;
1059
+ }).pipe(share());
1060
+ this.toDeviceMessages$ = fromEvent(this.matrixWidgetApi, 'action:send_to_device', function (event) {
1061
+ event.preventDefault();
1062
+ try {
1063
+ matrixWidgetApi.transport.reply(event.detail, {});
1064
+ }
1065
+ catch (_) {
1066
+ // Ignore errors while replying
1067
+ }
1068
+ return event;
1069
+ }).pipe(share());
1070
+ this.initialCapabilities = __spreadArray(__spreadArray([], capabilities, true), (supportStandalone ? [] : [MatrixCapabilities.RequiresClient]), true);
1324
1071
  }
1325
- var content = event.content;
1326
- if (!isStringToNumberMapOrUndefined(content.events)) {
1327
- return false;
1328
- }
1329
- if (!isNumberOrUndefined(content.state_default)) {
1330
- return false;
1331
- }
1332
- if (!isNumberOrUndefined(content.events_default)) {
1333
- return false;
1334
- }
1335
- if (!isStringToNumberMapOrUndefined(content.users)) {
1336
- return false;
1337
- }
1338
- if (!isNumberOrUndefined(content.users_default)) {
1339
- return false;
1340
- }
1341
- if (!isNumberOrUndefined(content.ban)) {
1342
- return false;
1343
- }
1344
- if (!isNumberOrUndefined(content.invite)) {
1345
- return false;
1346
- }
1347
- if (!isNumberOrUndefined(content.kick)) {
1348
- return false;
1349
- }
1350
- if (!isNumberOrUndefined(content.redact)) {
1351
- return false;
1352
- }
1353
- return true;
1354
- }
1355
- /**
1356
- * Check if a user has the power to send a specific room event.
1357
- *
1358
- * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
1359
- * @param userId - the id of the user
1360
- * @param eventType - the type of room event
1361
- * @returns if true, the user has the power
1362
- */
1363
- function hasRoomEventPower(powerLevelStateEvent, userId, eventType) {
1364
- if (!powerLevelStateEvent) {
1365
- // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L36-L43
1366
- return true;
1367
- }
1368
- var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
1369
- var eventLevel = calculateRoomEventPowerLevel(powerLevelStateEvent, eventType);
1370
- return userLevel >= eventLevel;
1371
- }
1372
- /**
1373
- * Check if a user has the power to send a specific state event.
1374
- *
1375
- * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
1376
- * @param userId - the id of the user
1377
- * @param eventType - the type of state event
1378
- * @returns if true, the user has the power
1379
- */
1380
- function hasStateEventPower(powerLevelStateEvent, userId, eventType) {
1381
- if (!powerLevelStateEvent) {
1382
- // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L36-L43
1383
- return true;
1384
- }
1385
- var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
1386
- var eventLevel = calculateStateEventPowerLevel(powerLevelStateEvent, eventType);
1387
- return userLevel >= eventLevel;
1388
- }
1389
- /**
1390
- * Check if a user has the power to perform a specific action.
1391
- *
1392
- * Supported actions:
1393
- * * invite: Invite a new user into the room
1394
- * * kick: Kick a user from the room
1395
- * * ban: Ban a user from the room
1396
- * * redact: Redact a message from another user
1397
- *
1398
- * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
1399
- * @param userId - the id of the user
1400
- * @param action - the action
1401
- * @returns if true, the user has the power
1402
- */
1403
- function hasActionPower(powerLevelStateEvent, userId, action) {
1404
- if (!powerLevelStateEvent) {
1405
- // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L36-L43
1406
- return true;
1407
- }
1408
- var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
1409
- var eventLevel = calculateActionPowerLevel(powerLevelStateEvent, action);
1410
- return userLevel >= eventLevel;
1411
- }
1412
- /**
1413
- * Calculate the power level of the user based on a `m.room.power_levels` event.
1414
- *
1415
- * @param powerLevelStateEvent - the content of the `m.room.power_levels` event.
1416
- * @param userId - the ID of the user.
1417
- * @returns the power level of the user.
1418
- */
1419
- function calculateUserPowerLevel(powerLevelStateEvent, userId) {
1420
- var _a, _b, _c;
1421
- // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L8-L12
1422
- return ((_c = (_b = (userId ? (_a = powerLevelStateEvent.users) === null || _a === void 0 ? void 0 : _a[userId] : undefined)) !== null && _b !== void 0 ? _b : powerLevelStateEvent.users_default) !== null && _c !== void 0 ? _c : 0);
1423
- }
1424
- /**
1425
- * Calculate the power level that a user needs send a specific room event.
1426
- *
1427
- * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
1428
- * @param eventType - the type of room event
1429
- * @returns the power level that is needed
1430
- */
1431
- function calculateRoomEventPowerLevel(powerLevelStateEvent, eventType) {
1432
- var _a, _b, _c;
1433
- // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L14-L19
1434
- return ((_c = (_b = (_a = powerLevelStateEvent.events) === null || _a === void 0 ? void 0 : _a[eventType]) !== null && _b !== void 0 ? _b : powerLevelStateEvent.events_default) !== null && _c !== void 0 ? _c : 0);
1435
- }
1436
- /**
1437
- * Calculate the power level that a user needs send a specific state event.
1438
- *
1439
- * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
1440
- * @param eventType - the type of state event
1441
- * @returns the power level that is needed
1442
- */
1443
- function calculateStateEventPowerLevel(powerLevelStateEvent, eventType) {
1444
- var _a, _b, _c;
1445
- // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L14-L19
1446
- return ((_c = (_b = (_a = powerLevelStateEvent.events) === null || _a === void 0 ? void 0 : _a[eventType]) !== null && _b !== void 0 ? _b : powerLevelStateEvent.state_default) !== null && _c !== void 0 ? _c : 50);
1447
- }
1448
- /**
1449
- * Calculate the power level that a user needs to perform an action.
1450
- *
1451
- * Supported actions:
1452
- * * invite: Invite a new user into the room
1453
- * * kick: Kick a user from the room
1454
- * * ban: Ban a user from the room
1455
- * * redact: Redact a message from another user
1456
- *
1457
- * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
1458
- * @param action - the action
1459
- * @returns the power level that is needed
1460
- */
1461
- function calculateActionPowerLevel(powerLevelStateEvent, action) {
1462
- var _a, _b;
1463
- // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L27-L32
1464
- if (action === 'invite') {
1465
- return (_a = powerLevelStateEvent === null || powerLevelStateEvent === void 0 ? void 0 : powerLevelStateEvent[action]) !== null && _a !== void 0 ? _a : 0;
1466
- }
1467
- return (_b = powerLevelStateEvent === null || powerLevelStateEvent === void 0 ? void 0 : powerLevelStateEvent[action]) !== null && _b !== void 0 ? _b : 50;
1468
- }
1469
-
1470
- /*
1471
- * Copyright 2022 Nordeck IT + Consulting GmbH
1472
- *
1473
- * Licensed under the Apache License, Version 2.0 (the "License");
1474
- * you may not use this file except in compliance with the License.
1475
- * You may obtain a copy of the License at
1476
- *
1477
- * http://www.apache.org/licenses/LICENSE-2.0
1478
- *
1479
- * Unless required by applicable law or agreed to in writing, software
1480
- * distributed under the License is distributed on an "AS IS" BASIS,
1481
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1482
- * See the License for the specific language governing permissions and
1483
- * limitations under the License.
1484
- */
1485
- var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1486
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1487
- return new (P || (P = Promise))(function (resolve, reject) {
1488
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1489
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1490
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1491
- step((generator = generator.apply(thisArg, _arguments || [])).next());
1492
- });
1493
- };
1494
- var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
1495
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
1496
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
1497
- function verb(n) { return function (v) { return step([n, v]); }; }
1498
- function step(op) {
1499
- if (f) throw new TypeError("Generator is already executing.");
1500
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
1501
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1502
- if (y = 0, t) op = [op[0] & 2, t.value];
1503
- switch (op[0]) {
1504
- case 0: case 1: t = op; break;
1505
- case 4: _.label++; return { value: op[1], done: false };
1506
- case 5: _.label++; y = op[1]; op = [0]; continue;
1507
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
1508
- default:
1509
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
1510
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
1511
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
1512
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
1513
- if (t[2]) _.ops.pop();
1514
- _.trys.pop(); continue;
1072
+ /**
1073
+ * Initialize a new widget API instance and wait till it is ready.
1074
+ * There should only be one instance of the widget API. The widget API should
1075
+ * be created as early as possible when starting the application. This is
1076
+ * required to match the timing of the API connection establishment with the
1077
+ * client, especially in Safari. Therefore it is recommended to create it
1078
+ * inside the entrypoint, before initializing rendering engines like react.
1079
+ *
1080
+ * @param param0 - {@link WidgetApiOptions}
1081
+ *
1082
+ * @returns A widget API instance ready to use.
1083
+ */
1084
+ WidgetApiImpl.create = function () {
1085
+ return __awaiter(this, arguments, void 0, function (_a) {
1086
+ var _b, clientOrigin, widgetId, widgetParameters, matrixWidgetApi, widgetApi;
1087
+ var _c = _a === void 0 ? {} : _a, _d = _c.capabilities, capabilities = _d === void 0 ? [] : _d, _e = _c.supportStandalone, supportStandalone = _e === void 0 ? false : _e;
1088
+ return __generator(this, function (_f) {
1089
+ switch (_f.label) {
1090
+ case 0:
1091
+ _b = extractWidgetApiParameters(), clientOrigin = _b.clientOrigin, widgetId = _b.widgetId;
1092
+ widgetParameters = extractWidgetParameters();
1093
+ matrixWidgetApi = new WidgetApi(widgetId, clientOrigin);
1094
+ widgetApi = new WidgetApiImpl(matrixWidgetApi, widgetId, widgetParameters, { capabilities: capabilities, supportStandalone: supportStandalone });
1095
+ return [4 /*yield*/, widgetApi.initialize()];
1096
+ case 1:
1097
+ _f.sent();
1098
+ return [2 /*return*/, widgetApi];
1099
+ }
1100
+ });
1101
+ });
1102
+ };
1103
+ /**
1104
+ * Initialize the widget API and wait till a connection with the client is
1105
+ * fully established.
1106
+ *
1107
+ * Waits till the user has approved the initial set of capabilities. The
1108
+ * method doesn't fail if the user doesn't approve all of them. It is
1109
+ * required to check manually afterwards.
1110
+ * In case of modal widgets it waits till the `widgetConfig` is received.
1111
+ *
1112
+ * @remarks Should only be called once during startup.
1113
+ */
1114
+ WidgetApiImpl.prototype.initialize = function () {
1115
+ return __awaiter(this, void 0, void 0, function () {
1116
+ var ready, isModal, configReady, rawCapabilities;
1117
+ var _this = this;
1118
+ return __generator(this, function (_a) {
1119
+ switch (_a.label) {
1120
+ case 0:
1121
+ ready = new Promise(function (resolve) {
1122
+ _this.matrixWidgetApi.once('ready', function () { return resolve(); });
1123
+ });
1124
+ isModal = parseWidgetId(this.widgetId).isModal;
1125
+ configReady = isModal
1126
+ ? (function () { return __awaiter(_this, void 0, void 0, function () {
1127
+ var widgetConfig$, _a;
1128
+ var _this = this;
1129
+ return __generator(this, function (_b) {
1130
+ switch (_b.label) {
1131
+ case 0:
1132
+ widgetConfig$ = fromEvent(this.matrixWidgetApi, "action:".concat(WidgetApiToWidgetAction.WidgetConfig), function (ev) {
1133
+ ev.preventDefault();
1134
+ _this.matrixWidgetApi.transport.reply(ev.detail, {});
1135
+ return ev.detail.data;
1136
+ });
1137
+ _a = this;
1138
+ return [4 /*yield*/, firstValueFrom(widgetConfig$)];
1139
+ case 1:
1140
+ _a.widgetConfig = _b.sent();
1141
+ return [2 /*return*/];
1142
+ }
1143
+ });
1144
+ }); })()
1145
+ : undefined;
1146
+ rawCapabilities = unique(convertToRawCapabilities(this.initialCapabilities));
1147
+ this.matrixWidgetApi.requestCapabilities(rawCapabilities);
1148
+ this.matrixWidgetApi.start();
1149
+ return [4 /*yield*/, ready];
1150
+ case 1:
1151
+ _a.sent();
1152
+ if (!configReady) return [3 /*break*/, 3];
1153
+ return [4 /*yield*/, configReady];
1154
+ case 2:
1155
+ _a.sent();
1156
+ _a.label = 3;
1157
+ case 3: return [2 /*return*/];
1158
+ }
1159
+ });
1160
+ });
1161
+ };
1162
+ /** {@inheritDoc WidgetApi.getWidgetConfig} */
1163
+ WidgetApiImpl.prototype.getWidgetConfig = function () {
1164
+ return this.widgetConfig;
1165
+ };
1166
+ /** {@inheritDoc WidgetApi.rerequestInitialCapabilities} */
1167
+ WidgetApiImpl.prototype.rerequestInitialCapabilities = function () {
1168
+ return __awaiter(this, void 0, void 0, function () {
1169
+ return __generator(this, function (_a) {
1170
+ switch (_a.label) {
1171
+ case 0: return [4 /*yield*/, this.requestCapabilities(this.initialCapabilities)];
1172
+ case 1: return [2 /*return*/, _a.sent()];
1173
+ }
1174
+ });
1175
+ });
1176
+ };
1177
+ /** {@inheritDoc WidgetApi.hasInitialCapabilities} */
1178
+ WidgetApiImpl.prototype.hasInitialCapabilities = function () {
1179
+ return this.hasCapabilities(this.initialCapabilities);
1180
+ };
1181
+ /** {@inheritDoc WidgetApi.requestCapabilities} */
1182
+ WidgetApiImpl.prototype.requestCapabilities = function (capabilities) {
1183
+ return __awaiter(this, void 0, void 0, function () {
1184
+ return __generator(this, function (_b) {
1185
+ switch (_b.label) {
1186
+ case 0:
1187
+ if (!this.outstandingCapabilitiesRequest) return [3 /*break*/, 4];
1188
+ _b.label = 1;
1189
+ case 1:
1190
+ _b.trys.push([1, 3, , 4]);
1191
+ return [4 /*yield*/, this.outstandingCapabilitiesRequest];
1192
+ case 2:
1193
+ _b.sent();
1194
+ return [3 /*break*/, 4];
1195
+ case 3:
1196
+ _b.sent();
1197
+ return [3 /*break*/, 4];
1198
+ case 4:
1199
+ _b.trys.push([4, , 6, 7]);
1200
+ this.outstandingCapabilitiesRequest =
1201
+ this.requestCapabilitiesInternal(capabilities);
1202
+ return [4 /*yield*/, this.outstandingCapabilitiesRequest];
1203
+ case 5:
1204
+ _b.sent();
1205
+ return [3 /*break*/, 7];
1206
+ case 6:
1207
+ this.outstandingCapabilitiesRequest = undefined;
1208
+ return [7 /*endfinally*/];
1209
+ case 7: return [2 /*return*/];
1210
+ }
1211
+ });
1212
+ });
1213
+ };
1214
+ WidgetApiImpl.prototype.requestCapabilitiesInternal = function (capabilities) {
1215
+ return __awaiter(this, void 0, void 0, function () {
1216
+ var rawCapabilities, requestedSet, capabilities$;
1217
+ var _this = this;
1218
+ return __generator(this, function (_a) {
1219
+ switch (_a.label) {
1220
+ case 0:
1221
+ rawCapabilities = unique(convertToRawCapabilities(capabilities));
1222
+ // Take shortcut if possible, that avoid extra roundtrips over the API.
1223
+ if (this.hasCapabilities(rawCapabilities)) {
1224
+ return [2 /*return*/];
1225
+ }
1226
+ requestedSet = new Set(rawCapabilities);
1227
+ capabilities$ = fromEvent(this.matrixWidgetApi, "action:".concat(WidgetApiToWidgetAction.NotifyCapabilities), function (ev) { return ev; }).pipe(
1228
+ // TODO: `hasCapability` in the matrix-widget-api isn't consistent when capability
1229
+ // upgrades happened. But `updateRequestedCapabilities` will deduplicate already
1230
+ // approved capabilities, so the the `requested` field will be inconsistent.
1231
+ // If we would enable this check, the function will never resolve. This should
1232
+ // be reactivated once the capability upgrade is working correctly. See also:
1233
+ // https://github.com/matrix-org/matrix-widget-api/issues/52
1234
+ // Ignore events from other parallel capability requests
1235
+ //filter((ev) =>
1236
+ // equalsSet(new Set(ev.detail.data.requested), requestedSet)
1237
+ //),
1238
+ map(function (ev) {
1239
+ var approvedSet = new Set(ev.detail.data.approved);
1240
+ var missingSet = subtractSet(requestedSet, approvedSet);
1241
+ if (missingSet.size > 0) {
1242
+ throw new Error("Capabilities rejected: ".concat(Array.from(missingSet).join(', ')));
1243
+ }
1244
+ }), first());
1245
+ return [4 /*yield*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1246
+ var subscription, err_1;
1247
+ return __generator(this, function (_a) {
1248
+ switch (_a.label) {
1249
+ case 0:
1250
+ subscription = capabilities$.subscribe({
1251
+ next: resolve,
1252
+ error: reject,
1253
+ });
1254
+ _a.label = 1;
1255
+ case 1:
1256
+ _a.trys.push([1, 3, , 4]);
1257
+ this.matrixWidgetApi.requestCapabilities(rawCapabilities);
1258
+ return [4 /*yield*/, this.matrixWidgetApi.updateRequestedCapabilities()];
1259
+ case 2:
1260
+ _a.sent();
1261
+ return [3 /*break*/, 4];
1262
+ case 3:
1263
+ err_1 = _a.sent();
1264
+ subscription.unsubscribe();
1265
+ reject(err_1);
1266
+ return [3 /*break*/, 4];
1267
+ case 4: return [2 /*return*/];
1268
+ }
1269
+ });
1270
+ }); })];
1271
+ case 1:
1272
+ _a.sent();
1273
+ return [2 /*return*/];
1274
+ }
1275
+ });
1276
+ });
1277
+ };
1278
+ /** {@inheritDoc WidgetApi.hasCapabilities} */
1279
+ WidgetApiImpl.prototype.hasCapabilities = function (capabilities) {
1280
+ var _this = this;
1281
+ var rawCapabilities = convertToRawCapabilities(capabilities);
1282
+ return rawCapabilities.every(function (c) { return _this.matrixWidgetApi.hasCapability(c); });
1283
+ };
1284
+ /** {@inheritDoc WidgetApi.receiveSingleStateEvent} */
1285
+ WidgetApiImpl.prototype.receiveSingleStateEvent = function (eventType_1) {
1286
+ return __awaiter(this, arguments, void 0, function (eventType, stateKey) {
1287
+ var events;
1288
+ if (stateKey === void 0) { stateKey = ''; }
1289
+ return __generator(this, function (_a) {
1290
+ switch (_a.label) {
1291
+ case 0: return [4 /*yield*/, this.receiveStateEvents(eventType, { stateKey: stateKey })];
1292
+ case 1:
1293
+ events = _a.sent();
1294
+ return [2 /*return*/, events && events[0]];
1295
+ }
1296
+ });
1297
+ });
1298
+ };
1299
+ /** {@inheritDoc WidgetApi.receiveStateEvents} */
1300
+ WidgetApiImpl.prototype.receiveStateEvents = function (eventType_1) {
1301
+ return __awaiter(this, arguments, void 0, function (eventType, _a) {
1302
+ var _b = _a === void 0 ? {} : _a, stateKey = _b.stateKey, roomIds = _b.roomIds;
1303
+ return __generator(this, function (_c) {
1304
+ switch (_c.label) {
1305
+ case 0: return [4 /*yield*/, this.matrixWidgetApi.readStateEvents(eventType, Number.MAX_SAFE_INTEGER, stateKey, typeof roomIds === 'string' ? [Symbols.AnyRoom] : roomIds)];
1306
+ case 1: return [2 /*return*/, (_c.sent())];
1307
+ }
1308
+ });
1309
+ });
1310
+ };
1311
+ /** {@inheritDoc WidgetApi.observeStateEvents} */
1312
+ WidgetApiImpl.prototype.observeStateEvents = function (eventType, _a) {
1313
+ var _b = _a === void 0 ? {} : _a, stateKey = _b.stateKey, roomIds = _b.roomIds;
1314
+ var currentRoomId = this.widgetParameters.roomId;
1315
+ if (!currentRoomId) {
1316
+ return throwError(function () { return new Error('Current room id is unknown'); });
1317
+ }
1318
+ var historyEvent$ = from(this.receiveStateEvents(eventType, { stateKey: stateKey, roomIds: roomIds })).pipe(mergeAll());
1319
+ var futureEvent$ = this.events$.pipe(map(function (event) {
1320
+ var matrixEvent = event.detail.data;
1321
+ if (matrixEvent.type === eventType &&
1322
+ matrixEvent.state_key !== undefined &&
1323
+ (stateKey === undefined || matrixEvent.state_key === stateKey) &&
1324
+ isInRoom(matrixEvent, currentRoomId, roomIds)) {
1325
+ return event.detail.data;
1515
1326
  }
1516
- op = body.call(thisArg, _);
1517
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
1518
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1519
- }
1520
- };
1521
- /**
1522
- * The name of the redaction room event.
1523
- */
1524
- var ROOM_EVENT_REDACTION = 'm.room.redaction';
1525
- /**
1526
- * Check whether the format of a redaction event is valid.
1527
- * @param event - The event to check.
1528
- * @returns True if the event format is valid, otherwise false.
1529
- */
1530
- function isValidRedactionEvent(event) {
1531
- if (event.type === ROOM_EVENT_REDACTION &&
1532
- typeof event.redacts === 'string') {
1533
- return true;
1534
- }
1535
- return false;
1536
- }
1537
- /**
1538
- * Redacts an event in the current room.
1539
- * @param widgetApi - An instance of the widget API.
1540
- * @param eventId - The id of the event to redact.
1541
- * @returns The redaction event that was send to the room.
1542
- */
1543
- function redactEvent(widgetApi, eventId) {
1544
- return __awaiter(this, void 0, void 0, function () {
1545
- var result;
1546
- return __generator(this, function (_a) {
1547
- switch (_a.label) {
1548
- case 0: return [4 /*yield*/, widgetApi.sendRoomEvent(ROOM_EVENT_REDACTION, { redacts: eventId })];
1549
- case 1:
1550
- result = _a.sent();
1551
- // The redaction event is special and needs to be casted, as the widget
1552
- // toolkit assumes that the content of an event is returned as we send it.
1553
- // However for redactions the content is copied directly into the event to
1554
- // make it available without decrypting the content.
1555
- return [2 /*return*/, result];
1327
+ return undefined;
1328
+ }), filter(isDefined));
1329
+ return concat(historyEvent$, futureEvent$);
1330
+ };
1331
+ /** {@inheritDoc WidgetApi.sendStateEvent} */
1332
+ WidgetApiImpl.prototype.sendStateEvent = function (eventType_1, content_1) {
1333
+ return __awaiter(this, arguments, void 0, function (eventType, content, _a) {
1334
+ var subject, subscription, _b, event_id_1, room_id_1, event_1;
1335
+ var _c = _a === void 0 ? {} : _a, roomId = _c.roomId, _d = _c.stateKey, stateKey = _d === void 0 ? '' : _d;
1336
+ return __generator(this, function (_e) {
1337
+ switch (_e.label) {
1338
+ case 0:
1339
+ subject = new ReplaySubject();
1340
+ subscription = this.events$.subscribe(function (e) { return subject.next(e); });
1341
+ _e.label = 1;
1342
+ case 1:
1343
+ _e.trys.push([1, , 4, 5]);
1344
+ return [4 /*yield*/, this.matrixWidgetApi.sendStateEvent(eventType, stateKey, content, roomId)];
1345
+ case 2:
1346
+ _b = _e.sent(), event_id_1 = _b.event_id, room_id_1 = _b.room_id;
1347
+ return [4 /*yield*/, firstValueFrom(subject.pipe(filter(function (event) {
1348
+ var matrixEvent = event.detail.data;
1349
+ return (matrixEvent.event_id === event_id_1 &&
1350
+ matrixEvent.room_id === room_id_1);
1351
+ }), map(function (event) { return event.detail.data; })))];
1352
+ case 3:
1353
+ event_1 = _e.sent();
1354
+ return [2 /*return*/, event_1];
1355
+ case 4:
1356
+ subscription.unsubscribe();
1357
+ return [7 /*endfinally*/];
1358
+ case 5: return [2 /*return*/];
1359
+ }
1360
+ });
1361
+ });
1362
+ };
1363
+ /** {@inheritDoc WidgetApi.receiveRoomEvents} */
1364
+ WidgetApiImpl.prototype.receiveRoomEvents = function (eventType_1) {
1365
+ return __awaiter(this, arguments, void 0, function (eventType, _a) {
1366
+ var _b = _a === void 0 ? {} : _a, messageType = _b.messageType, roomIds = _b.roomIds;
1367
+ return __generator(this, function (_c) {
1368
+ switch (_c.label) {
1369
+ case 0: return [4 /*yield*/, this.matrixWidgetApi.readRoomEvents(eventType, Number.MAX_SAFE_INTEGER, messageType, typeof roomIds === 'string' ? [Symbols.AnyRoom] : roomIds)];
1370
+ case 1: return [2 /*return*/, (_c.sent())];
1371
+ }
1372
+ });
1373
+ });
1374
+ };
1375
+ /** {@inheritDoc WidgetApi.observeRoomEvents} */
1376
+ WidgetApiImpl.prototype.observeRoomEvents = function (eventType, _a) {
1377
+ var _b = _a === void 0 ? {} : _a, messageType = _b.messageType, roomIds = _b.roomIds;
1378
+ var currentRoomId = this.widgetParameters.roomId;
1379
+ if (!currentRoomId) {
1380
+ return throwError(function () { return new Error('Current room id is unknown'); });
1381
+ }
1382
+ var historyEvent$ = from(this.receiveRoomEvents(eventType, { messageType: messageType, roomIds: roomIds })).pipe(mergeAll());
1383
+ var futureEvent$ = this.events$.pipe(map(function (event) {
1384
+ var matrixEvent = event.detail.data;
1385
+ if (matrixEvent.type === eventType &&
1386
+ matrixEvent.state_key === undefined &&
1387
+ (!messageType || matrixEvent.content.msgtype === messageType) &&
1388
+ isInRoom(matrixEvent, currentRoomId, roomIds)) {
1389
+ return event.detail.data;
1556
1390
  }
1391
+ return undefined;
1392
+ }), filter(isDefined));
1393
+ return concat(historyEvent$, futureEvent$);
1394
+ };
1395
+ /** {@inheritDoc WidgetApi.sendRoomEvent} */
1396
+ WidgetApiImpl.prototype.sendRoomEvent = function (eventType_1, content_1) {
1397
+ return __awaiter(this, arguments, void 0, function (eventType, content, _a) {
1398
+ var subject, subscription, _b, event_id_2, room_id_2, event_2;
1399
+ var _c = _a === void 0 ? {} : _a, roomId = _c.roomId;
1400
+ return __generator(this, function (_d) {
1401
+ switch (_d.label) {
1402
+ case 0:
1403
+ subject = new ReplaySubject();
1404
+ subscription = this.events$.subscribe(function (e) { return subject.next(e); });
1405
+ _d.label = 1;
1406
+ case 1:
1407
+ _d.trys.push([1, , 4, 5]);
1408
+ return [4 /*yield*/, this.matrixWidgetApi.sendRoomEvent(eventType, content, roomId)];
1409
+ case 2:
1410
+ _b = _d.sent(), event_id_2 = _b.event_id, room_id_2 = _b.room_id;
1411
+ return [4 /*yield*/, firstValueFrom(subject.pipe(filter(function (event) {
1412
+ var matrixEvent = event.detail.data;
1413
+ return (matrixEvent.event_id === event_id_2 &&
1414
+ matrixEvent.room_id === room_id_2);
1415
+ }), map(function (event) { return event.detail.data; })))];
1416
+ case 3:
1417
+ event_2 = _d.sent();
1418
+ return [2 /*return*/, event_2];
1419
+ case 4:
1420
+ subscription.unsubscribe();
1421
+ return [7 /*endfinally*/];
1422
+ case 5: return [2 /*return*/];
1423
+ }
1424
+ });
1425
+ });
1426
+ };
1427
+ /** {@inheritDoc WidgetApi.readEventRelations} */
1428
+ WidgetApiImpl.prototype.readEventRelations = function (eventId, options) {
1429
+ return __awaiter(this, void 0, void 0, function () {
1430
+ var _a, chunk, next_batch;
1431
+ return __generator(this, function (_b) {
1432
+ switch (_b.label) {
1433
+ case 0: return [4 /*yield*/, this.matrixWidgetApi.readEventRelations(eventId, options === null || options === void 0 ? void 0 : options.roomId, options === null || options === void 0 ? void 0 : options.relationType, options === null || options === void 0 ? void 0 : options.eventType, options === null || options === void 0 ? void 0 : options.limit, options === null || options === void 0 ? void 0 : options.from, undefined, options === null || options === void 0 ? void 0 : options.direction)];
1434
+ case 1:
1435
+ _a = _b.sent(), chunk = _a.chunk, next_batch = _a.next_batch;
1436
+ return [2 /*return*/, {
1437
+ chunk: chunk,
1438
+ nextToken: next_batch !== null && next_batch !== void 0 ? next_batch : undefined,
1439
+ }];
1440
+ }
1441
+ });
1442
+ });
1443
+ };
1444
+ /** {@inheritDoc WidgetApi.sendToDeviceMessage} */
1445
+ WidgetApiImpl.prototype.sendToDeviceMessage = function (eventType, encrypted, content) {
1446
+ return __awaiter(this, void 0, void 0, function () {
1447
+ return __generator(this, function (_a) {
1448
+ switch (_a.label) {
1449
+ case 0: return [4 /*yield*/, this.matrixWidgetApi.sendToDevice(eventType, encrypted, content)];
1450
+ case 1:
1451
+ _a.sent();
1452
+ return [2 /*return*/];
1453
+ }
1454
+ });
1455
+ });
1456
+ };
1457
+ /** {@inheritDoc WidgetApi.observeToDeviceMessages} */
1458
+ WidgetApiImpl.prototype.observeToDeviceMessages = function (eventType) {
1459
+ return this.toDeviceMessages$.pipe(map(function (e) { return e.detail.data; }), filter(function (e) { return e.type === eventType; }));
1460
+ };
1461
+ /** {@inheritDoc WidgetApi.openModal} */
1462
+ WidgetApiImpl.prototype.openModal = function (pathName, name, options) {
1463
+ return __awaiter(this, void 0, void 0, function () {
1464
+ var isModal, url, closeModalWidget$;
1465
+ var _this = this;
1466
+ return __generator(this, function (_a) {
1467
+ switch (_a.label) {
1468
+ case 0:
1469
+ isModal = parseWidgetId(this.widgetId).isModal;
1470
+ if (isModal) {
1471
+ throw new Error("Modals can't be opened from another modal widget");
1472
+ }
1473
+ url = generateWidgetRegistrationUrl({
1474
+ pathName: pathName,
1475
+ widgetParameters: this.widgetParameters,
1476
+ });
1477
+ return [4 /*yield*/, this.matrixWidgetApi.openModalWidget(url, name, options === null || options === void 0 ? void 0 : options.buttons, options === null || options === void 0 ? void 0 : options.data)];
1478
+ case 1:
1479
+ _a.sent();
1480
+ closeModalWidget$ = fromEvent(this.matrixWidgetApi, "action:".concat(WidgetApiToWidgetAction.CloseModalWidget), function (event) {
1481
+ var _a;
1482
+ event.preventDefault();
1483
+ _this.matrixWidgetApi.transport.reply(event.detail, {});
1484
+ if (((_a = event.detail.data) === null || _a === void 0 ? void 0 : _a['m.exited']) === true) {
1485
+ return undefined;
1486
+ }
1487
+ return event.detail.data;
1488
+ });
1489
+ return [2 /*return*/, firstValueFrom(closeModalWidget$)];
1490
+ }
1491
+ });
1492
+ });
1493
+ };
1494
+ /** {@inheritDoc WidgetApi.setModalButtonEnabled} */
1495
+ WidgetApiImpl.prototype.setModalButtonEnabled = function (buttonId, isEnabled) {
1496
+ return __awaiter(this, void 0, void 0, function () {
1497
+ var isModal;
1498
+ return __generator(this, function (_a) {
1499
+ switch (_a.label) {
1500
+ case 0:
1501
+ isModal = parseWidgetId(this.widgetId).isModal;
1502
+ if (!isModal) {
1503
+ throw new Error('Modal buttons can only be enabled from a modal widget');
1504
+ }
1505
+ return [4 /*yield*/, this.matrixWidgetApi.setModalButtonEnabled(buttonId, isEnabled)];
1506
+ case 1:
1507
+ _a.sent();
1508
+ return [2 /*return*/];
1509
+ }
1510
+ });
1511
+ });
1512
+ };
1513
+ /** {@inheritDoc WidgetApi.observeModalButtons} */
1514
+ WidgetApiImpl.prototype.observeModalButtons = function () {
1515
+ var _this = this;
1516
+ var isModal = parseWidgetId(this.widgetId).isModal;
1517
+ if (!isModal) {
1518
+ throw new Error('Modal buttons can only be observed from a modal widget');
1519
+ }
1520
+ return fromEvent(this.matrixWidgetApi, "action:".concat(WidgetApiToWidgetAction.ButtonClicked), function (event) {
1521
+ event.preventDefault();
1522
+ _this.matrixWidgetApi.transport.reply(event.detail, {});
1523
+ return event.detail.data.id;
1524
+ });
1525
+ };
1526
+ /** {@inheritDoc WidgetApi.closeModal} */
1527
+ WidgetApiImpl.prototype.closeModal = function (data) {
1528
+ return __awaiter(this, void 0, void 0, function () {
1529
+ var isModal;
1530
+ return __generator(this, function (_a) {
1531
+ switch (_a.label) {
1532
+ case 0:
1533
+ isModal = parseWidgetId(this.widgetId).isModal;
1534
+ if (!isModal) {
1535
+ throw new Error('Modals can only be closed from a modal widget');
1536
+ }
1537
+ return [4 /*yield*/, this.matrixWidgetApi.closeModalWidget(data ? data : { 'm.exited': true })];
1538
+ case 1:
1539
+ _a.sent();
1540
+ return [2 /*return*/];
1541
+ }
1542
+ });
1557
1543
  });
1558
- });
1559
- }
1560
- /**
1561
- * Observes redaction events in the current room.
1562
- * @param widgetApi - An instance of the widget API.
1563
- * @returns An observable of validated redaction events.
1564
- */
1565
- function observeRedactionEvents(widgetApi) {
1566
- return widgetApi
1567
- .observeRoomEvents(ROOM_EVENT_REDACTION)
1568
- .pipe(filter(isValidRedactionEvent));
1569
- }
1570
-
1571
- /*
1572
- * Copyright 2022 Nordeck IT + Consulting GmbH
1573
- *
1574
- * Licensed under the Apache License, Version 2.0 (the "License");
1575
- * you may not use this file except in compliance with the License.
1576
- * You may obtain a copy of the License at
1577
- *
1578
- * http://www.apache.org/licenses/LICENSE-2.0
1579
- *
1580
- * Unless required by applicable law or agreed to in writing, software
1581
- * distributed under the License is distributed on an "AS IS" BASIS,
1582
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1583
- * See the License for the specific language governing permissions and
1584
- * limitations under the License.
1585
- */
1586
- /**
1587
- * Get the original event id, or the event id of the current event if it
1588
- * doesn't relates to another event.
1589
- * @param event - The room event.
1590
- * @returns The event id of the original event, or the current event id.
1591
- */
1592
- function getOriginalEventId(event) {
1593
- var _a, _b, _c;
1594
- var newContentRelatesTo = event.content;
1595
- if (((_a = newContentRelatesTo['m.relates_to']) === null || _a === void 0 ? void 0 : _a.rel_type) === 'm.replace') {
1596
- return (_c = (_b = newContentRelatesTo['m.relates_to']) === null || _b === void 0 ? void 0 : _b.event_id) !== null && _c !== void 0 ? _c : event.event_id;
1597
- }
1598
- return event.event_id;
1599
- }
1600
- /**
1601
- * Get the content of the event, independent from whether it contains the
1602
- * content directly or contains a "m.new_content" key.
1603
- * @param event - The room event.
1604
- * @returns Only the content of the room event.
1605
- */
1606
- function getContent(event) {
1607
- var _a;
1608
- var newContentRelatesTo = event.content;
1609
- return (_a = newContentRelatesTo['m.new_content']) !== null && _a !== void 0 ? _a : event.content;
1610
- }
1611
- /**
1612
- * Validates that `event` has a valid structure for a
1613
- * {@link EventWithRelatesTo}.
1614
- * @param event - The event to validate.
1615
- * @returns True, if the event is valid.
1616
- */
1617
- function isValidEventWithRelatesTo(event) {
1618
- if (!event.content || typeof event.content !== 'object') {
1619
- return false;
1620
- }
1621
- var relatedEvent = event;
1622
- if (!relatedEvent.content['m.relates_to'] ||
1623
- typeof relatedEvent.content['m.relates_to'] !== 'object') {
1624
- return false;
1625
- }
1626
- if (typeof relatedEvent.content['m.relates_to'].rel_type !== 'string' ||
1627
- typeof relatedEvent.content['m.relates_to'].event_id !== 'string') {
1628
- return false;
1629
- }
1630
- return true;
1631
- }
1632
-
1633
- /*
1634
- * Copyright 2022 Nordeck IT + Consulting GmbH
1635
- *
1636
- * Licensed under the Apache License, Version 2.0 (the "License");
1637
- * you may not use this file except in compliance with the License.
1638
- * You may obtain a copy of the License at
1639
- *
1640
- * http://www.apache.org/licenses/LICENSE-2.0
1641
- *
1642
- * Unless required by applicable law or agreed to in writing, software
1643
- * distributed under the License is distributed on an "AS IS" BASIS,
1644
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1645
- * See the License for the specific language governing permissions and
1646
- * limitations under the License.
1647
- */
1648
- /**
1649
- * The name of the room member state event.
1650
- */
1651
- var STATE_EVENT_ROOM_MEMBER = 'm.room.member';
1652
- function isStringUndefinedOrNull(value) {
1653
- return value === undefined || value === null || typeof value === 'string';
1654
- }
1655
- /**
1656
- * Validates that `event` is has a valid structure for a
1657
- * {@link RoomMemberStateEventContent}.
1658
- * @param event - The event to validate.
1659
- * @returns True, if the event is valid.
1660
- */
1661
- function isValidRoomMemberStateEvent(event) {
1662
- if (event.type !== STATE_EVENT_ROOM_MEMBER ||
1663
- typeof event.content !== 'object') {
1664
- return false;
1665
- }
1666
- var content = event.content;
1667
- if (typeof content.membership !== 'string') {
1668
- return false;
1669
- }
1670
- if (!isStringUndefinedOrNull(content.displayname)) {
1671
- return false;
1672
- }
1673
- // the avatar_url shouldn't be null, but some implementations
1674
- // set it as a valid value
1675
- if (!isStringUndefinedOrNull(content.avatar_url)) {
1676
- return false;
1677
- }
1678
- return true;
1679
- }
1544
+ };
1545
+ /** {@inheritdoc WidgetApi.navigateTo} */
1546
+ WidgetApiImpl.prototype.navigateTo = function (uri) {
1547
+ return __awaiter(this, void 0, void 0, function () {
1548
+ return __generator(this, function (_a) {
1549
+ switch (_a.label) {
1550
+ case 0: return [4 /*yield*/, this.matrixWidgetApi.navigateTo(uri)];
1551
+ case 1:
1552
+ _a.sent();
1553
+ return [2 /*return*/];
1554
+ }
1555
+ });
1556
+ });
1557
+ };
1558
+ /** {@inheritdoc WidgetApi.requestOpenIDConnectToken} */
1559
+ WidgetApiImpl.prototype.requestOpenIDConnectToken = function () {
1560
+ return __awaiter(this, void 0, void 0, function () {
1561
+ return __generator(this, function (_b) {
1562
+ switch (_b.label) {
1563
+ case 0:
1564
+ if (!this.outstandingOpenIDConnectTokenRequest) return [3 /*break*/, 4];
1565
+ _b.label = 1;
1566
+ case 1:
1567
+ _b.trys.push([1, 3, , 4]);
1568
+ return [4 /*yield*/, this.outstandingOpenIDConnectTokenRequest];
1569
+ case 2:
1570
+ _b.sent();
1571
+ return [3 /*break*/, 4];
1572
+ case 3:
1573
+ _b.sent();
1574
+ return [3 /*break*/, 4];
1575
+ case 4:
1576
+ _b.trys.push([4, , 6, 7]);
1577
+ this.outstandingOpenIDConnectTokenRequest =
1578
+ this.requestOpenIDConnectTokenInternal();
1579
+ return [4 /*yield*/, this.outstandingOpenIDConnectTokenRequest];
1580
+ case 5: return [2 /*return*/, _b.sent()];
1581
+ case 6:
1582
+ this.outstandingOpenIDConnectTokenRequest = undefined;
1583
+ return [7 /*endfinally*/];
1584
+ case 7: return [2 /*return*/];
1585
+ }
1586
+ });
1587
+ });
1588
+ };
1589
+ WidgetApiImpl.prototype.requestOpenIDConnectTokenInternal = function () {
1590
+ return __awaiter(this, void 0, void 0, function () {
1591
+ var leywayMilliseconds, openIdToken, err_2;
1592
+ var _a;
1593
+ return __generator(this, function (_b) {
1594
+ switch (_b.label) {
1595
+ case 0:
1596
+ leywayMilliseconds = 30 * 1000;
1597
+ if (this.cachedOpenIdToken &&
1598
+ this.cachedOpenIdToken.expiresAt - leywayMilliseconds > Date.now()) {
1599
+ return [2 /*return*/, this.cachedOpenIdToken.openIdToken];
1600
+ }
1601
+ _b.label = 1;
1602
+ case 1:
1603
+ _b.trys.push([1, 3, , 4]);
1604
+ return [4 /*yield*/, this.matrixWidgetApi.requestOpenIDConnectToken()];
1605
+ case 2:
1606
+ openIdToken = _b.sent();
1607
+ this.cachedOpenIdToken = {
1608
+ openIdToken: openIdToken,
1609
+ expiresAt: Date.now() + ((_a = openIdToken.expires_in) !== null && _a !== void 0 ? _a : 0) * 1000,
1610
+ };
1611
+ return [2 /*return*/, openIdToken];
1612
+ case 3:
1613
+ err_2 = _b.sent();
1614
+ this.cachedOpenIdToken = undefined;
1615
+ throw err_2;
1616
+ case 4: return [2 /*return*/];
1617
+ }
1618
+ });
1619
+ });
1620
+ };
1621
+ /** {@inheritdoc WidgetApi.observeTurnServers} */
1622
+ WidgetApiImpl.prototype.observeTurnServers = function () {
1623
+ return from(this.matrixWidgetApi.getTurnServers()).pipe(
1624
+ // For some reason a different naming was chosen for the API, but
1625
+ // we already convert them to the right type for WebRTC consumers.
1626
+ map(function (_a) {
1627
+ var uris = _a.uris, username = _a.username, password = _a.password;
1628
+ return ({
1629
+ urls: uris,
1630
+ username: username,
1631
+ credential: password,
1632
+ });
1633
+ }));
1634
+ };
1635
+ /** {@inheritdoc WidgetApi.searchUserDirectory} */
1636
+ WidgetApiImpl.prototype.searchUserDirectory = function (searchTerm, options) {
1637
+ return __awaiter(this, void 0, void 0, function () {
1638
+ var results;
1639
+ return __generator(this, function (_a) {
1640
+ switch (_a.label) {
1641
+ case 0: return [4 /*yield*/, this.matrixWidgetApi.searchUserDirectory(searchTerm, options === null || options === void 0 ? void 0 : options.limit)];
1642
+ case 1:
1643
+ results = (_a.sent()).results;
1644
+ return [2 /*return*/, {
1645
+ results: results.map(function (_a) {
1646
+ var user_id = _a.user_id, display_name = _a.display_name, avatar_url = _a.avatar_url;
1647
+ return ({
1648
+ userId: user_id,
1649
+ displayName: display_name,
1650
+ avatarUrl: avatar_url,
1651
+ });
1652
+ }),
1653
+ }];
1654
+ }
1655
+ });
1656
+ });
1657
+ };
1658
+ /** {@inheritdoc WidgetApi.getMediaConfig} */
1659
+ WidgetApiImpl.prototype.getMediaConfig = function () {
1660
+ return __awaiter(this, void 0, void 0, function () {
1661
+ return __generator(this, function (_a) {
1662
+ switch (_a.label) {
1663
+ case 0: return [4 /*yield*/, this.matrixWidgetApi.getMediaConfig()];
1664
+ case 1: return [2 /*return*/, _a.sent()];
1665
+ }
1666
+ });
1667
+ });
1668
+ };
1669
+ /** {@inheritdoc WidgetApi.uploadFile} */
1670
+ WidgetApiImpl.prototype.uploadFile = function (file) {
1671
+ return __awaiter(this, void 0, void 0, function () {
1672
+ return __generator(this, function (_a) {
1673
+ switch (_a.label) {
1674
+ case 0: return [4 /*yield*/, this.matrixWidgetApi.uploadFile(file)];
1675
+ case 1: return [2 /*return*/, _a.sent()];
1676
+ }
1677
+ });
1678
+ });
1679
+ };
1680
+ return WidgetApiImpl;
1681
+ }());
1680
1682
 
1681
1683
  export { ROOM_EVENT_REDACTION, STATE_EVENT_POWER_LEVELS, STATE_EVENT_ROOM_MEMBER, WIDGET_CAPABILITY_NAVIGATE, WidgetApiImpl, calculateUserPowerLevel, compareOriginServerTS, extractRawWidgetParameters, extractWidgetApiParameters, extractWidgetParameters, generateRoomTimelineCapabilities, generateWidgetRegistrationUrl, getContent, getOriginalEventId, getRoomMemberDisplayName, hasActionPower, hasRequiredWidgetParameters, hasRoomEventPower, hasStateEventPower, isRoomEvent, isStateEvent, isValidEventWithRelatesTo, isValidPowerLevelStateEvent, isValidRedactionEvent, isValidRoomMemberStateEvent, navigateToRoom, observeRedactionEvents, parseWidgetId, redactEvent, repairWidgetRegistration };