@monterosa/sdk-util 2.0.0-rc.1 → 2.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js DELETED
@@ -1,1231 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var mitt = require('mitt');
6
-
7
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
-
9
- var mitt__default = /*#__PURE__*/_interopDefaultLegacy(mitt);
10
-
11
- /**
12
- * @license
13
- * @monterosa/sdk-util
14
- *
15
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
16
- *
17
- * More details on the license can be found at https://www.monterosa.co/sdk/license
18
- */
19
- var Emitter = /** @class */ (function () {
20
- function Emitter() {
21
- this.handlers = new Map();
22
- this.emitter = mitt__default["default"]();
23
- }
24
- Emitter.prototype.on = function (event, handler) {
25
- var _this = this;
26
- var mittHandler = function (args) {
27
- handler.apply(void 0, (Array.isArray(args) ? args : [args]));
28
- };
29
- this.handlers.set(handler, mittHandler);
30
- this.emitter.on(event, mittHandler);
31
- return function () { return _this.off(event, handler); };
32
- };
33
- Emitter.prototype.off = function (event, handler) {
34
- if (handler === undefined) {
35
- this.emitter.off(event);
36
- return;
37
- }
38
- var mittHandler = this.handlers.get(handler);
39
- if (mittHandler) {
40
- this.emitter.off(event, mittHandler);
41
- this.handlers.delete(handler);
42
- }
43
- };
44
- Emitter.prototype.emit = function (event) {
45
- var args = [];
46
- for (var _i = 1; _i < arguments.length; _i++) {
47
- args[_i - 1] = arguments[_i];
48
- }
49
- this.emitter.emit(event, args);
50
- };
51
- Emitter.prototype.once = function (event, handler) {
52
- var _this = this;
53
- var mittHandler = function (args) {
54
- handler.apply(void 0, (Array.isArray(args) ? args : [args]));
55
- _this.off(event, handler);
56
- };
57
- this.handlers.set(handler, mittHandler);
58
- this.emitter.on(event, mittHandler);
59
- return function () { return _this.off(event, handler); };
60
- };
61
- return Emitter;
62
- }());
63
- /**
64
- * @internal
65
- */
66
- var subscribe = function (emitter, event, callback) {
67
- emitter.on(event, callback);
68
- return function () { return emitter.off(event, callback); };
69
- };
70
-
71
- /******************************************************************************
72
- Copyright (c) Microsoft Corporation.
73
-
74
- Permission to use, copy, modify, and/or distribute this software for any
75
- purpose with or without fee is hereby granted.
76
-
77
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
78
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
79
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
80
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
81
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
82
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
83
- PERFORMANCE OF THIS SOFTWARE.
84
- ***************************************************************************** */
85
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
86
-
87
- var extendStatics = function(d, b) {
88
- extendStatics = Object.setPrototypeOf ||
89
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
90
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
91
- return extendStatics(d, b);
92
- };
93
-
94
- function __extends(d, b) {
95
- if (typeof b !== "function" && b !== null)
96
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
97
- extendStatics(d, b);
98
- function __() { this.constructor = d; }
99
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
100
- }
101
-
102
- function __awaiter(thisArg, _arguments, P, generator) {
103
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
104
- return new (P || (P = Promise))(function (resolve, reject) {
105
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
106
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
107
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
108
- step((generator = generator.apply(thisArg, _arguments || [])).next());
109
- });
110
- }
111
-
112
- function __generator(thisArg, body) {
113
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
114
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
115
- function verb(n) { return function (v) { return step([n, v]); }; }
116
- function step(op) {
117
- if (f) throw new TypeError("Generator is already executing.");
118
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
119
- 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;
120
- if (y = 0, t) op = [op[0] & 2, t.value];
121
- switch (op[0]) {
122
- case 0: case 1: t = op; break;
123
- case 4: _.label++; return { value: op[1], done: false };
124
- case 5: _.label++; y = op[1]; op = [0]; continue;
125
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
126
- default:
127
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
128
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
129
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
130
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
131
- if (t[2]) _.ops.pop();
132
- _.trys.pop(); continue;
133
- }
134
- op = body.call(thisArg, _);
135
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
136
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
137
- }
138
- }
139
-
140
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
141
- var e = new Error(message);
142
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
143
- };
144
-
145
- /**
146
- * @license
147
- * @monterosa/sdk-util
148
- *
149
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
150
- *
151
- * More details on the license can be found at https://www.monterosa.co/sdk/license
152
- */
153
- /**
154
- * @internal
155
- *
156
- * Delays the execution of the code for a given number of milliseconds.
157
- *
158
- * @param timeout - The timeout in milliseconds.
159
- *
160
- * @returns A promise that resolves after the timeout.
161
- */
162
- var delay = function (timeout) { return __awaiter(void 0, void 0, void 0, function () {
163
- return __generator(this, function (_a) {
164
- switch (_a.label) {
165
- case 0: return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, timeout); })];
166
- case 1:
167
- _a.sent();
168
- return [2 /*return*/];
169
- }
170
- });
171
- }); };
172
-
173
- /**
174
- * @license
175
- * @monterosa/sdk-util
176
- *
177
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
178
- *
179
- * More details on the license can be found at https://www.monterosa.co/sdk/license
180
- */
181
- /**
182
- * Creates a function that memoizes the result of `func`.
183
- *
184
- * @internal
185
- *
186
- * @param func - A function that returns a promise. The results of its work will be memoized.
187
- * @param resolver - A function that determines the cache key.
188
- * @param config - A configuration object with the following optional properties:
189
- * `clearOnResolve` - Deletes memoized result upon promise resolve. Defaults to `false`.
190
- * `clearOnReject` - Deletes memoized result upon promise reject. Defaults to `true`.
191
- */
192
- var memoizePromise = function (func, resolver, config) {
193
- var _a, _b;
194
- if (config === void 0) { config = {}; }
195
- var clearOnResolve = (_a = config.clearOnResolve) !== null && _a !== void 0 ? _a : false;
196
- var clearOnReject = (_b = config.clearOnReject) !== null && _b !== void 0 ? _b : true;
197
- var cache = new Map();
198
- var memoized = function () {
199
- var args = [];
200
- for (var _i = 0; _i < arguments.length; _i++) {
201
- args[_i] = arguments[_i];
202
- }
203
- var key = resolver.apply(void 0, args);
204
- if (cache.has(key)) {
205
- return cache.get(key);
206
- }
207
- var promise = func.apply(void 0, args);
208
- cache.set(key, promise);
209
- promise
210
- .then(function () { return clearOnResolve && cache.delete(key); })
211
- .catch(function () { return clearOnReject && cache.delete(key); });
212
- return promise;
213
- };
214
- memoized.cache = cache;
215
- return memoized;
216
- };
217
-
218
- /**
219
- * @license
220
- * @monterosa/sdk-util
221
- *
222
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
223
- *
224
- * More details on the license can be found at https://www.monterosa.co/sdk/license
225
- */
226
- /* eslint no-restricted-globals: "off" */
227
- /**
228
- * @preserve
229
- * Global object polyfill.
230
- * Based on MDN article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
231
- *
232
- * @internal
233
- *
234
- * @returns typeof globalThis
235
- */
236
- function getGlobal() {
237
- if (typeof self !== 'undefined') {
238
- return self;
239
- }
240
- if (typeof globalThis !== 'undefined') {
241
- return globalThis;
242
- }
243
- if (typeof window !== 'undefined') {
244
- return window;
245
- }
246
- if (typeof global !== 'undefined') {
247
- return global;
248
- }
249
- throw new Error('Unable to locate global object.');
250
- }
251
-
252
- /**
253
- * @license
254
- * @monterosa/sdk-util
255
- *
256
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
257
- *
258
- * More details on the license can be found at https://www.monterosa.co/sdk/license
259
- */
260
- var PREFIX = 'monterosa_sdk_';
261
- var BAIT = 'bait';
262
- var globals = getGlobal();
263
- /**
264
- * @internal
265
- */
266
- var getKey = function (name) { return "".concat(PREFIX).concat(name); };
267
- /**
268
- * @internal
269
- */
270
- function getItem(key) {
271
- return globals.localStorage.getItem(getKey(key));
272
- }
273
- /**
274
- * @internal
275
- */
276
- function setItem(key, value) {
277
- return globals.localStorage.setItem(getKey(key), value);
278
- }
279
- /**
280
- * @internal
281
- */
282
- function removeItem(key) {
283
- return globals.localStorage.removeItem(getKey(key));
284
- }
285
- /**
286
- * @internal
287
- */
288
- function clear() {
289
- return globals.localStorage.clear();
290
- }
291
- /**
292
- * Checks locastorage availability.
293
- * Based on MDN article: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
294
- * and Paul Irish gists: https://gist.github.com/paulirish/5558557
295
- *
296
- * @internal
297
- *
298
- * @returns boolean
299
- */
300
- function checkAvailability() {
301
- try {
302
- setItem(BAIT, BAIT);
303
- getItem(BAIT);
304
- removeItem(BAIT);
305
- return true;
306
- }
307
- catch (e) {
308
- return false;
309
- }
310
- }
311
-
312
- /**
313
- * @license
314
- * @monterosa/sdk-util
315
- *
316
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
317
- *
318
- * More details on the license can be found at https://www.monterosa.co/sdk/license
319
- */
320
- /* eslint max-classes-per-file: ["error", 2] */
321
- /**
322
- * MonterosaError extends the standard JavaScript `Error` object. It has
323
- * an error code so that user can identify the error. Also it has it's own
324
- * specific `name` "MonterosaError"
325
- */
326
- var MonterosaError = /** @class */ (function (_super) {
327
- __extends(MonterosaError, _super);
328
- /**
329
- * @param code - Error code string
330
- * @param message - A descriptive message for the error
331
- */
332
- function MonterosaError(code, message) {
333
- var _this = _super.call(this, message) || this;
334
- /**
335
- * The name property represents a name for the type of error.
336
- */
337
- _this.name = 'MonterosaError';
338
- _this.code = code;
339
- // Fix For ES5
340
- // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
341
- Object.setPrototypeOf(_this, MonterosaError.prototype);
342
- return _this;
343
- }
344
- return MonterosaError;
345
- }(Error));
346
- /**
347
- * @internal
348
- */
349
- function createError(code, messages) {
350
- var params = [];
351
- for (var _i = 2; _i < arguments.length; _i++) {
352
- params[_i - 2] = arguments[_i];
353
- }
354
- var message = messages[code].apply(messages, params);
355
- return new MonterosaError(code, message);
356
- }
357
- /**
358
- * @internal
359
- */
360
- function getErrorMessage(err) {
361
- if (err instanceof Error) {
362
- return err.message;
363
- }
364
- if (typeof err === 'string') {
365
- return err;
366
- }
367
- try {
368
- return JSON.stringify(err);
369
- }
370
- catch (_a) {
371
- return 'Unknown error';
372
- }
373
- }
374
-
375
- /**
376
- * @license
377
- * @monterosa/sdk-util
378
- *
379
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
380
- *
381
- * More details on the license can be found at https://www.monterosa.co/sdk/license
382
- */
383
- /* eslint-disable */
384
- // @ts-nocheck
385
- /**
386
- * @copyright
387
- * lodash (Custom Build) <https://lodash.com/>
388
- * Build: `lodash modularize exports="npm" -o ./`
389
- * Copyright jQuery Foundation and other contributors <https://jquery.org/>
390
- * Released under MIT license <https://lodash.com/license>
391
- * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
392
- * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
393
- */
394
- /** Used as the `TypeError` message for "Functions" methods. */
395
- var FUNC_ERROR_TEXT = 'Expected a function';
396
- /** Used as references for various `Number` constants. */
397
- var NAN = 0 / 0;
398
- /** `Object#toString` result references. */
399
- var symbolTag = '[object Symbol]';
400
- /** Used to match leading and trailing whitespace. */
401
- var reTrim = /^\s+|\s+$/g;
402
- /** Used to detect bad signed hexadecimal string values. */
403
- var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
404
- /** Used to detect binary string values. */
405
- var reIsBinary = /^0b[01]+$/i;
406
- /** Used to detect octal string values. */
407
- var reIsOctal = /^0o[0-7]+$/i;
408
- /** Built-in method references without a dependency on `root`. */
409
- var freeParseInt = parseInt;
410
- /** Detect free variable `global` from Node.js. */
411
- var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
412
- /** Detect free variable `self`. */
413
- var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
414
- /** Used as a reference to the global object. */
415
- var root = freeGlobal || freeSelf || Function('return this')();
416
- /** Used for built-in method references. */
417
- var objectProto = Object.prototype;
418
- /**
419
- * Used to resolve the
420
- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
421
- * of values.
422
- */
423
- var objectToString = objectProto.toString;
424
- /* Built-in method references for those with the same name as other `lodash` methods. */
425
- var nativeMax = Math.max, nativeMin = Math.min;
426
- /**
427
- * Gets the timestamp of the number of milliseconds that have elapsed since
428
- * the Unix epoch (1 January 1970 00:00:00 UTC).
429
- *
430
- * @static
431
- * @memberOf _
432
- * @since 2.4.0
433
- * @category Date
434
- * @returns {number} Returns the timestamp.
435
- * @example
436
- *
437
- * _.defer(function(stamp) {
438
- * console.log(_.now() - stamp);
439
- * }, _.now());
440
- * // => Logs the number of milliseconds it took for the deferred invocation.
441
- */
442
- var now$1 = function () {
443
- return root.Date.now();
444
- };
445
- /**
446
- * Creates a debounced function that delays invoking `func` until after `wait`
447
- * milliseconds have elapsed since the last time the debounced function was
448
- * invoked. The debounced function comes with a `cancel` method to cancel
449
- * delayed `func` invocations and a `flush` method to immediately invoke them.
450
- * Provide `options` to indicate whether `func` should be invoked on the
451
- * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
452
- * with the last arguments provided to the debounced function. Subsequent
453
- * calls to the debounced function return the result of the last `func`
454
- * invocation.
455
- *
456
- * **Note:** If `leading` and `trailing` options are `true`, `func` is
457
- * invoked on the trailing edge of the timeout only if the debounced function
458
- * is invoked more than once during the `wait` timeout.
459
- *
460
- * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
461
- * until to the next tick, similar to `setTimeout` with a timeout of `0`.
462
- *
463
- * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
464
- * for details over the differences between `_.debounce` and `_.throttle`.
465
- *
466
- * @static
467
- * @memberOf _
468
- * @since 0.1.0
469
- * @category Function
470
- * @param {Function} func The function to debounce.
471
- * @param {number} [wait=0] The number of milliseconds to delay.
472
- * @param {Object} [options={}] The options object.
473
- * @param {boolean} [options.leading=false]
474
- * Specify invoking on the leading edge of the timeout.
475
- * @param {number} [options.maxWait]
476
- * The maximum time `func` is allowed to be delayed before it's invoked.
477
- * @param {boolean} [options.trailing=true]
478
- * Specify invoking on the trailing edge of the timeout.
479
- * @returns {Function} Returns the new debounced function.
480
- * @example
481
- *
482
- * // Avoid costly calculations while the window size is in flux.
483
- * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
484
- *
485
- * // Invoke `sendMail` when clicked, debouncing subsequent calls.
486
- * jQuery(element).on('click', _.debounce(sendMail, 300, {
487
- * 'leading': true,
488
- * 'trailing': false
489
- * }));
490
- *
491
- * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
492
- * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
493
- * var source = new EventSource('/stream');
494
- * jQuery(source).on('message', debounced);
495
- *
496
- * // Cancel the trailing debounced invocation.
497
- * jQuery(window).on('popstate', debounced.cancel);
498
- */
499
- function debounce(func, wait, options) {
500
- var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
501
- if (typeof func != 'function') {
502
- throw new TypeError(FUNC_ERROR_TEXT);
503
- }
504
- wait = toNumber(wait) || 0;
505
- if (isObject(options)) {
506
- leading = !!options.leading;
507
- maxing = 'maxWait' in options;
508
- maxWait = maxing
509
- ? nativeMax(toNumber(options.maxWait) || 0, wait)
510
- : maxWait;
511
- trailing = 'trailing' in options ? !!options.trailing : trailing;
512
- }
513
- function invokeFunc(time) {
514
- var args = lastArgs, thisArg = lastThis;
515
- lastArgs = lastThis = undefined;
516
- lastInvokeTime = time;
517
- result = func.apply(thisArg, args);
518
- return result;
519
- }
520
- function leadingEdge(time) {
521
- // Reset any `maxWait` timer.
522
- lastInvokeTime = time;
523
- // Start the timer for the trailing edge.
524
- timerId = setTimeout(timerExpired, wait);
525
- // Invoke the leading edge.
526
- return leading ? invokeFunc(time) : result;
527
- }
528
- function remainingWait(time) {
529
- var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result = wait - timeSinceLastCall;
530
- return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;
531
- }
532
- function shouldInvoke(time) {
533
- var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
534
- // Either this is the first call, activity has stopped and we're at the
535
- // trailing edge, the system time has gone backwards and we're treating
536
- // it as the trailing edge, or we've hit the `maxWait` limit.
537
- return (lastCallTime === undefined ||
538
- timeSinceLastCall >= wait ||
539
- timeSinceLastCall < 0 ||
540
- (maxing && timeSinceLastInvoke >= maxWait));
541
- }
542
- function timerExpired() {
543
- var time = now$1();
544
- if (shouldInvoke(time)) {
545
- return trailingEdge(time);
546
- }
547
- // Restart the timer.
548
- timerId = setTimeout(timerExpired, remainingWait(time));
549
- }
550
- function trailingEdge(time) {
551
- timerId = undefined;
552
- // Only invoke if we have `lastArgs` which means `func` has been
553
- // debounced at least once.
554
- if (trailing && lastArgs) {
555
- return invokeFunc(time);
556
- }
557
- lastArgs = lastThis = undefined;
558
- return result;
559
- }
560
- function cancel() {
561
- if (timerId !== undefined) {
562
- clearTimeout(timerId);
563
- }
564
- lastInvokeTime = 0;
565
- lastArgs = lastCallTime = lastThis = timerId = undefined;
566
- }
567
- function flush() {
568
- return timerId === undefined ? result : trailingEdge(now$1());
569
- }
570
- function debounced() {
571
- var time = now$1(), isInvoking = shouldInvoke(time);
572
- lastArgs = arguments;
573
- lastThis = this;
574
- lastCallTime = time;
575
- if (isInvoking) {
576
- if (timerId === undefined) {
577
- return leadingEdge(lastCallTime);
578
- }
579
- if (maxing) {
580
- // Handle invocations in a tight loop.
581
- timerId = setTimeout(timerExpired, wait);
582
- return invokeFunc(lastCallTime);
583
- }
584
- }
585
- if (timerId === undefined) {
586
- timerId = setTimeout(timerExpired, wait);
587
- }
588
- return result;
589
- }
590
- debounced.cancel = cancel;
591
- debounced.flush = flush;
592
- return debounced;
593
- }
594
- /**
595
- * Creates a throttled function that only invokes `func` at most once per
596
- * every `wait` milliseconds. The throttled function comes with a `cancel`
597
- * method to cancel delayed `func` invocations and a `flush` method to
598
- * immediately invoke them. Provide `options` to indicate whether `func`
599
- * should be invoked on the leading and/or trailing edge of the `wait`
600
- * timeout. The `func` is invoked with the last arguments provided to the
601
- * throttled function. Subsequent calls to the throttled function return the
602
- * result of the last `func` invocation.
603
- *
604
- * **Note:** If `leading` and `trailing` options are `true`, `func` is
605
- * invoked on the trailing edge of the timeout only if the throttled function
606
- * is invoked more than once during the `wait` timeout.
607
- *
608
- * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
609
- * until to the next tick, similar to `setTimeout` with a timeout of `0`.
610
- *
611
- * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
612
- * for details over the differences between `_.throttle` and `_.debounce`.
613
- *
614
- * @internal
615
- *
616
- * @static
617
- * @memberOf _
618
- * @since 0.1.0
619
- * @category Function
620
- * @param {Function} func The function to throttle.
621
- * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
622
- * @param {Object} [options={}] The options object.
623
- * @param {boolean} [options.leading=true]
624
- * Specify invoking on the leading edge of the timeout.
625
- * @param {boolean} [options.trailing=true]
626
- * Specify invoking on the trailing edge of the timeout.
627
- * @returns {Function} Returns the new throttled function.
628
- * @example
629
- *
630
- * // Avoid excessively updating the position while scrolling.
631
- * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
632
- *
633
- * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
634
- * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
635
- * jQuery(element).on('click', throttled);
636
- *
637
- * // Cancel the trailing throttled invocation.
638
- * jQuery(window).on('popstate', throttled.cancel);
639
- */
640
- function throttle(func, wait, options) {
641
- var leading = true, trailing = true;
642
- if (typeof func != 'function') {
643
- throw new TypeError(FUNC_ERROR_TEXT);
644
- }
645
- if (isObject(options)) {
646
- leading = 'leading' in options ? !!options.leading : leading;
647
- trailing = 'trailing' in options ? !!options.trailing : trailing;
648
- }
649
- return debounce(func, wait, {
650
- leading: leading,
651
- maxWait: wait,
652
- trailing: trailing,
653
- });
654
- }
655
- /**
656
- * Checks if `value` is the
657
- * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
658
- * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
659
- *
660
- * @static
661
- * @memberOf _
662
- * @since 0.1.0
663
- * @category Lang
664
- * @param {*} value The value to check.
665
- * @returns {boolean} Returns `true` if `value` is an object, else `false`.
666
- * @example
667
- *
668
- * _.isObject({});
669
- * // => true
670
- *
671
- * _.isObject([1, 2, 3]);
672
- * // => true
673
- *
674
- * _.isObject(_.noop);
675
- * // => true
676
- *
677
- * _.isObject(null);
678
- * // => false
679
- */
680
- function isObject(value) {
681
- var type = typeof value;
682
- return !!value && (type == 'object' || type == 'function');
683
- }
684
- /**
685
- * Checks if `value` is object-like. A value is object-like if it's not `null`
686
- * and has a `typeof` result of "object".
687
- *
688
- * @static
689
- * @memberOf _
690
- * @since 4.0.0
691
- * @category Lang
692
- * @param {*} value The value to check.
693
- * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
694
- * @example
695
- *
696
- * _.isObjectLike({});
697
- * // => true
698
- *
699
- * _.isObjectLike([1, 2, 3]);
700
- * // => true
701
- *
702
- * _.isObjectLike(_.noop);
703
- * // => false
704
- *
705
- * _.isObjectLike(null);
706
- * // => false
707
- */
708
- function isObjectLike(value) {
709
- return !!value && typeof value == 'object';
710
- }
711
- /**
712
- * Checks if `value` is classified as a `Symbol` primitive or object.
713
- *
714
- * @static
715
- * @memberOf _
716
- * @since 4.0.0
717
- * @category Lang
718
- * @param {*} value The value to check.
719
- * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
720
- * @example
721
- *
722
- * _.isSymbol(Symbol.iterator);
723
- * // => true
724
- *
725
- * _.isSymbol('abc');
726
- * // => false
727
- */
728
- function isSymbol(value) {
729
- return (typeof value == 'symbol' ||
730
- (isObjectLike(value) && objectToString.call(value) == symbolTag));
731
- }
732
- /**
733
- * Converts `value` to a number.
734
- *
735
- * @static
736
- * @memberOf _
737
- * @since 4.0.0
738
- * @category Lang
739
- * @param {*} value The value to process.
740
- * @returns {number} Returns the number.
741
- * @example
742
- *
743
- * _.toNumber(3.2);
744
- * // => 3.2
745
- *
746
- * _.toNumber(Number.MIN_VALUE);
747
- * // => 5e-324
748
- *
749
- * _.toNumber(Infinity);
750
- * // => Infinity
751
- *
752
- * _.toNumber('3.2');
753
- * // => 3.2
754
- */
755
- function toNumber(value) {
756
- if (typeof value == 'number') {
757
- return value;
758
- }
759
- if (isSymbol(value)) {
760
- return NAN;
761
- }
762
- if (isObject(value)) {
763
- var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
764
- value = isObject(other) ? other + '' : other;
765
- }
766
- if (typeof value != 'string') {
767
- return value === 0 ? value : +value;
768
- }
769
- value = value.replace(reTrim, '');
770
- var isBinary = reIsBinary.test(value);
771
- return isBinary || reIsOctal.test(value)
772
- ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
773
- : reIsBadHex.test(value)
774
- ? NAN
775
- : +value;
776
- }
777
-
778
- /**
779
- * @license
780
- * @monterosa/sdk-interact-kit
781
- *
782
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
783
- *
784
- * More details on the license can be found at https://www.monterosa.co/sdk/license
785
- */
786
- var emitter = new Emitter();
787
- var serverTimestamp = 0;
788
- var lastTickTimestamp = 0;
789
- var tickTimeoutId;
790
- /**
791
- * Returns local timestamp in seconds
792
- */
793
- function getCurrentTimestamp() {
794
- return Date.now() / 1000;
795
- }
796
- /**
797
- * Normalizes the timestamp to reduce fluctuations due to `setTimeout` delays.
798
- * Ensures the fractional part is around 0.5 to avoid skipping a second.
799
- *
800
- * Returns half-second timestamp. It is used to be sure that timestamp will not
801
- * fluctuate more than in 1 second after each tick due to longer delays.
802
- * https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#reasons_for_delays_longer_than_specified
803
- *
804
- * For example if the initial timestamp has a fractional part 0.9999 then with
805
- * the setTimeout (tick) longer than specified we might jump over a one second.
806
- * Lets imaging setTimeout took 1.0002 second, then our timestamp will be 2.0001.
807
- * Thats why we are trying to keep fractional part in the middle of the second.
808
- */
809
- function getMiddleTimestamp(timestamp) {
810
- return Math.floor(timestamp) + 0.5;
811
- }
812
- /**
813
- * Calculates the delay for the next tick to keep timestamps stable.
814
- */
815
- function calculateNextTickDelay() {
816
- var expectedNextTick = getMiddleTimestamp(serverTimestamp) + 1;
817
- return (expectedNextTick - serverTimestamp) * 1000;
818
- }
819
- /**
820
- * Main function that maintains current timestamp
821
- */
822
- function tick() {
823
- clearTimeout(tickTimeoutId);
824
- var currentTimestamp = getCurrentTimestamp();
825
- var timeSinceLastTick = currentTimestamp - lastTickTimestamp;
826
- serverTimestamp += timeSinceLastTick;
827
- lastTickTimestamp = currentTimestamp;
828
- tickTimeoutId = setTimeout(tick, calculateNextTickDelay());
829
- emitter.emit('tick', serverTimestamp);
830
- }
831
- /**
832
- * @internal
833
- *
834
- * Sets or updates current timestamp
835
- *
836
- * @param timestamp - Current timestamp in seconds
837
- */
838
- function setTimestamp(timestamp) {
839
- lastTickTimestamp = getCurrentTimestamp();
840
- serverTimestamp = getMiddleTimestamp(timestamp);
841
- }
842
- /**
843
- * Returns current timestamp that is preserved by `tick()` function
844
- *
845
- * @returns Current timestamp in seconds
846
- */
847
- function now() {
848
- return Math.floor(serverTimestamp);
849
- }
850
- /**
851
- * Subscribes listener to the timestamp increment
852
- *
853
- * @param callback - A handler that executes when the timestamp is incremented
854
- *
855
- * @returns A function that unsubscribes the listener
856
- */
857
- function onTick(callback) {
858
- return subscribe(emitter, 'tick', callback);
859
- }
860
- // Initially timestamp is set based on a local date
861
- // Later on it can be overriden outside at any moment
862
- // in our case it is populated with the server timestamp
863
- // which comes from EnMasse session handshake message
864
- setTimestamp(getCurrentTimestamp());
865
- // Kicking in timestamp maintaining
866
- tick();
867
-
868
- /**
869
- * @license
870
- * fromentries.ts
871
- * util
872
- *
873
- * Copyright © 2023 Monterosa Productions Limited. All rights reserved.
874
- *
875
- * More details on the license can be found at https://www.monterosa.co/sdk/license
876
- */
877
- function fromEntries(entries) {
878
- return entries.reduce(function (obj, _a) {
879
- var key = _a[0], value = _a[1];
880
- obj[key] = value;
881
- return obj;
882
- }, {});
883
- }
884
-
885
- /**
886
- * @license
887
- * @monterosa/sdk-util
888
- *
889
- * Copyright © 2025 Monterosa Productions Limited. All rights reserved.
890
- *
891
- * More details on the license can be found at https://www.monterosa.co/sdk/license
892
- */
893
- /**
894
- * Calculate percentage of each value in the array.
895
- *
896
- * It uses Hamilton's method, also known as the method of largest remainder.
897
- * It is a system used for distributing vote percentages among different
898
- * options (like candidates or choices) based on their vote counts. It ensures
899
- * that each option receives at least its lower quota of percentage points, and
900
- * any remaining percentage points are allocated to those with the largest
901
- * fractional remainders. This method is used in the US Electoral College.
902
- *
903
- * @param values - Array of number values to calculate percentage for
904
- * @returns Array of percentages, where the sum of the array is 100%
905
- */
906
- var calculatePercentage = function (values) {
907
- // Calculate sum of all votes
908
- var sum = values.reduce(function (memo, value) { return memo + value; }, 0);
909
- // create array of hashes
910
- var results = values.map(function (value, idx) {
911
- var percentage = (100 * value) / sum || 0;
912
- return {
913
- idx: idx,
914
- votes: value,
915
- percentage: Math.floor(percentage),
916
- remainder: percentage % 1,
917
- };
918
- });
919
- // Sum them all up - this can't be higher than 100%
920
- var total = results.reduce(function (memo, _a) {
921
- var percentage = _a.percentage;
922
- return memo + percentage;
923
- }, 0);
924
- total = total || 100;
925
- // Calculate number of percent that we are missing
926
- var delta = 100 - total;
927
- // Order all options by remainder
928
- results.sort(function (a, b) {
929
- if (a.remainder !== b.remainder) {
930
- return b.remainder - a.remainder;
931
- }
932
- return a.idx - b.idx;
933
- });
934
- // Distribute delta to highest remainder options
935
- for (var i = 0; i < delta; i++) {
936
- results[i].percentage += 1;
937
- }
938
- // Restore options order
939
- results.sort(function (a, b) { return a.idx - b.idx; });
940
- return results.map(function (item) { return item.percentage; });
941
- };
942
-
943
- /**
944
- * @license
945
- * @monterosa/sdk-identify-kit
946
- *
947
- * Copyright © 2025 Monterosa Productions Limited. All rights reserved.
948
- *
949
- * More details on the license can be found at https://www.monterosa.co/sdk/license
950
- */
951
- /**
952
- * TaskQueue ensures that async tasks run sequentially (FIFO).
953
- *
954
- * Behavior:
955
- * - Tasks run one at a time in the order they were enqueued.
956
- * - If a task fails (throws/rejects), the queue is stopped
957
- * and all pending tasks are cleared.
958
- */
959
- var TaskQueue = /** @class */ (function () {
960
- function TaskQueue() {
961
- this.current = null;
962
- this.queue = [];
963
- this.paused = false;
964
- }
965
- TaskQueue.prototype.enqueue = function (fn) {
966
- this.queue.push(fn);
967
- this.process();
968
- };
969
- TaskQueue.prototype.enqueueFront = function (fn) {
970
- this.queue.unshift(fn);
971
- this.process();
972
- };
973
- TaskQueue.prototype.pause = function () {
974
- this.paused = true;
975
- };
976
- TaskQueue.prototype.resume = function () {
977
- this.paused = false;
978
- this.process();
979
- };
980
- TaskQueue.prototype.process = function () {
981
- var _this = this;
982
- if (this.current || this.paused) {
983
- return;
984
- }
985
- var next = this.queue.shift();
986
- if (!next) {
987
- return;
988
- }
989
- this.current = next()
990
- .then(function () {
991
- _this.current = null;
992
- _this.process();
993
- })
994
- .catch(function () {
995
- _this.clear();
996
- });
997
- };
998
- Object.defineProperty(TaskQueue.prototype, "length", {
999
- get: function () {
1000
- return this.queue.length;
1001
- },
1002
- enumerable: false,
1003
- configurable: true
1004
- });
1005
- TaskQueue.prototype.isEmpty = function () {
1006
- return this.queue.length === 0;
1007
- };
1008
- TaskQueue.prototype.hasActiveTask = function () {
1009
- return this.current !== null;
1010
- };
1011
- TaskQueue.prototype.clear = function () {
1012
- this.queue = [];
1013
- this.current = null;
1014
- };
1015
- return TaskQueue;
1016
- }());
1017
-
1018
- /**
1019
- * @license
1020
- * @monterosa/sdk-util
1021
- *
1022
- * Copyright © 2025 Monterosa Productions Limited. All rights reserved.
1023
- *
1024
- * More details on the license can be found at https://www.monterosa.co/sdk/license
1025
- */
1026
- /**
1027
- * Calculates the delay for a retry attempt based on the backoff strategy.
1028
- *
1029
- * @param backoffStrategy - The backoff strategy.
1030
- * @param attemptNumber - The current attempt number (0-indexed).
1031
- * @param baseDelay - The base delay in milliseconds.
1032
- * @param jitter - The maximum jitter to add in milliseconds.
1033
- * @param maxDelay - The maximum delay in milliseconds.
1034
- *
1035
- * @returns The calculated delay in milliseconds.
1036
- */
1037
- function calculateRetryDelay(backoffStrategy, attemptNumber, baseDelay, jitter, maxDelay) {
1038
- var delayMs;
1039
- switch (backoffStrategy) {
1040
- case 'fixed':
1041
- delayMs = baseDelay;
1042
- break;
1043
- case 'incremental':
1044
- delayMs = baseDelay * (attemptNumber + 1);
1045
- break;
1046
- case 'exponential':
1047
- default:
1048
- delayMs = baseDelay * Math.pow(2, attemptNumber);
1049
- }
1050
- // Add jitter (random value between 0 and jitter)
1051
- delayMs += Math.floor(Math.random() * jitter);
1052
- // Cap at maxDelay
1053
- return Math.min(delayMs, maxDelay);
1054
- }
1055
- /**
1056
- * Default configuration values for retry logic.
1057
- */
1058
- var DEFAULT_RETRY_CONFIG = {
1059
- backoffStrategy: 'exponential',
1060
- attempts: 3,
1061
- baseDelay: 500,
1062
- jitter: 500,
1063
- maxDelay: 10000,
1064
- };
1065
- /**
1066
- * Wraps an async function with retry logic and configurable backoff strategies.
1067
- *
1068
- * @template TArgs - The argument types of the wrapped function.
1069
- * @template TResult - The return type of the wrapped function.
1070
- *
1071
- * @param fn - The async function to wrap.
1072
- * @param config - Configuration object for retry behavior.
1073
- * - backoffStrategy: BackoffStrategy (default: 'exponential')
1074
- * - attempts: number of retry attempts (default: 3)
1075
- * - baseDelay: base delay in ms (default: 500)
1076
- * - jitter: max jitter in ms (default: 500)
1077
- * - maxDelay: max delay in ms (default: 10_000)
1078
- *
1079
- * @returns A new function that retries the given async function up to the
1080
- * specified number of attempts with the configured backoff strategy.
1081
- *
1082
- * @throws The last encountered error if all retry attempts fail.
1083
- *
1084
- * @example
1085
- * const fetchDataWithRetry = withRetryAsync(fetchData, {
1086
- * backoffStrategy: 'exponential',
1087
- * attempts: 3,
1088
- * baseDelay: 500
1089
- * });
1090
- *
1091
- * // Will retry up to 3 times with exponential backoff
1092
- * fetchDataWithRetry("https://api.example.com")
1093
- * .then(data => console.log(data))
1094
- * .catch(err => console.error("Failed after retries:", err));
1095
- */
1096
- function withRetryAsync(fn, config) {
1097
- var _this = this;
1098
- if (config === void 0) { config = {}; }
1099
- var _a = config.backoffStrategy, backoffStrategy = _a === void 0 ? DEFAULT_RETRY_CONFIG.backoffStrategy : _a, _b = config.attempts, attempts = _b === void 0 ? DEFAULT_RETRY_CONFIG.attempts : _b, _c = config.baseDelay, baseDelay = _c === void 0 ? DEFAULT_RETRY_CONFIG.baseDelay : _c, _d = config.jitter, jitter = _d === void 0 ? DEFAULT_RETRY_CONFIG.jitter : _d, _e = config.maxDelay, maxDelay = _e === void 0 ? DEFAULT_RETRY_CONFIG.maxDelay : _e;
1100
- return function () {
1101
- var args = [];
1102
- for (var _i = 0; _i < arguments.length; _i++) {
1103
- args[_i] = arguments[_i];
1104
- }
1105
- return __awaiter(_this, void 0, void 0, function () {
1106
- var lastError, i, error_1, delayMs;
1107
- return __generator(this, function (_a) {
1108
- switch (_a.label) {
1109
- case 0:
1110
- i = 0;
1111
- _a.label = 1;
1112
- case 1:
1113
- if (!(i < attempts)) return [3 /*break*/, 8];
1114
- _a.label = 2;
1115
- case 2:
1116
- _a.trys.push([2, 4, , 7]);
1117
- return [4 /*yield*/, fn.apply(void 0, args)];
1118
- case 3: return [2 /*return*/, _a.sent()];
1119
- case 4:
1120
- error_1 = _a.sent();
1121
- lastError = error_1;
1122
- if (!(i < attempts - 1)) return [3 /*break*/, 6];
1123
- delayMs = calculateRetryDelay(backoffStrategy, i, baseDelay, jitter, maxDelay);
1124
- return [4 /*yield*/, delay(delayMs)];
1125
- case 5:
1126
- _a.sent();
1127
- _a.label = 6;
1128
- case 6: return [3 /*break*/, 7];
1129
- case 7:
1130
- i++;
1131
- return [3 /*break*/, 1];
1132
- case 8: throw lastError instanceof Error ? lastError : new Error(String(lastError));
1133
- }
1134
- });
1135
- });
1136
- };
1137
- }
1138
-
1139
- /**
1140
- * @license
1141
- * checksum.ts
1142
- * util
1143
- *
1144
- * Copyright © 2025 Monterosa. All rights reserved.
1145
- *
1146
- * More details on the license can be found at https://www.monterosa.co/sdk/license
1147
- */
1148
- /* eslint no-bitwise: "off", global-require: "off" */
1149
- /**
1150
- * Detects if running in Node.js by checking for the 'process' object and
1151
- * 'versions.node' property. Required because TextEncoder must be imported
1152
- * from 'util' in Node.js, but is global in browsers.
1153
- *
1154
- * Cross-platform support is necessary primarily because Jest tests run in
1155
- * Node.js environment, where TextEncoder is not available globally and must
1156
- * be imported from the 'util' module. This ensures the code works correctly
1157
- * in both test environments (Node.js) and production browser environments.
1158
- */
1159
- var isNode = typeof process !== 'undefined' &&
1160
- process.versions != null &&
1161
- process.versions.node != null;
1162
- /**
1163
- * Reference to TextEncoder for UTF-8 string encoding. Initialised
1164
- * conditionally: Node.js uses 'util'.TextEncoder, browsers use the global
1165
- * TextEncoder.
1166
- */
1167
- var TextEncoderRef;
1168
- /**
1169
- * Initialise TextEncoderRef based on runtime environment.
1170
- * Node.js: imports from 'util' module via require().
1171
- * Browser: uses the global TextEncoder API.
1172
- */
1173
- if (isNode) {
1174
- TextEncoderRef = require('util').TextEncoder;
1175
- }
1176
- else {
1177
- TextEncoderRef = TextEncoder;
1178
- }
1179
- /**
1180
- * FNV-1a 32-bit hash function
1181
- * Produces a fast, non-cryptographic checksum for strings
1182
- *
1183
- * @param str - The input string to hash
1184
- *
1185
- * @returns 8-character hexadecimal string representing the hash
1186
- */
1187
- function checksum(str) {
1188
- // FNV-1a constants for 32-bit hashing
1189
- var FNV_PRIME = 0x01000193; // 16777619
1190
- var OFFSET_BASIS = 0x811c9dc5; // 2166136261
1191
- // initialise hash with the offset basis
1192
- var hash = OFFSET_BASIS;
1193
- // Convert string to UTF-8 bytes
1194
- var bytes = new TextEncoderRef().encode(str);
1195
- // Process each character in the input string
1196
- for (var i = 0; i < bytes.length; i++) {
1197
- // XOR with byte (0–255)
1198
- hash ^= bytes[i];
1199
- // Multiply by FNV prime and ensure 32-bit unsigned
1200
- hash = Math.imul(hash, FNV_PRIME) >>> 0;
1201
- }
1202
- // Convert to unsigned 32-bit and format as hex
1203
- return hash.toString(16).padStart(8, '0');
1204
- }
1205
-
1206
- exports.DEFAULT_RETRY_CONFIG = DEFAULT_RETRY_CONFIG;
1207
- exports.Emitter = Emitter;
1208
- exports.MonterosaError = MonterosaError;
1209
- exports.TaskQueue = TaskQueue;
1210
- exports.calculatePercentage = calculatePercentage;
1211
- exports.checkAvailability = checkAvailability;
1212
- exports.checksum = checksum;
1213
- exports.clear = clear;
1214
- exports.createError = createError;
1215
- exports.delay = delay;
1216
- exports.fromEntries = fromEntries;
1217
- exports.getErrorMessage = getErrorMessage;
1218
- exports.getGlobal = getGlobal;
1219
- exports.getItem = getItem;
1220
- exports.getKey = getKey;
1221
- exports.memoizePromise = memoizePromise;
1222
- exports.now = now;
1223
- exports.onTick = onTick;
1224
- exports.removeItem = removeItem;
1225
- exports.setItem = setItem;
1226
- exports.setTimestamp = setTimestamp;
1227
- exports.subscribe = subscribe;
1228
- exports.throttle = throttle;
1229
- exports.tick = tick;
1230
- exports.withRetryAsync = withRetryAsync;
1231
- //# sourceMappingURL=index.cjs.js.map