@matrix-widget-toolkit/api 1.0.1

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.
@@ -0,0 +1,1620 @@
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, share } from 'rxjs';
4
+
5
+ /*
6
+ * Copyright 2022 Nordeck IT + Consulting GmbH
7
+ *
8
+ * Licensed under the Apache License, Version 2.0 (the "License");
9
+ * you may not use this file except in compliance with the License.
10
+ * You may obtain a copy of the License at
11
+ *
12
+ * http://www.apache.org/licenses/LICENSE-2.0
13
+ *
14
+ * Unless required by applicable law or agreed to in writing, software
15
+ * distributed under the License is distributed on an "AS IS" BASIS,
16
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ * See the License for the specific language governing permissions and
18
+ * limitations under the License.
19
+ */
20
+ /**
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.
29
+ */
30
+ function generateRoomTimelineCapabilities(roomIds) {
31
+ if (roomIds === Symbols.AnyRoom) {
32
+ return ['org.matrix.msc2762.timeline:*'];
33
+ }
34
+ if (Array.isArray(roomIds)) {
35
+ return roomIds.map(function (id) { return "org.matrix.msc2762.timeline:".concat(id); });
36
+ }
37
+ return [];
38
+ }
39
+
40
+ /*
41
+ * Copyright 2022 Nordeck IT + Consulting GmbH
42
+ *
43
+ * Licensed under the Apache License, Version 2.0 (the "License");
44
+ * you may not use this file except in compliance with the License.
45
+ * You may obtain a copy of the License at
46
+ *
47
+ * http://www.apache.org/licenses/LICENSE-2.0
48
+ *
49
+ * Unless required by applicable law or agreed to in writing, software
50
+ * distributed under the License is distributed on an "AS IS" BASIS,
51
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
52
+ * See the License for the specific language governing permissions and
53
+ * limitations under the License.
54
+ */
55
+ /**
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.
63
+ */
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
+ }
92
+ }
93
+
94
+ /*
95
+ * Copyright 2022 Nordeck IT + Consulting GmbH
96
+ *
97
+ * Licensed under the Apache License, Version 2.0 (the "License");
98
+ * you may not use this file except in compliance with the License.
99
+ * You may obtain a copy of the License at
100
+ *
101
+ * http://www.apache.org/licenses/LICENSE-2.0
102
+ *
103
+ * Unless required by applicable law or agreed to in writing, software
104
+ * distributed under the License is distributed on an "AS IS" BASIS,
105
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
106
+ * See the License for the specific language governing permissions and
107
+ * limitations under the License.
108
+ */
109
+ /**
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}.
114
+ */
115
+ function isStateEvent(event) {
116
+ return 'state_key' in event && typeof event.state_key === 'string';
117
+ }
118
+ /**
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}.
123
+ */
124
+ function isRoomEvent(event) {
125
+ return !('state_key' in event);
126
+ }
127
+
128
+ /*
129
+ * Copyright 2022 Nordeck IT + Consulting GmbH
130
+ *
131
+ * Licensed under the Apache License, Version 2.0 (the "License");
132
+ * you may not use this file except in compliance with the License.
133
+ * You may obtain a copy of the License at
134
+ *
135
+ * http://www.apache.org/licenses/LICENSE-2.0
136
+ *
137
+ * Unless required by applicable law or agreed to in writing, software
138
+ * distributed under the License is distributed on an "AS IS" BASIS,
139
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
140
+ * See the License for the specific language governing permissions and
141
+ * limitations under the License.
142
+ */
143
+ var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
144
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
145
+ return new (P || (P = Promise))(function (resolve, reject) {
146
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
147
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
148
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
149
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
150
+ });
151
+ };
152
+ var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) {
153
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
154
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
155
+ function verb(n) { return function (v) { return step([n, v]); }; }
156
+ function step(op) {
157
+ if (f) throw new TypeError("Generator is already executing.");
158
+ while (_) try {
159
+ 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
+ if (y = 0, t) op = [op[0] & 2, t.value];
161
+ switch (op[0]) {
162
+ case 0: case 1: t = op; break;
163
+ case 4: _.label++; return { value: op[1], done: false };
164
+ case 5: _.label++; y = op[1]; op = [0]; continue;
165
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
166
+ default:
167
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
168
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
169
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
170
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
171
+ if (t[2]) _.ops.pop();
172
+ _.trys.pop(); continue;
173
+ }
174
+ op = body.call(thisArg, _);
175
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
176
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
177
+ }
178
+ };
179
+ /**
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.
187
+ *
188
+ * @param widgetApi - the {@link WidgetApi} instance.
189
+ * @param roomId - the room ID.
190
+ * @param opts - {@link NavigateToRoomOptions}
191
+ */
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
+ });
209
+ }
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
+ /**
227
+ * Compares two room events by their origin server timestamp.
228
+ *
229
+ * @param a - A room event
230
+ * @param b - A room event
231
+ * @returns Either zero if the timestamp is equal, \>0 if a is newer, or \<0 if
232
+ * b is newer.
233
+ */
234
+ function compareOriginServerTS(a, b) {
235
+ return a.origin_server_ts - b.origin_server_ts;
236
+ }
237
+
238
+ /*
239
+ * Copyright 2022 Nordeck IT + Consulting GmbH
240
+ *
241
+ * Licensed under the Apache License, Version 2.0 (the "License");
242
+ * you may not use this file except in compliance with the License.
243
+ * You may obtain a copy of the License at
244
+ *
245
+ * http://www.apache.org/licenses/LICENSE-2.0
246
+ *
247
+ * Unless required by applicable law or agreed to in writing, software
248
+ * distributed under the License is distributed on an "AS IS" BASIS,
249
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
250
+ * See the License for the specific language governing permissions and
251
+ * limitations under the License.
252
+ */
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';
259
+ }
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
+ })));
268
+ }
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;
309
+ }
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;
326
+ }
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;
339
+ }
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
361
+ return true;
362
+ }
363
+ var userLevel = calculateUserPowerLevel(powerLevelStateEvent, userId);
364
+ var eventLevel = calculateActionPowerLevel(powerLevelStateEvent, action);
365
+ return userLevel >= eventLevel;
366
+ }
367
+ /**
368
+ * Calculate the power level of the user based on a `m.room.power_levels` event.
369
+ *
370
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event.
371
+ * @param userId - the ID of the user.
372
+ * @returns the power level of the user.
373
+ */
374
+ function calculateUserPowerLevel(powerLevelStateEvent, userId) {
375
+ var _a, _b, _c;
376
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L8-L12
377
+ return ((_c = (_b = (userId ? (_a = powerLevelStateEvent.users) === null || _a === void 0 ? void 0 : _a[userId] : undefined)) !== null && _b !== void 0 ? _b : powerLevelStateEvent.users_default) !== null && _c !== void 0 ? _c : 0);
378
+ }
379
+ /**
380
+ * Calculate the power level that a user needs send a specific room event.
381
+ *
382
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
383
+ * @param eventType - the type of room event
384
+ * @returns the power level that is needed
385
+ */
386
+ function calculateRoomEventPowerLevel(powerLevelStateEvent, eventType) {
387
+ var _a, _b, _c;
388
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L14-L19
389
+ return ((_c = (_b = (_a = powerLevelStateEvent.events) === null || _a === void 0 ? void 0 : _a[eventType]) !== null && _b !== void 0 ? _b : powerLevelStateEvent.events_default) !== null && _c !== void 0 ? _c : 0);
390
+ }
391
+ /**
392
+ * Calculate the power level that a user needs send a specific state event.
393
+ *
394
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
395
+ * @param eventType - the type of state event
396
+ * @returns the power level that is needed
397
+ */
398
+ function calculateStateEventPowerLevel(powerLevelStateEvent, eventType) {
399
+ var _a, _b, _c;
400
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L14-L19
401
+ return ((_c = (_b = (_a = powerLevelStateEvent.events) === null || _a === void 0 ? void 0 : _a[eventType]) !== null && _b !== void 0 ? _b : powerLevelStateEvent.state_default) !== null && _c !== void 0 ? _c : 50);
402
+ }
403
+ /**
404
+ * Calculate the power level that a user needs to perform an action.
405
+ *
406
+ * Supported actions:
407
+ * * invite: Invite a new user into the room
408
+ * * kick: Kick a user from the room
409
+ * * ban: Ban a user from the room
410
+ * * redact: Redact a message from another user
411
+ *
412
+ * @param powerLevelStateEvent - the content of the `m.room.power_levels` event
413
+ * @param action - the action
414
+ * @returns the power level that is needed
415
+ */
416
+ function calculateActionPowerLevel(powerLevelStateEvent, action) {
417
+ var _a, _b;
418
+ // See https://github.com/matrix-org/matrix-spec/blob/203b9756f52adfc2a3b63d664f18cdbf9f8bf126/data/event-schemas/schema/m.room.power_levels.yaml#L27-L32
419
+ if (action === 'invite') {
420
+ return (_a = powerLevelStateEvent === null || powerLevelStateEvent === void 0 ? void 0 : powerLevelStateEvent[action]) !== null && _a !== void 0 ? _a : 0;
421
+ }
422
+ return (_b = powerLevelStateEvent === null || powerLevelStateEvent === void 0 ? void 0 : powerLevelStateEvent[action]) !== null && _b !== void 0 ? _b : 50;
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.
439
+ */
440
+ var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
441
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
442
+ return new (P || (P = Promise))(function (resolve, reject) {
443
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
444
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
445
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
446
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
447
+ });
448
+ };
449
+ var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) {
450
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
451
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
452
+ function verb(n) { return function (v) { return step([n, v]); }; }
453
+ function step(op) {
454
+ if (f) throw new TypeError("Generator is already executing.");
455
+ while (_) try {
456
+ 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
+ if (y = 0, t) op = [op[0] & 2, t.value];
458
+ switch (op[0]) {
459
+ case 0: case 1: t = op; break;
460
+ case 4: _.label++; return { value: op[1], done: false };
461
+ case 5: _.label++; y = op[1]; op = [0]; continue;
462
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
463
+ default:
464
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
465
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
466
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
467
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
468
+ if (t[2]) _.ops.pop();
469
+ _.trys.pop(); continue;
470
+ }
471
+ op = body.call(thisArg, _);
472
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
473
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
474
+ }
475
+ };
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;
552
+ }
553
+ return event.event_id;
554
+ }
555
+ /**
556
+ * Get the content of the event, independent from whether it contains the
557
+ * content directly or contains a "m.new_content" key.
558
+ * @param event - The room event.
559
+ * @returns Only the content of the room event.
560
+ */
561
+ function getContent(event) {
562
+ var _a;
563
+ var newContentRelatesTo = event.content;
564
+ return (_a = newContentRelatesTo['m.new_content']) !== null && _a !== void 0 ? _a : event.content;
565
+ }
566
+ /**
567
+ * Validates that `event` has a valid structure for a
568
+ * {@link EventWithRelatesTo}.
569
+ * @param event - The event to validate.
570
+ * @returns True, if the event is valid.
571
+ */
572
+ function isValidEventWithRelatesTo(event) {
573
+ if (!event.content || typeof event.content !== 'object') {
574
+ return false;
575
+ }
576
+ var relatedEvent = event;
577
+ if (!relatedEvent.content['m.relates_to'] ||
578
+ typeof relatedEvent.content['m.relates_to'] !== 'object') {
579
+ return false;
580
+ }
581
+ if (typeof relatedEvent.content['m.relates_to'].rel_type !== 'string' ||
582
+ typeof relatedEvent.content['m.relates_to'].event_id !== 'string') {
583
+ return false;
584
+ }
585
+ return true;
586
+ }
587
+
588
+ /*
589
+ * Copyright 2022 Nordeck IT + Consulting GmbH
590
+ *
591
+ * Licensed under the Apache License, Version 2.0 (the "License");
592
+ * you may not use this file except in compliance with the License.
593
+ * You may obtain a copy of the License at
594
+ *
595
+ * http://www.apache.org/licenses/LICENSE-2.0
596
+ *
597
+ * Unless required by applicable law or agreed to in writing, software
598
+ * distributed under the License is distributed on an "AS IS" BASIS,
599
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
600
+ * See the License for the specific language governing permissions and
601
+ * limitations under the License.
602
+ */
603
+ /**
604
+ * The name of the room member state event.
605
+ */
606
+ var STATE_EVENT_ROOM_MEMBER = 'm.room.member';
607
+ function isStringOrUndefined(value) {
608
+ return value === undefined || typeof value === 'string';
609
+ }
610
+ /**
611
+ * Validates that `event` is has a valid structure for a
612
+ * {@link RoomMemberStateEventContent}.
613
+ * @param event - The event to validate.
614
+ * @returns True, if the event is valid.
615
+ */
616
+ function isValidRoomMemberStateEvent(event) {
617
+ if (event.type !== STATE_EVENT_ROOM_MEMBER ||
618
+ typeof event.content !== 'object') {
619
+ return false;
620
+ }
621
+ var content = event.content;
622
+ if (typeof content.membership !== 'string') {
623
+ return false;
624
+ }
625
+ if (!isStringOrUndefined(content.displayname)) {
626
+ return false;
627
+ }
628
+ if (!isStringOrUndefined(content.avatar_url)) {
629
+ return false;
630
+ }
631
+ return true;
632
+ }
633
+
634
+ /*
635
+ * Copyright 2022 Nordeck IT + Consulting GmbH
636
+ *
637
+ * Licensed under the Apache License, Version 2.0 (the "License");
638
+ * you may not use this file except in compliance with the License.
639
+ * You may obtain a copy of the License at
640
+ *
641
+ * http://www.apache.org/licenses/LICENSE-2.0
642
+ *
643
+ * Unless required by applicable law or agreed to in writing, software
644
+ * distributed under the License is distributed on an "AS IS" BASIS,
645
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
646
+ * See the License for the specific language governing permissions and
647
+ * limitations under the License.
648
+ */
649
+ var __assign$1 = (undefined && undefined.__assign) || function () {
650
+ __assign$1 = Object.assign || function(t) {
651
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
652
+ s = arguments[i];
653
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
654
+ t[p] = s[p];
655
+ }
656
+ return t;
657
+ };
658
+ return __assign$1.apply(this, arguments);
659
+ };
660
+ /**
661
+ * Extract the parameters used to initialize the widget API from the current
662
+ * `window.location`.
663
+ * @returns The parameters required for initializing the widget API.
664
+ */
665
+ function extractWidgetApiParameters() {
666
+ var query = parse(window.location.search, { ignoreQueryPrefix: true });
667
+ // If either parentUrl or widgetId is missing, we have no element context and
668
+ // want to inform the user that the widget only works inside of element.
669
+ if (typeof query.parentUrl !== 'string') {
670
+ throw Error('Missing parameter "parentUrl"');
671
+ }
672
+ var clientOrigin = new URL(query.parentUrl).origin;
673
+ if (typeof query.widgetId !== 'string') {
674
+ throw Error('Missing parameter "widgetId"');
675
+ }
676
+ var widgetId = query.widgetId;
677
+ return { widgetId: widgetId, clientOrigin: clientOrigin };
678
+ }
679
+ /**
680
+ * Extract the widget parameters from the current `window.location`.
681
+ * @returns The all unprocessed raw widget parameters.
682
+ */
683
+ function extractRawWidgetParameters() {
684
+ var hash = window.location.hash.substring(window.location.hash.indexOf('?') + 1);
685
+ var params = __assign$1(__assign$1({}, parse(window.location.search, { ignoreQueryPrefix: true })), parse(hash));
686
+ return Object.fromEntries(Object.entries(params).filter(
687
+ // For now only use simple values, don't allow them to be specified more
688
+ // than once.
689
+ function (e) { return typeof e[1] === 'string'; }));
690
+ }
691
+ /**
692
+ * Extract the widget parameters from the current `window.location`.
693
+ * @returns The widget parameters.
694
+ */
695
+ function extractWidgetParameters() {
696
+ var params = extractRawWidgetParameters();
697
+ // This is a hack to detect whether we are in a mobile client that supports widgets,
698
+ // but not the widget API. Mobile clients are not passing the parameters required for
699
+ // the widget API (like widgetId), but are passing the replaced placeholder values for
700
+ // the widget parameters.
701
+ var roomId = params['matrix_room_id'];
702
+ var isOpenedByClient = typeof roomId === 'string' && roomId !== '$matrix_room_id';
703
+ return {
704
+ userId: params['matrix_user_id'],
705
+ displayName: params['matrix_display_name'],
706
+ avatarUrl: params['matrix_avatar_url'],
707
+ roomId: roomId,
708
+ theme: params['theme'],
709
+ clientId: params['matrix_client_id'],
710
+ clientLanguage: params['matrix_client_language'],
711
+ isOpenedByClient: isOpenedByClient,
712
+ };
713
+ }
714
+ /**
715
+ * Parse a widget id into the individual fields.
716
+ * @param widgetId - The widget id to parse.
717
+ * @returns The individual fields encoded inside a widget id.
718
+ */
719
+ function parseWidgetId(widgetId) {
720
+ // TODO: Is this whole parsing still working for user widgets?
721
+ var mainWidgetId = decodeURIComponent(widgetId).replace(/^modal_/, '');
722
+ var roomId = mainWidgetId.indexOf('_')
723
+ ? decodeURIComponent(mainWidgetId.split('_')[0])
724
+ : undefined;
725
+ var creator = (mainWidgetId.match(/_/g) || []).length > 1
726
+ ? decodeURIComponent(mainWidgetId.split('_')[1])
727
+ : undefined;
728
+ var isModal = decodeURIComponent(widgetId).startsWith('modal_');
729
+ return {
730
+ mainWidgetId: mainWidgetId,
731
+ roomId: roomId,
732
+ creator: creator,
733
+ isModal: isModal,
734
+ };
735
+ }
736
+
737
+ /*
738
+ * Copyright 2022 Nordeck IT + Consulting GmbH
739
+ *
740
+ * Licensed under the Apache License, Version 2.0 (the "License");
741
+ * you may not use this file except in compliance with the License.
742
+ * You may obtain a copy of the License at
743
+ *
744
+ * http://www.apache.org/licenses/LICENSE-2.0
745
+ *
746
+ * Unless required by applicable law or agreed to in writing, software
747
+ * distributed under the License is distributed on an "AS IS" BASIS,
748
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
749
+ * See the License for the specific language governing permissions and
750
+ * limitations under the License.
751
+ */
752
+ var __assign = (undefined && undefined.__assign) || function () {
753
+ __assign = Object.assign || function(t) {
754
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
755
+ s = arguments[i];
756
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
757
+ t[p] = s[p];
758
+ }
759
+ return t;
760
+ };
761
+ return __assign.apply(this, arguments);
762
+ };
763
+ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
764
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
765
+ return new (P || (P = Promise))(function (resolve, reject) {
766
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
767
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
768
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
769
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
770
+ });
771
+ };
772
+ var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) {
773
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
774
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
775
+ function verb(n) { return function (v) { return step([n, v]); }; }
776
+ function step(op) {
777
+ if (f) throw new TypeError("Generator is already executing.");
778
+ while (_) try {
779
+ 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;
780
+ if (y = 0, t) op = [op[0] & 2, t.value];
781
+ switch (op[0]) {
782
+ case 0: case 1: t = op; break;
783
+ case 4: _.label++; return { value: op[1], done: false };
784
+ case 5: _.label++; y = op[1]; op = [0]; continue;
785
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
786
+ default:
787
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
788
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
789
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
790
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
791
+ if (t[2]) _.ops.pop();
792
+ _.trys.pop(); continue;
793
+ }
794
+ op = body.call(thisArg, _);
795
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
796
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
797
+ }
798
+ };
799
+ var __rest = (undefined && undefined.__rest) || function (s, e) {
800
+ var t = {};
801
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
802
+ t[p] = s[p];
803
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
804
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
805
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
806
+ t[p[i]] = s[p[i]];
807
+ }
808
+ return t;
809
+ };
810
+ /**
811
+ * Checks whether all widget parameters were provided to the widget.
812
+ *
813
+ * @param widgetApi - The widget api to read the parameters from
814
+ * @returns True, if all parameters were provided.
815
+ */
816
+ function hasRequiredWidgetParameters(widgetApi) {
817
+ return (typeof widgetApi.widgetParameters.userId === 'string' &&
818
+ typeof widgetApi.widgetParameters.displayName === 'string' &&
819
+ typeof widgetApi.widgetParameters.avatarUrl === 'string' &&
820
+ typeof widgetApi.widgetParameters.roomId === 'string' &&
821
+ typeof widgetApi.widgetParameters.theme === 'string' &&
822
+ typeof widgetApi.widgetParameters.clientId === 'string' &&
823
+ typeof widgetApi.widgetParameters.clientLanguage === 'string');
824
+ }
825
+ /**
826
+ * Generate a registration URL for the widget based on the current URL and
827
+ * include all widget parameters (and their placeholders).
828
+ * @param options - Options for generating the URL.
829
+ * Use `pathName` to include an optional sub path in the URL.
830
+ * Use `includeParameters` to append the widget parameters to
831
+ * the URL, defaults to `true`.
832
+ * @returns The generated URL.
833
+ */
834
+ function generateWidgetRegistrationUrl(options) {
835
+ var _a, _b, _c, _d, _e, _f, _g;
836
+ if (options === void 0) { options = {}; }
837
+ var pathName = options.pathName, _h = options.includeParameters, includeParameters = _h === void 0 ? true : _h, widgetParameters = options.widgetParameters;
838
+ // don't forward widgetId and parentUrl as they will be generated by the client
839
+ var _j = extractRawWidgetParameters(); _j.widgetId; _j.parentUrl; var rawWidgetParameters = __rest(_j, ["widgetId", "parentUrl"]);
840
+ 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' }))
841
+ .map(function (_a) {
842
+ var k = _a[0], v = _a[1];
843
+ return "".concat(k, "=").concat(v);
844
+ })
845
+ .join('&');
846
+ var url = new URL(window.location.href);
847
+ if (pathName) {
848
+ url.pathname = pathName;
849
+ }
850
+ else {
851
+ // ensure trailing '/'
852
+ url.pathname = url.pathname.replace(/\/?$/, '/');
853
+ }
854
+ url.search = '';
855
+ url.hash = includeParameters ? "#/?".concat(parameters) : '';
856
+ return url.toString();
857
+ }
858
+ var STATE_EVENT_WIDGETS = 'im.vector.modular.widgets';
859
+ /**
860
+ * Repair/configure the registration of the current widget.
861
+ * This steps make sure to include all the required widget parameters in the
862
+ * URL. Support setting a widget name and additional parameters.
863
+ *
864
+ * @param widgetApi - The widget api of the current widget.
865
+ * @param registration - Optional configuration options for the widget
866
+ * registration, like the display name of the widget.
867
+ */
868
+ function repairWidgetRegistration(widgetApi, registration) {
869
+ if (registration === void 0) { registration = {}; }
870
+ return __awaiter$1(this, void 0, void 0, function () {
871
+ var readResult, url, name, type, data;
872
+ return __generator$1(this, function (_a) {
873
+ switch (_a.label) {
874
+ case 0: return [4 /*yield*/, widgetApi.requestCapabilities([
875
+ WidgetEventCapability.forStateEvent(EventDirection.Send, STATE_EVENT_WIDGETS, widgetApi.widgetId),
876
+ WidgetEventCapability.forStateEvent(EventDirection.Receive, STATE_EVENT_WIDGETS, widgetApi.widgetId),
877
+ ])];
878
+ case 1:
879
+ _a.sent();
880
+ return [4 /*yield*/, widgetApi.receiveSingleStateEvent(STATE_EVENT_WIDGETS, widgetApi.widgetId)];
881
+ case 2:
882
+ readResult = _a.sent();
883
+ if (!readResult) {
884
+ throw new Error("Error while repairing registration, can't find existing registration.");
885
+ }
886
+ url = generateWidgetRegistrationUrl();
887
+ name = registration.name &&
888
+ (!readResult.content.name ||
889
+ readResult.content.name === 'Custom Widget' ||
890
+ readResult.content.name === 'Custom')
891
+ ? registration.name
892
+ : readResult.content.name;
893
+ type = registration.type &&
894
+ (!readResult.content.type || readResult.content.type === 'm.custom')
895
+ ? registration.type
896
+ : readResult.content.type;
897
+ data = registration.data
898
+ ? __assign(__assign({}, readResult.content.data), registration.data) : readResult.content.data;
899
+ // This is a workaround because changing the widget config is breaking the
900
+ // widget API communication. However we need to fail in case the power level
901
+ // for this change is missing. As the error happens quite fast, we just wait
902
+ // a moment and then consider the operation as succeeded.
903
+ return [4 /*yield*/, Promise.race([
904
+ widgetApi.sendStateEvent(STATE_EVENT_WIDGETS, __assign(__assign({}, readResult.content), { url: url.toString(), name: name, type: type, data: data }), { stateKey: widgetApi.widgetId }),
905
+ new Promise(function (resolve) { return setTimeout(resolve, 1000); }),
906
+ ])];
907
+ case 3:
908
+ // This is a workaround because changing the widget config is breaking the
909
+ // widget API communication. However we need to fail in case the power level
910
+ // for this change is missing. As the error happens quite fast, we just wait
911
+ // a moment and then consider the operation as succeeded.
912
+ _a.sent();
913
+ return [2 /*return*/];
914
+ }
915
+ });
916
+ });
917
+ }
918
+
919
+ /*
920
+ * Copyright 2022 Nordeck IT + Consulting GmbH
921
+ *
922
+ * Licensed under the Apache License, Version 2.0 (the "License");
923
+ * you may not use this file except in compliance with the License.
924
+ * You may obtain a copy of the License at
925
+ *
926
+ * http://www.apache.org/licenses/LICENSE-2.0
927
+ *
928
+ * Unless required by applicable law or agreed to in writing, software
929
+ * distributed under the License is distributed on an "AS IS" BASIS,
930
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
931
+ * See the License for the specific language governing permissions and
932
+ * limitations under the License.
933
+ */
934
+ function convertToRawCapabilities(rawCapabilities) {
935
+ return rawCapabilities.map(function (c) { return (typeof c === 'string' ? c : c.raw); });
936
+ }
937
+ function isDefined(arg) {
938
+ return arg !== null && arg !== undefined;
939
+ }
940
+ function unique(items) {
941
+ return Array.from(new Set(items));
942
+ }
943
+ function subtractSet(as, bs) {
944
+ var result = new Set(as);
945
+ bs.forEach(function (v) { return result.delete(v); });
946
+ return result;
947
+ }
948
+ function isInRoom(matrixEvent, currentRoomId, roomIds) {
949
+ if (!roomIds) {
950
+ return matrixEvent.room_id === currentRoomId;
951
+ }
952
+ if (typeof roomIds === 'string') {
953
+ if (roomIds !== Symbols.AnyRoom) {
954
+ throw Error("Unknown room id symbol: ".concat(roomIds));
955
+ }
956
+ return true;
957
+ }
958
+ return roomIds.includes(matrixEvent.room_id);
959
+ }
960
+
961
+ /*
962
+ * Copyright 2022 Nordeck IT + Consulting GmbH
963
+ *
964
+ * Licensed under the Apache License, Version 2.0 (the "License");
965
+ * you may not use this file except in compliance with the License.
966
+ * You may obtain a copy of the License at
967
+ *
968
+ * http://www.apache.org/licenses/LICENSE-2.0
969
+ *
970
+ * Unless required by applicable law or agreed to in writing, software
971
+ * distributed under the License is distributed on an "AS IS" BASIS,
972
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
973
+ * See the License for the specific language governing permissions and
974
+ * limitations under the License.
975
+ */
976
+ var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
977
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
978
+ return new (P || (P = Promise))(function (resolve, reject) {
979
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
980
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
981
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
982
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
983
+ });
984
+ };
985
+ var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
986
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
987
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
988
+ function verb(n) { return function (v) { return step([n, v]); }; }
989
+ function step(op) {
990
+ if (f) throw new TypeError("Generator is already executing.");
991
+ while (_) try {
992
+ 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;
993
+ if (y = 0, t) op = [op[0] & 2, t.value];
994
+ switch (op[0]) {
995
+ case 0: case 1: t = op; break;
996
+ case 4: _.label++; return { value: op[1], done: false };
997
+ case 5: _.label++; y = op[1]; op = [0]; continue;
998
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
999
+ default:
1000
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
1001
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
1002
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
1003
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
1004
+ if (t[2]) _.ops.pop();
1005
+ _.trys.pop(); continue;
1006
+ }
1007
+ op = body.call(thisArg, _);
1008
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
1009
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1010
+ }
1011
+ };
1012
+ var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
1013
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
1014
+ if (ar || !(i in from)) {
1015
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
1016
+ ar[i] = from[i];
1017
+ }
1018
+ }
1019
+ return to.concat(ar || Array.prototype.slice.call(from));
1020
+ };
1021
+ /**
1022
+ * Implementation of the API from the widget to the client.
1023
+ *
1024
+ * @remarks Widget API is specified here:
1025
+ * https://docs.google.com/document/d/1uPF7XWY_dXTKVKV7jZQ2KmsI19wn9-kFRgQ1tFQP7wQ/edit#heading=h.9rn9lt6ctkgi
1026
+ */
1027
+ var WidgetApiImpl = /** @class */ (function () {
1028
+ function WidgetApiImpl(
1029
+ /**
1030
+ * Provide access to the underlying widget API from `matrix-widget-sdk`.
1031
+ *
1032
+ * @remarks Normally there is no need to use it, however if features are
1033
+ * missing from `WidgetApi` it can be handy to work with the
1034
+ * original API.
1035
+ */
1036
+ matrixWidgetApi,
1037
+ /** {@inheritDoc WidgetApi.widgetId} */
1038
+ widgetId,
1039
+ /** {@inheritDoc WidgetApi.widgetParameters} */
1040
+ widgetParameters, _a) {
1041
+ var _b = _a === void 0 ? {} : _a, _c = _b.capabilities, capabilities = _c === void 0 ? [] : _c, _d = _b.supportStandalone, supportStandalone = _d === void 0 ? false : _d;
1042
+ this.matrixWidgetApi = matrixWidgetApi;
1043
+ this.widgetId = widgetId;
1044
+ this.widgetParameters = widgetParameters;
1045
+ var eventName = "action:".concat(WidgetApiToWidgetAction.SendEvent);
1046
+ this.events$ = fromEvent(this.matrixWidgetApi, eventName, function (event) {
1047
+ event.preventDefault();
1048
+ return event;
1049
+ }).pipe(share());
1050
+ this.initialCapabilities = __spreadArray(__spreadArray([], capabilities, true), (supportStandalone ? [] : [MatrixCapabilities.RequiresClient]), true);
1051
+ }
1052
+ /**
1053
+ * Initialize a new widget API instance and wait till it is ready.
1054
+ * There should only be one instance of the widget API. The widget API should
1055
+ * be created as early as possible when starting the application. This is
1056
+ * required to match the timing of the API connection establishment with the
1057
+ * client, especially in Safari. Therefore it is recommended to create it
1058
+ * inside the entrypoint, before initializing rendering engines like react.
1059
+ *
1060
+ * @param param0 - {@link WidgetApiOptions}
1061
+ *
1062
+ * @returns A widget API instance ready to use.
1063
+ */
1064
+ WidgetApiImpl.create = function (_a) {
1065
+ var _b = _a === void 0 ? {} : _a, _c = _b.capabilities, capabilities = _c === void 0 ? [] : _c, _d = _b.supportStandalone, supportStandalone = _d === void 0 ? false : _d;
1066
+ return __awaiter(this, void 0, void 0, function () {
1067
+ var _e, clientOrigin, widgetId, widgetParameters, matrixWidgetApi, widgetApi;
1068
+ return __generator(this, function (_f) {
1069
+ switch (_f.label) {
1070
+ case 0:
1071
+ _e = extractWidgetApiParameters(), clientOrigin = _e.clientOrigin, widgetId = _e.widgetId;
1072
+ widgetParameters = extractWidgetParameters();
1073
+ matrixWidgetApi = new WidgetApi(widgetId, clientOrigin);
1074
+ widgetApi = new WidgetApiImpl(matrixWidgetApi, widgetId, widgetParameters, { capabilities: capabilities, supportStandalone: supportStandalone });
1075
+ return [4 /*yield*/, widgetApi.initialize()];
1076
+ case 1:
1077
+ _f.sent();
1078
+ return [2 /*return*/, widgetApi];
1079
+ }
1080
+ });
1081
+ });
1082
+ };
1083
+ /**
1084
+ * Initialize the widget API and wait till a connection with the client is
1085
+ * fully established.
1086
+ *
1087
+ * Waits till the user has approved the initial set of capabilities. The
1088
+ * method doesn't fail if the user doesn't approve all of them. It is
1089
+ * required to check manually afterwards.
1090
+ * In case of modal widgets it waits till the `widgetConfig` is received.
1091
+ *
1092
+ * @remarks Should only be called once during startup.
1093
+ */
1094
+ WidgetApiImpl.prototype.initialize = function () {
1095
+ return __awaiter(this, void 0, void 0, function () {
1096
+ var ready, isModal, configReady, rawCapabilities;
1097
+ var _this = this;
1098
+ return __generator(this, function (_a) {
1099
+ switch (_a.label) {
1100
+ case 0:
1101
+ ready = new Promise(function (resolve) {
1102
+ _this.matrixWidgetApi.once('ready', function () { return resolve(); });
1103
+ });
1104
+ isModal = parseWidgetId(this.widgetId).isModal;
1105
+ configReady = isModal
1106
+ ? (function () { return __awaiter(_this, void 0, void 0, function () {
1107
+ var widgetConfig$, _a;
1108
+ var _this = this;
1109
+ return __generator(this, function (_b) {
1110
+ switch (_b.label) {
1111
+ case 0:
1112
+ widgetConfig$ = fromEvent(this.matrixWidgetApi, "action:".concat(WidgetApiToWidgetAction.WidgetConfig), function (ev) {
1113
+ ev.preventDefault();
1114
+ _this.matrixWidgetApi.transport.reply(ev.detail, {});
1115
+ return ev.detail.data;
1116
+ });
1117
+ _a = this;
1118
+ return [4 /*yield*/, firstValueFrom(widgetConfig$)];
1119
+ case 1:
1120
+ _a.widgetConfig = _b.sent();
1121
+ return [2 /*return*/];
1122
+ }
1123
+ });
1124
+ }); })()
1125
+ : undefined;
1126
+ rawCapabilities = unique(convertToRawCapabilities(this.initialCapabilities));
1127
+ this.matrixWidgetApi.requestCapabilities(rawCapabilities);
1128
+ this.matrixWidgetApi.start();
1129
+ return [4 /*yield*/, ready];
1130
+ case 1:
1131
+ _a.sent();
1132
+ if (!configReady) return [3 /*break*/, 3];
1133
+ return [4 /*yield*/, configReady];
1134
+ case 2:
1135
+ _a.sent();
1136
+ _a.label = 3;
1137
+ case 3: return [2 /*return*/];
1138
+ }
1139
+ });
1140
+ });
1141
+ };
1142
+ /** {@inheritDoc WidgetApi.getWidgetConfig} */
1143
+ WidgetApiImpl.prototype.getWidgetConfig = function () {
1144
+ return this.widgetConfig;
1145
+ };
1146
+ /** {@inheritDoc WidgetApi.rerequestInitialCapabilities} */
1147
+ WidgetApiImpl.prototype.rerequestInitialCapabilities = function () {
1148
+ return __awaiter(this, void 0, void 0, function () {
1149
+ return __generator(this, function (_a) {
1150
+ switch (_a.label) {
1151
+ case 0: return [4 /*yield*/, this.requestCapabilities(this.initialCapabilities)];
1152
+ case 1: return [2 /*return*/, _a.sent()];
1153
+ }
1154
+ });
1155
+ });
1156
+ };
1157
+ /** {@inheritDoc WidgetApi.hasInitialCapabilities} */
1158
+ WidgetApiImpl.prototype.hasInitialCapabilities = function () {
1159
+ return this.hasCapabilities(this.initialCapabilities);
1160
+ };
1161
+ /** {@inheritDoc WidgetApi.requestCapabilities} */
1162
+ WidgetApiImpl.prototype.requestCapabilities = function (capabilities) {
1163
+ return __awaiter(this, void 0, void 0, function () {
1164
+ return __generator(this, function (_b) {
1165
+ switch (_b.label) {
1166
+ case 0:
1167
+ if (!this.outstandingCapabilitiesRequest) return [3 /*break*/, 4];
1168
+ _b.label = 1;
1169
+ case 1:
1170
+ _b.trys.push([1, 3, , 4]);
1171
+ return [4 /*yield*/, this.outstandingCapabilitiesRequest];
1172
+ case 2:
1173
+ _b.sent();
1174
+ return [3 /*break*/, 4];
1175
+ case 3:
1176
+ _b.sent();
1177
+ return [3 /*break*/, 4];
1178
+ case 4:
1179
+ _b.trys.push([4, , 6, 7]);
1180
+ this.outstandingCapabilitiesRequest =
1181
+ this.requestCapabilitiesInternal(capabilities);
1182
+ return [4 /*yield*/, this.outstandingCapabilitiesRequest];
1183
+ case 5:
1184
+ _b.sent();
1185
+ return [3 /*break*/, 7];
1186
+ case 6:
1187
+ this.outstandingCapabilitiesRequest = undefined;
1188
+ return [7 /*endfinally*/];
1189
+ case 7: return [2 /*return*/];
1190
+ }
1191
+ });
1192
+ });
1193
+ };
1194
+ WidgetApiImpl.prototype.requestCapabilitiesInternal = function (capabilities) {
1195
+ return __awaiter(this, void 0, void 0, function () {
1196
+ var rawCapabilities, requestedSet, capabilities$;
1197
+ var _this = this;
1198
+ return __generator(this, function (_a) {
1199
+ switch (_a.label) {
1200
+ case 0:
1201
+ rawCapabilities = unique(convertToRawCapabilities(capabilities));
1202
+ // Take shortcut if possible, that avoid extra roundtrips over the API.
1203
+ if (this.hasCapabilities(rawCapabilities)) {
1204
+ return [2 /*return*/];
1205
+ }
1206
+ requestedSet = new Set(rawCapabilities);
1207
+ capabilities$ = fromEvent(this.matrixWidgetApi, "action:".concat(WidgetApiToWidgetAction.NotifyCapabilities), function (ev) { return ev; }).pipe(
1208
+ // TODO: `hasCapability` in the matrix-widget-api isn't consistent when capability
1209
+ // upgrades happened. But `updateRequestedCapabilities` will deduplicate already
1210
+ // approved capabilities, so the the `requested` field will be inconsistent.
1211
+ // If we would enable this check, the function will never resolve. This should
1212
+ // be reactivated once the capability upgrade is working correctly. See also:
1213
+ // https://github.com/matrix-org/matrix-widget-api/issues/52
1214
+ // Ignore events from other parallel capability requests
1215
+ //filter((ev) =>
1216
+ // equalsSet(new Set(ev.detail.data.requested), requestedSet)
1217
+ //),
1218
+ map(function (ev) {
1219
+ var approvedSet = new Set(ev.detail.data.approved);
1220
+ var missingSet = subtractSet(requestedSet, approvedSet);
1221
+ if (missingSet.size > 0) {
1222
+ throw new Error("Capabilities rejected: ".concat(Array.from(missingSet).join(', ')));
1223
+ }
1224
+ }), first());
1225
+ return [4 /*yield*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1226
+ var subscription, err_1;
1227
+ return __generator(this, function (_a) {
1228
+ switch (_a.label) {
1229
+ case 0:
1230
+ subscription = capabilities$.subscribe({
1231
+ next: resolve,
1232
+ error: reject,
1233
+ });
1234
+ _a.label = 1;
1235
+ case 1:
1236
+ _a.trys.push([1, 3, , 4]);
1237
+ this.matrixWidgetApi.requestCapabilities(rawCapabilities);
1238
+ return [4 /*yield*/, this.matrixWidgetApi.updateRequestedCapabilities()];
1239
+ case 2:
1240
+ _a.sent();
1241
+ return [3 /*break*/, 4];
1242
+ case 3:
1243
+ err_1 = _a.sent();
1244
+ subscription.unsubscribe();
1245
+ reject(err_1);
1246
+ return [3 /*break*/, 4];
1247
+ case 4: return [2 /*return*/];
1248
+ }
1249
+ });
1250
+ }); })];
1251
+ case 1:
1252
+ _a.sent();
1253
+ return [2 /*return*/];
1254
+ }
1255
+ });
1256
+ });
1257
+ };
1258
+ /** {@inheritDoc WidgetApi.hasCapabilities} */
1259
+ WidgetApiImpl.prototype.hasCapabilities = function (capabilities) {
1260
+ var _this = this;
1261
+ var rawCapabilities = convertToRawCapabilities(capabilities);
1262
+ return rawCapabilities.every(function (c) { return _this.matrixWidgetApi.hasCapability(c); });
1263
+ };
1264
+ /** {@inheritDoc WidgetApi.receiveSingleStateEvent} */
1265
+ WidgetApiImpl.prototype.receiveSingleStateEvent = function (eventType, stateKey) {
1266
+ if (stateKey === void 0) { stateKey = ''; }
1267
+ return __awaiter(this, void 0, void 0, function () {
1268
+ var events;
1269
+ return __generator(this, function (_a) {
1270
+ switch (_a.label) {
1271
+ case 0: return [4 /*yield*/, this.receiveStateEvents(eventType, { stateKey: stateKey })];
1272
+ case 1:
1273
+ events = _a.sent();
1274
+ return [2 /*return*/, events && events[0]];
1275
+ }
1276
+ });
1277
+ });
1278
+ };
1279
+ /** {@inheritDoc WidgetApi.receiveStateEvents} */
1280
+ WidgetApiImpl.prototype.receiveStateEvents = function (eventType, _a) {
1281
+ var _b = _a === void 0 ? {} : _a, stateKey = _b.stateKey, roomIds = _b.roomIds;
1282
+ return __awaiter(this, void 0, void 0, function () {
1283
+ return __generator(this, function (_c) {
1284
+ switch (_c.label) {
1285
+ case 0: return [4 /*yield*/, this.matrixWidgetApi.readStateEvents(eventType, Number.MAX_SAFE_INTEGER, stateKey, typeof roomIds === 'string' ? [Symbols.AnyRoom] : roomIds)];
1286
+ case 1: return [2 /*return*/, (_c.sent())];
1287
+ }
1288
+ });
1289
+ });
1290
+ };
1291
+ /** {@inheritDoc WidgetApi.observeStateEvents} */
1292
+ WidgetApiImpl.prototype.observeStateEvents = function (eventType, _a) {
1293
+ var _this = this;
1294
+ var _b = _a === void 0 ? {} : _a, stateKey = _b.stateKey, roomIds = _b.roomIds;
1295
+ var currentRoomId = this.widgetParameters.roomId;
1296
+ if (!currentRoomId) {
1297
+ return throwError(function () { return new Error('Current room id is unknown'); });
1298
+ }
1299
+ var historyEvent$ = from(this.receiveStateEvents(eventType, { stateKey: stateKey, roomIds: roomIds })).pipe(mergeAll());
1300
+ var futureEvent$ = this.events$.pipe(map(function (event) {
1301
+ var matrixEvent = event.detail.data;
1302
+ if (matrixEvent.type === eventType &&
1303
+ matrixEvent.state_key !== undefined &&
1304
+ (stateKey === undefined || matrixEvent.state_key === stateKey) &&
1305
+ isInRoom(matrixEvent, currentRoomId, roomIds)) {
1306
+ _this.matrixWidgetApi.transport.reply(event.detail, {});
1307
+ return event.detail.data;
1308
+ }
1309
+ return undefined;
1310
+ }), filter(isDefined));
1311
+ return concat(historyEvent$, futureEvent$);
1312
+ };
1313
+ /** {@inheritDoc WidgetApi.sendStateEvent} */
1314
+ WidgetApiImpl.prototype.sendStateEvent = function (eventType, content, _a) {
1315
+ var _b = _a === void 0 ? {} : _a, roomId = _b.roomId, _c = _b.stateKey, stateKey = _c === void 0 ? '' : _c;
1316
+ return __awaiter(this, void 0, void 0, function () {
1317
+ var firstEvent$;
1318
+ var _this = this;
1319
+ return __generator(this, function (_d) {
1320
+ firstEvent$ = this.events$.pipe(map(function (event) {
1321
+ var matrixEvent = event.detail.data;
1322
+ if (matrixEvent.sender === _this.widgetParameters.userId &&
1323
+ matrixEvent.state_key !== undefined &&
1324
+ matrixEvent.type === eventType &&
1325
+ (!roomId || matrixEvent.room_id === roomId)) {
1326
+ _this.matrixWidgetApi.transport.reply(event.detail, {});
1327
+ return event.detail.data;
1328
+ }
1329
+ return undefined;
1330
+ }), filter(isDefined), first());
1331
+ return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1332
+ var subscription, err_2;
1333
+ return __generator(this, function (_a) {
1334
+ switch (_a.label) {
1335
+ case 0:
1336
+ subscription = firstEvent$.subscribe({
1337
+ next: function (event) { return resolve(event); },
1338
+ error: function (err) { return reject(err); },
1339
+ });
1340
+ _a.label = 1;
1341
+ case 1:
1342
+ _a.trys.push([1, 3, , 4]);
1343
+ return [4 /*yield*/, this.matrixWidgetApi.sendStateEvent(eventType, stateKey, content, roomId)];
1344
+ case 2:
1345
+ _a.sent();
1346
+ return [3 /*break*/, 4];
1347
+ case 3:
1348
+ err_2 = _a.sent();
1349
+ subscription.unsubscribe();
1350
+ reject(err_2);
1351
+ return [3 /*break*/, 4];
1352
+ case 4: return [2 /*return*/];
1353
+ }
1354
+ });
1355
+ }); })];
1356
+ });
1357
+ });
1358
+ };
1359
+ /** {@inheritDoc WidgetApi.receiveRoomEvents} */
1360
+ WidgetApiImpl.prototype.receiveRoomEvents = function (eventType, _a) {
1361
+ var _b = _a === void 0 ? {} : _a, messageType = _b.messageType, roomIds = _b.roomIds;
1362
+ return __awaiter(this, void 0, void 0, function () {
1363
+ return __generator(this, function (_c) {
1364
+ switch (_c.label) {
1365
+ case 0: return [4 /*yield*/, this.matrixWidgetApi.readRoomEvents(eventType, Number.MAX_SAFE_INTEGER, messageType, typeof roomIds === 'string' ? [Symbols.AnyRoom] : roomIds)];
1366
+ case 1: return [2 /*return*/, (_c.sent())];
1367
+ }
1368
+ });
1369
+ });
1370
+ };
1371
+ /** {@inheritDoc WidgetApi.observeRoomEvents} */
1372
+ WidgetApiImpl.prototype.observeRoomEvents = function (eventType, _a) {
1373
+ var _this = this;
1374
+ var _b = _a === void 0 ? {} : _a, messageType = _b.messageType, roomIds = _b.roomIds;
1375
+ var currentRoomId = this.widgetParameters.roomId;
1376
+ if (!currentRoomId) {
1377
+ return throwError(function () { return new Error('Current room id is unknown'); });
1378
+ }
1379
+ var historyEvent$ = from(this.receiveRoomEvents(eventType, { messageType: messageType, roomIds: roomIds })).pipe(mergeAll());
1380
+ var futureEvent$ = this.events$.pipe(map(function (event) {
1381
+ var matrixEvent = event.detail.data;
1382
+ if (matrixEvent.type === eventType &&
1383
+ matrixEvent.state_key === undefined &&
1384
+ (!messageType || matrixEvent.content.msgtype === messageType) &&
1385
+ isInRoom(matrixEvent, currentRoomId, roomIds)) {
1386
+ _this.matrixWidgetApi.transport.reply(event.detail, {});
1387
+ return event.detail.data;
1388
+ }
1389
+ return undefined;
1390
+ }), filter(isDefined));
1391
+ return concat(historyEvent$, futureEvent$);
1392
+ };
1393
+ /** {@inheritDoc WidgetApi.sendRoomEvent} */
1394
+ WidgetApiImpl.prototype.sendRoomEvent = function (eventType, content, _a) {
1395
+ var _b = _a === void 0 ? {} : _a, roomId = _b.roomId;
1396
+ return __awaiter(this, void 0, void 0, function () {
1397
+ var firstEvents$;
1398
+ var _this = this;
1399
+ return __generator(this, function (_c) {
1400
+ firstEvents$ = this.events$.pipe(map(function (event) {
1401
+ var matrixEvent = event.detail.data;
1402
+ if (matrixEvent.sender === _this.widgetParameters.userId &&
1403
+ matrixEvent.state_key === undefined &&
1404
+ matrixEvent.type === eventType &&
1405
+ (!roomId || matrixEvent.room_id === roomId)) {
1406
+ _this.matrixWidgetApi.transport.reply(event.detail, {});
1407
+ return event.detail.data;
1408
+ }
1409
+ return undefined;
1410
+ }), filter(isDefined), first());
1411
+ return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
1412
+ var subscription, err_3;
1413
+ return __generator(this, function (_a) {
1414
+ switch (_a.label) {
1415
+ case 0:
1416
+ subscription = firstEvents$.subscribe({
1417
+ next: function (event) { return resolve(event); },
1418
+ error: function (err) { return reject(err); },
1419
+ });
1420
+ _a.label = 1;
1421
+ case 1:
1422
+ _a.trys.push([1, 3, , 4]);
1423
+ return [4 /*yield*/, this.matrixWidgetApi.sendRoomEvent(eventType, content, roomId)];
1424
+ case 2:
1425
+ _a.sent();
1426
+ return [3 /*break*/, 4];
1427
+ case 3:
1428
+ err_3 = _a.sent();
1429
+ subscription.unsubscribe();
1430
+ reject(err_3);
1431
+ return [3 /*break*/, 4];
1432
+ case 4: return [2 /*return*/];
1433
+ }
1434
+ });
1435
+ }); })];
1436
+ });
1437
+ });
1438
+ };
1439
+ /** {@inheritDoc WidgetApi.readEventRelations} */
1440
+ WidgetApiImpl.prototype.readEventRelations = function (eventId, options) {
1441
+ return __awaiter(this, void 0, void 0, function () {
1442
+ var _a, original_event, chunk, next_batch;
1443
+ return __generator(this, function (_b) {
1444
+ switch (_b.label) {
1445
+ 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)];
1446
+ case 1:
1447
+ _a = _b.sent(), original_event = _a.original_event, chunk = _a.chunk, next_batch = _a.next_batch;
1448
+ return [2 /*return*/, {
1449
+ originalEvent: original_event,
1450
+ chunk: chunk,
1451
+ nextToken: next_batch,
1452
+ }];
1453
+ }
1454
+ });
1455
+ });
1456
+ };
1457
+ /** {@inheritDoc WidgetApi.openModal} */
1458
+ WidgetApiImpl.prototype.openModal = function (pathName, name, options) {
1459
+ return __awaiter(this, void 0, void 0, function () {
1460
+ var isModal, url, closeModalWidget$;
1461
+ var _this = this;
1462
+ return __generator(this, function (_a) {
1463
+ switch (_a.label) {
1464
+ case 0:
1465
+ isModal = parseWidgetId(this.widgetId).isModal;
1466
+ if (isModal) {
1467
+ throw new Error("Modals can't be opened from another modal widget");
1468
+ }
1469
+ url = generateWidgetRegistrationUrl({
1470
+ pathName: pathName,
1471
+ widgetParameters: this.widgetParameters,
1472
+ });
1473
+ return [4 /*yield*/, this.matrixWidgetApi.openModalWidget(url, name, options === null || options === void 0 ? void 0 : options.buttons, options === null || options === void 0 ? void 0 : options.data)];
1474
+ case 1:
1475
+ _a.sent();
1476
+ closeModalWidget$ = fromEvent(this.matrixWidgetApi, "action:".concat(WidgetApiToWidgetAction.CloseModalWidget), function (event) {
1477
+ var _a;
1478
+ event.preventDefault();
1479
+ _this.matrixWidgetApi.transport.reply(event.detail, {});
1480
+ if (((_a = event.detail.data) === null || _a === void 0 ? void 0 : _a['m.exited']) === true) {
1481
+ return undefined;
1482
+ }
1483
+ return event.detail.data;
1484
+ });
1485
+ return [2 /*return*/, firstValueFrom(closeModalWidget$)];
1486
+ }
1487
+ });
1488
+ });
1489
+ };
1490
+ /** {@inheritDoc WidgetApi.setModalButtonEnabled} */
1491
+ WidgetApiImpl.prototype.setModalButtonEnabled = function (buttonId, isEnabled) {
1492
+ return __awaiter(this, void 0, void 0, function () {
1493
+ var isModal;
1494
+ return __generator(this, function (_a) {
1495
+ switch (_a.label) {
1496
+ case 0:
1497
+ isModal = parseWidgetId(this.widgetId).isModal;
1498
+ if (!isModal) {
1499
+ throw new Error('Modal buttons can only be enabled from a modal widget');
1500
+ }
1501
+ return [4 /*yield*/, this.matrixWidgetApi.setModalButtonEnabled(buttonId, isEnabled)];
1502
+ case 1:
1503
+ _a.sent();
1504
+ return [2 /*return*/];
1505
+ }
1506
+ });
1507
+ });
1508
+ };
1509
+ /** {@inheritDoc WidgetApi.observeModalButtons} */
1510
+ WidgetApiImpl.prototype.observeModalButtons = function () {
1511
+ var _this = this;
1512
+ var isModal = parseWidgetId(this.widgetId).isModal;
1513
+ if (!isModal) {
1514
+ throw new Error('Modal buttons can only be observed from a modal widget');
1515
+ }
1516
+ return fromEvent(this.matrixWidgetApi, "action:".concat(WidgetApiToWidgetAction.ButtonClicked), function (event) {
1517
+ event.preventDefault();
1518
+ _this.matrixWidgetApi.transport.reply(event.detail, {});
1519
+ return event.detail.data.id;
1520
+ });
1521
+ };
1522
+ /** {@inheritDoc WidgetApi.closeModal} */
1523
+ WidgetApiImpl.prototype.closeModal = function (data) {
1524
+ return __awaiter(this, void 0, void 0, function () {
1525
+ var isModal;
1526
+ return __generator(this, function (_a) {
1527
+ switch (_a.label) {
1528
+ case 0:
1529
+ isModal = parseWidgetId(this.widgetId).isModal;
1530
+ if (!isModal) {
1531
+ throw new Error('Modals can only be closed from a modal widget');
1532
+ }
1533
+ return [4 /*yield*/, this.matrixWidgetApi.closeModalWidget(data ? data : { 'm.exited': true })];
1534
+ case 1:
1535
+ _a.sent();
1536
+ return [2 /*return*/];
1537
+ }
1538
+ });
1539
+ });
1540
+ };
1541
+ /** {@inheritdoc WidgetApi.navigateTo} */
1542
+ WidgetApiImpl.prototype.navigateTo = function (uri) {
1543
+ return __awaiter(this, void 0, void 0, function () {
1544
+ return __generator(this, function (_a) {
1545
+ switch (_a.label) {
1546
+ case 0: return [4 /*yield*/, this.matrixWidgetApi.navigateTo(uri)];
1547
+ case 1:
1548
+ _a.sent();
1549
+ return [2 /*return*/];
1550
+ }
1551
+ });
1552
+ });
1553
+ };
1554
+ /** {@inheritdoc WidgetApi.requestOpenIDConnectToken} */
1555
+ WidgetApiImpl.prototype.requestOpenIDConnectToken = function () {
1556
+ return __awaiter(this, void 0, void 0, function () {
1557
+ return __generator(this, function (_b) {
1558
+ switch (_b.label) {
1559
+ case 0:
1560
+ if (!this.outstandingOpenIDConnectTokenRequest) return [3 /*break*/, 4];
1561
+ _b.label = 1;
1562
+ case 1:
1563
+ _b.trys.push([1, 3, , 4]);
1564
+ return [4 /*yield*/, this.outstandingOpenIDConnectTokenRequest];
1565
+ case 2:
1566
+ _b.sent();
1567
+ return [3 /*break*/, 4];
1568
+ case 3:
1569
+ _b.sent();
1570
+ return [3 /*break*/, 4];
1571
+ case 4:
1572
+ _b.trys.push([4, , 6, 7]);
1573
+ this.outstandingOpenIDConnectTokenRequest =
1574
+ this.requestOpenIDConnectTokenInternal();
1575
+ return [4 /*yield*/, this.outstandingOpenIDConnectTokenRequest];
1576
+ case 5: return [2 /*return*/, _b.sent()];
1577
+ case 6:
1578
+ this.outstandingOpenIDConnectTokenRequest = undefined;
1579
+ return [7 /*endfinally*/];
1580
+ case 7: return [2 /*return*/];
1581
+ }
1582
+ });
1583
+ });
1584
+ };
1585
+ WidgetApiImpl.prototype.requestOpenIDConnectTokenInternal = function () {
1586
+ var _a;
1587
+ return __awaiter(this, void 0, void 0, function () {
1588
+ var leywayMilliseconds, openIdToken, err_4;
1589
+ return __generator(this, function (_b) {
1590
+ switch (_b.label) {
1591
+ case 0:
1592
+ leywayMilliseconds = 30 * 1000;
1593
+ if (this.cachedOpenIdToken &&
1594
+ this.cachedOpenIdToken.expiresAt - leywayMilliseconds > Date.now()) {
1595
+ return [2 /*return*/, this.cachedOpenIdToken.openIdToken];
1596
+ }
1597
+ _b.label = 1;
1598
+ case 1:
1599
+ _b.trys.push([1, 3, , 4]);
1600
+ return [4 /*yield*/, this.matrixWidgetApi.requestOpenIDConnectToken()];
1601
+ case 2:
1602
+ openIdToken = _b.sent();
1603
+ this.cachedOpenIdToken = {
1604
+ openIdToken: openIdToken,
1605
+ expiresAt: Date.now() + ((_a = openIdToken.expires_in) !== null && _a !== void 0 ? _a : 0) * 1000,
1606
+ };
1607
+ return [2 /*return*/, openIdToken];
1608
+ case 3:
1609
+ err_4 = _b.sent();
1610
+ this.cachedOpenIdToken = undefined;
1611
+ throw err_4;
1612
+ case 4: return [2 /*return*/];
1613
+ }
1614
+ });
1615
+ });
1616
+ };
1617
+ return WidgetApiImpl;
1618
+ }());
1619
+
1620
+ 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 };