Files
matrix-quotes-bot/node_modules/matrix-widget-api/lib/WidgetApi.js
unfunny dfe4cc537f init
2026-09-13 00:29:11 -04:00

1186 lines
61 KiB
JavaScript

"use strict";
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.WidgetApiResponseError = exports.WidgetApi = void 0;
var _events = require("events");
var _Capabilities = require("./interfaces/Capabilities");
var _WidgetApiDirection = require("./interfaces/WidgetApiDirection");
var _ApiVersion = require("./interfaces/ApiVersion");
var _PostmessageTransport = require("./transport/PostmessageTransport");
var _WidgetApiAction = require("./interfaces/WidgetApiAction");
var _GetOpenIDAction = require("./interfaces/GetOpenIDAction");
var _WidgetType = require("./interfaces/WidgetType");
var _ModalWidgetActions = require("./interfaces/ModalWidgetActions");
var _WidgetEventCapability = require("./models/WidgetEventCapability");
var _Symbols = require("./Symbols");
var _UpdateDelayedEventAction = require("./interfaces/UpdateDelayedEventAction");
function _regeneratorRuntime() { "use strict"; var r = _regenerator(), e = r.m(_regeneratorRuntime), t = (Object.getPrototypeOf ? Object.getPrototypeOf(e) : e.__proto__).constructor; function n(r) { var e = "function" == typeof r && r.constructor; return !!e && (e === t || "GeneratorFunction" === (e.displayName || e.name)); } var o = { "throw": 1, "return": 2, "break": 3, "continue": 3 }; function a(r) { var e, t; return function (n) { e || (e = { stop: function stop() { return t(n.a, 2); }, "catch": function _catch() { return n.v; }, abrupt: function abrupt(r, e) { return t(n.a, o[r], e); }, delegateYield: function delegateYield(r, o, a) { return e.resultName = o, t(n.d, _regeneratorValues(r), a); }, finish: function finish(r) { return t(n.f, r); } }, t = function t(r, _t, o) { n.p = e.prev, n.n = e.next; try { return r(_t, o); } finally { e.next = n.n; } }), e.resultName && (e[e.resultName] = n.v, e.resultName = void 0), e.sent = n.v, e.next = n.n; try { return r.call(this, e); } finally { n.p = e.prev, n.n = e.next; } }; } return (_regeneratorRuntime = function _regeneratorRuntime() { return { wrap: function wrap(e, t, n, o) { return r.w(a(e), t, n, o && o.reverse()); }, isGeneratorFunction: n, mark: r.m, awrap: function awrap(r, e) { return new _OverloadYield(r, e); }, AsyncIterator: _regeneratorAsyncIterator, async: function async(r, e, t, o, u) { return (n(e) ? _regeneratorAsyncGen : _regeneratorAsync)(a(r), e, t, o, u); }, keys: _regeneratorKeys, values: _regeneratorValues }; })(); }
function _regeneratorValues(e) { if (null != e) { var t = e["function" == typeof Symbol && Symbol.iterator || "@@iterator"], r = 0; if (t) return t.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) return { next: function next() { return e && r >= e.length && (e = void 0), { value: e && e[r++], done: !e }; } }; } throw new TypeError(_typeof(e) + " is not iterable"); }
function _regeneratorKeys(e) { var n = Object(e), r = []; for (var t in n) r.unshift(t); return function e() { for (; r.length;) if ((t = r.pop()) in n) return e.value = t, e.done = !1, e; return e.done = !0, e; }; }
function _regeneratorAsync(n, e, r, t, o) { var a = _regeneratorAsyncGen(n, e, r, t, o); return a.next().then(function (n) { return n.done ? n.value : a.next(); }); }
function _regeneratorAsyncGen(r, e, t, o, n) { return new _regeneratorAsyncIterator(_regenerator().w(r, e, t, o), n || Promise); }
function _regeneratorAsyncIterator(t, e) { function n(r, o, i, f) { try { var c = t[r](o), u = c.value; return u instanceof _OverloadYield ? e.resolve(u.v).then(function (t) { n("next", t, i, f); }, function (t) { n("throw", t, i, f); }) : e.resolve(u).then(function (t) { c.value = t, i(c); }, function (t) { return n("throw", t, i, f); }); } catch (t) { f(t); } } var r; this.next || (_regeneratorDefine2(_regeneratorAsyncIterator.prototype), _regeneratorDefine2(_regeneratorAsyncIterator.prototype, "function" == typeof Symbol && Symbol.asyncIterator || "@asyncIterator", function () { return this; })), _regeneratorDefine2(this, "_invoke", function (t, o, i) { function f() { return new e(function (e, r) { n(t, i, e, r); }); } return r = r ? r.then(f, f) : f(); }, !0); }
function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _createSuper(t) { var r = _isNativeReflectConstruct(); return function () { var e, o = _getPrototypeOf(t); if (r) { var s = _getPrototypeOf(this).constructor; e = Reflect.construct(o, arguments, s); } else e = o.apply(this, arguments); return _possibleConstructorReturn(this, e); }; }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); }
function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _awaitAsyncGenerator(e) { return new _OverloadYield(e, 0); }
function _wrapAsyncGenerator(e) { return function () { return new AsyncGenerator(e.apply(this, arguments)); }; }
function AsyncGenerator(e) { var t, n; function resume(t, n) { try { var r = e[t](n), o = r.value, u = o instanceof _OverloadYield; Promise.resolve(u ? o.v : o).then(function (n) { if (u) { var i = "return" === t && o.k ? t : "next"; if (!o.k || n.done) return resume(i, n); n = e[i](n).value; } settle(!!r.done, n); }, function (e) { resume("throw", e); }); } catch (e) { settle(2, e); } } function settle(e, r) { 2 === e ? t.reject(r) : t.resolve({ value: r, done: e }), (t = t.next) ? resume(t.key, t.arg) : n = null; } this._invoke = function (e, r) { return new Promise(function (o, u) { var i = { key: e, arg: r, resolve: o, reject: u, next: null }; n ? n = n.next = i : (t = n = i, resume(e, r)); }); }, "function" != typeof e["return"] && (this["return"] = void 0); }
AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function () { return this; }, AsyncGenerator.prototype.next = function (e) { return this._invoke("next", e); }, AsyncGenerator.prototype["throw"] = function (e) { return this._invoke("throw", e); }, AsyncGenerator.prototype["return"] = function (e) { return this._invoke("return", e); };
function _OverloadYield(e, d) { this.v = e, this.k = d; } /*
* Copyright 2020 - 2024 The Matrix.org Foundation C.I.C.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var WidgetApiResponseError = /*#__PURE__*/function (_Error) {
_inherits(WidgetApiResponseError, _Error);
var _super = _createSuper(WidgetApiResponseError);
function WidgetApiResponseError(message, data) {
var _this2;
_classCallCheck(this, WidgetApiResponseError);
_this2 = _super.call(this, message);
_this2.data = data;
return _this2;
}
return _createClass(WidgetApiResponseError);
}(/*#__PURE__*/_wrapNativeSuper(Error));
/**
* API handler for widgets. This raises events for each action
* received as `action:${action}` (eg: "action:screenshot").
* Default handling can be prevented by using preventDefault()
* on the raised event. The default handling varies for each
* action: ones which the SDK can handle safely are acknowledged
* appropriately and ones which are unhandled (custom or require
* the widget to do something) are rejected with an error.
*
* Events which are preventDefault()ed must reply using the
* transport. The events raised will have a detail of an
* IWidgetApiRequest interface.
*
* When the WidgetApi is ready to start sending requests, it will
* raise a "ready" CustomEvent. After the ready event fires, actions
* can be sent and the transport will be ready.
*/
exports.WidgetApiResponseError = WidgetApiResponseError;
WidgetApiResponseError.prototype.name = WidgetApiResponseError.name;
var WidgetApi = /*#__PURE__*/function (_EventEmitter) {
_inherits(WidgetApi, _EventEmitter);
var _super2 = _createSuper(WidgetApi);
/**
* Creates a new API handler for the given widget.
* @param {string} widgetId The widget ID to listen for. If not supplied then
* the API will use the widget ID from the first valid request it receives.
* @param {string} clientOrigin The origin of the client, or null if not known.
*/
function WidgetApi() {
var _this3;
var widgetId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var clientOrigin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
_classCallCheck(this, WidgetApi);
_this3 = _super2.call(this);
_defineProperty(_assertThisInitialized(_this3), "transport", void 0);
_defineProperty(_assertThisInitialized(_this3), "capabilitiesFinished", false);
_defineProperty(_assertThisInitialized(_this3), "supportsMSC2974Renegotiate", false);
_defineProperty(_assertThisInitialized(_this3), "requestedCapabilities", []);
_defineProperty(_assertThisInitialized(_this3), "approvedCapabilities", void 0);
_defineProperty(_assertThisInitialized(_this3), "cachedClientVersions", void 0);
_defineProperty(_assertThisInitialized(_this3), "turnServerWatchers", 0);
if (!globalThis.parent) {
throw new Error("No parent window. This widget doesn't appear to be embedded properly.");
}
_this3.transport = new _PostmessageTransport.PostmessageTransport(_WidgetApiDirection.WidgetApiDirection.FromWidget, widgetId, globalThis.parent, globalThis);
_this3.transport.targetOrigin = clientOrigin;
_this3.transport.on("message", _this3.handleMessage.bind(_assertThisInitialized(_this3)));
return _this3;
}
/**
* Determines if the widget was granted a particular capability. Note that on
* clients where the capabilities are not fed back to the widget this function
* will rely on requested capabilities instead.
* @param {Capability} capability The capability to check for approval of.
* @returns {boolean} True if the widget has approval for the given capability.
*/
_createClass(WidgetApi, [{
key: "hasCapability",
value: function hasCapability(capability) {
if (Array.isArray(this.approvedCapabilities)) {
return this.approvedCapabilities.includes(capability);
}
return this.requestedCapabilities.includes(capability);
}
/**
* Request a capability from the client. It is not guaranteed to be allowed,
* but will be asked for.
* @param {Capability} capability The capability to request.
* @throws Throws if the capabilities negotiation has already started and the
* widget is unable to request additional capabilities.
*/
}, {
key: "requestCapability",
value: function requestCapability(capability) {
if (this.capabilitiesFinished && !this.supportsMSC2974Renegotiate) {
throw new Error("Capabilities have already been negotiated");
}
this.requestedCapabilities.push(capability);
}
/**
* Request capabilities from the client. They are not guaranteed to be allowed,
* but will be asked for if the negotiation has not already happened.
* @param {Capability[]} capabilities The capabilities to request.
* @throws Throws if the capabilities negotiation has already started.
*/
}, {
key: "requestCapabilities",
value: function requestCapabilities(capabilities) {
var _iterator = _createForOfIteratorHelper(capabilities),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var cap = _step.value;
this.requestCapability(cap);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
/**
* Requests the capability to interact with rooms other than the user's currently
* viewed room. Applies to event receiving and sending.
* @param {string | Symbols.AnyRoom} roomId The room ID, or `Symbols.AnyRoom` to
* denote all known rooms.
*/
}, {
key: "requestCapabilityForRoomTimeline",
value: function requestCapabilityForRoomTimeline(roomId) {
this.requestCapability("org.matrix.msc2762.timeline:".concat(roomId));
}
/**
* Requests the capability to send a given state event with optional explicit
* state key. It is not guaranteed to be allowed, but will be asked for if the
* negotiation has not already happened.
* @param {string} eventType The state event type to ask for.
* @param {string} stateKey If specified, the specific state key to request.
* Otherwise all state keys will be requested.
*/
}, {
key: "requestCapabilityToSendState",
value: function requestCapabilityToSendState(eventType, stateKey) {
this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forStateEvent(_WidgetEventCapability.EventDirection.Send, eventType, stateKey).raw);
}
/**
* Requests the capability to receive a given state event with optional explicit
* state key. It is not guaranteed to be allowed, but will be asked for if the
* negotiation has not already happened.
* @param {string} eventType The state event type to ask for.
* @param {string} stateKey If specified, the specific state key to request.
* Otherwise all state keys will be requested.
*/
}, {
key: "requestCapabilityToReceiveState",
value: function requestCapabilityToReceiveState(eventType, stateKey) {
this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forStateEvent(_WidgetEventCapability.EventDirection.Receive, eventType, stateKey).raw);
}
/**
* Requests the capability to send a given to-device event. It is not
* guaranteed to be allowed, but will be asked for if the negotiation has
* not already happened.
* @param {string} eventType The room event type to ask for.
*/
}, {
key: "requestCapabilityToSendToDevice",
value: function requestCapabilityToSendToDevice(eventType) {
this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forToDeviceEvent(_WidgetEventCapability.EventDirection.Send, eventType).raw);
}
/**
* Requests the capability to receive a given to-device event. It is not
* guaranteed to be allowed, but will be asked for if the negotiation has
* not already happened.
* @param {string} eventType The room event type to ask for.
*/
}, {
key: "requestCapabilityToReceiveToDevice",
value: function requestCapabilityToReceiveToDevice(eventType) {
this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forToDeviceEvent(_WidgetEventCapability.EventDirection.Receive, eventType).raw);
}
/**
* Requests the capability to send a given room event. It is not guaranteed to be
* allowed, but will be asked for if the negotiation has not already happened.
* @param {string} eventType The room event type to ask for.
*/
}, {
key: "requestCapabilityToSendEvent",
value: function requestCapabilityToSendEvent(eventType) {
this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forRoomEvent(_WidgetEventCapability.EventDirection.Send, eventType).raw);
}
/**
* Requests the capability to receive a given room event. It is not guaranteed to be
* allowed, but will be asked for if the negotiation has not already happened.
* @param {string} eventType The room event type to ask for.
*/
}, {
key: "requestCapabilityToReceiveEvent",
value: function requestCapabilityToReceiveEvent(eventType) {
this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forRoomEvent(_WidgetEventCapability.EventDirection.Receive, eventType).raw);
}
/**
* Requests the capability to send a given message event with optional explicit
* `msgtype`. It is not guaranteed to be allowed, but will be asked for if the
* negotiation has not already happened.
* @param {string} msgtype If specified, the specific msgtype to request.
* Otherwise all message types will be requested.
*/
}, {
key: "requestCapabilityToSendMessage",
value: function requestCapabilityToSendMessage(msgtype) {
this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forRoomMessageEvent(_WidgetEventCapability.EventDirection.Send, msgtype).raw);
}
/**
* Requests the capability to receive a given message event with optional explicit
* `msgtype`. It is not guaranteed to be allowed, but will be asked for if the
* negotiation has not already happened.
* @param {string} msgtype If specified, the specific msgtype to request.
* Otherwise all message types will be requested.
*/
}, {
key: "requestCapabilityToReceiveMessage",
value: function requestCapabilityToReceiveMessage(msgtype) {
this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forRoomMessageEvent(_WidgetEventCapability.EventDirection.Receive, msgtype).raw);
}
/**
* Requests the capability to receive a given item in room account data. It is not guaranteed to be
* allowed, but will be asked for if the negotiation has not already happened.
* @param {string} eventType The state event type to ask for.
*/
}, {
key: "requestCapabilityToReceiveRoomAccountData",
value: function requestCapabilityToReceiveRoomAccountData(eventType) {
this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forRoomAccountData(_WidgetEventCapability.EventDirection.Receive, eventType).raw);
}
/**
* Requests the capability to obtain a JWT for a LiveKit SFU through the client.
* It is not guaranteed to be allowed, but will be asked for if the negotiation
* has not already happened.
* @see {@link https://github.com/matrix-org/matrix-spec-proposals/pull/4533|MSC4533}
*/
}, {
key: "requestCapabilityToGetRtcLivekitToken",
value: function requestCapabilityToGetRtcLivekitToken() {
this.requestCapability(_Capabilities.MatrixCapabilities.MSC4533RtcLivekitGetToken);
}
/**
* Requests the capability to hand a MatrixRTC session's delayed leave event over
* to the server through the client. It is not guaranteed to be allowed, but will
* be asked for if the negotiation has not already happened.
* @see {@link https://github.com/matrix-org/matrix-spec-proposals/pull/4533|MSC4533}
*/
}, {
key: "requestCapabilityToDelegateRtcLivekitDelayedLeave",
value: function requestCapabilityToDelegateRtcLivekitDelayedLeave() {
this.requestCapability(_Capabilities.MatrixCapabilities.MSC4533RtcLivekitDelegateDelayedLeave);
}
/**
* Requests an OpenID Connect token from the client for the currently logged in
* user. This token can be validated server-side with the federation API. Note
* that the widget is responsible for validating the token and caching any results
* it needs.
* @returns {Promise<IOpenIDCredentials>} Resolves to a token for verification.
* @throws Throws if the user rejected the request or the request failed.
*/
}, {
key: "requestOpenIDConnectToken",
value: function requestOpenIDConnectToken() {
var _this4 = this;
return new Promise(function (resolve, reject) {
_this4.transport.sendComplete(_WidgetApiAction.WidgetApiFromWidgetAction.GetOpenIDCredentials, {}).then(function (response) {
var rdata = response.response;
if (rdata.state === _GetOpenIDAction.OpenIDRequestState.Allowed) {
resolve(rdata);
} else if (rdata.state === _GetOpenIDAction.OpenIDRequestState.Blocked) {
reject(new Error("User declined to verify their identity"));
} else if (rdata.state === _GetOpenIDAction.OpenIDRequestState.PendingUserConfirmation) {
var handlerFn = function handlerFn(ev) {
ev.preventDefault();
var request = ev.detail;
if (request.data.original_request_id !== response.requestId) return;
if (request.data.state === _GetOpenIDAction.OpenIDRequestState.Allowed) {
resolve(request.data);
_this4.transport.reply(request, {}); // ack
} else if (request.data.state === _GetOpenIDAction.OpenIDRequestState.Blocked) {
reject(new Error("User declined to verify their identity"));
_this4.transport.reply(request, {}); // ack
} else {
reject(new Error("Invalid state on reply: " + rdata.state));
_this4.transport.reply(request, {
error: {
message: "Invalid state"
}
});
}
_this4.off("action:".concat(_WidgetApiAction.WidgetApiToWidgetAction.OpenIDCredentials), handlerFn);
};
_this4.on("action:".concat(_WidgetApiAction.WidgetApiToWidgetAction.OpenIDCredentials), handlerFn);
} else {
reject(new Error("Invalid state: " + rdata.state));
}
})["catch"](reject);
});
}
/**
* Asks the client for additional capabilities. Capabilities can be queued for this
* request with the requestCapability() functions.
* @returns {Promise<void>} Resolves when complete. Note that the promise resolves when
* the capabilities request has gone through, not when the capabilities are approved/denied.
* Use the WidgetApiToWidgetAction.NotifyCapabilities action to detect changes.
*/
}, {
key: "updateRequestedCapabilities",
value: function updateRequestedCapabilities() {
return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities, {
capabilities: this.requestedCapabilities
}).then();
}
/**
* Tell the client that the content has been loaded.
* @returns {Promise} Resolves when the client acknowledges the request.
*/
}, {
key: "sendContentLoaded",
value: function sendContentLoaded() {
return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.ContentLoaded, {}).then();
}
/**
* Sends a sticker to the client.
* @param {IStickerActionRequestData} sticker The sticker to send.
* @returns {Promise} Resolves when the client acknowledges the request.
*/
}, {
key: "sendSticker",
value: function sendSticker(sticker) {
return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SendSticker, sticker).then();
}
/**
* Asks the client to set the always-on-screen status for this widget.
* @param {boolean} value The new state to request.
* @returns {Promise<boolean>} Resolve with true if the client was able to fulfill
* the request, resolves to false otherwise. Rejects if an error occurred.
*/
}, {
key: "setAlwaysOnScreen",
value: function setAlwaysOnScreen(value) {
return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.UpdateAlwaysOnScreen, {
value: value
}).then(function (res) {
return res.success;
});
}
/**
* Opens a modal widget.
* @param {string} url The URL to the modal widget.
* @param {string} name The name of the widget.
* @param {IModalWidgetOpenRequestDataButton[]} buttons The buttons to have on the widget.
* @param {IModalWidgetCreateData} data Data to supply to the modal widget.
* @param {WidgetType} type The type of modal widget.
* @returns {Promise<void>} Resolves when the modal widget has been opened.
*/
}, {
key: "openModalWidget",
value: function openModalWidget(url, name) {
var buttons = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
var data = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var type = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : _WidgetType.MatrixWidgetType.Custom;
return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.OpenModalWidget, {
type: type,
url: url,
name: name,
buttons: buttons,
data: data
}).then();
}
/**
* Closes the modal widget. The widget's session will be terminated shortly after.
* @param {IModalWidgetReturnData} data Optional data to close the modal widget with.
* @returns {Promise<void>} Resolves when complete.
*/
}, {
key: "closeModalWidget",
value: function closeModalWidget() {
var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.CloseModalWidget, data).then();
}
}, {
key: "sendRoomEvent",
value: function sendRoomEvent(eventType, content, roomId, delay, parentDelayIdOrStickyDurationMs, stickyDurationMs) {
var parentDelayId;
if (typeof parentDelayIdOrStickyDurationMs === "number") {
stickyDurationMs = parentDelayIdOrStickyDurationMs;
} else {
parentDelayId = parentDelayIdOrStickyDurationMs;
}
return this.sendEvent(eventType, undefined, content, roomId, delay, parentDelayId, stickyDurationMs);
}
}, {
key: "sendStateEvent",
value: function sendStateEvent(eventType, stateKey, content, roomId, delay, parentDelayId) {
return this.sendEvent(eventType, stateKey, content, roomId, delay, parentDelayId);
}
}, {
key: "sendEvent",
value: function sendEvent(eventType, stateKey, content, roomId, delay, parentDelayId, stickyDurationMs) {
return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SendEvent, _objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread({
type: eventType,
content: content
}, stateKey !== undefined && {
state_key: stateKey
}), roomId !== undefined && {
room_id: roomId
}), delay !== undefined && {
delay: delay
}), parentDelayId !== undefined && {
parent_delay_id: parentDelayId
}), stickyDurationMs !== undefined && {
sticky_duration_ms: stickyDurationMs
}));
}
/**
* @experimental This currently relies on an unstable MSC (MSC4157).
*/
}, {
key: "cancelScheduledDelayedEvent",
value: function cancelScheduledDelayedEvent(delayId) {
return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC4157UpdateDelayedEvent, {
delay_id: delayId,
action: _UpdateDelayedEventAction.UpdateDelayedEventAction.Cancel
});
}
/**
* @experimental This currently relies on an unstable MSC (MSC4157).
*/
}, {
key: "restartScheduledDelayedEvent",
value: function restartScheduledDelayedEvent(delayId) {
return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC4157UpdateDelayedEvent, {
delay_id: delayId,
action: _UpdateDelayedEventAction.UpdateDelayedEventAction.Restart
});
}
/**
* @experimental This currently relies on an unstable MSC (MSC4157).
*/
}, {
key: "sendScheduledDelayedEvent",
value: function sendScheduledDelayedEvent(delayId) {
return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC4157UpdateDelayedEvent, {
delay_id: delayId,
action: _UpdateDelayedEventAction.UpdateDelayedEventAction.Send
});
}
/**
* Sends a to-device event.
* @param {string} eventType The type of events being sent.
* @param {boolean} encrypted Whether to encrypt the message contents.
* @param {Object} contentMap A map from user IDs to device IDs to message contents.
* @returns {Promise<ISendToDeviceFromWidgetResponseData>} Resolves when complete.
*/
}, {
key: "sendToDevice",
value: function sendToDevice(eventType, encrypted, contentMap) {
return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SendToDevice, {
type: eventType,
encrypted: encrypted,
messages: contentMap
});
}
}, {
key: "readRoomAccountData",
value: function readRoomAccountData(eventType, roomIds) {
var data = {
type: eventType
};
if (roomIds) {
if (roomIds.includes(_Symbols.Symbols.AnyRoom)) {
data.room_ids = _Symbols.Symbols.AnyRoom;
} else {
data.room_ids = roomIds;
}
}
return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.BeeperReadRoomAccountData, data).then(function (r) {
return r.events;
});
}
}, {
key: "readRoomEvents",
value: function readRoomEvents(eventType, limit, msgtype, roomIds, since) {
var data = {
type: eventType,
msgtype: msgtype
};
if (limit !== undefined) {
data.limit = limit;
}
if (roomIds) {
if (roomIds.includes(_Symbols.Symbols.AnyRoom)) {
data.room_ids = _Symbols.Symbols.AnyRoom;
} else {
data.room_ids = roomIds;
}
}
if (since) {
data.since = since;
}
return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC2876ReadEvents, data).then(function (r) {
return r.events;
});
}
/**
* Reads all related events given a known eventId.
* @param eventId The id of the parent event to be read.
* @param roomId The room to look within. When undefined, the user's currently
* viewed room.
* @param relationType The relationship type of child events to search for.
* When undefined, all relations are returned.
* @param eventType The event type of child events to search for. When undefined,
* all related events are returned.
* @param limit The maximum number of events to retrieve per room. If not
* supplied, the server will apply a default limit.
* @param from The pagination token to start returning results from, as
* received from a previous call. If not supplied, results start at the most
* recent topological event known to the server.
* @param to The pagination token to stop returning results at. If not
* supplied, results continue up to limit or until there are no more events.
* @param direction The direction to search for according to MSC3715.
* @returns Resolves to the room relations.
*/
}, {
key: "readEventRelations",
value: (function () {
var _readEventRelations = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(eventId, roomId, relationType, eventType, limit, from, to, direction) {
var versions, data;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return this.getClientVersions();
case 2:
versions = _context.sent;
if (versions.includes(_ApiVersion.UnstableApiVersion.MSC3869)) {
_context.next = 5;
break;
}
throw new Error("The read_relations action is not supported by the client.");
case 5:
data = {
event_id: eventId,
rel_type: relationType,
event_type: eventType,
room_id: roomId,
to: to,
from: from,
limit: limit,
direction: direction
};
return _context.abrupt("return", this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC3869ReadRelations, data));
case 7:
case "end":
return _context.stop();
}
}, _callee, this);
}));
function readEventRelations(_x, _x2, _x3, _x4, _x5, _x6, _x7, _x8) {
return _readEventRelations.apply(this, arguments);
}
return readEventRelations;
}())
}, {
key: "readStateEvents",
value: function readStateEvents(eventType, limit, stateKey, roomIds) {
var data = {
type: eventType,
state_key: stateKey === undefined ? true : stateKey
};
if (limit !== undefined) {
data.limit = limit;
}
if (roomIds) {
if (roomIds.includes(_Symbols.Symbols.AnyRoom)) {
data.room_ids = _Symbols.Symbols.AnyRoom;
} else {
data.room_ids = roomIds;
}
}
return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC2876ReadEvents, data).then(function (r) {
return r.events;
});
}
/**
* Sets a button as disabled or enabled on the modal widget. Buttons are enabled by default.
* @param {ModalButtonID} buttonId The button ID to enable/disable.
* @param {boolean} isEnabled Whether or not the button is enabled.
* @returns {Promise<void>} Resolves when complete.
* @throws Throws if the button cannot be disabled, or the client refuses to disable the button.
*/
}, {
key: "setModalButtonEnabled",
value: function setModalButtonEnabled(buttonId, isEnabled) {
if (buttonId === _ModalWidgetActions.BuiltInModalButtonID.Close) {
throw new Error("The close button cannot be disabled");
}
return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SetModalButtonEnabled, {
button: buttonId,
enabled: isEnabled
}).then();
}
/**
* Attempts to navigate the client to the given URI. This can only be called with Matrix URIs
* (currently only matrix.to, but in future a Matrix URI scheme will be defined).
* @param {string} uri The URI to navigate to.
* @returns {Promise<void>} Resolves when complete.
* @throws Throws if the URI is invalid or cannot be processed.
* @experimental This currently relies on an unstable MSC (MSC2931).
*/
}, {
key: "navigateTo",
value: function navigateTo(uri) {
if (!uri || !uri.startsWith("https://matrix.to/#")) {
throw new Error("Invalid matrix.to URI");
}
return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC2931Navigate, {
uri: uri
}).then();
}
/**
* Starts watching for TURN servers, yielding an initial set of credentials as soon as possible,
* and thereafter yielding new credentials whenever the previous ones expire.
* @yields {ITurnServer} The TURN server URIs and credentials currently available to the widget.
*/
}, {
key: "getTurnServers",
value: function getTurnServers() {
var _this = this;
return _wrapAsyncGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
var setTurnServer, onUpdateTurnServers;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
onUpdateTurnServers = /*#__PURE__*/function () {
var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(ev) {
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
ev.preventDefault();
setTurnServer(ev.detail.data);
_this.transport.reply(ev.detail, {});
case 3:
case "end":
return _context2.stop();
}
}, _callee2);
}));
return function onUpdateTurnServers(_x9) {
return _ref.apply(this, arguments);
};
}(); // Start listening for updates before we even start watching, to catch
// TURN data that is sent immediately
_this.on("action:".concat(_WidgetApiAction.WidgetApiToWidgetAction.UpdateTurnServers), onUpdateTurnServers);
// Only send the 'watch' action if we aren't already watching
if (!(_this.turnServerWatchers === 0)) {
_context3.next = 12;
break;
}
_context3.prev = 3;
_context3.next = 6;
return _awaitAsyncGenerator(_this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.WatchTurnServers, {}));
case 6:
_context3.next = 12;
break;
case 8:
_context3.prev = 8;
_context3.t0 = _context3["catch"](3);
_this.off("action:".concat(_WidgetApiAction.WidgetApiToWidgetAction.UpdateTurnServers), onUpdateTurnServers);
throw _context3.t0;
case 12:
_this.turnServerWatchers++;
_context3.prev = 13;
case 14:
if (!true) {
_context3.next = 21;
break;
}
_context3.next = 17;
return _awaitAsyncGenerator(new Promise(function (resolve) {
return setTurnServer = resolve;
}));
case 17:
_context3.next = 19;
return _context3.sent;
case 19:
_context3.next = 14;
break;
case 21:
_context3.prev = 21;
// The loop was broken by the caller - clean up
_this.off("action:".concat(_WidgetApiAction.WidgetApiToWidgetAction.UpdateTurnServers), onUpdateTurnServers);
// Since sending the 'unwatch' action will end updates for all other
// consumers, only send it if we're the only consumer remaining
_this.turnServerWatchers--;
if (!(_this.turnServerWatchers === 0)) {
_context3.next = 27;
break;
}
_context3.next = 27;
return _awaitAsyncGenerator(_this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.UnwatchTurnServers, {}));
case 27:
return _context3.finish(21);
case 28:
case "end":
return _context3.stop();
}
}, _callee3, null, [[3, 8], [13,, 21, 28]]);
}))();
}
/**
* Search for users in the user directory.
* @param searchTerm The term to search for.
* @param limit The maximum number of results to return. If not supplied, the
* @returns Resolves to the search results.
*/
}, {
key: "searchUserDirectory",
value: (function () {
var _searchUserDirectory = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(searchTerm, limit) {
var versions, data;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return this.getClientVersions();
case 2:
versions = _context4.sent;
if (versions.includes(_ApiVersion.UnstableApiVersion.MSC3973)) {
_context4.next = 5;
break;
}
throw new Error("The user_directory_search action is not supported by the client.");
case 5:
data = {
search_term: searchTerm,
limit: limit
};
return _context4.abrupt("return", this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC3973UserDirectorySearch, data));
case 7:
case "end":
return _context4.stop();
}
}, _callee4, this);
}));
function searchUserDirectory(_x0, _x1) {
return _searchUserDirectory.apply(this, arguments);
}
return searchUserDirectory;
}()
/**
* Get the config for the media repository.
* @returns Promise which resolves with an object containing the config.
*/
)
}, {
key: "getMediaConfig",
value: (function () {
var _getMediaConfig = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
var versions, data;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
_context5.next = 2;
return this.getClientVersions();
case 2:
versions = _context5.sent;
if (versions.includes(_ApiVersion.UnstableApiVersion.MSC4039)) {
_context5.next = 5;
break;
}
throw new Error("The get_media_config action is not supported by the client.");
case 5:
data = {};
return _context5.abrupt("return", this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC4039GetMediaConfigAction, data));
case 7:
case "end":
return _context5.stop();
}
}, _callee5, this);
}));
function getMediaConfig() {
return _getMediaConfig.apply(this, arguments);
}
return getMediaConfig;
}()
/**
* Discover the RTC transports (e.g. SFUs, TURN servers) the homeserver
* supports (MSC4515 / MSC4143).
* @returns Promise which resolves with the available RTC transports.
*/
)
}, {
key: "getRtcTransports",
value: (function () {
var _getRtcTransports = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
var versions, data;
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
_context6.next = 2;
return this.getClientVersions();
case 2:
versions = _context6.sent;
if (versions.includes(_ApiVersion.UnstableApiVersion.MSC4515)) {
_context6.next = 5;
break;
}
throw new Error("The get_rtc_transports action is not supported by the client.");
case 5:
data = {};
return _context6.abrupt("return", this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC4515GetRtcTransports, data));
case 7:
case "end":
return _context6.stop();
}
}, _callee6, this);
}));
function getRtcTransports() {
return _getRtcTransports.apply(this, arguments);
}
return getRtcTransports;
}()
/**
* Upload a file to the media repository on the homeserver.
* @param file - The object to upload. Something that can be sent to
* XMLHttpRequest.send (typically a File).
* @returns Resolves to the location of the uploaded file.
*/
)
}, {
key: "uploadFile",
value: (function () {
var _uploadFile = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(file) {
var versions, data;
return _regeneratorRuntime().wrap(function _callee7$(_context7) {
while (1) switch (_context7.prev = _context7.next) {
case 0:
_context7.next = 2;
return this.getClientVersions();
case 2:
versions = _context7.sent;
if (versions.includes(_ApiVersion.UnstableApiVersion.MSC4039)) {
_context7.next = 5;
break;
}
throw new Error("The upload_file action is not supported by the client.");
case 5:
data = {
file: file
};
return _context7.abrupt("return", this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC4039UploadFileAction, data));
case 7:
case "end":
return _context7.stop();
}
}, _callee7, this);
}));
function uploadFile(_x10) {
return _uploadFile.apply(this, arguments);
}
return uploadFile;
}()
/**
* Download a file from the media repository on the homeserver.
* @param contentUri - MXC URI of the file to download.
* @returns Resolves to the contents of the file.
*/
)
}, {
key: "downloadFile",
value: (function () {
var _downloadFile = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(contentUri) {
var versions, data;
return _regeneratorRuntime().wrap(function _callee8$(_context8) {
while (1) switch (_context8.prev = _context8.next) {
case 0:
_context8.next = 2;
return this.getClientVersions();
case 2:
versions = _context8.sent;
if (versions.includes(_ApiVersion.UnstableApiVersion.MSC4039)) {
_context8.next = 5;
break;
}
throw new Error("The download_file action is not supported by the client.");
case 5:
data = {
content_uri: contentUri
};
return _context8.abrupt("return", this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC4039DownloadFileAction, data));
case 7:
case "end":
return _context8.stop();
}
}, _callee8, this);
}));
function downloadFile(_x11) {
return _downloadFile.apply(this, arguments);
}
return downloadFile;
}()
/**
* Obtains a JWT for a LiveKit SFU, by asking the client to call the homeserver's
* `/rtc/livekit/get_token` endpoint on the widget's behalf.
* @param data The request data, which the client uses as the request body verbatim.
* @returns Resolves to the response body of the endpoint, verbatim.
* @see {@link https://github.com/matrix-org/matrix-spec-proposals/pull/4533|MSC4533}
*/
)
}, {
key: "getRtcLivekitToken",
value: (function () {
var _getRtcLivekitToken = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(data) {
var versions;
return _regeneratorRuntime().wrap(function _callee9$(_context9) {
while (1) switch (_context9.prev = _context9.next) {
case 0:
_context9.next = 2;
return this.getClientVersions();
case 2:
versions = _context9.sent;
if (versions.includes(_ApiVersion.UnstableApiVersion.MSC4533)) {
_context9.next = 5;
break;
}
throw new Error("The rtc_livekit_get_token action is not supported by the client.");
case 5:
return _context9.abrupt("return", this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC4533RtcLivekitGetToken, data));
case 6:
case "end":
return _context9.stop();
}
}, _callee9, this);
}));
function getRtcLivekitToken(_x12) {
return _getRtcLivekitToken.apply(this, arguments);
}
return getRtcLivekitToken;
}()
/**
* Hands a MatrixRTC session's delayed leave event over to the server, by asking the
* client to call the homeserver's `/rtc/livekit/delegate_delayed_leave` endpoint on
* the widget's behalf.
*
* Homeservers may not support this endpoint, in which case the request rejects with a
* {@link WidgetApiResponseError} whose `matrix_api_error` reports an HTTP 404 with
* `M_UNRECOGNIZED`. The widget is then responsible for refreshing the delayed leave
* event itself.
* @param data The request data, which the client uses as the request body verbatim.
* @returns Resolves to the response body of the endpoint, verbatim.
* @see {@link https://github.com/matrix-org/matrix-spec-proposals/pull/4533|MSC4533}
*/
)
}, {
key: "delegateRtcLivekitDelayedLeave",
value: (function () {
var _delegateRtcLivekitDelayedLeave = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee0(data) {
var versions;
return _regeneratorRuntime().wrap(function _callee0$(_context0) {
while (1) switch (_context0.prev = _context0.next) {
case 0:
_context0.next = 2;
return this.getClientVersions();
case 2:
versions = _context0.sent;
if (versions.includes(_ApiVersion.UnstableApiVersion.MSC4533)) {
_context0.next = 5;
break;
}
throw new Error("The rtc_livekit_delegate_delayed_leave action is not supported by the client.");
case 5:
return _context0.abrupt("return", this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC4533RtcLivekitDelegateDelayedLeave, data));
case 6:
case "end":
return _context0.stop();
}
}, _callee0, this);
}));
function delegateRtcLivekitDelayedLeave(_x13) {
return _delegateRtcLivekitDelayedLeave.apply(this, arguments);
}
return delegateRtcLivekitDelayedLeave;
}()
/**
* Starts the communication channel. This should be done early to ensure
* that messages are not missed. Communication can only be stopped by the client.
*/
)
}, {
key: "start",
value: function start() {
var _this5 = this;
this.transport.start();
this.getClientVersions().then(function (v) {
if (v.includes(_ApiVersion.UnstableApiVersion.MSC2974)) {
_this5.supportsMSC2974Renegotiate = true;
}
});
}
}, {
key: "handleMessage",
value: function handleMessage(ev) {
var actionEv = new CustomEvent("action:".concat(ev.detail.action), {
detail: ev.detail,
cancelable: true
});
this.emit("action:".concat(ev.detail.action), actionEv);
if (!actionEv.defaultPrevented) {
switch (ev.detail.action) {
case _WidgetApiAction.WidgetApiToWidgetAction.SupportedApiVersions:
return this.replyVersions(ev.detail);
case _WidgetApiAction.WidgetApiToWidgetAction.Capabilities:
return this.handleCapabilities(ev.detail);
case _WidgetApiAction.WidgetApiToWidgetAction.UpdateVisibility:
return this.transport.reply(ev.detail, {});
// ack to avoid error spam
case _WidgetApiAction.WidgetApiToWidgetAction.NotifyCapabilities:
return this.transport.reply(ev.detail, {});
// ack to avoid error spam
default:
return this.transport.reply(ev.detail, {
error: {
message: "Unknown or unsupported to-widget action: " + ev.detail.action
}
});
}
}
}
}, {
key: "replyVersions",
value: function replyVersions(request) {
this.transport.reply(request, {
supported_versions: _ApiVersion.CurrentApiVersions
});
}
}, {
key: "getClientVersions",
value: function getClientVersions() {
var _this6 = this;
if (Array.isArray(this.cachedClientVersions)) {
return Promise.resolve(this.cachedClientVersions);
}
return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SupportedApiVersions, {}).then(function (r) {
_this6.cachedClientVersions = r.supported_versions;
return r.supported_versions;
})["catch"](function (e) {
console.warn("non-fatal error getting supported client versions: ", e);
return [];
});
}
}, {
key: "handleCapabilities",
value: function handleCapabilities(request) {
var _this7 = this;
if (this.capabilitiesFinished) {
return this.transport.reply(request, {
error: {
message: "Capability negotiation already completed"
}
});
}
// See if we can expect a capabilities notification or not
return this.getClientVersions().then(function (v) {
if (v.includes(_ApiVersion.UnstableApiVersion.MSC2871)) {
_this7.once("action:".concat(_WidgetApiAction.WidgetApiToWidgetAction.NotifyCapabilities), function (ev) {
_this7.approvedCapabilities = ev.detail.data.approved;
_this7.emit("ready");
});
} else {
// if we can't expect notification, we're as done as we can be
_this7.emit("ready");
}
// in either case, reply to that capabilities request
_this7.capabilitiesFinished = true;
return _this7.transport.reply(request, {
capabilities: _this7.requestedCapabilities
});
});
}
}]);
return WidgetApi;
}(_events.EventEmitter);
exports.WidgetApi = WidgetApi;
//# sourceMappingURL=WidgetApi.js.map