@monterosa/sdk-interact-kit 0.17.1-rc.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +1 -0
  2. package/dist/index.cjs.js +2709 -0
  3. package/dist/index.cjs.js.map +1 -0
  4. package/dist/index.esm2017.js +1894 -0
  5. package/dist/index.esm2017.js.map +1 -0
  6. package/dist/index.esm5.js +2673 -0
  7. package/dist/index.esm5.js.map +1 -0
  8. package/dist/jest/helpers/language.d.ts +12 -0
  9. package/dist/src/api.d.ts +38 -0
  10. package/dist/src/core/connect/api.d.ts +16 -0
  11. package/dist/src/core/connect/connect_impl.d.ts +34 -0
  12. package/dist/src/core/connect/index.d.ts +12 -0
  13. package/dist/src/core/connect/public-types.d.ts +64 -0
  14. package/dist/src/core/connection_health/connection_health_impl.d.ts +21 -0
  15. package/dist/src/core/connection_health/index.d.ts +24 -0
  16. package/dist/src/core/connection_health/public-types.d.ts +34 -0
  17. package/dist/src/core/element/answer.d.ts +66 -0
  18. package/dist/src/core/element/api.d.ts +235 -0
  19. package/dist/src/core/element/context.d.ts +18 -0
  20. package/dist/src/core/element/element_impl.d.ts +62 -0
  21. package/dist/src/core/element/factory.d.ts +21 -0
  22. package/dist/src/core/element/index.d.ts +15 -0
  23. package/dist/src/core/element/public-types.d.ts +228 -0
  24. package/dist/src/core/element/types.d.ts +93 -0
  25. package/dist/src/core/event/api.d.ts +84 -0
  26. package/dist/src/core/event/context.d.ts +16 -0
  27. package/dist/src/core/event/event_impl.d.ts +53 -0
  28. package/dist/src/core/event/factory.d.ts +22 -0
  29. package/dist/src/core/event/index.d.ts +13 -0
  30. package/dist/src/core/event/internal.d.ts +12 -0
  31. package/dist/src/core/event/public-types.d.ts +119 -0
  32. package/dist/src/core/event/types.d.ts +32 -0
  33. package/dist/src/core/index.d.ts +15 -0
  34. package/dist/src/core/project/api.d.ts +36 -0
  35. package/dist/src/core/project/constants.d.ts +11 -0
  36. package/dist/src/core/project/context.d.ts +14 -0
  37. package/dist/src/core/project/factory.d.ts +16 -0
  38. package/dist/src/core/project/index.d.ts +13 -0
  39. package/dist/src/core/project/internal.d.ts +12 -0
  40. package/dist/src/core/project/project_impl.d.ts +51 -0
  41. package/dist/src/core/project/public-types.d.ts +158 -0
  42. package/dist/src/index.d.ts +17 -0
  43. package/dist/src/services/http_request.d.ts +47 -0
  44. package/dist/src/types.d.ts +18 -0
  45. package/dist/src/utils/calculate_percentage.d.ts +11 -0
  46. package/dist/src/utils/locale.d.ts +20 -0
  47. package/package.json +50 -0
@@ -0,0 +1,2709 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var sdkConnectKit = require('@monterosa/sdk-connect-kit');
6
+ var sdkUtil = require('@monterosa/sdk-util');
7
+ var sdkCore = require('@monterosa/sdk-core');
8
+
9
+ /*! *****************************************************************************
10
+ Copyright (c) Microsoft Corporation.
11
+
12
+ Permission to use, copy, modify, and/or distribute this software for any
13
+ purpose with or without fee is hereby granted.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
16
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
17
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
18
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
19
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
20
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
21
+ PERFORMANCE OF THIS SOFTWARE.
22
+ ***************************************************************************** */
23
+ /* global Reflect, Promise */
24
+
25
+ var extendStatics = function(d, b) {
26
+ extendStatics = Object.setPrototypeOf ||
27
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
29
+ return extendStatics(d, b);
30
+ };
31
+
32
+ function __extends(d, b) {
33
+ if (typeof b !== "function" && b !== null)
34
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
35
+ extendStatics(d, b);
36
+ function __() { this.constructor = d; }
37
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
38
+ }
39
+
40
+ var __assign = function() {
41
+ __assign = Object.assign || function __assign(t) {
42
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
43
+ s = arguments[i];
44
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
45
+ }
46
+ return t;
47
+ };
48
+ return __assign.apply(this, arguments);
49
+ };
50
+
51
+ function __awaiter(thisArg, _arguments, P, generator) {
52
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
53
+ return new (P || (P = Promise))(function (resolve, reject) {
54
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
55
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
56
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
57
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
58
+ });
59
+ }
60
+
61
+ function __generator(thisArg, body) {
62
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
63
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
64
+ function verb(n) { return function (v) { return step([n, v]); }; }
65
+ function step(op) {
66
+ if (f) throw new TypeError("Generator is already executing.");
67
+ while (_) try {
68
+ 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;
69
+ if (y = 0, t) op = [op[0] & 2, t.value];
70
+ switch (op[0]) {
71
+ case 0: case 1: t = op; break;
72
+ case 4: _.label++; return { value: op[1], done: false };
73
+ case 5: _.label++; y = op[1]; op = [0]; continue;
74
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
75
+ default:
76
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
77
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
78
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
79
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
80
+ if (t[2]) _.ops.pop();
81
+ _.trys.pop(); continue;
82
+ }
83
+ op = body.call(thisArg, _);
84
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
85
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
86
+ }
87
+ }
88
+
89
+ function __values(o) {
90
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
91
+ if (m) return m.call(o);
92
+ if (o && typeof o.length === "number") return {
93
+ next: function () {
94
+ if (o && i >= o.length) o = void 0;
95
+ return { value: o && o[i++], done: !o };
96
+ }
97
+ };
98
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
99
+ }
100
+
101
+ function __spreadArray(to, from) {
102
+ for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
103
+ to[j] = from[i];
104
+ return to;
105
+ }
106
+
107
+ function __asyncValues(o) {
108
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
109
+ var m = o[Symbol.asyncIterator], i;
110
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
111
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
112
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
113
+ }
114
+
115
+ /**
116
+ * @license
117
+ * api.ts
118
+ * interact-kit
119
+ *
120
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2023-05-24
121
+ * Copyright © 2023 Monterosa. All rights reserved.
122
+ *
123
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
124
+ */
125
+ /**
126
+ * Sign in the user to submit data that requires a verified user.
127
+ *
128
+ * @example
129
+ * ```javascript
130
+ * try {
131
+ * const sdk = getSdk();
132
+ * const userId = "b236e331-ee62-4238-90d0-47588c7facdc";
133
+ * const timestamp = 1684934960;
134
+ * const signature = "9ABC4892838DC13986A63B736E95A7D99DF95C72";
135
+ *
136
+ * await login(sdk, userId, timestamp, signature);
137
+ *
138
+ * console.log('logged in successfully!');
139
+ * } catch (err) {
140
+ * console.log(err)
141
+ * }
142
+ * ```
143
+ *
144
+ * @param sdk - Monterosa SDK instance
145
+ * @param userId - The unique user UUID
146
+ * @param timestamp - The timecode when the signature was generated
147
+ * @param signature - A unique identifier that serves as proof of the user's authenticity.
148
+ * The signature must only contain the following characters: 0-9, a-z, A-Z, and must be uppercased
149
+ * @returns A Promise that resolves with `void` when the login is successful, otherwise it rejects.
150
+ */
151
+ function login(sdk, userId, timestamp, signature) {
152
+ return __awaiter(this, void 0, void 0, function () {
153
+ var connect;
154
+ return __generator(this, function (_a) {
155
+ switch (_a.label) {
156
+ case 0: return [4 /*yield*/, sdkConnectKit.getConnect(sdk.options.host)];
157
+ case 1:
158
+ connect = _a.sent();
159
+ return [2 /*return*/, sdkConnectKit.login(connect, userId, timestamp, signature)];
160
+ }
161
+ });
162
+ });
163
+ }
164
+
165
+ /**
166
+ * @license
167
+ * public-types.ts
168
+ * interact-kit
169
+ *
170
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-11-24
171
+ * Copyright © 2022 Monterosa. All rights reserved.
172
+ *
173
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
174
+ */
175
+ /**
176
+ * @internal
177
+ */
178
+ exports.State = void 0;
179
+ (function (State) {
180
+ State["Ok"] = "ok";
181
+ State["Error"] = "error";
182
+ })(exports.State || (exports.State = {}));
183
+ /**
184
+ * @internal
185
+ */
186
+ exports.Klass = void 0;
187
+ (function (Klass) {
188
+ Klass["Listings"] = "listings";
189
+ Klass["History"] = "history";
190
+ Klass["Create"] = "create";
191
+ Klass["Revoke"] = "revoke";
192
+ Klass["Stop"] = "stop";
193
+ Klass["Reveal"] = "reveal";
194
+ Klass["Poll"] = "p";
195
+ Klass["Feedback"] = "fb";
196
+ Klass["Eoc"] = "eoc";
197
+ Klass["Vote"] = "v";
198
+ })(exports.Klass || (exports.Klass = {}));
199
+ /**
200
+ * @internal
201
+ */
202
+ exports.Channel = void 0;
203
+ (function (Channel) {
204
+ Channel["Poll"] = "p";
205
+ Channel["Live"] = "l";
206
+ })(exports.Channel || (exports.Channel = {}));
207
+
208
+ /**
209
+ * @license
210
+ * connect_impl.ts
211
+ * interact-kit
212
+ *
213
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-11-24
214
+ * Copyright © 2022 Monterosa. All rights reserved.
215
+ *
216
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
217
+ */
218
+ var ConnectImpl = /** @class */ (function (_super) {
219
+ __extends(ConnectImpl, _super);
220
+ function ConnectImpl(host) {
221
+ var _this = _super.call(this) || this;
222
+ _this.host = host;
223
+ _this._state = exports.State.Ok;
224
+ _this._enmasse = null;
225
+ return _this;
226
+ }
227
+ Object.defineProperty(ConnectImpl.prototype, "state", {
228
+ get: function () {
229
+ return this._state;
230
+ },
231
+ set: function (state) {
232
+ if (state === this._state) {
233
+ return;
234
+ }
235
+ this._state = state;
236
+ this.emit('state', this._state);
237
+ },
238
+ enumerable: false,
239
+ configurable: true
240
+ });
241
+ Object.defineProperty(ConnectImpl.prototype, "enmasse", {
242
+ get: function () {
243
+ if (this._enmasse === null) {
244
+ throw new Error('Connect is not initialised, init() method should be called first.');
245
+ }
246
+ return this._enmasse;
247
+ },
248
+ set: function (enmasse) {
249
+ this._enmasse = enmasse;
250
+ },
251
+ enumerable: false,
252
+ configurable: true
253
+ });
254
+ ConnectImpl.prototype.init = function () {
255
+ return __awaiter(this, void 0, void 0, function () {
256
+ var _a;
257
+ return __generator(this, function (_b) {
258
+ switch (_b.label) {
259
+ case 0:
260
+ _a = this;
261
+ return [4 /*yield*/, sdkConnectKit.getConnect(this.host)];
262
+ case 1:
263
+ _a.enmasse = _b.sent();
264
+ this.enmasse.on('message', this.handleMessage.bind(this));
265
+ this.enmasse.on('state', this.handleState.bind(this));
266
+ return [2 /*return*/];
267
+ }
268
+ });
269
+ });
270
+ };
271
+ ConnectImpl.prototype.connect = function () {
272
+ return __awaiter(this, void 0, void 0, function () {
273
+ return __generator(this, function (_a) {
274
+ switch (_a.label) {
275
+ case 0: return [4 /*yield*/, sdkConnectKit.connect(this.enmasse)];
276
+ case 1:
277
+ _a.sent();
278
+ return [2 /*return*/];
279
+ }
280
+ });
281
+ });
282
+ };
283
+ ConnectImpl.prototype.disconnect = function () {
284
+ sdkConnectKit.disconnect(this.enmasse);
285
+ };
286
+ ConnectImpl.prototype.subscribeProject = function (id) {
287
+ return __awaiter(this, void 0, void 0, function () {
288
+ return __generator(this, function (_a) {
289
+ switch (_a.label) {
290
+ case 0: return [4 /*yield*/, sdkConnectKit.subscribe(this.enmasse, exports.Channel.Live + "-" + id)];
291
+ case 1:
292
+ _a.sent();
293
+ return [2 /*return*/];
294
+ }
295
+ });
296
+ });
297
+ };
298
+ ConnectImpl.prototype.unsubscribeProject = function (id) {
299
+ sdkConnectKit.unsubscribe(this.enmasse, exports.Channel.Live + "-" + id);
300
+ };
301
+ ConnectImpl.prototype.subscribeEvent = function (id) {
302
+ return __awaiter(this, void 0, void 0, function () {
303
+ return __generator(this, function (_a) {
304
+ switch (_a.label) {
305
+ case 0: return [4 /*yield*/, Promise.all([
306
+ sdkConnectKit.subscribe(this.enmasse, exports.Channel.Live + "-" + id),
307
+ sdkConnectKit.subscribe(this.enmasse, exports.Channel.Poll + "-" + id),
308
+ ])];
309
+ case 1:
310
+ _a.sent();
311
+ return [2 /*return*/];
312
+ }
313
+ });
314
+ });
315
+ };
316
+ ConnectImpl.prototype.unsubscribeEvent = function (id) {
317
+ sdkConnectKit.unsubscribe(this.enmasse, exports.Channel.Live + "-" + id);
318
+ sdkConnectKit.unsubscribe(this.enmasse, exports.Channel.Poll + "-" + id);
319
+ };
320
+ ConnectImpl.prototype.sendVote = function (eventId, pollId, answer) {
321
+ sdkConnectKit.send(this.enmasse, exports.Channel.Poll + "-" + eventId, exports.Klass.Vote, [
322
+ pollId,
323
+ answer,
324
+ '',
325
+ ]);
326
+ };
327
+ ConnectImpl.prototype.handleMessage = function (message) {
328
+ var klass = message.klass, data = message.body, channel = message.channel;
329
+ var id = channel.substring(channel.indexOf('-') + 1);
330
+ this.emit('message', {
331
+ id: id,
332
+ klass: klass,
333
+ data: data,
334
+ });
335
+ };
336
+ ConnectImpl.prototype.handleState = function (state) {
337
+ var args = [];
338
+ for (var _i = 1; _i < arguments.length; _i++) {
339
+ args[_i - 1] = arguments[_i];
340
+ }
341
+ switch (state) {
342
+ case sdkConnectKit.ConnState.Disconnected:
343
+ this.state = exports.State.Error;
344
+ break;
345
+ case sdkConnectKit.ConnState.Connecting: {
346
+ var attempt = args[0];
347
+ if (attempt > 1) {
348
+ this.state = exports.State.Error;
349
+ }
350
+ break;
351
+ }
352
+ case sdkConnectKit.ConnState.Connected:
353
+ this.state = exports.State.Ok;
354
+ break;
355
+ }
356
+ };
357
+ return ConnectImpl;
358
+ }(sdkUtil.Emitter));
359
+
360
+ /**
361
+ * @license
362
+ * api.ts
363
+ * interact-kit
364
+ *
365
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-11-24
366
+ * Copyright © 2022 Monterosa. All rights reserved.
367
+ *
368
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
369
+ */
370
+ var getConnectMemoized = sdkUtil.memoizePromise(function (host) { return __awaiter(void 0, void 0, void 0, function () {
371
+ var connect;
372
+ return __generator(this, function (_a) {
373
+ switch (_a.label) {
374
+ case 0:
375
+ connect = new ConnectImpl(host);
376
+ return [4 /*yield*/, connect.init()];
377
+ case 1:
378
+ _a.sent();
379
+ return [4 /*yield*/, connect.connect()];
380
+ case 2:
381
+ _a.sent();
382
+ return [2 /*return*/, connect];
383
+ }
384
+ });
385
+ }); }, function (host) { return host; });
386
+ /**
387
+ * @internal
388
+ */
389
+ function getConnect(host) {
390
+ return getConnectMemoized(host);
391
+ }
392
+
393
+ /**
394
+ * @license
395
+ * public-types.ts
396
+ * interact-kit
397
+ *
398
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-03-24
399
+ * Copyright © 2022 Monterosa. All rights reserved.
400
+ *
401
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
402
+ */
403
+ /**
404
+ * Provides states of the connection health
405
+ */
406
+ exports.ConnectionHealthState = void 0;
407
+ (function (ConnectionHealthState) {
408
+ /**
409
+ * The client is connected and the connection is healthy
410
+ */
411
+ ConnectionHealthState["Ok"] = "ok";
412
+ /**
413
+ * The client is either trying to establish a connection but failing, or
414
+ * the client has been explicetily {@link @monterosa/sdk-connect-kit#disconnect() | disconnected}
415
+ */
416
+ ConnectionHealthState["Error"] = "error";
417
+ })(exports.ConnectionHealthState || (exports.ConnectionHealthState = {}));
418
+
419
+ /**
420
+ * @license
421
+ * connection_health_impl.ts
422
+ * interact-kit
423
+ *
424
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-02-15
425
+ * Copyright © 2022 Monterosa. All rights reserved.
426
+ *
427
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
428
+ */
429
+ var ConnectionHealthImpl = /** @class */ (function (_super) {
430
+ __extends(ConnectionHealthImpl, _super);
431
+ function ConnectionHealthImpl(connect) {
432
+ var _this = _super.call(this) || this;
433
+ _this.connect = connect;
434
+ _this._state = exports.ConnectionHealthState.Ok;
435
+ _this.connect.on('state', _this.handleState.bind(_this));
436
+ return _this;
437
+ }
438
+ Object.defineProperty(ConnectionHealthImpl.prototype, "state", {
439
+ get: function () {
440
+ return this._state;
441
+ },
442
+ set: function (state) {
443
+ this._state = state;
444
+ this.emit('state', state);
445
+ },
446
+ enumerable: false,
447
+ configurable: true
448
+ });
449
+ ConnectionHealthImpl.prototype.handleState = function () {
450
+ switch (this.connect.state) {
451
+ default:
452
+ case exports.State.Ok:
453
+ this.state = exports.ConnectionHealthState.Ok;
454
+ break;
455
+ case exports.State.Error:
456
+ this.state = exports.ConnectionHealthState.Error;
457
+ break;
458
+ }
459
+ };
460
+ return ConnectionHealthImpl;
461
+ }(sdkUtil.Emitter));
462
+
463
+ /**
464
+ * @license
465
+ * index.ts
466
+ * interact-kit
467
+ *
468
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-02-15
469
+ * Copyright © 2022 Monterosa. All rights reserved.
470
+ *
471
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
472
+ */
473
+ var getConnectionHealthMemoized = sdkUtil.memoizePromise(function (sdk) { return __awaiter(void 0, void 0, void 0, function () {
474
+ var connect, connectionHealth;
475
+ return __generator(this, function (_a) {
476
+ switch (_a.label) {
477
+ case 0: return [4 /*yield*/, getConnect(sdk.options.host)];
478
+ case 1:
479
+ connect = _a.sent();
480
+ connectionHealth = new ConnectionHealthImpl(connect);
481
+ return [2 /*return*/, connectionHealth];
482
+ }
483
+ });
484
+ }); }, function (sdk) { return sdk.options.host; });
485
+ /**
486
+ * Returns {@link ConnectionHealth | connection health} instance
487
+ */
488
+ function getConnectionHealth(sdk) {
489
+ if (sdk === void 0) { sdk = sdkCore.getSdk(); }
490
+ return getConnectionHealthMemoized(sdk);
491
+ }
492
+ /**
493
+ * Adds an observer for when
494
+ * {@link ConnectionHealth.state | connection health state} changed
495
+ */
496
+ function onConnectionHealthState(connectionHealth, callback) {
497
+ return sdkUtil.subscribe(connectionHealth, 'state', callback);
498
+ }
499
+
500
+ /**
501
+ * @license
502
+ * internal.ts
503
+ * interact-kit
504
+ *
505
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-02-15
506
+ * Copyright © 2022 Monterosa. All rights reserved.
507
+ *
508
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
509
+ */
510
+ function fetchSettings(host, id) {
511
+ return __awaiter(this, void 0, void 0, function () {
512
+ var response, data;
513
+ return __generator(this, function (_a) {
514
+ switch (_a.label) {
515
+ case 0: return [4 /*yield*/, fetch("https://" + host + "/projects/" + id.substring(0, 2) + "/" + id + "/settings.json")];
516
+ case 1:
517
+ response = _a.sent();
518
+ return [4 /*yield*/, response.json()];
519
+ case 2:
520
+ data = _a.sent();
521
+ return [2 /*return*/, data];
522
+ }
523
+ });
524
+ });
525
+ }
526
+
527
+ /**
528
+ * @license
529
+ * constants.ts
530
+ * interact-kit
531
+ *
532
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-06-02
533
+ * Copyright © 2022 Monterosa. All rights reserved.
534
+ *
535
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
536
+ */
537
+ var DEFAULT_IGNORE_TIME = 30;
538
+
539
+ /**
540
+ * @license
541
+ * locale.ts
542
+ * interact-kit
543
+ *
544
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-10-18
545
+ * Copyright © 2022 Monterosa. All rights reserved.
546
+ *
547
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
548
+ */
549
+ /**
550
+ * Converts tag for identifying languages (rfc5646) into ISO language code
551
+ */
552
+ function tagToLanguage(tag) {
553
+ // The tag is split not only by `-` as its stated in the rfc
554
+ // but also by `_` as it is returned by Studio for some locales
555
+ var chunks = tag.split(/[-_]/);
556
+ return chunks[0];
557
+ }
558
+ /**
559
+ * Returns either:
560
+ * * a locale from the list of provided locales that correspond OS locale preferences
561
+ * * or default locale if OS locale doesn't correspond to any from the provided list
562
+ *
563
+ * * @internal
564
+ */
565
+ function getLocale(locales) {
566
+ // The list of user's preferred language tags,
567
+ var languageTags = __spreadArray([
568
+ // where the first item is the user's default language
569
+ navigator.language
570
+ ], navigator.languages);
571
+ // firstly, trying to check if one of languages tag
572
+ // has a full match with passed locales
573
+ for (var _i = 0, languageTags_1 = languageTags; _i < languageTags_1.length; _i++) {
574
+ var tag = languageTags_1[_i];
575
+ if (locales.includes(tag)) {
576
+ // if language tag has a match return it right away
577
+ return tag;
578
+ }
579
+ }
580
+ // secondly, checking if user's language (ISO string)
581
+ // has occurrences in the list of locales
582
+ for (var _a = 0, languageTags_2 = languageTags; _a < languageTags_2.length; _a++) {
583
+ var tag = languageTags_2[_a];
584
+ var userLang = tagToLanguage(tag);
585
+ for (var _b = 0, locales_1 = locales; _b < locales_1.length; _b++) {
586
+ var locale = locales_1[_b];
587
+ var studioLang = tagToLanguage(locale);
588
+ if (studioLang === userLang) {
589
+ // return the first locale that has the same
590
+ // language ISO string as the user language tag
591
+ return locale;
592
+ }
593
+ }
594
+ }
595
+ // if none locales matches users preferred languages tags
596
+ // return default locale
597
+ return locales[0];
598
+ }
599
+ function localise(value, locale) {
600
+ if (Object.prototype.hasOwnProperty.call(value, locale)) {
601
+ return value[locale];
602
+ }
603
+ return value.all;
604
+ }
605
+
606
+ /**
607
+ * @license
608
+ * project_impl.ts
609
+ * interact-kit
610
+ *
611
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-02-15
612
+ * Copyright © 2022 Monterosa. All rights reserved.
613
+ *
614
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
615
+ */
616
+ /**
617
+ * @internal
618
+ */
619
+ var ProjectImpl = /** @class */ (function (_super) {
620
+ __extends(ProjectImpl, _super);
621
+ function ProjectImpl(options, context) {
622
+ var _this = _super.call(this) || this;
623
+ _this.id = options.id;
624
+ _this.host = options.host;
625
+ _this._context = context;
626
+ return _this;
627
+ }
628
+ Object.defineProperty(ProjectImpl.prototype, "context", {
629
+ get: function () {
630
+ return this._context;
631
+ },
632
+ enumerable: false,
633
+ configurable: true
634
+ });
635
+ Object.defineProperty(ProjectImpl.prototype, "embedUrl", {
636
+ get: function () {
637
+ var _a;
638
+ return (_a = this._listings) === null || _a === void 0 ? void 0 : _a.project.embed;
639
+ },
640
+ enumerable: false,
641
+ configurable: true
642
+ });
643
+ Object.defineProperty(ProjectImpl.prototype, "uuid", {
644
+ get: function () {
645
+ var _a;
646
+ return (_a = this._listings) === null || _a === void 0 ? void 0 : _a.project.uuid;
647
+ },
648
+ enumerable: false,
649
+ configurable: true
650
+ });
651
+ Object.defineProperty(ProjectImpl.prototype, "events", {
652
+ get: function () {
653
+ var _a;
654
+ return ((_a = this._listings) === null || _a === void 0 ? void 0 : _a.events) || [];
655
+ },
656
+ enumerable: false,
657
+ configurable: true
658
+ });
659
+ Object.defineProperty(ProjectImpl.prototype, "listings", {
660
+ get: function () {
661
+ return this._listings;
662
+ },
663
+ set: function (value) {
664
+ var _this = this;
665
+ var createdEvents = [];
666
+ var deletedEvents = [];
667
+ if (this._listings) {
668
+ createdEvents = value.events.filter(function (_a) {
669
+ var id = _a.id;
670
+ return !_this._listings.events.some(function (event) { return id === event.id; });
671
+ });
672
+ }
673
+ if (this._listings) {
674
+ deletedEvents = this.listings.events.filter(function (_a) {
675
+ var id = _a.id;
676
+ return !value.events.some(function (event) { return id === event.id; });
677
+ });
678
+ }
679
+ this._listings = __assign({}, value);
680
+ this._locales = this._listings.project.locales
681
+ // clone the array first
682
+ .map(function (locale) { return (__assign({}, locale)); })
683
+ // sort an array so that the default locale is the first
684
+ .sort(function (locale) { return (locale.default ? -1 : 0); })
685
+ // return only keys of the locales
686
+ .map(function (locale) { return locale.key; });
687
+ this._locale = getLocale(this._locales);
688
+ if (createdEvents.length > 0) {
689
+ this.emit('listings_events_created', createdEvents);
690
+ }
691
+ if (deletedEvents.length > 0) {
692
+ this.emit('listings_events_deleted', deletedEvents);
693
+ }
694
+ this.emit('listings');
695
+ },
696
+ enumerable: false,
697
+ configurable: true
698
+ });
699
+ Object.defineProperty(ProjectImpl.prototype, "isLocalisationSupported", {
700
+ get: function () {
701
+ var _a;
702
+ return (_a = this._listings) === null || _a === void 0 ? void 0 : _a.project.is_localisation_supported;
703
+ },
704
+ enumerable: false,
705
+ configurable: true
706
+ });
707
+ Object.defineProperty(ProjectImpl.prototype, "locale", {
708
+ get: function () {
709
+ return this._locale;
710
+ },
711
+ set: function (locale) {
712
+ if (!this.locales.includes(locale)) {
713
+ throw new Error("Unknown locale name \"" + locale + "\"");
714
+ }
715
+ this._locale = locale;
716
+ },
717
+ enumerable: false,
718
+ configurable: true
719
+ });
720
+ Object.defineProperty(ProjectImpl.prototype, "locales", {
721
+ get: function () {
722
+ return this._locales;
723
+ },
724
+ enumerable: false,
725
+ configurable: true
726
+ });
727
+ Object.defineProperty(ProjectImpl.prototype, "fields", {
728
+ get: function () {
729
+ if (this._fields !== undefined) {
730
+ return localise(this._fields, this.locale);
731
+ }
732
+ return {};
733
+ },
734
+ /**
735
+ * Sets custom fields
736
+ *
737
+ * It accepts both Localised<Record<string, unknown>> and Record<string, unknown> to
738
+ * avoid mistyping between setter and getter
739
+ *
740
+ * @internal
741
+ */
742
+ set: function (value) {
743
+ var isUpdate = typeof this._fields !== 'undefined';
744
+ this._fields = __assign({}, value);
745
+ if (isUpdate) {
746
+ this.emit('updated');
747
+ }
748
+ },
749
+ enumerable: false,
750
+ configurable: true
751
+ });
752
+ Object.defineProperty(ProjectImpl.prototype, "extensions", {
753
+ get: function () {
754
+ var _a;
755
+ return (_a = this._listings) === null || _a === void 0 ? void 0 : _a.assets;
756
+ },
757
+ enumerable: false,
758
+ configurable: true
759
+ });
760
+ Object.defineProperty(ProjectImpl.prototype, "historyIgnore", {
761
+ get: function () {
762
+ var _a;
763
+ var value = (_a = this._listings) === null || _a === void 0 ? void 0 : _a.project.history_ignore;
764
+ if (value && value > 0) {
765
+ return value;
766
+ }
767
+ return DEFAULT_IGNORE_TIME;
768
+ },
769
+ enumerable: false,
770
+ configurable: true
771
+ });
772
+ // TODO: must be implemented
773
+ // eslint-disable-next-line
774
+ ProjectImpl.prototype.delete = function () { };
775
+ return ProjectImpl;
776
+ }(sdkUtil.Emitter));
777
+
778
+ /**
779
+ * @license
780
+ * factory.ts
781
+ * interact-kit
782
+ *
783
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-02-15
784
+ * Copyright © 2022 Monterosa. All rights reserved.
785
+ *
786
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
787
+ */
788
+ var projects = new Map();
789
+ var connects = new Map();
790
+ function buildProject(options, context) {
791
+ return __awaiter(this, void 0, void 0, function () {
792
+ var id, host, project, setup, _a, err_1, connect;
793
+ return __generator(this, function (_b) {
794
+ switch (_b.label) {
795
+ case 0:
796
+ id = options.id, host = options.host;
797
+ if (projects.has(id)) {
798
+ return [2 /*return*/, projects.get(id)];
799
+ }
800
+ project = new ProjectImpl(options, context);
801
+ /**
802
+ * Add it to the cache of projects, so that we could find it to populate it
803
+ * with the data when /listings/ message is coming from the Enmasse.
804
+ */
805
+ projects.set(id, project);
806
+ _b.label = 1;
807
+ case 1:
808
+ _b.trys.push([1, 5, , 6]);
809
+ return [4 /*yield*/, setupConnect(host)];
810
+ case 2:
811
+ setup = _b.sent();
812
+ return [4 /*yield*/, setup.subscribeProject(id)];
813
+ case 3:
814
+ _b.sent();
815
+ /**
816
+ * By the time goLive successfully resolved listings must be present
817
+ * in project. If they are not, then there is no /listings/ in the channel's cache.
818
+ * This might be due to either studio is malfunctioning or project id is incorrect.
819
+ */
820
+ if (!project.listings) {
821
+ throw new Error("Unable to fetch project " + id + " listings. Possibly wrong project id.");
822
+ }
823
+ _a = project;
824
+ return [4 /*yield*/, fetchSettings(project.host, project.id)];
825
+ case 4:
826
+ _a.fields = _b.sent();
827
+ return [2 /*return*/, project];
828
+ case 5:
829
+ err_1 = _b.sent();
830
+ /**
831
+ * If anything goes wrong we need to unsubscribe from the Enmasse project's
832
+ * channel by switching it to the offline mode.
833
+ */
834
+ if (connects.has(id)) {
835
+ connect = connects.get(id);
836
+ connect.unsubscribeProject(id);
837
+ }
838
+ /**
839
+ * And project should be removed from the list of cached projects so that
840
+ * it won't be automatically returned upon consequent buildProject call
841
+ */
842
+ projects.delete(id);
843
+ throw err_1;
844
+ case 6: return [2 /*return*/];
845
+ }
846
+ });
847
+ });
848
+ }
849
+ function setupConnect(host) {
850
+ return __awaiter(this, void 0, void 0, function () {
851
+ var connect;
852
+ return __generator(this, function (_a) {
853
+ switch (_a.label) {
854
+ case 0:
855
+ if (connects.has(host)) {
856
+ return [2 /*return*/, connects.get(host)];
857
+ }
858
+ return [4 /*yield*/, getConnect(host)];
859
+ case 1:
860
+ connect = _a.sent();
861
+ connect.on('message', handleConnectMessage$1);
862
+ return [2 /*return*/, connect];
863
+ }
864
+ });
865
+ });
866
+ }
867
+ function handleConnectMessage$1(message) {
868
+ return __awaiter(this, void 0, void 0, function () {
869
+ var id, klass, data, project, _a;
870
+ return __generator(this, function (_b) {
871
+ switch (_b.label) {
872
+ case 0:
873
+ id = message.id, klass = message.klass, data = message.data;
874
+ project = projects.get(id);
875
+ if (!project) {
876
+ return [2 /*return*/];
877
+ }
878
+ _a = klass;
879
+ switch (_a) {
880
+ case exports.Klass.Listings: return [3 /*break*/, 1];
881
+ }
882
+ return [3 /*break*/, 3];
883
+ case 1: return [4 /*yield*/, handleListings(project, data[0])];
884
+ case 2:
885
+ _b.sent();
886
+ return [3 /*break*/, 3];
887
+ case 3: return [2 /*return*/];
888
+ }
889
+ });
890
+ });
891
+ }
892
+ function handleListings(project, data) {
893
+ var _a;
894
+ return __awaiter(this, void 0, void 0, function () {
895
+ var listings, newDigest, oldDigest, _b;
896
+ return __generator(this, function (_d) {
897
+ switch (_d.label) {
898
+ case 0:
899
+ listings = JSON.parse(data);
900
+ newDigest = listings.project.app_settings_digest;
901
+ oldDigest = (_a = project.listings) === null || _a === void 0 ? void 0 : _a.project.app_settings_digest;
902
+ project.listings = listings;
903
+ _d.label = 1;
904
+ case 1:
905
+ _d.trys.push([1, 4, , 5]);
906
+ if (!(oldDigest !== undefined && newDigest !== oldDigest)) return [3 /*break*/, 3];
907
+ _b = project;
908
+ return [4 /*yield*/, fetchSettings(project.host, project.id)];
909
+ case 2:
910
+ _b.fields = _d.sent();
911
+ _d.label = 3;
912
+ case 3: return [3 /*break*/, 5];
913
+ case 4:
914
+ _d.sent();
915
+ console.warn("Unable to fetch project " + project.id + " settings");
916
+ return [3 /*break*/, 5];
917
+ case 5: return [2 /*return*/];
918
+ }
919
+ });
920
+ });
921
+ }
922
+
923
+ /**
924
+ * @license
925
+ * api.ts
926
+ * interact-kit
927
+ *
928
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-02-15
929
+ * Copyright © 2022 Monterosa. All rights reserved.
930
+ *
931
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
932
+ */
933
+ /**
934
+ * @internal
935
+ */
936
+ var getProjectMemoized = sdkUtil.memoizePromise(function (sdk) { return __awaiter(void 0, void 0, void 0, function () {
937
+ var project;
938
+ return __generator(this, function (_a) {
939
+ switch (_a.label) {
940
+ case 0: return [4 /*yield*/, buildProject({
941
+ id: sdk.options.projectId,
942
+ host: sdk.options.host,
943
+ }, {
944
+ sdk: sdk,
945
+ })];
946
+ case 1:
947
+ project = _a.sent();
948
+ return [2 /*return*/, project];
949
+ }
950
+ });
951
+ }); }, function (sdk) { return sdk.options.projectId; });
952
+ /**
953
+ * Returns {@link InteractProject | project instance} associated
954
+ * with the {@link @monterosa/sdk-core#MonterosaSdk | configured sdk}
955
+ */
956
+ function getProject(sdk) {
957
+ if (sdk === void 0) { sdk = sdkCore.getSdk(); }
958
+ return getProjectMemoized(sdk);
959
+ }
960
+ /**
961
+ * @internal
962
+ */
963
+ function fetchListings(host, projectId) {
964
+ return __awaiter(this, void 0, void 0, function () {
965
+ var response, data;
966
+ return __generator(this, function (_a) {
967
+ switch (_a.label) {
968
+ case 0: return [4 /*yield*/, fetch("https://" + host + "/projects/" + projectId.substring(0, 2) + "/" + projectId + "/listings.json")];
969
+ case 1:
970
+ response = _a.sent();
971
+ return [4 /*yield*/, response.json()];
972
+ case 2:
973
+ data = (_a.sent());
974
+ return [2 /*return*/, data];
975
+ }
976
+ });
977
+ });
978
+ }
979
+ /**
980
+ * Adds an observer for when {@link InteractProject.fields | project fields}
981
+ * are updated
982
+ */
983
+ function onProjectFieldsUpdated(project, callback) {
984
+ return sdkUtil.subscribe(project, 'updated', callback);
985
+ }
986
+ /**
987
+ * @internal
988
+ */
989
+ function onProjectListingsUpdated(project, callback) {
990
+ return sdkUtil.subscribe(project, 'listings', callback);
991
+ }
992
+
993
+ /**
994
+ * @license
995
+ * internal.ts
996
+ * interact-kit
997
+ *
998
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-03-24
999
+ * Copyright © 2022 Monterosa. All rights reserved.
1000
+ *
1001
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
1002
+ */
1003
+ function fetchHistory(host, id) {
1004
+ return __awaiter(this, void 0, void 0, function () {
1005
+ var response, data;
1006
+ return __generator(this, function (_a) {
1007
+ switch (_a.label) {
1008
+ case 0: return [4 /*yield*/, fetch("https://" + host + "/events/" + id.substring(0, 2) + "/" + id + "/history.json")];
1009
+ case 1:
1010
+ response = _a.sent();
1011
+ if (!response.ok) {
1012
+ throw new Error("Failed to fetch event " + id + " history");
1013
+ }
1014
+ return [4 /*yield*/, response.json()];
1015
+ case 2:
1016
+ data = _a.sent();
1017
+ return [2 /*return*/, data];
1018
+ }
1019
+ });
1020
+ });
1021
+ }
1022
+
1023
+ /**
1024
+ * @license
1025
+ * public-types.ts
1026
+ * interact-kit
1027
+ *
1028
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-03-24
1029
+ * Copyright © 2022 Monterosa. All rights reserved.
1030
+ *
1031
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
1032
+ */
1033
+ /**
1034
+ * Describes the event state.
1035
+ */
1036
+ exports.EventState = void 0;
1037
+ (function (EventState) {
1038
+ /**
1039
+ * The event is in the `upcoming` state when its {@link InteractEvent.startAt | start time}
1040
+ * less than the {@link now | current time}.
1041
+ */
1042
+ EventState["Upcoming"] = "upcoming";
1043
+ /**
1044
+ * The event is in the `active` state when its {@link InteractEvent.startAt | start time}
1045
+ * equal or more than the {@link now | current time} and less than the
1046
+ * {@link InteractEvent.endAt | end time}.
1047
+ */
1048
+ EventState["Active"] = "active";
1049
+ /**
1050
+ * @internal
1051
+ */
1052
+ EventState["Prolonged"] = "prolonged";
1053
+ /**
1054
+ * The event is in the `finished` state when its {@link InteractEvent.endAt | end time}
1055
+ * equal or more than the {@link now | current time}.
1056
+ */
1057
+ EventState["Finished"] = "finished";
1058
+ })(exports.EventState || (exports.EventState = {}));
1059
+ var InitState;
1060
+ (function (InitState) {
1061
+ InitState["Uninitialised"] = "uninitialised";
1062
+ InitState["Initialising"] = "initialising";
1063
+ InitState["Initialised"] = "initialised";
1064
+ })(InitState || (InitState = {}));
1065
+
1066
+ /**
1067
+ * @license
1068
+ * event_impl.ts
1069
+ * interact-kit
1070
+ *
1071
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-02-15
1072
+ * Copyright © 2022 Monterosa. All rights reserved.
1073
+ *
1074
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
1075
+ */
1076
+ /**
1077
+ * @internal
1078
+ */
1079
+ var EventImpl = /** @class */ (function (_super) {
1080
+ __extends(EventImpl, _super);
1081
+ function EventImpl(data, context) {
1082
+ var _this = _super.call(this) || this;
1083
+ _this._initState = InitState.Uninitialised;
1084
+ _this._history = null;
1085
+ _this._data = data;
1086
+ _this._context = context;
1087
+ _this._state = _this.calculateState();
1088
+ _this._internalState = _this.calculateInternalState();
1089
+ _this.unsubscribeStateHandler = sdkUtil.onTick(function () { return _this.handleState(); });
1090
+ _this.unsubscribeInternalStateHandler = sdkUtil.onTick(function () {
1091
+ _this.handleInternalState();
1092
+ });
1093
+ _this.unsubscribeListingsHandler = onProjectListingsUpdated(context.project, function () { return _this.handleListings(); });
1094
+ return _this;
1095
+ }
1096
+ EventImpl.prototype.calculateState = function () {
1097
+ if (!this._data.started || sdkUtil.now() < this.startAt) {
1098
+ return exports.EventState.Upcoming;
1099
+ }
1100
+ if (sdkUtil.now() < this.endAt) {
1101
+ return exports.EventState.Active;
1102
+ }
1103
+ return exports.EventState.Finished;
1104
+ };
1105
+ EventImpl.prototype.calculateInternalState = function () {
1106
+ if (!this._data.started || sdkUtil.now() < this.startAt) {
1107
+ return exports.EventState.Upcoming;
1108
+ }
1109
+ if (sdkUtil.now() < this.endAt) {
1110
+ return exports.EventState.Active;
1111
+ }
1112
+ if (sdkUtil.now() < this.endAt + this._data.extra_time) {
1113
+ return exports.EventState.Prolonged;
1114
+ }
1115
+ return exports.EventState.Finished;
1116
+ };
1117
+ EventImpl.prototype.handleState = function () {
1118
+ var state = this.calculateState();
1119
+ if (state === exports.EventState.Finished) {
1120
+ this.unsubscribeStateHandler();
1121
+ }
1122
+ if (state !== this._state) {
1123
+ this._state = state;
1124
+ this.emit('state', state);
1125
+ }
1126
+ };
1127
+ EventImpl.prototype.handleInternalState = function () {
1128
+ var internalState = this.calculateInternalState();
1129
+ if (internalState === exports.EventState.Finished) {
1130
+ this.unsubscribeInternalStateHandler();
1131
+ }
1132
+ if (internalState !== this._internalState) {
1133
+ this._internalState = internalState;
1134
+ this.emit('internal_state', internalState);
1135
+ }
1136
+ };
1137
+ EventImpl.prototype.handleListings = function () {
1138
+ var _this = this;
1139
+ var project = this.context.project;
1140
+ var data = project.events.find(function (_a) {
1141
+ var id = _a.id;
1142
+ return id === _this.id;
1143
+ });
1144
+ if (data && this._data.digest !== data.digest) {
1145
+ this._data = data;
1146
+ this.emit('updated');
1147
+ }
1148
+ };
1149
+ /** @internal */
1150
+ EventImpl.prototype.destroy = function () {
1151
+ this.unsubscribeStateHandler();
1152
+ this.unsubscribeInternalStateHandler();
1153
+ this.unsubscribeListingsHandler();
1154
+ };
1155
+ Object.defineProperty(EventImpl.prototype, "context", {
1156
+ get: function () {
1157
+ return this._context;
1158
+ },
1159
+ enumerable: false,
1160
+ configurable: true
1161
+ });
1162
+ Object.defineProperty(EventImpl.prototype, "id", {
1163
+ get: function () {
1164
+ return this._data.id;
1165
+ },
1166
+ enumerable: false,
1167
+ configurable: true
1168
+ });
1169
+ Object.defineProperty(EventImpl.prototype, "name", {
1170
+ get: function () {
1171
+ return this._data.name;
1172
+ },
1173
+ enumerable: false,
1174
+ configurable: true
1175
+ });
1176
+ Object.defineProperty(EventImpl.prototype, "startAt", {
1177
+ get: function () {
1178
+ return this._data.start_at;
1179
+ },
1180
+ enumerable: false,
1181
+ configurable: true
1182
+ });
1183
+ Object.defineProperty(EventImpl.prototype, "startAtIso", {
1184
+ get: function () {
1185
+ return this._data.start_at_iso;
1186
+ },
1187
+ enumerable: false,
1188
+ configurable: true
1189
+ });
1190
+ Object.defineProperty(EventImpl.prototype, "endAt", {
1191
+ get: function () {
1192
+ return this._data.end_at;
1193
+ },
1194
+ enumerable: false,
1195
+ configurable: true
1196
+ });
1197
+ Object.defineProperty(EventImpl.prototype, "endAtIso", {
1198
+ get: function () {
1199
+ return this._data.end_at_iso;
1200
+ },
1201
+ enumerable: false,
1202
+ configurable: true
1203
+ });
1204
+ Object.defineProperty(EventImpl.prototype, "duration", {
1205
+ get: function () {
1206
+ return this._data.duration;
1207
+ },
1208
+ enumerable: false,
1209
+ configurable: true
1210
+ });
1211
+ Object.defineProperty(EventImpl.prototype, "fields", {
1212
+ get: function () {
1213
+ var locale = this.context.project.locale;
1214
+ return localise(this._data.custom_fields, locale);
1215
+ },
1216
+ enumerable: false,
1217
+ configurable: true
1218
+ });
1219
+ Object.defineProperty(EventImpl.prototype, "state", {
1220
+ get: function () {
1221
+ return this._state;
1222
+ },
1223
+ enumerable: false,
1224
+ configurable: true
1225
+ });
1226
+ Object.defineProperty(EventImpl.prototype, "internalState", {
1227
+ get: function () {
1228
+ return this._internalState;
1229
+ },
1230
+ enumerable: false,
1231
+ configurable: true
1232
+ });
1233
+ Object.defineProperty(EventImpl.prototype, "initState", {
1234
+ get: function () {
1235
+ return this._initState;
1236
+ },
1237
+ set: function (state) {
1238
+ this._initState = state;
1239
+ },
1240
+ enumerable: false,
1241
+ configurable: true
1242
+ });
1243
+ Object.defineProperty(EventImpl.prototype, "history", {
1244
+ get: function () {
1245
+ return this._history;
1246
+ },
1247
+ set: function (value) {
1248
+ this._history = value;
1249
+ this.emit('history', value);
1250
+ },
1251
+ enumerable: false,
1252
+ configurable: true
1253
+ });
1254
+ Object.defineProperty(EventImpl.prototype, "canSubscribe", {
1255
+ get: function () {
1256
+ return (this._internalState === exports.EventState.Active ||
1257
+ this._internalState === exports.EventState.Prolonged);
1258
+ },
1259
+ enumerable: false,
1260
+ configurable: true
1261
+ });
1262
+ Object.defineProperty(EventImpl.prototype, "canLoadHistory", {
1263
+ get: function () {
1264
+ return sdkUtil.now() >= this.startAt + this.context.project.historyIgnore;
1265
+ },
1266
+ enumerable: false,
1267
+ configurable: true
1268
+ });
1269
+ return EventImpl;
1270
+ }(sdkUtil.Emitter));
1271
+
1272
+ /**
1273
+ * @license
1274
+ * factory.ts
1275
+ * interact-kit
1276
+ *
1277
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-02-22
1278
+ * Copyright © 2022 Monterosa. All rights reserved.
1279
+ *
1280
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
1281
+ */
1282
+ var events = new Map();
1283
+ var healthListeners = new Map();
1284
+ function buildEvent(options, context) {
1285
+ if (events.has(options.id)) {
1286
+ return events.get(options.id);
1287
+ }
1288
+ var event = new EventImpl(options, context);
1289
+ event.on('internal_state', handleEventInternalState.bind(event));
1290
+ events.set(options.id, event);
1291
+ return event;
1292
+ }
1293
+ function init(event) {
1294
+ return __awaiter(this, void 0, void 0, function () {
1295
+ var history_1;
1296
+ return __generator(this, function (_a) {
1297
+ switch (_a.label) {
1298
+ case 0:
1299
+ if (event.initState === InitState.Initialising) {
1300
+ return [2 /*return*/, Promise.reject(new Error("can't initialise event, event is already being initialised"))];
1301
+ }
1302
+ if (event.initState === InitState.Initialised) {
1303
+ return [2 /*return*/, Promise.reject(new Error("can't initialise event, event is already initialised"))];
1304
+ }
1305
+ event.initState = InitState.Initialising;
1306
+ if (!(event.canLoadHistory && event.history === null)) return [3 /*break*/, 2];
1307
+ return [4 /*yield*/, fetchHistory(event.context.project.host, event.id)];
1308
+ case 1:
1309
+ history_1 = _a.sent();
1310
+ event.history = history_1;
1311
+ _a.label = 2;
1312
+ case 2:
1313
+ if (!event.canSubscribe) return [3 /*break*/, 4];
1314
+ return [4 /*yield*/, subscribe(event)];
1315
+ case 3:
1316
+ _a.sent();
1317
+ _a.label = 4;
1318
+ case 4: return [4 /*yield*/, listenConnHealth(event)];
1319
+ case 5:
1320
+ _a.sent();
1321
+ event.initState = InitState.Initialised;
1322
+ return [2 /*return*/, Promise.resolve()];
1323
+ }
1324
+ });
1325
+ });
1326
+ }
1327
+ function subscribe(event) {
1328
+ return __awaiter(this, void 0, void 0, function () {
1329
+ var connect;
1330
+ return __generator(this, function (_a) {
1331
+ switch (_a.label) {
1332
+ case 0:
1333
+ if (!event.canSubscribe) {
1334
+ return [2 /*return*/, Promise.reject(new Error("Event can't be subscribed"))];
1335
+ }
1336
+ return [4 /*yield*/, getConnect(event.context.project.host)];
1337
+ case 1:
1338
+ connect = _a.sent();
1339
+ return [4 /*yield*/, connect.subscribeEvent(event.id)];
1340
+ case 2:
1341
+ _a.sent();
1342
+ return [2 /*return*/, Promise.resolve()];
1343
+ }
1344
+ });
1345
+ });
1346
+ }
1347
+ function unsubscribe(event) {
1348
+ return __awaiter(this, void 0, void 0, function () {
1349
+ var connect;
1350
+ return __generator(this, function (_a) {
1351
+ switch (_a.label) {
1352
+ case 0: return [4 /*yield*/, getConnect(event.context.project.host)];
1353
+ case 1:
1354
+ connect = _a.sent();
1355
+ return [4 /*yield*/, connect.unsubscribeEvent(event.id)];
1356
+ case 2:
1357
+ _a.sent();
1358
+ return [2 /*return*/, Promise.resolve()];
1359
+ }
1360
+ });
1361
+ });
1362
+ }
1363
+ function listenConnHealth(event) {
1364
+ return __awaiter(this, void 0, void 0, function () {
1365
+ var project, connect, unsub;
1366
+ return __generator(this, function (_a) {
1367
+ switch (_a.label) {
1368
+ case 0:
1369
+ project = event.context.project;
1370
+ if (healthListeners.has(project.id)) {
1371
+ return [2 /*return*/];
1372
+ }
1373
+ return [4 /*yield*/, getConnect(project.host)];
1374
+ case 1:
1375
+ connect = _a.sent();
1376
+ if (connect.enmasse !== null) {
1377
+ unsub = sdkConnectKit.onConnected(connect.enmasse, handleEnmasseConnected);
1378
+ healthListeners.set(project.id, unsub);
1379
+ }
1380
+ return [2 /*return*/];
1381
+ }
1382
+ });
1383
+ });
1384
+ }
1385
+ function handleEventInternalState(state) {
1386
+ return __awaiter(this, void 0, void 0, function () {
1387
+ return __generator(this, function (_a) {
1388
+ switch (_a.label) {
1389
+ case 0:
1390
+ if (!(state === exports.EventState.Finished)) return [3 /*break*/, 2];
1391
+ return [4 /*yield*/, unsubscribe(this)];
1392
+ case 1:
1393
+ _a.sent();
1394
+ _a.label = 2;
1395
+ case 2: return [2 /*return*/];
1396
+ }
1397
+ });
1398
+ });
1399
+ }
1400
+ function handleEnmasseConnected() {
1401
+ var e_1, _a;
1402
+ return __awaiter(this, void 0, void 0, function () {
1403
+ var _b, _c, event_1, history_2, e_1_1;
1404
+ return __generator(this, function (_d) {
1405
+ switch (_d.label) {
1406
+ case 0:
1407
+ _d.trys.push([0, 6, 7, 12]);
1408
+ _b = __asyncValues(Array.from(events.values()));
1409
+ _d.label = 1;
1410
+ case 1: return [4 /*yield*/, _b.next()];
1411
+ case 2:
1412
+ if (!(_c = _d.sent(), !_c.done)) return [3 /*break*/, 5];
1413
+ event_1 = _c.value;
1414
+ if (!(event_1.initState === InitState.Initialised)) return [3 /*break*/, 4];
1415
+ return [4 /*yield*/, fetchHistory(event_1.context.project.host, event_1.id)];
1416
+ case 3:
1417
+ history_2 = _d.sent();
1418
+ event_1.history = history_2;
1419
+ _d.label = 4;
1420
+ case 4: return [3 /*break*/, 1];
1421
+ case 5: return [3 /*break*/, 12];
1422
+ case 6:
1423
+ e_1_1 = _d.sent();
1424
+ e_1 = { error: e_1_1 };
1425
+ return [3 /*break*/, 12];
1426
+ case 7:
1427
+ _d.trys.push([7, , 10, 11]);
1428
+ if (!(_c && !_c.done && (_a = _b.return))) return [3 /*break*/, 9];
1429
+ return [4 /*yield*/, _a.call(_b)];
1430
+ case 8:
1431
+ _d.sent();
1432
+ _d.label = 9;
1433
+ case 9: return [3 /*break*/, 11];
1434
+ case 10:
1435
+ if (e_1) throw e_1.error;
1436
+ return [7 /*endfinally*/];
1437
+ case 11: return [7 /*endfinally*/];
1438
+ case 12: return [2 /*return*/];
1439
+ }
1440
+ });
1441
+ });
1442
+ }
1443
+
1444
+ /**
1445
+ * @internal
1446
+ */
1447
+ var getEventsMemoized = sdkUtil.memoizePromise(function (project) { return __awaiter(void 0, void 0, void 0, function () {
1448
+ var context;
1449
+ return __generator(this, function (_a) {
1450
+ switch (_a.label) {
1451
+ case 0:
1452
+ if (!(project === undefined)) return [3 /*break*/, 2];
1453
+ return [4 /*yield*/, getProject()];
1454
+ case 1:
1455
+ project = _a.sent();
1456
+ _a.label = 2;
1457
+ case 2:
1458
+ context = __assign(__assign({}, project.context), { project: project });
1459
+ return [2 /*return*/, (project.events
1460
+ // Calling builder function that creates an event instance.
1461
+ // Existing event will be returned if it already exists in the cache
1462
+ .map(function (data) { return buildEvent(data, context); })
1463
+ // Sort events so the most recent event is first, and the oldest is last
1464
+ .sort(function (a, b) { return a.startAt - b.startAt; }))];
1465
+ }
1466
+ });
1467
+ }); }, function (project) {
1468
+ if (project === undefined) {
1469
+ var sdk = sdkCore.getSdk();
1470
+ return sdk.options.projectId;
1471
+ }
1472
+ return project.id;
1473
+ });
1474
+ /**
1475
+ * Returns all events in a project, including all active events and
1476
+ * past/upcoming events, according to Listings settings in Project Setup
1477
+ * in Studio.
1478
+ *
1479
+ * @param project - A project instance. If not provided,
1480
+ * the one from the default sdk will be fetched.
1481
+ */
1482
+ function getEvents(project) {
1483
+ return getEventsMemoized(project);
1484
+ }
1485
+ /**
1486
+ * @internal
1487
+ */
1488
+ var getEventMemoized = sdkUtil.memoizePromise(function (id, project) { return __awaiter(void 0, void 0, void 0, function () {
1489
+ var context, data, event_1, history_1, history_2, event_2;
1490
+ return __generator(this, function (_a) {
1491
+ switch (_a.label) {
1492
+ case 0:
1493
+ if (!(project === undefined)) return [3 /*break*/, 2];
1494
+ return [4 /*yield*/, getProject()];
1495
+ case 1:
1496
+ project = _a.sent();
1497
+ _a.label = 2;
1498
+ case 2:
1499
+ if (events.has(id)) {
1500
+ return [2 /*return*/, events.get(id)];
1501
+ }
1502
+ context = __assign(__assign({}, project.context), { project: project });
1503
+ data = project.events.find(function (eventData) { return eventData.id === id; });
1504
+ if (!(data !== undefined)) return [3 /*break*/, 5];
1505
+ event_1 = buildEvent(data, context);
1506
+ if (!event_1.canLoadHistory) return [3 /*break*/, 4];
1507
+ return [4 /*yield*/, fetchHistory(project.host, id)];
1508
+ case 3:
1509
+ history_1 = _a.sent();
1510
+ event_1.history = history_1;
1511
+ _a.label = 4;
1512
+ case 4: return [2 /*return*/, event_1];
1513
+ case 5:
1514
+ _a.trys.push([5, 7, , 8]);
1515
+ return [4 /*yield*/, fetchHistory(project.host, id)];
1516
+ case 6:
1517
+ history_2 = _a.sent();
1518
+ event_2 = buildEvent(history_2.config, context);
1519
+ event_2.history = history_2;
1520
+ return [2 /*return*/, event_2];
1521
+ case 7:
1522
+ _a.sent();
1523
+ return [2 /*return*/, null];
1524
+ case 8: return [2 /*return*/];
1525
+ }
1526
+ });
1527
+ }); }, function (id) { return id; });
1528
+ /**
1529
+ * Returns an event by its id
1530
+ *
1531
+ * @param id - Id of the event
1532
+ * @param project - A project instance. If not provided,
1533
+ * the one from the default sdk will be fetched.
1534
+ *
1535
+ * @returns A an event associated with the provided id and project or null if no such
1536
+ * event exists in the project.
1537
+ */
1538
+ function getEvent(id, project) {
1539
+ return getEventMemoized(id, project);
1540
+ }
1541
+ /**
1542
+ * Adds an observer for when {@link InteractEvent.state | event state} changed
1543
+ */
1544
+ function onEventState(event, callback) {
1545
+ return sdkUtil.subscribe(event, 'state', callback);
1546
+ }
1547
+ /**
1548
+ * Adds an observer for when event's data changed
1549
+ */
1550
+ function onEventUpdated(event, callback) {
1551
+ return sdkUtil.subscribe(event, 'updated', callback);
1552
+ }
1553
+ /**
1554
+ * Adds an observer that is called when an event is added to listings.
1555
+ *
1556
+ * @remarks
1557
+ * The following actions will result in adding an event to listings:
1558
+ *
1559
+ * - The start of the event in Studio
1560
+ *
1561
+ * - The scheduling of a future event in Studio, when listings are configured
1562
+ * to include future events in Project Settings.
1563
+ *
1564
+ * - When a future event starts, a new future event may be added to the list,
1565
+ * depending on the project configuration, to ensure a minimum number of
1566
+ * upcoming events are always available.
1567
+ */
1568
+ function onEventAdded(project, callback) {
1569
+ var _this = this;
1570
+ return sdkUtil.subscribe(project, 'listings_events_created', function (data) { var data_1, data_1_1; return __awaiter(_this, void 0, void 0, function () {
1571
+ var options, event_3, e_1_1;
1572
+ var e_1, _a;
1573
+ return __generator(this, function (_b) {
1574
+ switch (_b.label) {
1575
+ case 0:
1576
+ _b.trys.push([0, 6, 7, 12]);
1577
+ data_1 = __asyncValues(data);
1578
+ _b.label = 1;
1579
+ case 1: return [4 /*yield*/, data_1.next()];
1580
+ case 2:
1581
+ if (!(data_1_1 = _b.sent(), !data_1_1.done)) return [3 /*break*/, 5];
1582
+ options = data_1_1.value;
1583
+ return [4 /*yield*/, getEvent(options.id, project)];
1584
+ case 3:
1585
+ event_3 = _b.sent();
1586
+ if (event_3 !== null) {
1587
+ callback(event_3);
1588
+ }
1589
+ _b.label = 4;
1590
+ case 4: return [3 /*break*/, 1];
1591
+ case 5: return [3 /*break*/, 12];
1592
+ case 6:
1593
+ e_1_1 = _b.sent();
1594
+ e_1 = { error: e_1_1 };
1595
+ return [3 /*break*/, 12];
1596
+ case 7:
1597
+ _b.trys.push([7, , 10, 11]);
1598
+ if (!(data_1_1 && !data_1_1.done && (_a = data_1.return))) return [3 /*break*/, 9];
1599
+ return [4 /*yield*/, _a.call(data_1)];
1600
+ case 8:
1601
+ _b.sent();
1602
+ _b.label = 9;
1603
+ case 9: return [3 /*break*/, 11];
1604
+ case 10:
1605
+ if (e_1) throw e_1.error;
1606
+ return [7 /*endfinally*/];
1607
+ case 11: return [7 /*endfinally*/];
1608
+ case 12: return [2 /*return*/];
1609
+ }
1610
+ });
1611
+ }); });
1612
+ }
1613
+ /**
1614
+ * {@link onEventAdded} alias.
1615
+ *
1616
+ * @deprecated Use the new {@link onEventAdded} function instead.
1617
+ */
1618
+ function onEventPublished(project, callback) {
1619
+ console.warn('onEventPublished() is deprecated. Please use onEventAdded() instead');
1620
+ return onEventAdded(project, callback);
1621
+ }
1622
+ /**
1623
+ * Adds an observer that is called when an event is removed from listings.
1624
+ *
1625
+ * @remarks
1626
+ * The following actions will result in removing an event from listings:
1627
+ *
1628
+ * - The deletion of the event from Studio
1629
+ *
1630
+ * - The change of listings confuguration in Project Settings to exclude future
1631
+ * or past events.
1632
+ *
1633
+ * - The event is removed after a period of time since its completion. This period
1634
+ * is calculated as 45 seconds plus the Maximum allowed delay (configured in
1635
+ * Project Settings in Studio).
1636
+ */
1637
+ function onEventRemoved(project, callback) {
1638
+ var _this = this;
1639
+ return sdkUtil.subscribe(project, 'listings_events_deleted', function (data) { var data_2, data_2_1; return __awaiter(_this, void 0, void 0, function () {
1640
+ var options, event_4, e_2_1;
1641
+ var e_2, _a;
1642
+ return __generator(this, function (_b) {
1643
+ switch (_b.label) {
1644
+ case 0:
1645
+ _b.trys.push([0, 6, 7, 12]);
1646
+ data_2 = __asyncValues(data);
1647
+ _b.label = 1;
1648
+ case 1: return [4 /*yield*/, data_2.next()];
1649
+ case 2:
1650
+ if (!(data_2_1 = _b.sent(), !data_2_1.done)) return [3 /*break*/, 5];
1651
+ options = data_2_1.value;
1652
+ return [4 /*yield*/, getEvent(options.id, project)];
1653
+ case 3:
1654
+ event_4 = _b.sent();
1655
+ if (event_4 !== null) {
1656
+ callback(event_4);
1657
+ }
1658
+ _b.label = 4;
1659
+ case 4: return [3 /*break*/, 1];
1660
+ case 5: return [3 /*break*/, 12];
1661
+ case 6:
1662
+ e_2_1 = _b.sent();
1663
+ e_2 = { error: e_2_1 };
1664
+ return [3 /*break*/, 12];
1665
+ case 7:
1666
+ _b.trys.push([7, , 10, 11]);
1667
+ if (!(data_2_1 && !data_2_1.done && (_a = data_2.return))) return [3 /*break*/, 9];
1668
+ return [4 /*yield*/, _a.call(data_2)];
1669
+ case 8:
1670
+ _b.sent();
1671
+ _b.label = 9;
1672
+ case 9: return [3 /*break*/, 11];
1673
+ case 10:
1674
+ if (e_2) throw e_2.error;
1675
+ return [7 /*endfinally*/];
1676
+ case 11: return [7 /*endfinally*/];
1677
+ case 12: return [2 /*return*/];
1678
+ }
1679
+ });
1680
+ }); });
1681
+ }
1682
+
1683
+ /**
1684
+ * @license
1685
+ * public-types.ts
1686
+ * interact-kit
1687
+ *
1688
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-03-24
1689
+ * Copyright © 2022 Monterosa. All rights reserved.
1690
+ *
1691
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
1692
+ */
1693
+ var _a;
1694
+ /**
1695
+ * A map of potential error codes to compare with errors thrown by
1696
+ * vote() or validateAnswer() functions.
1697
+ */
1698
+ exports.AnswerError = void 0;
1699
+ (function (AnswerError) {
1700
+ AnswerError["OptionIndexOutOfRange"] = "out_of_range";
1701
+ AnswerError["BelowMinVoteOptions"] = "below_min_vote_options";
1702
+ AnswerError["AboveMaxVoteOptions"] = "above_max_vote_options";
1703
+ AnswerError["AboveMaxVotesPerUser"] = "above_max_per_user";
1704
+ AnswerError["AboveMaxVotesPerOption"] = "above_max_per_option";
1705
+ AnswerError["VotedOnNonInteractiveElement"] = "non_interactive_element";
1706
+ AnswerError["VotedOnClosedElement"] = "closed_element";
1707
+ AnswerError["EmptyVote"] = "empty_vote";
1708
+ })(exports.AnswerError || (exports.AnswerError = {}));
1709
+ var AnswerErrorMessages = (_a = {},
1710
+ _a[exports.AnswerError.OptionIndexOutOfRange] = function (max, idx) {
1711
+ return "Options index " + idx + " is out of range [0.." + max + "]";
1712
+ },
1713
+ _a[exports.AnswerError.BelowMinVoteOptions] = function (min, total) {
1714
+ return "Below min (" + min + ") vote options: " + total;
1715
+ },
1716
+ _a[exports.AnswerError.AboveMaxVoteOptions] = function (max, total) {
1717
+ return "Above max (" + max + ") vote options: " + total;
1718
+ },
1719
+ _a[exports.AnswerError.AboveMaxVotesPerUser] = function (max, total) {
1720
+ return "Above max (" + max + ") votes per user: " + total;
1721
+ },
1722
+ _a[exports.AnswerError.AboveMaxVotesPerOption] = function (max, total) {
1723
+ return "Above max (" + max + ") votes per option: " + total;
1724
+ },
1725
+ _a[exports.AnswerError.VotedOnNonInteractiveElement] = function (id) {
1726
+ return "Non interact element " + id;
1727
+ },
1728
+ _a[exports.AnswerError.VotedOnClosedElement] = function (id) { return "Element " + id + " is closed"; },
1729
+ _a[exports.AnswerError.EmptyVote] = function (indices) {
1730
+ return "Empty value for options indices: " + indices;
1731
+ },
1732
+ _a);
1733
+ /**
1734
+ * The ElementState represents the potential states an element is in.
1735
+ */
1736
+ exports.ElementState = void 0;
1737
+ (function (ElementState) {
1738
+ /**
1739
+ * Element is opened and active. The user can vote if
1740
+ * element is `interactive`
1741
+ */
1742
+ ElementState["Opened"] = "opened";
1743
+ /**
1744
+ * Element is closed and the user can no longer vote for
1745
+ * `interactive` elements
1746
+ */
1747
+ ElementState["Closed"] = "closed";
1748
+ })(exports.ElementState || (exports.ElementState = {}));
1749
+
1750
+ /**
1751
+ * @license
1752
+ * answer.ts
1753
+ * interact-kit
1754
+ *
1755
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-04-13
1756
+ * Copyright © 2022 Monterosa. All rights reserved.
1757
+ *
1758
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
1759
+ */
1760
+ /**
1761
+ * An `Answer` contains data of the user answer. Can be used to manage number of
1762
+ * votes that the user placed for a specific option.
1763
+ */
1764
+ var Answer = /** @class */ (function () {
1765
+ function Answer(answers) {
1766
+ if (answers === void 0) { answers = []; }
1767
+ this._answers = new Map();
1768
+ for (var _i = 0, answers_1 = answers; _i < answers_1.length; _i++) {
1769
+ var _a = answers_1[_i], option = _a.option, value = _a.value;
1770
+ this._answers.set(option, value);
1771
+ }
1772
+ }
1773
+ Object.defineProperty(Answer.prototype, "answers", {
1774
+ /**
1775
+ * The array of user answers
1776
+ */
1777
+ get: function () {
1778
+ return Array.from(this._answers.entries()).map(function (_a) {
1779
+ var option = _a[0], value = _a[1];
1780
+ return ({
1781
+ option: option,
1782
+ value: value,
1783
+ });
1784
+ });
1785
+ },
1786
+ enumerable: false,
1787
+ configurable: true
1788
+ });
1789
+ /**
1790
+ * Instantiate Answer class with the provided options indices. Number
1791
+ * of votes will be set to 1 for all options
1792
+ *
1793
+ * @example
1794
+ * ```javascript
1795
+ * // user votes for the first and fourth options
1796
+ * const answer = Answer.fromIndices([0, 3]);
1797
+ * ```
1798
+ *
1799
+ * @param indices - The array of option indices
1800
+ */
1801
+ Answer.fromIndices = function (indices) {
1802
+ return new Answer(indices.map(function (option) { return ({
1803
+ option: option,
1804
+ value: 1,
1805
+ }); }));
1806
+ };
1807
+ /**
1808
+ * Adds a vote for the provided option index
1809
+ *
1810
+ * @param option - The index of the option, starting with 0
1811
+ * @param value - The number of votes that will be placed against the option
1812
+ */
1813
+ Answer.prototype.set = function (option, value) {
1814
+ this._answers.set(option, value);
1815
+ return this;
1816
+ };
1817
+ /**
1818
+ * Removes the vote for the provided option index
1819
+ *
1820
+ * @param option - The index of the option, starting with 0
1821
+ */
1822
+ Answer.prototype.remove = function (option) {
1823
+ this._answers.delete(option);
1824
+ return this;
1825
+ };
1826
+ /** @internal */
1827
+ Answer.prototype.toJSON = function () {
1828
+ return this.answers;
1829
+ };
1830
+ /** @internal */
1831
+ Answer.fromJSON = function (value) {
1832
+ return new Answer(JSON.parse(value));
1833
+ };
1834
+ return Answer;
1835
+ }());
1836
+
1837
+ /**
1838
+ * @license
1839
+ * types.ts
1840
+ * interact-kit
1841
+ *
1842
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-03-24
1843
+ * Copyright © 2022 Monterosa. All rights reserved.
1844
+ *
1845
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
1846
+ */
1847
+ /**
1848
+ * Describes element types
1849
+ */
1850
+ exports.ElementType = void 0;
1851
+ (function (ElementType) {
1852
+ /**
1853
+ * Data element
1854
+ */
1855
+ ElementType["Data"] = "data";
1856
+ /**
1857
+ * Poll element
1858
+ */
1859
+ ElementType["Poll"] = "poll";
1860
+ /**
1861
+ * Regular poll element
1862
+ */
1863
+ ElementType["RegularPoll"] = "rpoll";
1864
+ /**
1865
+ * Diametric poll element
1866
+ */
1867
+ ElementType["DiametricPoll"] = "dpoll";
1868
+ /**
1869
+ * Emoting poll
1870
+ */
1871
+ ElementType["EmotingPoll"] = "emo";
1872
+ /**
1873
+ * Powerbar element
1874
+ */
1875
+ ElementType["Powerbar"] = "powerbar";
1876
+ /**
1877
+ * Prediction element
1878
+ */
1879
+ ElementType["Prediction"] = "prediction";
1880
+ /**
1881
+ * Trivia element
1882
+ */
1883
+ ElementType["Trivia"] = "trivia";
1884
+ })(exports.ElementType || (exports.ElementType = {}));
1885
+ var ShowResultsMode;
1886
+ (function (ShowResultsMode) {
1887
+ ShowResultsMode["OnVote"] = "vote";
1888
+ ShowResultsMode["OnClose"] = "close";
1889
+ ShowResultsMode["OnEventEnd"] = "event_end";
1890
+ ShowResultsMode["Manual"] = "manual";
1891
+ ShowResultsMode["Never"] = "never";
1892
+ ShowResultsMode["Always"] = "always";
1893
+ })(ShowResultsMode || (ShowResultsMode = {}));
1894
+
1895
+ /**
1896
+ * @license
1897
+ * element_impl.ts
1898
+ * interact-kit
1899
+ *
1900
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-03-24
1901
+ * Copyright © 2022 Monterosa. All rights reserved.
1902
+ *
1903
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
1904
+ */
1905
+ /**
1906
+ * @internal
1907
+ */
1908
+ var ElementImpl = /** @class */ (function (_super) {
1909
+ __extends(ElementImpl, _super);
1910
+ function ElementImpl(data, context) {
1911
+ var _a, _b;
1912
+ var _this = _super.call(this) || this;
1913
+ _this._results = null;
1914
+ _this._userAnswer = null;
1915
+ _this._correctOption = null;
1916
+ _this._data = data;
1917
+ _this._context = context;
1918
+ _this._results = ((_a = data.data) === null || _a === void 0 ? void 0 : _a.results) || null;
1919
+ _this._correctOption = ((_b = data.data) === null || _b === void 0 ? void 0 : _b.correct_option)
1920
+ ? data.data.correct_option - 1
1921
+ : null;
1922
+ _this._state = _this.calculateState();
1923
+ _this.unsubscribeStateHandler = sdkUtil.onTick(function () { return _this.handleState(); });
1924
+ return _this;
1925
+ }
1926
+ ElementImpl.prototype.calculateState = function () {
1927
+ if (sdkUtil.now() < this.publishedAt + this.duration) {
1928
+ return exports.ElementState.Opened;
1929
+ }
1930
+ return exports.ElementState.Closed;
1931
+ };
1932
+ ElementImpl.prototype.handleState = function () {
1933
+ var state = this.calculateState();
1934
+ if (state === exports.ElementState.Closed) {
1935
+ this.unsubscribeStateHandler();
1936
+ }
1937
+ if (state !== this._state) {
1938
+ this._state = state;
1939
+ this.emit('state', state);
1940
+ }
1941
+ };
1942
+ ElementImpl.prototype.update = function (data) {
1943
+ this._data = data;
1944
+ };
1945
+ ElementImpl.prototype.destroy = function () {
1946
+ this.unsubscribeStateHandler();
1947
+ };
1948
+ Object.defineProperty(ElementImpl.prototype, "context", {
1949
+ get: function () {
1950
+ return this._context;
1951
+ },
1952
+ enumerable: false,
1953
+ configurable: true
1954
+ });
1955
+ Object.defineProperty(ElementImpl.prototype, "id", {
1956
+ get: function () {
1957
+ return this._data.id;
1958
+ },
1959
+ enumerable: false,
1960
+ configurable: true
1961
+ });
1962
+ Object.defineProperty(ElementImpl.prototype, "eventId", {
1963
+ get: function () {
1964
+ return this.context.event.id;
1965
+ },
1966
+ enumerable: false,
1967
+ configurable: true
1968
+ });
1969
+ Object.defineProperty(ElementImpl.prototype, "state", {
1970
+ get: function () {
1971
+ return this._state;
1972
+ },
1973
+ enumerable: false,
1974
+ configurable: true
1975
+ });
1976
+ Object.defineProperty(ElementImpl.prototype, "type", {
1977
+ get: function () {
1978
+ return this._data.type;
1979
+ },
1980
+ enumerable: false,
1981
+ configurable: true
1982
+ });
1983
+ Object.defineProperty(ElementImpl.prototype, "contentType", {
1984
+ get: function () {
1985
+ return this._data.content_type;
1986
+ },
1987
+ enumerable: false,
1988
+ configurable: true
1989
+ });
1990
+ Object.defineProperty(ElementImpl.prototype, "publishedAt", {
1991
+ get: function () {
1992
+ return this._data.published_at;
1993
+ },
1994
+ enumerable: false,
1995
+ configurable: true
1996
+ });
1997
+ Object.defineProperty(ElementImpl.prototype, "publishedAtIso", {
1998
+ get: function () {
1999
+ return this._data.published_at_iso;
2000
+ },
2001
+ enumerable: false,
2002
+ configurable: true
2003
+ });
2004
+ Object.defineProperty(ElementImpl.prototype, "updatedAt", {
2005
+ get: function () {
2006
+ return this._data.updated_at;
2007
+ },
2008
+ enumerable: false,
2009
+ configurable: true
2010
+ });
2011
+ Object.defineProperty(ElementImpl.prototype, "updatedAtIso", {
2012
+ get: function () {
2013
+ return this._data.updated_at_iso;
2014
+ },
2015
+ enumerable: false,
2016
+ configurable: true
2017
+ });
2018
+ Object.defineProperty(ElementImpl.prototype, "duration", {
2019
+ get: function () {
2020
+ return this._data.duration;
2021
+ },
2022
+ enumerable: false,
2023
+ configurable: true
2024
+ });
2025
+ Object.defineProperty(ElementImpl.prototype, "fields", {
2026
+ get: function () {
2027
+ var locale = this.context.project.locale;
2028
+ return localise(this._data.custom_fields, locale);
2029
+ },
2030
+ enumerable: false,
2031
+ configurable: true
2032
+ });
2033
+ Object.defineProperty(ElementImpl.prototype, "interactive", {
2034
+ get: function () {
2035
+ return this.type !== exports.ElementType.Data;
2036
+ },
2037
+ enumerable: false,
2038
+ configurable: true
2039
+ });
2040
+ Object.defineProperty(ElementImpl.prototype, "pollId", {
2041
+ get: function () {
2042
+ return this._data.data.id || null;
2043
+ },
2044
+ enumerable: false,
2045
+ configurable: true
2046
+ });
2047
+ Object.defineProperty(ElementImpl.prototype, "question", {
2048
+ get: function () {
2049
+ var locale = this.context.project.locale;
2050
+ if (this._data.data.question === undefined) {
2051
+ return null;
2052
+ }
2053
+ return localise(this._data.data.question, locale);
2054
+ },
2055
+ enumerable: false,
2056
+ configurable: true
2057
+ });
2058
+ Object.defineProperty(ElementImpl.prototype, "answerOptions", {
2059
+ get: function () {
2060
+ var locale = this.context.project.locale;
2061
+ if (this._data.data.options === undefined) {
2062
+ return null;
2063
+ }
2064
+ return localise(this._data.data.options, locale);
2065
+ },
2066
+ enumerable: false,
2067
+ configurable: true
2068
+ });
2069
+ Object.defineProperty(ElementImpl.prototype, "minOptionsPerVote", {
2070
+ get: function () {
2071
+ return this._data.data.min_options_per_vote || 1;
2072
+ },
2073
+ enumerable: false,
2074
+ configurable: true
2075
+ });
2076
+ Object.defineProperty(ElementImpl.prototype, "maxOptionsPerVote", {
2077
+ get: function () {
2078
+ return this._data.data.max_options_per_vote || 1;
2079
+ },
2080
+ enumerable: false,
2081
+ configurable: true
2082
+ });
2083
+ Object.defineProperty(ElementImpl.prototype, "maxVotesPerOption", {
2084
+ get: function () {
2085
+ return this._data.data.max_votes_per_option || 1;
2086
+ },
2087
+ enumerable: false,
2088
+ configurable: true
2089
+ });
2090
+ Object.defineProperty(ElementImpl.prototype, "maxVotesPerUser", {
2091
+ get: function () {
2092
+ return this._data.data.max_votes_per_user || null;
2093
+ },
2094
+ enumerable: false,
2095
+ configurable: true
2096
+ });
2097
+ Object.defineProperty(ElementImpl.prototype, "userAnswer", {
2098
+ get: function () {
2099
+ return this._userAnswer;
2100
+ },
2101
+ set: function (value) {
2102
+ this._userAnswer = value;
2103
+ },
2104
+ enumerable: false,
2105
+ configurable: true
2106
+ });
2107
+ Object.defineProperty(ElementImpl.prototype, "hasBeenAnswered", {
2108
+ get: function () {
2109
+ return this._userAnswer !== null;
2110
+ },
2111
+ enumerable: false,
2112
+ configurable: true
2113
+ });
2114
+ Object.defineProperty(ElementImpl.prototype, "showResultsMode", {
2115
+ get: function () {
2116
+ return this._data.data.reveal_results_mode || null;
2117
+ },
2118
+ enumerable: false,
2119
+ configurable: true
2120
+ });
2121
+ Object.defineProperty(ElementImpl.prototype, "canShowResults", {
2122
+ get: function () {
2123
+ switch (this.showResultsMode) {
2124
+ case ShowResultsMode.OnVote:
2125
+ return this.hasBeenAnswered || this.state === exports.ElementState.Closed;
2126
+ case ShowResultsMode.OnClose:
2127
+ return this.state === exports.ElementState.Closed;
2128
+ case ShowResultsMode.Manual:
2129
+ return this._results !== null;
2130
+ case ShowResultsMode.OnEventEnd:
2131
+ return this.context.event.state === exports.EventState.Finished;
2132
+ case ShowResultsMode.Never:
2133
+ return false;
2134
+ case ShowResultsMode.Always:
2135
+ default:
2136
+ return true;
2137
+ }
2138
+ },
2139
+ enumerable: false,
2140
+ configurable: true
2141
+ });
2142
+ Object.defineProperty(ElementImpl.prototype, "results", {
2143
+ get: function () {
2144
+ if (!this.canShowResults) {
2145
+ return null;
2146
+ }
2147
+ return this._results;
2148
+ },
2149
+ set: function (results) {
2150
+ // skip setting results if they weren't changed
2151
+ if (JSON.stringify(results) === JSON.stringify(this.results)) {
2152
+ return;
2153
+ }
2154
+ this._results = results;
2155
+ if (this.canShowResults) {
2156
+ this.emit('results');
2157
+ }
2158
+ },
2159
+ enumerable: false,
2160
+ configurable: true
2161
+ });
2162
+ Object.defineProperty(ElementImpl.prototype, "correctOption", {
2163
+ get: function () {
2164
+ return this._correctOption;
2165
+ },
2166
+ set: function (value) {
2167
+ this._correctOption = value;
2168
+ },
2169
+ enumerable: false,
2170
+ configurable: true
2171
+ });
2172
+ Object.defineProperty(ElementImpl.prototype, "isCorrectOptionRevealed", {
2173
+ get: function () {
2174
+ return this._correctOption !== null;
2175
+ },
2176
+ enumerable: false,
2177
+ configurable: true
2178
+ });
2179
+ return ElementImpl;
2180
+ }(sdkUtil.Emitter));
2181
+
2182
+ /**
2183
+ * @license
2184
+ * calculate_percentage.ts
2185
+ * interact-kit
2186
+ *
2187
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-04-07
2188
+ * Copyright © 2022 Monterosa. All rights reserved.
2189
+ *
2190
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
2191
+ */
2192
+ var calculatePercentage = function (values) {
2193
+ // Calculate sum of all votes
2194
+ var sum = values.reduce(function (memo, value) { return memo + value; }, 0);
2195
+ // create array of hashes
2196
+ var results = values.map(function (value, idx) { return ({
2197
+ idx: idx,
2198
+ votes: value,
2199
+ percentage: Math.round((100 * value) / sum) || 0,
2200
+ }); });
2201
+ // Sum them all up - this can be less, equal or greater than a 100%
2202
+ var total = results.reduce(function (memo, _a) {
2203
+ var percentage = _a.percentage;
2204
+ return memo + percentage;
2205
+ }, 0);
2206
+ total = total || 100;
2207
+ // Calculate number of percent that we are missing or that we need to lose
2208
+ var delta = 100 - total;
2209
+ var sign = delta >= 0 ? 1 : -1;
2210
+ // Order all options by number of votes
2211
+ results.sort(function (a, b) {
2212
+ var result = sign * (b.votes - a.votes);
2213
+ if (result !== 0) {
2214
+ return result;
2215
+ }
2216
+ return sign * (a.idx - b.idx);
2217
+ });
2218
+ // If we have percents to lose then take one percent off lowest options
2219
+ // If we are missing percents then add one percent to highest options
2220
+ var i = 0;
2221
+ while (delta !== 0) {
2222
+ if (results[i].votes > 0) {
2223
+ results[i].percentage += sign;
2224
+ delta -= sign;
2225
+ }
2226
+ i++;
2227
+ }
2228
+ // Restore options order
2229
+ results.sort(function (a, b) { return a.idx - b.idx; });
2230
+ return results.map(function (item) { return item.percentage; });
2231
+ };
2232
+
2233
+ /**
2234
+ * @license
2235
+ * factory.ts
2236
+ * interact-kit
2237
+ *
2238
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-03-24
2239
+ * Copyright © 2022 Monterosa. All rights reserved.
2240
+ *
2241
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
2242
+ */
2243
+ var elements = new Map();
2244
+ var storageAvailable = sdkUtil.checkAvailability();
2245
+ function buildElement(options, context) {
2246
+ if (elements.has(options.id)) {
2247
+ return elements.get(options.id);
2248
+ }
2249
+ var element = new ElementImpl(options, context);
2250
+ restoreAnswer(element);
2251
+ elements.set(element.id, element);
2252
+ return element;
2253
+ }
2254
+ function getElementByPolld(pollId) {
2255
+ return Array.from(elements.values()).find(function (element) { return element.pollId === pollId; });
2256
+ }
2257
+ var configureEventMemoized = sdkUtil.memoizePromise(function (event) { return __awaiter(void 0, void 0, void 0, function () {
2258
+ return __generator(this, function (_a) {
2259
+ switch (_a.label) {
2260
+ case 0:
2261
+ event.on('history', handleEventHistory);
2262
+ if (event.history !== null) {
2263
+ handleEventHistory(event.history);
2264
+ }
2265
+ return [4 /*yield*/, configureConnect(event.context.sdk.options.host)];
2266
+ case 1:
2267
+ _a.sent();
2268
+ return [4 /*yield*/, init(event)];
2269
+ case 2:
2270
+ _a.sent();
2271
+ return [2 /*return*/];
2272
+ }
2273
+ });
2274
+ }); }, function (event) { return event.id; });
2275
+ function configureEvent(event) {
2276
+ return __awaiter(this, void 0, void 0, function () {
2277
+ return __generator(this, function (_a) {
2278
+ return [2 /*return*/, configureEventMemoized(event)];
2279
+ });
2280
+ });
2281
+ }
2282
+ var configureConnectMemoized = sdkUtil.memoizePromise(function (host) { return __awaiter(void 0, void 0, void 0, function () {
2283
+ var connect;
2284
+ return __generator(this, function (_a) {
2285
+ switch (_a.label) {
2286
+ case 0: return [4 /*yield*/, getConnect(host)];
2287
+ case 1:
2288
+ connect = _a.sent();
2289
+ connect.on('message', handleConnectMessage);
2290
+ return [2 /*return*/];
2291
+ }
2292
+ });
2293
+ }); }, function (host) { return host; });
2294
+ function configureConnect(host) {
2295
+ return __awaiter(this, void 0, void 0, function () {
2296
+ return __generator(this, function (_a) {
2297
+ return [2 /*return*/, configureConnectMemoized(host)];
2298
+ });
2299
+ });
2300
+ }
2301
+ function handleConnectMessage(message) {
2302
+ return __awaiter(this, void 0, void 0, function () {
2303
+ var klass, _a;
2304
+ return __generator(this, function (_b) {
2305
+ switch (_b.label) {
2306
+ case 0:
2307
+ klass = message.klass;
2308
+ _a = klass;
2309
+ switch (_a) {
2310
+ case exports.Klass.Create: return [3 /*break*/, 1];
2311
+ case exports.Klass.Revoke: return [3 /*break*/, 3];
2312
+ case exports.Klass.Feedback: return [3 /*break*/, 5];
2313
+ case exports.Klass.Reveal: return [3 /*break*/, 7];
2314
+ }
2315
+ return [3 /*break*/, 9];
2316
+ case 1: return [4 /*yield*/, handleCreateMessage(message)];
2317
+ case 2:
2318
+ _b.sent();
2319
+ return [3 /*break*/, 9];
2320
+ case 3: return [4 /*yield*/, handleRevokeMessage(message)];
2321
+ case 4:
2322
+ _b.sent();
2323
+ return [3 /*break*/, 9];
2324
+ case 5: return [4 /*yield*/, handleFeedbackMessage(message)];
2325
+ case 6:
2326
+ _b.sent();
2327
+ return [3 /*break*/, 9];
2328
+ case 7: return [4 /*yield*/, handleRevealMessage(message)];
2329
+ case 8:
2330
+ _b.sent();
2331
+ return [3 /*break*/, 9];
2332
+ case 9: return [2 /*return*/];
2333
+ }
2334
+ });
2335
+ });
2336
+ }
2337
+ function handleCreateMessage(message) {
2338
+ return __awaiter(this, void 0, void 0, function () {
2339
+ var id, data, options, event, element, context, element;
2340
+ return __generator(this, function (_a) {
2341
+ switch (_a.label) {
2342
+ case 0:
2343
+ id = message.id, data = message.data;
2344
+ options = JSON.parse(data[0]);
2345
+ return [4 /*yield*/, getEvent(id)];
2346
+ case 1:
2347
+ event = _a.sent();
2348
+ if (event === null) {
2349
+ return [2 /*return*/];
2350
+ }
2351
+ if (elements.has(options.id)) {
2352
+ element = elements.get(options.id);
2353
+ if (options.updated_at > element.updatedAt) {
2354
+ element.update(options);
2355
+ event.emit('update', element);
2356
+ }
2357
+ }
2358
+ else {
2359
+ context = __assign(__assign({}, event.context), { event: event });
2360
+ element = buildElement(options, context);
2361
+ event.emit('publish', element);
2362
+ }
2363
+ return [2 /*return*/];
2364
+ }
2365
+ });
2366
+ });
2367
+ }
2368
+ function handleRevokeMessage(message) {
2369
+ var data = message.data;
2370
+ var id = JSON.parse(data[0]).id;
2371
+ if (!elements.has(id)) {
2372
+ return;
2373
+ }
2374
+ var element = elements.get(id);
2375
+ elements.delete(id);
2376
+ element.destroy();
2377
+ element.context.event.emit('revoke', element);
2378
+ }
2379
+ function handleFeedbackMessage(message) {
2380
+ return __awaiter(this, void 0, void 0, function () {
2381
+ var data, pollId, counters, element, votes, percentages, results;
2382
+ return __generator(this, function (_a) {
2383
+ data = message.data;
2384
+ pollId = +data[0];
2385
+ counters = data[3];
2386
+ element = getElementByPolld(pollId);
2387
+ if (!element) {
2388
+ return [2 /*return*/];
2389
+ }
2390
+ votes = counters.split(':').map(function (value) { return +value; });
2391
+ percentages = calculatePercentage(votes);
2392
+ results = votes.map(function (item, idx) { return ({
2393
+ percentage: percentages[idx],
2394
+ votes: item,
2395
+ }); });
2396
+ element.results = results;
2397
+ return [2 /*return*/];
2398
+ });
2399
+ });
2400
+ }
2401
+ function handleRevealMessage(message) {
2402
+ var data = message.data;
2403
+ // Reveal message format:
2404
+ //
2405
+ // [pollId, index (1-based), timestamp]
2406
+ var pollId = +data[0];
2407
+ var correctOption = +data[1] - 1;
2408
+ var element = getElementByPolld(pollId);
2409
+ if (!element) {
2410
+ return;
2411
+ }
2412
+ element.correctOption = correctOption;
2413
+ element.context.event.emit('update', element);
2414
+ }
2415
+ function handleEventHistory(history) {
2416
+ return __awaiter(this, void 0, void 0, function () {
2417
+ var event, context, _i, _a, snapshot;
2418
+ return __generator(this, function (_b) {
2419
+ switch (_b.label) {
2420
+ case 0:
2421
+ if (history.timeline.length === 0) {
2422
+ return [2 /*return*/];
2423
+ }
2424
+ return [4 /*yield*/, getEvent(history.config.id)];
2425
+ case 1:
2426
+ event = _b.sent();
2427
+ if (event === null) {
2428
+ return [2 /*return*/];
2429
+ }
2430
+ context = __assign(__assign({}, event.context), { event: event });
2431
+ for (_i = 0, _a = history.timeline; _i < _a.length; _i++) {
2432
+ snapshot = _a[_i];
2433
+ if (!elements.has(snapshot.id)) {
2434
+ buildElement(snapshot, context);
2435
+ }
2436
+ }
2437
+ return [2 /*return*/];
2438
+ }
2439
+ });
2440
+ });
2441
+ }
2442
+ function sendAnswer(element, userAnswer) {
2443
+ return __awaiter(this, void 0, void 0, function () {
2444
+ var _a, project, event, connect, answer;
2445
+ return __generator(this, function (_b) {
2446
+ switch (_b.label) {
2447
+ case 0:
2448
+ _a = element.context, project = _a.project, event = _a.event;
2449
+ return [4 /*yield*/, getConnect(project.host)];
2450
+ case 1:
2451
+ connect = _b.sent();
2452
+ answer = userAnswer.answers
2453
+ .map(function (_a) {
2454
+ var option = _a.option, value = _a.value;
2455
+ return [option + 1, value];
2456
+ })
2457
+ .flat()
2458
+ .join(':');
2459
+ connect.sendVote(event.id, element.pollId, answer);
2460
+ return [2 /*return*/];
2461
+ }
2462
+ });
2463
+ });
2464
+ }
2465
+ function storeAnswer(element, userAnswer) {
2466
+ try {
2467
+ element.userAnswer = userAnswer;
2468
+ if (storageAvailable) {
2469
+ // Can throw a "QuotaExceededError" DOMException exception
2470
+ // if the quota has been exceeded.
2471
+ sdkUtil.setItem("element_" + element.id + "_vote", JSON.stringify(userAnswer));
2472
+ }
2473
+ }
2474
+ catch (err) {
2475
+ if (err instanceof Error) {
2476
+ console.warn("Can't store user answer: " + err.message);
2477
+ }
2478
+ }
2479
+ }
2480
+ function restoreAnswer(element) {
2481
+ if (storageAvailable) {
2482
+ var userAnswer = sdkUtil.getItem("element_" + element.id + "_vote");
2483
+ if (userAnswer !== null) {
2484
+ element.userAnswer = Answer.fromJSON(userAnswer);
2485
+ }
2486
+ }
2487
+ }
2488
+
2489
+ /**
2490
+ * @license
2491
+ * api.ts
2492
+ * interact-kit
2493
+ *
2494
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-03-24
2495
+ * Copyright © 2022 Monterosa. All rights reserved.
2496
+ *
2497
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
2498
+ */
2499
+ /**
2500
+ * @internal
2501
+ */
2502
+ var getElementMemoized = sdkUtil.memoizePromise(function (event, id) { return __awaiter(void 0, void 0, void 0, function () {
2503
+ var element;
2504
+ return __generator(this, function (_a) {
2505
+ switch (_a.label) {
2506
+ case 0: return [4 /*yield*/, configureEvent(event)];
2507
+ case 1:
2508
+ _a.sent();
2509
+ element = Array.from(elements.values()).find(function (el) { return el.id === id; });
2510
+ return [2 /*return*/, element || null];
2511
+ }
2512
+ });
2513
+ }); }, function (event, id) { return id; });
2514
+ /**
2515
+ * Returns an element of a specific event by its id
2516
+ */
2517
+ function getElement(event, id) {
2518
+ return getElementMemoized(event, id);
2519
+ }
2520
+ /**
2521
+ * @internal
2522
+ */
2523
+ var getElementsMemoized = sdkUtil.memoizePromise(function (event) { return __awaiter(void 0, void 0, void 0, function () {
2524
+ return __generator(this, function (_a) {
2525
+ switch (_a.label) {
2526
+ case 0: return [4 /*yield*/, configureEvent(event)];
2527
+ case 1:
2528
+ _a.sent();
2529
+ return [2 /*return*/, (Array.from(elements.values())
2530
+ // Get elements which belong only to the provided event
2531
+ .filter(function (element) { return element.eventId === event.id; })
2532
+ // Sort elements so the most recent event is first, and the oldest is last
2533
+ .sort(function (a, b) { return a.publishedAt - b.publishedAt; }))];
2534
+ }
2535
+ });
2536
+ }); }, function (event) { return event.id; }, {
2537
+ clearOnResolve: true,
2538
+ });
2539
+ /**
2540
+ * Returns the list of elements published in a specific event
2541
+ */
2542
+ function getElements(event) {
2543
+ return getElementsMemoized(event);
2544
+ }
2545
+ function answer(element) {
2546
+ var value = [];
2547
+ for (var _i = 1; _i < arguments.length; _i++) {
2548
+ value[_i - 1] = arguments[_i];
2549
+ }
2550
+ var answerObj = answerParametersToAnswer.apply(void 0, value);
2551
+ validateAnswer.apply(void 0, __spreadArray([element], value));
2552
+ sendAnswer(element, answerObj);
2553
+ storeAnswer(element, answerObj);
2554
+ }
2555
+ function validateAnswer(element) {
2556
+ var value = [];
2557
+ for (var _i = 1; _i < arguments.length; _i++) {
2558
+ value[_i - 1] = arguments[_i];
2559
+ }
2560
+ var answerObj = answerParametersToAnswer.apply(void 0, value);
2561
+ var answers = answerObj.answers;
2562
+ var indices = answers.map(function (_a) {
2563
+ var option = _a.option;
2564
+ return option;
2565
+ });
2566
+ var values = answers.map(function (_a) {
2567
+ var v = _a.value;
2568
+ return v;
2569
+ });
2570
+ var maxIndex = Math.max.apply(Math, indices);
2571
+ var maxValue = Math.max.apply(Math, values);
2572
+ var sumValues = values.reduce(function (memo, val) { return memo + val; }, 0);
2573
+ var emptyIndices = values.reduce(function (memo, val, idx) {
2574
+ if (val === 0) {
2575
+ memo.push(indices[idx]);
2576
+ }
2577
+ return memo;
2578
+ }, []);
2579
+ if (!element.interactive) {
2580
+ throw sdkUtil.createError(exports.AnswerError.VotedOnNonInteractiveElement, AnswerErrorMessages, element.id);
2581
+ }
2582
+ if (element.state === exports.ElementState.Closed) {
2583
+ throw sdkUtil.createError(exports.AnswerError.VotedOnClosedElement, AnswerErrorMessages, element.id);
2584
+ }
2585
+ if (maxIndex > element.answerOptions.length - 1) {
2586
+ throw sdkUtil.createError(exports.AnswerError.OptionIndexOutOfRange, AnswerErrorMessages, element.answerOptions.length - 1, maxIndex);
2587
+ }
2588
+ if (element.minOptionsPerVote !== null &&
2589
+ indices.length < element.minOptionsPerVote) {
2590
+ throw sdkUtil.createError(exports.AnswerError.BelowMinVoteOptions, AnswerErrorMessages, element.minOptionsPerVote, indices.length);
2591
+ }
2592
+ if (element.maxOptionsPerVote !== null &&
2593
+ indices.length > element.maxOptionsPerVote) {
2594
+ throw sdkUtil.createError(exports.AnswerError.AboveMaxVoteOptions, AnswerErrorMessages, element.maxOptionsPerVote, indices.length);
2595
+ }
2596
+ if (sumValues > element.maxVotesPerUser) {
2597
+ throw sdkUtil.createError(exports.AnswerError.AboveMaxVotesPerUser, AnswerErrorMessages, element.maxVotesPerUser, sumValues);
2598
+ }
2599
+ if (maxValue > element.maxVotesPerOption) {
2600
+ throw sdkUtil.createError(exports.AnswerError.AboveMaxVotesPerOption, AnswerErrorMessages, element.maxVotesPerOption, maxValue);
2601
+ }
2602
+ if (emptyIndices.length > 0) {
2603
+ throw sdkUtil.createError(exports.AnswerError.EmptyVote, AnswerErrorMessages, emptyIndices.join(', '));
2604
+ }
2605
+ }
2606
+ function answerParametersToAnswer() {
2607
+ var value = [];
2608
+ for (var _i = 0; _i < arguments.length; _i++) {
2609
+ value[_i] = arguments[_i];
2610
+ }
2611
+ var answerValues = value.flat();
2612
+ if (isAnswer(answerValues[0])) {
2613
+ return answerValues[0];
2614
+ }
2615
+ if (isNumbers(answerValues)) {
2616
+ return Answer.fromIndices(answerValues);
2617
+ }
2618
+ if (isAnswerValues(answerValues)) {
2619
+ return new Answer(answerValues);
2620
+ }
2621
+ return new Answer();
2622
+ }
2623
+ function isAnswer(value) {
2624
+ return value instanceof Answer;
2625
+ }
2626
+ function isAnswerValues(value) {
2627
+ return value.every(function (v) {
2628
+ return Object.prototype.hasOwnProperty.call(v, 'option') &&
2629
+ Object.prototype.hasOwnProperty.call(v, 'value');
2630
+ });
2631
+ }
2632
+ function isNumbers(value) {
2633
+ return value.every(function (v) { return typeof v === 'number'; });
2634
+ }
2635
+ /**
2636
+ * Adds an observer for when {@link InteractElement.results | element results}
2637
+ * are updated
2638
+ */
2639
+ function onElementResults(element, callback) {
2640
+ return sdkUtil.subscribe(element, 'results', callback);
2641
+ }
2642
+ /**
2643
+ * Adds an observer for when {@link InteractElement.state | element state}
2644
+ * changed
2645
+ */
2646
+ function onElementStateChanged(element, callback) {
2647
+ return sdkUtil.subscribe(element, 'state', callback);
2648
+ }
2649
+ /**
2650
+ * Adds an observer for when {@link InteractElement.fields | element's data}
2651
+ * is updated
2652
+ */
2653
+ function onElementUpdated(event, callback) {
2654
+ configureEvent(event);
2655
+ return sdkUtil.subscribe(event, 'update', callback);
2656
+ }
2657
+ /**
2658
+ * Adds an observer for when a new element is published
2659
+ */
2660
+ function onElementPublished(event, callback) {
2661
+ configureEvent(event);
2662
+ return sdkUtil.subscribe(event, 'publish', function (element) {
2663
+ if (event.initState === InitState.Initialised) {
2664
+ callback(element);
2665
+ }
2666
+ });
2667
+ }
2668
+ /**
2669
+ * Adds an observer for when an element is revoked
2670
+ */
2671
+ function onElementRevoked(event, callback) {
2672
+ configureEvent(event);
2673
+ return sdkUtil.subscribe(event, 'revoke', callback);
2674
+ }
2675
+
2676
+ exports.Answer = Answer;
2677
+ exports.ElementImpl = ElementImpl;
2678
+ exports.EventImpl = EventImpl;
2679
+ exports.ProjectImpl = ProjectImpl;
2680
+ exports.answer = answer;
2681
+ exports.fetchListings = fetchListings;
2682
+ exports.getConnect = getConnect;
2683
+ exports.getConnectionHealth = getConnectionHealth;
2684
+ exports.getElement = getElement;
2685
+ exports.getElementMemoized = getElementMemoized;
2686
+ exports.getElements = getElements;
2687
+ exports.getElementsMemoized = getElementsMemoized;
2688
+ exports.getEvent = getEvent;
2689
+ exports.getEventMemoized = getEventMemoized;
2690
+ exports.getEvents = getEvents;
2691
+ exports.getEventsMemoized = getEventsMemoized;
2692
+ exports.getProject = getProject;
2693
+ exports.getProjectMemoized = getProjectMemoized;
2694
+ exports.login = login;
2695
+ exports.onConnectionHealthState = onConnectionHealthState;
2696
+ exports.onElementPublished = onElementPublished;
2697
+ exports.onElementResults = onElementResults;
2698
+ exports.onElementRevoked = onElementRevoked;
2699
+ exports.onElementStateChanged = onElementStateChanged;
2700
+ exports.onElementUpdated = onElementUpdated;
2701
+ exports.onEventAdded = onEventAdded;
2702
+ exports.onEventPublished = onEventPublished;
2703
+ exports.onEventRemoved = onEventRemoved;
2704
+ exports.onEventState = onEventState;
2705
+ exports.onEventUpdated = onEventUpdated;
2706
+ exports.onProjectFieldsUpdated = onProjectFieldsUpdated;
2707
+ exports.onProjectListingsUpdated = onProjectListingsUpdated;
2708
+ exports.validateAnswer = validateAnswer;
2709
+ //# sourceMappingURL=index.cjs.js.map