@matrix-widget-toolkit/api 3.2.0 → 3.2.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 { 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';
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';
4
4
 
5
5
  /*
6
6
  * Copyright 2022 Nordeck IT + Consulting GmbH
@@ -17,112 +17,92 @@ import { filter, fromEvent, firstValueFrom, map, first, throwError, from, mergeA
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
+ };
20
31
  /**
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.
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.
29
35
  */
30
- function generateRoomTimelineCapabilities(roomIds) {
31
- if (roomIds === Symbols.AnyRoom) {
32
- return ['org.matrix.msc2762.timeline:*'];
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"');
33
42
  }
34
- if (Array.isArray(roomIds)) {
35
- return roomIds.map(function (id) { return "org.matrix.msc2762.timeline:".concat(id); });
43
+ var clientOrigin = new URL(query.parentUrl).origin;
44
+ if (typeof query.widgetId !== 'string') {
45
+ throw Error('Missing parameter "widgetId"');
36
46
  }
37
- return [];
47
+ var widgetId = query.widgetId;
48
+ return { widgetId: widgetId, clientOrigin: clientOrigin };
38
49
  }
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
- */
55
50
  /**
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.
51
+ * Extract the widget parameters from the current `window.location`.
52
+ * @returns The all unprocessed raw widget parameters.
63
53
  */
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
- }
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'; }));
92
61
  }
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
- */
109
62
  /**
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}.
63
+ * Extract the widget parameters from the current `window.location`.
64
+ * @returns The widget parameters.
114
65
  */
115
- function isStateEvent(event) {
116
- return 'state_key' in event && typeof event.state_key === 'string';
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
+ };
117
84
  }
118
85
  /**
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}.
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.
123
89
  */
124
- function isRoomEvent(event) {
125
- return !('state_key' in event);
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
+ };
126
106
  }
127
107
 
128
108
  /*
@@ -140,6 +120,17 @@ function isRoomEvent(event) {
140
120
  * See the License for the specific language governing permissions and
141
121
  * limitations under the License.
142
122
  */
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
+ };
143
134
  var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
144
135
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
145
136
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -155,7 +146,7 @@ var __generator$3 = (undefined && undefined.__generator) || function (thisArg, b
155
146
  function verb(n) { return function (v) { return step([n, v]); }; }
156
147
  function step(op) {
157
148
  if (f) throw new TypeError("Generator is already executing.");
158
- while (_) try {
149
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
159
150
  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;
160
151
  if (y = 0, t) op = [op[0] & 2, t.value];
161
152
  switch (op[0]) {
@@ -176,63 +167,124 @@ var __generator$3 = (undefined && undefined.__generator) || function (thisArg, b
176
167
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
177
168
  }
178
169
  };
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
+ };
179
181
  /**
180
- * The capability that needs to be requested in order to navigate to another room.
181
- */
182
- var WIDGET_CAPABILITY_NAVIGATE = 'org.matrix.msc2931.navigate';
183
- /**
184
- * Navigate the client to another matrix room.
185
- *
186
- * @remarks This requires the {@link WIDGET_CAPABILITY_NAVIGATE} capability.
182
+ * Checks whether all widget parameters were provided to the widget.
187
183
  *
188
- * @param widgetApi - the {@link WidgetApi} instance.
189
- * @param roomId - the room ID.
190
- * @param opts - {@link NavigateToRoomOptions}
184
+ * @param widgetApi - The widget api to read the parameters from
185
+ * @returns True, if all parameters were provided.
191
186
  */
192
- function navigateToRoom(widgetApi, roomId, opts) {
193
- if (opts === void 0) { opts = {}; }
194
- return __awaiter$3(this, void 0, void 0, function () {
195
- var _a, via, params, url;
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
- });
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');
209
195
  }
210
-
211
- /*
212
- * Copyright 2022 Nordeck IT + Consulting GmbH
213
- *
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.
225
- */
226
196
  /**
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.
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.
233
204
  */
234
- function compareOriginServerTS(a, b) {
235
- return a.origin_server_ts - b.origin_server_ts;
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();
228
+ }
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.
234
+ *
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.
238
+ */
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
+ });
236
288
  }
237
289
 
238
290
  /*
@@ -250,192 +302,47 @@ function compareOriginServerTS(a, b) {
250
302
  * See the License for the specific language governing permissions and
251
303
  * limitations under the License.
252
304
  */
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';
305
+ function convertToRawCapabilities(rawCapabilities) {
306
+ return rawCapabilities.map(function (c) { return (typeof c === 'string' ? c : c.raw); });
259
307
  }
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
- })));
308
+ function isDefined(arg) {
309
+ return arg !== null && arg !== undefined;
268
310
  }
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;
311
+ function unique(items) {
312
+ return Array.from(new Set(items));
309
313
  }
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;
314
+ function subtractSet(as, bs) {
315
+ var result = new Set(as);
316
+ bs.forEach(function (v) { return result.delete(v); });
317
+ return result;
326
318
  }
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;
319
+ function isInRoom(matrixEvent, currentRoomId, roomIds) {
320
+ if (!roomIds) {
321
+ return matrixEvent.room_id === currentRoomId;
339
322
  }
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
323
+ if (typeof roomIds === 'string') {
324
+ if (roomIds !== Symbols.AnyRoom) {
325
+ throw Error("Unknown room id symbol: ".concat(roomIds));
326
+ }
361
327
  return true;
362
328
  }
363
- var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
364
- var eventLevel = calculateActionPowerLevel(powerLevelStateEvent, action);
365
- return userLevel >= eventLevel;
329
+ return roomIds.includes(matrixEvent.room_id);
366
330
  }
367
- /**
368
- * Calculate the power level of the user based on a `m.room.power_levels` event.
331
+
332
+ /*
333
+ * Copyright 2022 Nordeck IT + Consulting GmbH
369
334
  *
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.
335
+ * Licensed under the Apache License, Version 2.0 (the "License");
336
+ * you may not use this file except in compliance with the License.
337
+ * You may obtain a copy of the License at
381
338
  *
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.
339
+ * http://www.apache.org/licenses/LICENSE-2.0
393
340
  *
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;
423
- }
424
-
425
- /*
426
- * Copyright 2022 Nordeck IT + Consulting GmbH
427
- *
428
- * Licensed under the Apache License, Version 2.0 (the "License");
429
- * you may not use this file except in compliance with the License.
430
- * You may obtain a copy of the License at
431
- *
432
- * http://www.apache.org/licenses/LICENSE-2.0
433
- *
434
- * Unless required by applicable law or agreed to in writing, software
435
- * distributed under the License is distributed on an "AS IS" BASIS,
436
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
437
- * See the License for the specific language governing permissions and
438
- * limitations under the License.
341
+ * Unless required by applicable law or agreed to in writing, software
342
+ * distributed under the License is distributed on an "AS IS" BASIS,
343
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
344
+ * See the License for the specific language governing permissions and
345
+ * limitations under the License.
439
346
  */
440
347
  var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
441
348
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
@@ -452,7 +359,7 @@ var __generator$2 = (undefined && undefined.__generator) || function (thisArg, b
452
359
  function verb(n) { return function (v) { return step([n, v]); }; }
453
360
  function step(op) {
454
361
  if (f) throw new TypeError("Generator is already executing.");
455
- while (_) try {
362
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
456
363
  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;
457
364
  if (y = 0, t) op = [op[0] & 2, t.value];
458
365
  switch (op[0]) {
@@ -473,704 +380,166 @@ var __generator$2 = (undefined && undefined.__generator) || function (thisArg, b
473
380
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
474
381
  }
475
382
  };
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;
489
- }
490
- return false;
491
- }
492
- /**
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.
497
- */
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];
511
- }
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;
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
+ }
552
389
  }
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
- }
390
+ return to.concat(ar || Array.prototype.slice.call(from));
391
+ };
566
392
  /**
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
393
+ * Implementation of the API from the widget to the client.
596
394
  *
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.
395
+ * @remarks Widget API is specified here:
396
+ * https://docs.google.com/document/d/1uPF7XWY_dXTKVKV7jZQ2KmsI19wn9-kFRgQ1tFQP7wQ/edit#heading=h.9rn9lt6ctkgi
615
397
  */
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;
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
434
+ }
435
+ return event;
436
+ }).pipe(share());
437
+ this.initialCapabilities = __spreadArray(__spreadArray([], capabilities, true), (supportStandalone ? [] : [MatrixCapabilities.RequiresClient]), true);
632
438
  }
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;
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
+ });
659
469
  };
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
- isOpenedByClient: isOpenedByClient,
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
+ });
714
528
  };
715
- }
716
- /**
717
- * Parse a widget id into the individual fields.
718
- * @param widgetId - The widget id to parse.
719
- * @returns The individual fields encoded inside a widget id.
720
- */
721
- function parseWidgetId(widgetId) {
722
- // TODO: Is this whole parsing still working for user widgets?
723
- var mainWidgetId = decodeURIComponent(widgetId).replace(/^modal_/, '');
724
- var roomId = mainWidgetId.indexOf('_')
725
- ? decodeURIComponent(mainWidgetId.split('_')[0])
726
- : undefined;
727
- var creator = (mainWidgetId.match(/_/g) || []).length > 1
728
- ? decodeURIComponent(mainWidgetId.split('_')[1])
729
- : undefined;
730
- var isModal = decodeURIComponent(widgetId).startsWith('modal_');
731
- return {
732
- mainWidgetId: mainWidgetId,
733
- roomId: roomId,
734
- creator: creator,
735
- isModal: isModal,
529
+ /** {@inheritDoc WidgetApi.getWidgetConfig} */
530
+ WidgetApiImpl.prototype.getWidgetConfig = function () {
531
+ return this.widgetConfig;
736
532
  };
737
- }
738
-
739
- /*
740
- * Copyright 2022 Nordeck IT + Consulting GmbH
741
- *
742
- * Licensed under the Apache License, Version 2.0 (the "License");
743
- * you may not use this file except in compliance with the License.
744
- * You may obtain a copy of the License at
745
- *
746
- * http://www.apache.org/licenses/LICENSE-2.0
747
- *
748
- * Unless required by applicable law or agreed to in writing, software
749
- * distributed under the License is distributed on an "AS IS" BASIS,
750
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
751
- * See the License for the specific language governing permissions and
752
- * limitations under the License.
753
- */
754
- var __assign = (undefined && undefined.__assign) || function () {
755
- __assign = Object.assign || function(t) {
756
- for (var s, i = 1, n = arguments.length; i < n; i++) {
757
- s = arguments[i];
758
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
759
- t[p] = s[p];
760
- }
761
- return t;
762
- };
763
- return __assign.apply(this, arguments);
764
- };
765
- var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
766
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
767
- return new (P || (P = Promise))(function (resolve, reject) {
768
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
769
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
770
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
771
- step((generator = generator.apply(thisArg, _arguments || [])).next());
772
- });
773
- };
774
- var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) {
775
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
776
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
777
- function verb(n) { return function (v) { return step([n, v]); }; }
778
- function step(op) {
779
- if (f) throw new TypeError("Generator is already executing.");
780
- while (_) try {
781
- 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;
782
- if (y = 0, t) op = [op[0] & 2, t.value];
783
- switch (op[0]) {
784
- case 0: case 1: t = op; break;
785
- case 4: _.label++; return { value: op[1], done: false };
786
- case 5: _.label++; y = op[1]; op = [0]; continue;
787
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
788
- default:
789
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
790
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
791
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
792
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
793
- if (t[2]) _.ops.pop();
794
- _.trys.pop(); continue;
795
- }
796
- op = body.call(thisArg, _);
797
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
798
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
799
- }
800
- };
801
- var __rest = (undefined && undefined.__rest) || function (s, e) {
802
- var t = {};
803
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
804
- t[p] = s[p];
805
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
806
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
807
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
808
- t[p[i]] = s[p[i]];
809
- }
810
- return t;
811
- };
812
- /**
813
- * Checks whether all widget parameters were provided to the widget.
814
- *
815
- * @param widgetApi - The widget api to read the parameters from
816
- * @returns True, if all parameters were provided.
817
- */
818
- function hasRequiredWidgetParameters(widgetApi) {
819
- return (typeof widgetApi.widgetParameters.userId === 'string' &&
820
- typeof widgetApi.widgetParameters.displayName === 'string' &&
821
- typeof widgetApi.widgetParameters.avatarUrl === 'string' &&
822
- typeof widgetApi.widgetParameters.roomId === 'string' &&
823
- typeof widgetApi.widgetParameters.theme === 'string' &&
824
- typeof widgetApi.widgetParameters.clientId === 'string' &&
825
- typeof widgetApi.widgetParameters.clientLanguage === 'string');
826
- }
827
- /**
828
- * Generate a registration URL for the widget based on the current URL and
829
- * include all widget parameters (and their placeholders).
830
- * @param options - Options for generating the URL.
831
- * Use `pathName` to include an optional sub path in the URL.
832
- * Use `includeParameters` to append the widget parameters to
833
- * the URL, defaults to `true`.
834
- * @returns The generated URL.
835
- */
836
- function generateWidgetRegistrationUrl(options) {
837
- var _a, _b, _c, _d, _e, _f, _g;
838
- if (options === void 0) { options = {}; }
839
- var pathName = options.pathName, _h = options.includeParameters, includeParameters = _h === void 0 ? true : _h, widgetParameters = options.widgetParameters;
840
- // don't forward widgetId and parentUrl as they will be generated by the client
841
- var _j = extractRawWidgetParameters(); _j.widgetId; _j.parentUrl; var rawWidgetParameters = __rest(_j, ["widgetId", "parentUrl"]);
842
- 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' }))
843
- .map(function (_a) {
844
- var k = _a[0], v = _a[1];
845
- return "".concat(k, "=").concat(v);
846
- })
847
- .join('&');
848
- var url = new URL(window.location.href);
849
- if (pathName) {
850
- url.pathname = pathName;
851
- }
852
- else {
853
- // ensure trailing '/'
854
- url.pathname = url.pathname.replace(/\/?$/, '/');
855
- }
856
- url.search = '';
857
- url.hash = includeParameters ? "#/?".concat(parameters) : '';
858
- return url.toString();
859
- }
860
- var STATE_EVENT_WIDGETS = 'im.vector.modular.widgets';
861
- /**
862
- * Repair/configure the registration of the current widget.
863
- * This steps make sure to include all the required widget parameters in the
864
- * URL. Support setting a widget name and additional parameters.
865
- *
866
- * @param widgetApi - The widget api of the current widget.
867
- * @param registration - Optional configuration options for the widget
868
- * registration, like the display name of the widget.
869
- */
870
- function repairWidgetRegistration(widgetApi, registration) {
871
- if (registration === void 0) { registration = {}; }
872
- return __awaiter$1(this, void 0, void 0, function () {
873
- var readResult, url, name, type, data;
874
- return __generator$1(this, function (_a) {
875
- switch (_a.label) {
876
- case 0: return [4 /*yield*/, widgetApi.requestCapabilities([
877
- WidgetEventCapability.forStateEvent(EventDirection.Send, STATE_EVENT_WIDGETS, widgetApi.widgetId),
878
- WidgetEventCapability.forStateEvent(EventDirection.Receive, STATE_EVENT_WIDGETS, widgetApi.widgetId),
879
- ])];
880
- case 1:
881
- _a.sent();
882
- return [4 /*yield*/, widgetApi.receiveSingleStateEvent(STATE_EVENT_WIDGETS, widgetApi.widgetId)];
883
- case 2:
884
- readResult = _a.sent();
885
- if (!readResult) {
886
- throw new Error("Error while repairing registration, can't find existing registration.");
887
- }
888
- url = generateWidgetRegistrationUrl();
889
- name = registration.name &&
890
- (!readResult.content.name ||
891
- readResult.content.name === 'Custom Widget' ||
892
- readResult.content.name === 'Custom')
893
- ? registration.name
894
- : readResult.content.name;
895
- type = registration.type &&
896
- (!readResult.content.type || readResult.content.type === 'm.custom')
897
- ? registration.type
898
- : readResult.content.type;
899
- data = registration.data
900
- ? __assign(__assign({}, readResult.content.data), registration.data) : readResult.content.data;
901
- // This is a workaround because changing the widget config is breaking the
902
- // widget API communication. However we need to fail in case the power level
903
- // for this change is missing. As the error happens quite fast, we just wait
904
- // a moment and then consider the operation as succeeded.
905
- return [4 /*yield*/, Promise.race([
906
- widgetApi.sendStateEvent(STATE_EVENT_WIDGETS, __assign(__assign({}, readResult.content), { url: url.toString(), name: name, type: type, data: data }), { stateKey: widgetApi.widgetId }),
907
- new Promise(function (resolve) { return setTimeout(resolve, 1000); }),
908
- ])];
909
- case 3:
910
- // This is a workaround because changing the widget config is breaking the
911
- // widget API communication. However we need to fail in case the power level
912
- // for this change is missing. As the error happens quite fast, we just wait
913
- // a moment and then consider the operation as succeeded.
914
- _a.sent();
915
- return [2 /*return*/];
916
- }
917
- });
918
- });
919
- }
920
-
921
- /*
922
- * Copyright 2022 Nordeck IT + Consulting GmbH
923
- *
924
- * Licensed under the Apache License, Version 2.0 (the "License");
925
- * you may not use this file except in compliance with the License.
926
- * You may obtain a copy of the License at
927
- *
928
- * http://www.apache.org/licenses/LICENSE-2.0
929
- *
930
- * Unless required by applicable law or agreed to in writing, software
931
- * distributed under the License is distributed on an "AS IS" BASIS,
932
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
933
- * See the License for the specific language governing permissions and
934
- * limitations under the License.
935
- */
936
- function convertToRawCapabilities(rawCapabilities) {
937
- return rawCapabilities.map(function (c) { return (typeof c === 'string' ? c : c.raw); });
938
- }
939
- function isDefined(arg) {
940
- return arg !== null && arg !== undefined;
941
- }
942
- function unique(items) {
943
- return Array.from(new Set(items));
944
- }
945
- function subtractSet(as, bs) {
946
- var result = new Set(as);
947
- bs.forEach(function (v) { return result.delete(v); });
948
- return result;
949
- }
950
- function isInRoom(matrixEvent, currentRoomId, roomIds) {
951
- if (!roomIds) {
952
- return matrixEvent.room_id === currentRoomId;
953
- }
954
- if (typeof roomIds === 'string') {
955
- if (roomIds !== Symbols.AnyRoom) {
956
- throw Error("Unknown room id symbol: ".concat(roomIds));
957
- }
958
- return true;
959
- }
960
- return roomIds.includes(matrixEvent.room_id);
961
- }
962
-
963
- /*
964
- * Copyright 2022 Nordeck IT + Consulting GmbH
965
- *
966
- * Licensed under the Apache License, Version 2.0 (the "License");
967
- * you may not use this file except in compliance with the License.
968
- * You may obtain a copy of the License at
969
- *
970
- * http://www.apache.org/licenses/LICENSE-2.0
971
- *
972
- * Unless required by applicable law or agreed to in writing, software
973
- * distributed under the License is distributed on an "AS IS" BASIS,
974
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
975
- * See the License for the specific language governing permissions and
976
- * limitations under the License.
977
- */
978
- var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
979
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
980
- return new (P || (P = Promise))(function (resolve, reject) {
981
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
982
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
983
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
984
- step((generator = generator.apply(thisArg, _arguments || [])).next());
985
- });
986
- };
987
- var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
988
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
989
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
990
- function verb(n) { return function (v) { return step([n, v]); }; }
991
- function step(op) {
992
- if (f) throw new TypeError("Generator is already executing.");
993
- while (_) try {
994
- 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;
995
- if (y = 0, t) op = [op[0] & 2, t.value];
996
- switch (op[0]) {
997
- case 0: case 1: t = op; break;
998
- case 4: _.label++; return { value: op[1], done: false };
999
- case 5: _.label++; y = op[1]; op = [0]; continue;
1000
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
1001
- default:
1002
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
1003
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
1004
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
1005
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
1006
- if (t[2]) _.ops.pop();
1007
- _.trys.pop(); continue;
1008
- }
1009
- op = body.call(thisArg, _);
1010
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
1011
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1012
- }
1013
- };
1014
- var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
1015
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
1016
- if (ar || !(i in from)) {
1017
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
1018
- ar[i] = from[i];
1019
- }
1020
- }
1021
- return to.concat(ar || Array.prototype.slice.call(from));
1022
- };
1023
- /**
1024
- * Implementation of the API from the widget to the client.
1025
- *
1026
- * @remarks Widget API is specified here:
1027
- * https://docs.google.com/document/d/1uPF7XWY_dXTKVKV7jZQ2KmsI19wn9-kFRgQ1tFQP7wQ/edit#heading=h.9rn9lt6ctkgi
1028
- */
1029
- var WidgetApiImpl = /** @class */ (function () {
1030
- function WidgetApiImpl(
1031
- /**
1032
- * Provide access to the underlying widget API from `matrix-widget-sdk`.
1033
- *
1034
- * @remarks Normally there is no need to use it, however if features are
1035
- * missing from `WidgetApi` it can be handy to work with the
1036
- * original API.
1037
- */
1038
- matrixWidgetApi,
1039
- /** {@inheritDoc WidgetApi.widgetId} */
1040
- widgetId,
1041
- /** {@inheritDoc WidgetApi.widgetParameters} */
1042
- widgetParameters, _a) {
1043
- var _b = _a === void 0 ? {} : _a, _c = _b.capabilities, capabilities = _c === void 0 ? [] : _c, _d = _b.supportStandalone, supportStandalone = _d === void 0 ? false : _d;
1044
- var _this = this;
1045
- this.matrixWidgetApi = matrixWidgetApi;
1046
- this.widgetId = widgetId;
1047
- this.widgetParameters = widgetParameters;
1048
- this.events$ = fromEvent(this.matrixWidgetApi, "action:".concat(WidgetApiToWidgetAction.SendEvent), function (event) {
1049
- event.preventDefault();
1050
- try {
1051
- _this.matrixWidgetApi.transport.reply(event.detail, {});
1052
- }
1053
- catch (_) {
1054
- // Ignore errors while replying
1055
- }
1056
- return event;
1057
- }).pipe(share());
1058
- this.toDeviceMessages$ = fromEvent(this.matrixWidgetApi, 'action:send_to_device', function (event) {
1059
- event.preventDefault();
1060
- try {
1061
- matrixWidgetApi.transport.reply(event.detail, {});
1062
- }
1063
- catch (_) {
1064
- // Ignore errors while replying
1065
- }
1066
- return event;
1067
- }).pipe(share());
1068
- this.initialCapabilities = __spreadArray(__spreadArray([], capabilities, true), (supportStandalone ? [] : [MatrixCapabilities.RequiresClient]), true);
1069
- }
1070
- /**
1071
- * Initialize a new widget API instance and wait till it is ready.
1072
- * There should only be one instance of the widget API. The widget API should
1073
- * be created as early as possible when starting the application. This is
1074
- * required to match the timing of the API connection establishment with the
1075
- * client, especially in Safari. Therefore it is recommended to create it
1076
- * inside the entrypoint, before initializing rendering engines like react.
1077
- *
1078
- * @param param0 - {@link WidgetApiOptions}
1079
- *
1080
- * @returns A widget API instance ready to use.
1081
- */
1082
- WidgetApiImpl.create = function (_a) {
1083
- var _b = _a === void 0 ? {} : _a, _c = _b.capabilities, capabilities = _c === void 0 ? [] : _c, _d = _b.supportStandalone, supportStandalone = _d === void 0 ? false : _d;
1084
- return __awaiter(this, void 0, void 0, function () {
1085
- var _e, clientOrigin, widgetId, widgetParameters, matrixWidgetApi, widgetApi;
1086
- return __generator(this, function (_f) {
1087
- switch (_f.label) {
1088
- case 0:
1089
- _e = extractWidgetApiParameters(), clientOrigin = _e.clientOrigin, widgetId = _e.widgetId;
1090
- widgetParameters = extractWidgetParameters();
1091
- matrixWidgetApi = new WidgetApi(widgetId, clientOrigin);
1092
- widgetApi = new WidgetApiImpl(matrixWidgetApi, widgetId, widgetParameters, { capabilities: capabilities, supportStandalone: supportStandalone });
1093
- return [4 /*yield*/, widgetApi.initialize()];
1094
- case 1:
1095
- _f.sent();
1096
- return [2 /*return*/, widgetApi];
1097
- }
1098
- });
1099
- });
1100
- };
1101
- /**
1102
- * Initialize the widget API and wait till a connection with the client is
1103
- * fully established.
1104
- *
1105
- * Waits till the user has approved the initial set of capabilities. The
1106
- * method doesn't fail if the user doesn't approve all of them. It is
1107
- * required to check manually afterwards.
1108
- * In case of modal widgets it waits till the `widgetConfig` is received.
1109
- *
1110
- * @remarks Should only be called once during startup.
1111
- */
1112
- WidgetApiImpl.prototype.initialize = function () {
1113
- return __awaiter(this, void 0, void 0, function () {
1114
- var ready, isModal, configReady, rawCapabilities;
1115
- var _this = this;
1116
- return __generator(this, function (_a) {
1117
- switch (_a.label) {
1118
- case 0:
1119
- ready = new Promise(function (resolve) {
1120
- _this.matrixWidgetApi.once('ready', function () { return resolve(); });
1121
- });
1122
- isModal = parseWidgetId(this.widgetId).isModal;
1123
- configReady = isModal
1124
- ? (function () { return __awaiter(_this, void 0, void 0, function () {
1125
- var widgetConfig$, _a;
1126
- var _this = this;
1127
- return __generator(this, function (_b) {
1128
- switch (_b.label) {
1129
- case 0:
1130
- widgetConfig$ = fromEvent(this.matrixWidgetApi, "action:".concat(WidgetApiToWidgetAction.WidgetConfig), function (ev) {
1131
- ev.preventDefault();
1132
- _this.matrixWidgetApi.transport.reply(ev.detail, {});
1133
- return ev.detail.data;
1134
- });
1135
- _a = this;
1136
- return [4 /*yield*/, firstValueFrom(widgetConfig$)];
1137
- case 1:
1138
- _a.widgetConfig = _b.sent();
1139
- return [2 /*return*/];
1140
- }
1141
- });
1142
- }); })()
1143
- : undefined;
1144
- rawCapabilities = unique(convertToRawCapabilities(this.initialCapabilities));
1145
- this.matrixWidgetApi.requestCapabilities(rawCapabilities);
1146
- this.matrixWidgetApi.start();
1147
- return [4 /*yield*/, ready];
1148
- case 1:
1149
- _a.sent();
1150
- if (!configReady) return [3 /*break*/, 3];
1151
- return [4 /*yield*/, configReady];
1152
- case 2:
1153
- _a.sent();
1154
- _a.label = 3;
1155
- case 3: return [2 /*return*/];
1156
- }
1157
- });
1158
- });
1159
- };
1160
- /** {@inheritDoc WidgetApi.getWidgetConfig} */
1161
- WidgetApiImpl.prototype.getWidgetConfig = function () {
1162
- return this.widgetConfig;
1163
- };
1164
- /** {@inheritDoc WidgetApi.rerequestInitialCapabilities} */
1165
- WidgetApiImpl.prototype.rerequestInitialCapabilities = function () {
1166
- return __awaiter(this, void 0, void 0, function () {
1167
- return __generator(this, function (_a) {
1168
- switch (_a.label) {
1169
- case 0: return [4 /*yield*/, this.requestCapabilities(this.initialCapabilities)];
1170
- case 1: return [2 /*return*/, _a.sent()];
1171
- }
1172
- });
1173
- });
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
+ });
1174
543
  };
1175
544
  /** {@inheritDoc WidgetApi.hasInitialCapabilities} */
1176
545
  WidgetApiImpl.prototype.hasInitialCapabilities = function () {
@@ -1178,8 +547,8 @@ var WidgetApiImpl = /** @class */ (function () {
1178
547
  };
1179
548
  /** {@inheritDoc WidgetApi.requestCapabilities} */
1180
549
  WidgetApiImpl.prototype.requestCapabilities = function (capabilities) {
1181
- return __awaiter(this, void 0, void 0, function () {
1182
- return __generator(this, function (_b) {
550
+ return __awaiter$2(this, void 0, void 0, function () {
551
+ return __generator$2(this, function (_b) {
1183
552
  switch (_b.label) {
1184
553
  case 0:
1185
554
  if (!this.outstandingCapabilitiesRequest) return [3 /*break*/, 4];
@@ -1210,10 +579,10 @@ var WidgetApiImpl = /** @class */ (function () {
1210
579
  });
1211
580
  };
1212
581
  WidgetApiImpl.prototype.requestCapabilitiesInternal = function (capabilities) {
1213
- return __awaiter(this, void 0, void 0, function () {
582
+ return __awaiter$2(this, void 0, void 0, function () {
1214
583
  var rawCapabilities, requestedSet, capabilities$;
1215
584
  var _this = this;
1216
- return __generator(this, function (_a) {
585
+ return __generator$2(this, function (_a) {
1217
586
  switch (_a.label) {
1218
587
  case 0:
1219
588
  rawCapabilities = unique(convertToRawCapabilities(capabilities));
@@ -1240,9 +609,9 @@ var WidgetApiImpl = /** @class */ (function () {
1240
609
  throw new Error("Capabilities rejected: ".concat(Array.from(missingSet).join(', ')));
1241
610
  }
1242
611
  }), first());
1243
- return [4 /*yield*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
612
+ return [4 /*yield*/, new Promise(function (resolve, reject) { return __awaiter$2(_this, void 0, void 0, function () {
1244
613
  var subscription, err_1;
1245
- return __generator(this, function (_a) {
614
+ return __generator$2(this, function (_a) {
1246
615
  switch (_a.label) {
1247
616
  case 0:
1248
617
  subscription = capabilities$.subscribe({
@@ -1282,9 +651,9 @@ var WidgetApiImpl = /** @class */ (function () {
1282
651
  /** {@inheritDoc WidgetApi.receiveSingleStateEvent} */
1283
652
  WidgetApiImpl.prototype.receiveSingleStateEvent = function (eventType, stateKey) {
1284
653
  if (stateKey === void 0) { stateKey = ''; }
1285
- return __awaiter(this, void 0, void 0, function () {
654
+ return __awaiter$2(this, void 0, void 0, function () {
1286
655
  var events;
1287
- return __generator(this, function (_a) {
656
+ return __generator$2(this, function (_a) {
1288
657
  switch (_a.label) {
1289
658
  case 0: return [4 /*yield*/, this.receiveStateEvents(eventType, { stateKey: stateKey })];
1290
659
  case 1:
@@ -1297,8 +666,8 @@ var WidgetApiImpl = /** @class */ (function () {
1297
666
  /** {@inheritDoc WidgetApi.receiveStateEvents} */
1298
667
  WidgetApiImpl.prototype.receiveStateEvents = function (eventType, _a) {
1299
668
  var _b = _a === void 0 ? {} : _a, stateKey = _b.stateKey, roomIds = _b.roomIds;
1300
- return __awaiter(this, void 0, void 0, function () {
1301
- return __generator(this, function (_c) {
669
+ return __awaiter$2(this, void 0, void 0, function () {
670
+ return __generator$2(this, function (_c) {
1302
671
  switch (_c.label) {
1303
672
  case 0: return [4 /*yield*/, this.matrixWidgetApi.readStateEvents(eventType, Number.MAX_SAFE_INTEGER, stateKey, typeof roomIds === 'string' ? [Symbols.AnyRoom] : roomIds)];
1304
673
  case 1: return [2 /*return*/, (_c.sent())];
@@ -1329,9 +698,9 @@ var WidgetApiImpl = /** @class */ (function () {
1329
698
  /** {@inheritDoc WidgetApi.sendStateEvent} */
1330
699
  WidgetApiImpl.prototype.sendStateEvent = function (eventType, content, _a) {
1331
700
  var _b = _a === void 0 ? {} : _a, roomId = _b.roomId, _c = _b.stateKey, stateKey = _c === void 0 ? '' : _c;
1332
- return __awaiter(this, void 0, void 0, function () {
701
+ return __awaiter$2(this, void 0, void 0, function () {
1333
702
  var subject, subscription, _d, event_id_1, room_id_1, event_1;
1334
- return __generator(this, function (_e) {
703
+ return __generator$2(this, function (_e) {
1335
704
  switch (_e.label) {
1336
705
  case 0:
1337
706
  subject = new ReplaySubject();
@@ -1361,8 +730,8 @@ var WidgetApiImpl = /** @class */ (function () {
1361
730
  /** {@inheritDoc WidgetApi.receiveRoomEvents} */
1362
731
  WidgetApiImpl.prototype.receiveRoomEvents = function (eventType, _a) {
1363
732
  var _b = _a === void 0 ? {} : _a, messageType = _b.messageType, roomIds = _b.roomIds;
1364
- return __awaiter(this, void 0, void 0, function () {
1365
- return __generator(this, function (_c) {
733
+ return __awaiter$2(this, void 0, void 0, function () {
734
+ return __generator$2(this, function (_c) {
1366
735
  switch (_c.label) {
1367
736
  case 0: return [4 /*yield*/, this.matrixWidgetApi.readRoomEvents(eventType, Number.MAX_SAFE_INTEGER, messageType, typeof roomIds === 'string' ? [Symbols.AnyRoom] : roomIds)];
1368
737
  case 1: return [2 /*return*/, (_c.sent())];
@@ -1393,9 +762,9 @@ var WidgetApiImpl = /** @class */ (function () {
1393
762
  /** {@inheritDoc WidgetApi.sendRoomEvent} */
1394
763
  WidgetApiImpl.prototype.sendRoomEvent = function (eventType, content, _a) {
1395
764
  var _b = _a === void 0 ? {} : _a, roomId = _b.roomId;
1396
- return __awaiter(this, void 0, void 0, function () {
765
+ return __awaiter$2(this, void 0, void 0, function () {
1397
766
  var subject, subscription, _c, event_id_2, room_id_2, event_2;
1398
- return __generator(this, function (_d) {
767
+ return __generator$2(this, function (_d) {
1399
768
  switch (_d.label) {
1400
769
  case 0:
1401
770
  subject = new ReplaySubject();
@@ -1424,9 +793,9 @@ var WidgetApiImpl = /** @class */ (function () {
1424
793
  };
1425
794
  /** {@inheritDoc WidgetApi.readEventRelations} */
1426
795
  WidgetApiImpl.prototype.readEventRelations = function (eventId, options) {
1427
- return __awaiter(this, void 0, void 0, function () {
796
+ return __awaiter$2(this, void 0, void 0, function () {
1428
797
  var _a, chunk, next_batch;
1429
- return __generator(this, function (_b) {
798
+ return __generator$2(this, function (_b) {
1430
799
  switch (_b.label) {
1431
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)];
1432
801
  case 1:
@@ -1441,8 +810,8 @@ var WidgetApiImpl = /** @class */ (function () {
1441
810
  };
1442
811
  /** {@inheritDoc WidgetApi.sendToDeviceMessage} */
1443
812
  WidgetApiImpl.prototype.sendToDeviceMessage = function (eventType, encrypted, content) {
1444
- return __awaiter(this, void 0, void 0, function () {
1445
- return __generator(this, function (_a) {
813
+ return __awaiter$2(this, void 0, void 0, function () {
814
+ return __generator$2(this, function (_a) {
1446
815
  switch (_a.label) {
1447
816
  case 0: return [4 /*yield*/, this.matrixWidgetApi.sendToDevice(eventType, encrypted, content)];
1448
817
  case 1:
@@ -1458,10 +827,10 @@ var WidgetApiImpl = /** @class */ (function () {
1458
827
  };
1459
828
  /** {@inheritDoc WidgetApi.openModal} */
1460
829
  WidgetApiImpl.prototype.openModal = function (pathName, name, options) {
1461
- return __awaiter(this, void 0, void 0, function () {
830
+ return __awaiter$2(this, void 0, void 0, function () {
1462
831
  var isModal, url, closeModalWidget$;
1463
832
  var _this = this;
1464
- return __generator(this, function (_a) {
833
+ return __generator$2(this, function (_a) {
1465
834
  switch (_a.label) {
1466
835
  case 0:
1467
836
  isModal = parseWidgetId(this.widgetId).isModal;
@@ -1491,9 +860,9 @@ var WidgetApiImpl = /** @class */ (function () {
1491
860
  };
1492
861
  /** {@inheritDoc WidgetApi.setModalButtonEnabled} */
1493
862
  WidgetApiImpl.prototype.setModalButtonEnabled = function (buttonId, isEnabled) {
1494
- return __awaiter(this, void 0, void 0, function () {
863
+ return __awaiter$2(this, void 0, void 0, function () {
1495
864
  var isModal;
1496
- return __generator(this, function (_a) {
865
+ return __generator$2(this, function (_a) {
1497
866
  switch (_a.label) {
1498
867
  case 0:
1499
868
  isModal = parseWidgetId(this.widgetId).isModal;
@@ -1523,9 +892,9 @@ var WidgetApiImpl = /** @class */ (function () {
1523
892
  };
1524
893
  /** {@inheritDoc WidgetApi.closeModal} */
1525
894
  WidgetApiImpl.prototype.closeModal = function (data) {
1526
- return __awaiter(this, void 0, void 0, function () {
895
+ return __awaiter$2(this, void 0, void 0, function () {
1527
896
  var isModal;
1528
- return __generator(this, function (_a) {
897
+ return __generator$2(this, function (_a) {
1529
898
  switch (_a.label) {
1530
899
  case 0:
1531
900
  isModal = parseWidgetId(this.widgetId).isModal;
@@ -1542,8 +911,8 @@ var WidgetApiImpl = /** @class */ (function () {
1542
911
  };
1543
912
  /** {@inheritdoc WidgetApi.navigateTo} */
1544
913
  WidgetApiImpl.prototype.navigateTo = function (uri) {
1545
- return __awaiter(this, void 0, void 0, function () {
1546
- return __generator(this, function (_a) {
914
+ return __awaiter$2(this, void 0, void 0, function () {
915
+ return __generator$2(this, function (_a) {
1547
916
  switch (_a.label) {
1548
917
  case 0: return [4 /*yield*/, this.matrixWidgetApi.navigateTo(uri)];
1549
918
  case 1:
@@ -1555,8 +924,8 @@ var WidgetApiImpl = /** @class */ (function () {
1555
924
  };
1556
925
  /** {@inheritdoc WidgetApi.requestOpenIDConnectToken} */
1557
926
  WidgetApiImpl.prototype.requestOpenIDConnectToken = function () {
1558
- return __awaiter(this, void 0, void 0, function () {
1559
- return __generator(this, function (_b) {
927
+ return __awaiter$2(this, void 0, void 0, function () {
928
+ return __generator$2(this, function (_b) {
1560
929
  switch (_b.label) {
1561
930
  case 0:
1562
931
  if (!this.outstandingOpenIDConnectTokenRequest) return [3 /*break*/, 4];
@@ -1586,9 +955,9 @@ var WidgetApiImpl = /** @class */ (function () {
1586
955
  };
1587
956
  WidgetApiImpl.prototype.requestOpenIDConnectTokenInternal = function () {
1588
957
  var _a;
1589
- return __awaiter(this, void 0, void 0, function () {
958
+ return __awaiter$2(this, void 0, void 0, function () {
1590
959
  var leywayMilliseconds, openIdToken, err_2;
1591
- return __generator(this, function (_b) {
960
+ return __generator$2(this, function (_b) {
1592
961
  switch (_b.label) {
1593
962
  case 0:
1594
963
  leywayMilliseconds = 30 * 1000;
@@ -1615,45 +984,676 @@ var WidgetApiImpl = /** @class */ (function () {
1615
984
  }
1616
985
  });
1617
986
  });
1618
- };
1619
- /** {@inheritdoc WidgetApi.observeTurnServers} */
1620
- WidgetApiImpl.prototype.observeTurnServers = function () {
1621
- return from(this.matrixWidgetApi.getTurnServers()).pipe(
1622
- // For some reason a different naming was chosen for the API, but
1623
- // we already convert them to the right type for WebRTC consumers.
1624
- map(function (_a) {
1625
- var uris = _a.uris, username = _a.username, password = _a.password;
1626
- return ({
1627
- urls: uris,
1628
- username: username,
1629
- credential: password,
1630
- });
1631
- }));
1632
- };
1633
- /** {@inheritdoc WidgetApi.searchUserDirectory} */
1634
- WidgetApiImpl.prototype.searchUserDirectory = function (searchTerm, options) {
1635
- return __awaiter(this, void 0, void 0, function () {
1636
- var results;
1637
- return __generator(this, function (_a) {
1638
- switch (_a.label) {
1639
- case 0: return [4 /*yield*/, this.matrixWidgetApi.searchUserDirectory(searchTerm, options === null || options === void 0 ? void 0 : options.limit)];
1640
- case 1:
1641
- results = (_a.sent()).results;
1642
- return [2 /*return*/, {
1643
- results: results.map(function (_a) {
1644
- var user_id = _a.user_id, display_name = _a.display_name, avatar_url = _a.avatar_url;
1645
- return ({
1646
- userId: user_id,
1647
- displayName: display_name,
1648
- avatarUrl: avatar_url,
1649
- });
1650
- }),
1651
- }];
1652
- }
1653
- });
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
+ return WidgetApiImpl;
1026
+ }());
1027
+
1028
+ /*
1029
+ * Copyright 2022 Nordeck IT + Consulting GmbH
1030
+ *
1031
+ * Licensed under the Apache License, Version 2.0 (the "License");
1032
+ * you may not use this file except in compliance with the License.
1033
+ * You may obtain a copy of the License at
1034
+ *
1035
+ * http://www.apache.org/licenses/LICENSE-2.0
1036
+ *
1037
+ * Unless required by applicable law or agreed to in writing, software
1038
+ * distributed under the License is distributed on an "AS IS" BASIS,
1039
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1040
+ * See the License for the specific language governing permissions and
1041
+ * limitations under the License.
1042
+ */
1043
+ /**
1044
+ * Generate a list of capabilities to access the timeline of other rooms.
1045
+ * If enabled, all previously or future capabilities will apply to _all_
1046
+ * selected rooms.
1047
+ * If `Symbols.AnyRoom` is passed, this is expanded to all joined
1048
+ * or invited rooms the client is able to see, current and future.
1049
+ *
1050
+ * @param roomIds - a list of room ids or `@link Symbols.AnyRoom`.
1051
+ * @returns the generated capabilities.
1052
+ */
1053
+ function generateRoomTimelineCapabilities(roomIds) {
1054
+ if (roomIds === Symbols.AnyRoom) {
1055
+ return ['org.matrix.msc2762.timeline:*'];
1056
+ }
1057
+ if (Array.isArray(roomIds)) {
1058
+ return roomIds.map(function (id) { return "org.matrix.msc2762.timeline:".concat(id); });
1059
+ }
1060
+ return [];
1061
+ }
1062
+
1063
+ /*
1064
+ * Copyright 2022 Nordeck IT + Consulting GmbH
1065
+ *
1066
+ * Licensed under the Apache License, Version 2.0 (the "License");
1067
+ * you may not use this file except in compliance with the License.
1068
+ * You may obtain a copy of the License at
1069
+ *
1070
+ * http://www.apache.org/licenses/LICENSE-2.0
1071
+ *
1072
+ * Unless required by applicable law or agreed to in writing, software
1073
+ * distributed under the License is distributed on an "AS IS" BASIS,
1074
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1075
+ * See the License for the specific language governing permissions and
1076
+ * limitations under the License.
1077
+ */
1078
+ /**
1079
+ * Generate a unique displayname of a user that is consistent across Matrix clients.
1080
+ *
1081
+ * @remarks The algorithm is based on https://spec.matrix.org/v1.1/client-server-api/#calculating-the-display-name-for-a-user
1082
+ *
1083
+ * @param member - the member to generate a name for.
1084
+ * @param allRoomMembers - a list of all members of the same room.
1085
+ * @returns the displayname that is unique in given the set of all room members.
1086
+ */
1087
+ function getRoomMemberDisplayName(member, allRoomMembers) {
1088
+ if (allRoomMembers === void 0) { allRoomMembers = []; }
1089
+ // If the m.room.member state event has no displayname field, or if that field
1090
+ // has a null value, use the raw user id as the display name.
1091
+ if (typeof member.content.displayname !== 'string') {
1092
+ return member.state_key;
1093
+ }
1094
+ // If the m.room.member event has a displayname which is unique among members of
1095
+ // the room with membership: join or membership: invite, ...
1096
+ var hasDuplicateDisplayName = allRoomMembers.some(function (m) {
1097
+ // same room
1098
+ return m.room_id === member.room_id &&
1099
+ // not the own event
1100
+ m.state_key !== member.state_key &&
1101
+ // only join or invite state
1102
+ ['join', 'invite'].includes(m.content.membership) &&
1103
+ // same displayname
1104
+ m.content.displayname === member.content.displayname;
1105
+ });
1106
+ if (!hasDuplicateDisplayName) {
1107
+ // ... use the given displayname as the user-visible display name.
1108
+ return member.content.displayname;
1109
+ }
1110
+ else {
1111
+ // The m.room.member event has a non-unique displayname. This should be
1112
+ // disambiguated using the user id, for example “display name (@id:homeserver.org)”.
1113
+ return "".concat(member.content.displayname, " (").concat(member.state_key, ")");
1114
+ }
1115
+ }
1116
+
1117
+ /*
1118
+ * Copyright 2022 Nordeck IT + Consulting GmbH
1119
+ *
1120
+ * Licensed under the Apache License, Version 2.0 (the "License");
1121
+ * you may not use this file except in compliance with the License.
1122
+ * You may obtain a copy of the License at
1123
+ *
1124
+ * http://www.apache.org/licenses/LICENSE-2.0
1125
+ *
1126
+ * Unless required by applicable law or agreed to in writing, software
1127
+ * distributed under the License is distributed on an "AS IS" BASIS,
1128
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1129
+ * See the License for the specific language governing permissions and
1130
+ * limitations under the License.
1131
+ */
1132
+ /**
1133
+ * Check if the given event is a {@link StateEvent}.
1134
+ *
1135
+ * @param event - An event that is either a {@link RoomEvent} or a {@link StateEvent}.
1136
+ * @returns True, if the event is a {@link StateEvent}.
1137
+ */
1138
+ function isStateEvent(event) {
1139
+ return 'state_key' in event && typeof event.state_key === 'string';
1140
+ }
1141
+ /**
1142
+ * Check if the given event is a {@link RoomEvent}.
1143
+ *
1144
+ * @param event - An event that is either a {@link RoomEvent} or a {@link StateEvent}.
1145
+ * @returns True, if the event is a {@link RoomEvent}.
1146
+ */
1147
+ function isRoomEvent(event) {
1148
+ return !('state_key' in event);
1149
+ }
1150
+
1151
+ /*
1152
+ * Copyright 2022 Nordeck IT + Consulting GmbH
1153
+ *
1154
+ * Licensed under the Apache License, Version 2.0 (the "License");
1155
+ * you may not use this file except in compliance with the License.
1156
+ * You may obtain a copy of the License at
1157
+ *
1158
+ * http://www.apache.org/licenses/LICENSE-2.0
1159
+ *
1160
+ * Unless required by applicable law or agreed to in writing, software
1161
+ * distributed under the License is distributed on an "AS IS" BASIS,
1162
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1163
+ * See the License for the specific language governing permissions and
1164
+ * limitations under the License.
1165
+ */
1166
+ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1167
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1168
+ return new (P || (P = Promise))(function (resolve, reject) {
1169
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1170
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1171
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1172
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
1173
+ });
1174
+ };
1175
+ var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) {
1176
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
1177
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
1178
+ function verb(n) { return function (v) { return step([n, v]); }; }
1179
+ function step(op) {
1180
+ if (f) throw new TypeError("Generator is already executing.");
1181
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
1182
+ 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;
1183
+ if (y = 0, t) op = [op[0] & 2, t.value];
1184
+ switch (op[0]) {
1185
+ case 0: case 1: t = op; break;
1186
+ case 4: _.label++; return { value: op[1], done: false };
1187
+ case 5: _.label++; y = op[1]; op = [0]; continue;
1188
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
1189
+ default:
1190
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
1191
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
1192
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
1193
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
1194
+ if (t[2]) _.ops.pop();
1195
+ _.trys.pop(); continue;
1196
+ }
1197
+ op = body.call(thisArg, _);
1198
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
1199
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1200
+ }
1201
+ };
1202
+ /**
1203
+ * The capability that needs to be requested in order to navigate to another room.
1204
+ */
1205
+ var WIDGET_CAPABILITY_NAVIGATE = 'org.matrix.msc2931.navigate';
1206
+ /**
1207
+ * Navigate the client to another matrix room.
1208
+ *
1209
+ * @remarks This requires the {@link WIDGET_CAPABILITY_NAVIGATE} capability.
1210
+ *
1211
+ * @param widgetApi - the {@link WidgetApi} instance.
1212
+ * @param roomId - the room ID.
1213
+ * @param opts - {@link NavigateToRoomOptions}
1214
+ */
1215
+ function navigateToRoom(widgetApi, roomId, opts) {
1216
+ if (opts === void 0) { opts = {}; }
1217
+ return __awaiter$1(this, void 0, void 0, function () {
1218
+ var _a, via, params, url;
1219
+ return __generator$1(this, function (_b) {
1220
+ switch (_b.label) {
1221
+ case 0:
1222
+ _a = opts.via, via = _a === void 0 ? [] : _a;
1223
+ params = stringify({ via: via }, { addQueryPrefix: true, arrayFormat: 'repeat' });
1224
+ url = "https://matrix.to/#/".concat(encodeURIComponent(roomId)).concat(params);
1225
+ return [4 /*yield*/, widgetApi.navigateTo(url)];
1226
+ case 1:
1227
+ _b.sent();
1228
+ return [2 /*return*/];
1229
+ }
1230
+ });
1231
+ });
1232
+ }
1233
+
1234
+ /*
1235
+ * Copyright 2022 Nordeck IT + Consulting GmbH
1236
+ *
1237
+ * Licensed under the Apache License, Version 2.0 (the "License");
1238
+ * you may not use this file except in compliance with the License.
1239
+ * You may obtain a copy of the License at
1240
+ *
1241
+ * http://www.apache.org/licenses/LICENSE-2.0
1242
+ *
1243
+ * Unless required by applicable law or agreed to in writing, software
1244
+ * distributed under the License is distributed on an "AS IS" BASIS,
1245
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1246
+ * See the License for the specific language governing permissions and
1247
+ * limitations under the License.
1248
+ */
1249
+ /**
1250
+ * Compares two room events by their origin server timestamp.
1251
+ *
1252
+ * @param a - A room event
1253
+ * @param b - A room event
1254
+ * @returns Either zero if the timestamp is equal, \>0 if a is newer, or \<0 if
1255
+ * b is newer.
1256
+ */
1257
+ function compareOriginServerTS(a, b) {
1258
+ return a.origin_server_ts - b.origin_server_ts;
1259
+ }
1260
+
1261
+ /*
1262
+ * Copyright 2022 Nordeck IT + Consulting GmbH
1263
+ *
1264
+ * Licensed under the Apache License, Version 2.0 (the "License");
1265
+ * you may not use this file except in compliance with the License.
1266
+ * You may obtain a copy of the License at
1267
+ *
1268
+ * http://www.apache.org/licenses/LICENSE-2.0
1269
+ *
1270
+ * Unless required by applicable law or agreed to in writing, software
1271
+ * distributed under the License is distributed on an "AS IS" BASIS,
1272
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1273
+ * See the License for the specific language governing permissions and
1274
+ * limitations under the License.
1275
+ */
1276
+ /**
1277
+ * The name of the power levels state event.
1278
+ */
1279
+ var STATE_EVENT_POWER_LEVELS = 'm.room.power_levels';
1280
+ function isNumberOrUndefined(value) {
1281
+ return value === undefined || typeof value === 'number';
1282
+ }
1283
+ function isStringToNumberMapOrUndefined(value) {
1284
+ return (value === undefined ||
1285
+ (value !== null &&
1286
+ typeof value === 'object' &&
1287
+ Object.entries(value).every(function (_a) {
1288
+ var k = _a[0], v = _a[1];
1289
+ return typeof k === 'string' && typeof v === 'number';
1290
+ })));
1291
+ }
1292
+ /**
1293
+ * Validates that `event` is has a valid structure for a
1294
+ * {@link PowerLevelsStateEvent}.
1295
+ * @param event - The event to validate.
1296
+ * @returns True, if the event is valid.
1297
+ */
1298
+ function isValidPowerLevelStateEvent(event) {
1299
+ if (event.type !== STATE_EVENT_POWER_LEVELS ||
1300
+ typeof event.content !== 'object') {
1301
+ return false;
1302
+ }
1303
+ var content = event.content;
1304
+ if (!isStringToNumberMapOrUndefined(content.events)) {
1305
+ return false;
1306
+ }
1307
+ if (!isNumberOrUndefined(content.state_default)) {
1308
+ return false;
1309
+ }
1310
+ if (!isNumberOrUndefined(content.events_default)) {
1311
+ return false;
1312
+ }
1313
+ if (!isStringToNumberMapOrUndefined(content.users)) {
1314
+ return false;
1315
+ }
1316
+ if (!isNumberOrUndefined(content.users_default)) {
1317
+ return false;
1318
+ }
1319
+ if (!isNumberOrUndefined(content.ban)) {
1320
+ return false;
1321
+ }
1322
+ if (!isNumberOrUndefined(content.invite)) {
1323
+ return false;
1324
+ }
1325
+ if (!isNumberOrUndefined(content.kick)) {
1326
+ return false;
1327
+ }
1328
+ if (!isNumberOrUndefined(content.redact)) {
1329
+ return false;
1330
+ }
1331
+ return true;
1332
+ }
1333
+ /**
1334
+ * Check if a user has the power to send a specific room event.
1335
+ *
1336
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
1337
+ * @param userId - the id of the user
1338
+ * @param eventType - the type of room event
1339
+ * @returns if true, the user has the power
1340
+ */
1341
+ function hasRoomEventPower(powerLevelStateEvent, userId, eventType) {
1342
+ if (!powerLevelStateEvent) {
1343
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L36-L43
1344
+ return true;
1345
+ }
1346
+ var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
1347
+ var eventLevel = calculateRoomEventPowerLevel(powerLevelStateEvent, eventType);
1348
+ return userLevel >= eventLevel;
1349
+ }
1350
+ /**
1351
+ * Check if a user has the power to send a specific state event.
1352
+ *
1353
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
1354
+ * @param userId - the id of the user
1355
+ * @param eventType - the type of state event
1356
+ * @returns if true, the user has the power
1357
+ */
1358
+ function hasStateEventPower(powerLevelStateEvent, userId, eventType) {
1359
+ if (!powerLevelStateEvent) {
1360
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L36-L43
1361
+ return true;
1362
+ }
1363
+ var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
1364
+ var eventLevel = calculateStateEventPowerLevel(powerLevelStateEvent, eventType);
1365
+ return userLevel >= eventLevel;
1366
+ }
1367
+ /**
1368
+ * Check if a user has the power to perform a specific action.
1369
+ *
1370
+ * Supported actions:
1371
+ * * invite: Invite a new user into the room
1372
+ * * kick: Kick a user from the room
1373
+ * * ban: Ban a user from the room
1374
+ * * redact: Redact a message from another user
1375
+ *
1376
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
1377
+ * @param userId - the id of the user
1378
+ * @param action - the action
1379
+ * @returns if true, the user has the power
1380
+ */
1381
+ function hasActionPower(powerLevelStateEvent, userId, action) {
1382
+ if (!powerLevelStateEvent) {
1383
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L36-L43
1384
+ return true;
1385
+ }
1386
+ var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
1387
+ var eventLevel = calculateActionPowerLevel(powerLevelStateEvent, action);
1388
+ return userLevel >= eventLevel;
1389
+ }
1390
+ /**
1391
+ * Calculate the power level of the user based on a `m.room.power_levels` event.
1392
+ *
1393
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event.
1394
+ * @param userId - the ID of the user.
1395
+ * @returns the power level of the user.
1396
+ */
1397
+ function calculateUserPowerLevel(powerLevelStateEvent, userId) {
1398
+ var _a, _b, _c;
1399
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L8-L12
1400
+ 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);
1401
+ }
1402
+ /**
1403
+ * Calculate the power level that a user needs send a specific room event.
1404
+ *
1405
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
1406
+ * @param eventType - the type of room event
1407
+ * @returns the power level that is needed
1408
+ */
1409
+ function calculateRoomEventPowerLevel(powerLevelStateEvent, eventType) {
1410
+ var _a, _b, _c;
1411
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L14-L19
1412
+ 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);
1413
+ }
1414
+ /**
1415
+ * Calculate the power level that a user needs send a specific state event.
1416
+ *
1417
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
1418
+ * @param eventType - the type of state event
1419
+ * @returns the power level that is needed
1420
+ */
1421
+ function calculateStateEventPowerLevel(powerLevelStateEvent, eventType) {
1422
+ var _a, _b, _c;
1423
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L14-L19
1424
+ 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);
1425
+ }
1426
+ /**
1427
+ * Calculate the power level that a user needs to perform an action.
1428
+ *
1429
+ * Supported actions:
1430
+ * * invite: Invite a new user into the room
1431
+ * * kick: Kick a user from the room
1432
+ * * ban: Ban a user from the room
1433
+ * * redact: Redact a message from another user
1434
+ *
1435
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
1436
+ * @param action - the action
1437
+ * @returns the power level that is needed
1438
+ */
1439
+ function calculateActionPowerLevel(powerLevelStateEvent, action) {
1440
+ var _a, _b;
1441
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L27-L32
1442
+ if (action === 'invite') {
1443
+ return (_a = powerLevelStateEvent === null || powerLevelStateEvent === void 0 ? void 0 : powerLevelStateEvent[action]) !== null && _a !== void 0 ? _a : 0;
1444
+ }
1445
+ return (_b = powerLevelStateEvent === null || powerLevelStateEvent === void 0 ? void 0 : powerLevelStateEvent[action]) !== null && _b !== void 0 ? _b : 50;
1446
+ }
1447
+
1448
+ /*
1449
+ * Copyright 2022 Nordeck IT + Consulting GmbH
1450
+ *
1451
+ * Licensed under the Apache License, Version 2.0 (the "License");
1452
+ * you may not use this file except in compliance with the License.
1453
+ * You may obtain a copy of the License at
1454
+ *
1455
+ * http://www.apache.org/licenses/LICENSE-2.0
1456
+ *
1457
+ * Unless required by applicable law or agreed to in writing, software
1458
+ * distributed under the License is distributed on an "AS IS" BASIS,
1459
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1460
+ * See the License for the specific language governing permissions and
1461
+ * limitations under the License.
1462
+ */
1463
+ var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1464
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1465
+ return new (P || (P = Promise))(function (resolve, reject) {
1466
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1467
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1468
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1469
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
1470
+ });
1471
+ };
1472
+ var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
1473
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
1474
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
1475
+ function verb(n) { return function (v) { return step([n, v]); }; }
1476
+ function step(op) {
1477
+ if (f) throw new TypeError("Generator is already executing.");
1478
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
1479
+ 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;
1480
+ if (y = 0, t) op = [op[0] & 2, t.value];
1481
+ switch (op[0]) {
1482
+ case 0: case 1: t = op; break;
1483
+ case 4: _.label++; return { value: op[1], done: false };
1484
+ case 5: _.label++; y = op[1]; op = [0]; continue;
1485
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
1486
+ default:
1487
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
1488
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
1489
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
1490
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
1491
+ if (t[2]) _.ops.pop();
1492
+ _.trys.pop(); continue;
1493
+ }
1494
+ op = body.call(thisArg, _);
1495
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
1496
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1497
+ }
1498
+ };
1499
+ /**
1500
+ * The name of the redaction room event.
1501
+ */
1502
+ var ROOM_EVENT_REDACTION = 'm.room.redaction';
1503
+ /**
1504
+ * Check whether the format of a redaction event is valid.
1505
+ * @param event - The event to check.
1506
+ * @returns True if the event format is valid, otherwise false.
1507
+ */
1508
+ function isValidRedactionEvent(event) {
1509
+ if (event.type === ROOM_EVENT_REDACTION &&
1510
+ typeof event.redacts === 'string') {
1511
+ return true;
1512
+ }
1513
+ return false;
1514
+ }
1515
+ /**
1516
+ * Redacts an event in the current room.
1517
+ * @param widgetApi - An instance of the widget API.
1518
+ * @param eventId - The id of the event to redact.
1519
+ * @returns The redaction event that was send to the room.
1520
+ */
1521
+ function redactEvent(widgetApi, eventId) {
1522
+ return __awaiter(this, void 0, void 0, function () {
1523
+ var result;
1524
+ return __generator(this, function (_a) {
1525
+ switch (_a.label) {
1526
+ case 0: return [4 /*yield*/, widgetApi.sendRoomEvent(ROOM_EVENT_REDACTION, { redacts: eventId })];
1527
+ case 1:
1528
+ result = _a.sent();
1529
+ // The redaction event is special and needs to be casted, as the widget
1530
+ // toolkit assumes that the content of an event is returned as we send it.
1531
+ // However for redactions the content is copied directly into the event to
1532
+ // make it available without decrypting the content.
1533
+ return [2 /*return*/, result];
1534
+ }
1654
1535
  });
1655
- };
1656
- return WidgetApiImpl;
1657
- }());
1536
+ });
1537
+ }
1538
+ /**
1539
+ * Observes redaction events in the current room.
1540
+ * @param widgetApi - An instance of the widget API.
1541
+ * @returns An observable of validated redaction events.
1542
+ */
1543
+ function observeRedactionEvents(widgetApi) {
1544
+ return widgetApi
1545
+ .observeRoomEvents(ROOM_EVENT_REDACTION)
1546
+ .pipe(filter(isValidRedactionEvent));
1547
+ }
1548
+
1549
+ /*
1550
+ * Copyright 2022 Nordeck IT + Consulting GmbH
1551
+ *
1552
+ * Licensed under the Apache License, Version 2.0 (the "License");
1553
+ * you may not use this file except in compliance with the License.
1554
+ * You may obtain a copy of the License at
1555
+ *
1556
+ * http://www.apache.org/licenses/LICENSE-2.0
1557
+ *
1558
+ * Unless required by applicable law or agreed to in writing, software
1559
+ * distributed under the License is distributed on an "AS IS" BASIS,
1560
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1561
+ * See the License for the specific language governing permissions and
1562
+ * limitations under the License.
1563
+ */
1564
+ /**
1565
+ * Get the original event id, or the event id of the current event if it
1566
+ * doesn't relates to another event.
1567
+ * @param event - The room event.
1568
+ * @returns The event id of the original event, or the current event id.
1569
+ */
1570
+ function getOriginalEventId(event) {
1571
+ var _a, _b, _c;
1572
+ var newContentRelatesTo = event.content;
1573
+ if (((_a = newContentRelatesTo['m.relates_to']) === null || _a === void 0 ? void 0 : _a.rel_type) === 'm.replace') {
1574
+ return (_c = (_b = newContentRelatesTo['m.relates_to']) === null || _b === void 0 ? void 0 : _b.event_id) !== null && _c !== void 0 ? _c : event.event_id;
1575
+ }
1576
+ return event.event_id;
1577
+ }
1578
+ /**
1579
+ * Get the content of the event, independent from whether it contains the
1580
+ * content directly or contains a "m.new_content" key.
1581
+ * @param event - The room event.
1582
+ * @returns Only the content of the room event.
1583
+ */
1584
+ function getContent(event) {
1585
+ var _a;
1586
+ var newContentRelatesTo = event.content;
1587
+ return (_a = newContentRelatesTo['m.new_content']) !== null && _a !== void 0 ? _a : event.content;
1588
+ }
1589
+ /**
1590
+ * Validates that `event` has a valid structure for a
1591
+ * {@link EventWithRelatesTo}.
1592
+ * @param event - The event to validate.
1593
+ * @returns True, if the event is valid.
1594
+ */
1595
+ function isValidEventWithRelatesTo(event) {
1596
+ if (!event.content || typeof event.content !== 'object') {
1597
+ return false;
1598
+ }
1599
+ var relatedEvent = event;
1600
+ if (!relatedEvent.content['m.relates_to'] ||
1601
+ typeof relatedEvent.content['m.relates_to'] !== 'object') {
1602
+ return false;
1603
+ }
1604
+ if (typeof relatedEvent.content['m.relates_to'].rel_type !== 'string' ||
1605
+ typeof relatedEvent.content['m.relates_to'].event_id !== 'string') {
1606
+ return false;
1607
+ }
1608
+ return true;
1609
+ }
1610
+
1611
+ /*
1612
+ * Copyright 2022 Nordeck IT + Consulting GmbH
1613
+ *
1614
+ * Licensed under the Apache License, Version 2.0 (the "License");
1615
+ * you may not use this file except in compliance with the License.
1616
+ * You may obtain a copy of the License at
1617
+ *
1618
+ * http://www.apache.org/licenses/LICENSE-2.0
1619
+ *
1620
+ * Unless required by applicable law or agreed to in writing, software
1621
+ * distributed under the License is distributed on an "AS IS" BASIS,
1622
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1623
+ * See the License for the specific language governing permissions and
1624
+ * limitations under the License.
1625
+ */
1626
+ /**
1627
+ * The name of the room member state event.
1628
+ */
1629
+ var STATE_EVENT_ROOM_MEMBER = 'm.room.member';
1630
+ function isStringUndefinedOrNull(value) {
1631
+ return value === undefined || value === null || typeof value === 'string';
1632
+ }
1633
+ /**
1634
+ * Validates that `event` is has a valid structure for a
1635
+ * {@link RoomMemberStateEventContent}.
1636
+ * @param event - The event to validate.
1637
+ * @returns True, if the event is valid.
1638
+ */
1639
+ function isValidRoomMemberStateEvent(event) {
1640
+ if (event.type !== STATE_EVENT_ROOM_MEMBER ||
1641
+ typeof event.content !== 'object') {
1642
+ return false;
1643
+ }
1644
+ var content = event.content;
1645
+ if (typeof content.membership !== 'string') {
1646
+ return false;
1647
+ }
1648
+ if (!isStringUndefinedOrNull(content.displayname)) {
1649
+ return false;
1650
+ }
1651
+ // the avatar_url shouldn't be null, but some implementations
1652
+ // set it as a valid value
1653
+ if (!isStringUndefinedOrNull(content.avatar_url)) {
1654
+ return false;
1655
+ }
1656
+ return true;
1657
+ }
1658
1658
 
1659
1659
  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 };