@monterosa/sdk-util 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.
@@ -0,0 +1,871 @@
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
+ * subscribe.ts
14
+ * util
15
+ *
16
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-02-22
17
+ * Copyright © 2022 Monterosa. All rights reserved.
18
+ *
19
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
20
+ */
21
+ var Emitter = /** @class */ (function () {
22
+ function Emitter() {
23
+ this.handlers = new Map();
24
+ this.emitter = mitt__default["default"]();
25
+ }
26
+ Emitter.prototype.on = function (event, handler) {
27
+ var _this = this;
28
+ var mittHandler = function (args) {
29
+ handler.apply(void 0, (Array.isArray(args) ? args : [args]));
30
+ };
31
+ this.handlers.set(handler, mittHandler);
32
+ this.emitter.on(event, mittHandler);
33
+ return function () { return _this.off(event, handler); };
34
+ };
35
+ Emitter.prototype.off = function (event, handler) {
36
+ if (handler === undefined) {
37
+ this.emitter.off(event);
38
+ return;
39
+ }
40
+ var mittHandler = this.handlers.get(handler);
41
+ if (mittHandler) {
42
+ this.emitter.off(event, mittHandler);
43
+ this.handlers.delete(handler);
44
+ }
45
+ };
46
+ Emitter.prototype.emit = function (event) {
47
+ var args = [];
48
+ for (var _i = 1; _i < arguments.length; _i++) {
49
+ args[_i - 1] = arguments[_i];
50
+ }
51
+ this.emitter.emit(event, args);
52
+ };
53
+ Emitter.prototype.once = function (event, handler) {
54
+ var _this = this;
55
+ var mittHandler = function (args) {
56
+ handler.apply(void 0, (Array.isArray(args) ? args : [args]));
57
+ _this.off(event, handler);
58
+ };
59
+ this.handlers.set(handler, mittHandler);
60
+ this.emitter.on(event, mittHandler);
61
+ return function () { return _this.off(event, handler); };
62
+ };
63
+ return Emitter;
64
+ }());
65
+ /**
66
+ * @internal
67
+ */
68
+ var subscribe = function (emitter, event, callback) {
69
+ emitter.on(event, callback);
70
+ return function () { return emitter.off(event, callback); };
71
+ };
72
+
73
+ /*! *****************************************************************************
74
+ Copyright (c) Microsoft Corporation.
75
+
76
+ Permission to use, copy, modify, and/or distribute this software for any
77
+ purpose with or without fee is hereby granted.
78
+
79
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
80
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
81
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
82
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
83
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
84
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
85
+ PERFORMANCE OF THIS SOFTWARE.
86
+ ***************************************************************************** */
87
+ /* global Reflect, Promise */
88
+
89
+ var extendStatics = function(d, b) {
90
+ extendStatics = Object.setPrototypeOf ||
91
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
92
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
93
+ return extendStatics(d, b);
94
+ };
95
+
96
+ function __extends(d, b) {
97
+ if (typeof b !== "function" && b !== null)
98
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
99
+ extendStatics(d, b);
100
+ function __() { this.constructor = d; }
101
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
102
+ }
103
+
104
+ function __awaiter(thisArg, _arguments, P, generator) {
105
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
106
+ return new (P || (P = Promise))(function (resolve, reject) {
107
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
108
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
109
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
110
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
111
+ });
112
+ }
113
+
114
+ function __generator(thisArg, body) {
115
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
116
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
117
+ function verb(n) { return function (v) { return step([n, v]); }; }
118
+ function step(op) {
119
+ if (f) throw new TypeError("Generator is already executing.");
120
+ while (_) try {
121
+ 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;
122
+ if (y = 0, t) op = [op[0] & 2, t.value];
123
+ switch (op[0]) {
124
+ case 0: case 1: t = op; break;
125
+ case 4: _.label++; return { value: op[1], done: false };
126
+ case 5: _.label++; y = op[1]; op = [0]; continue;
127
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
128
+ default:
129
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
130
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
131
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
132
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
133
+ if (t[2]) _.ops.pop();
134
+ _.trys.pop(); continue;
135
+ }
136
+ op = body.call(thisArg, _);
137
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
138
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
139
+ }
140
+ }
141
+
142
+ /**
143
+ * @license
144
+ * delay.ts
145
+ * util
146
+ *
147
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-03-24
148
+ * Copyright © 2022 Monterosa. All rights reserved.
149
+ *
150
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
151
+ */
152
+ /**
153
+ * @internal
154
+ */
155
+ var delay = function (timeout) { return __awaiter(void 0, void 0, void 0, function () {
156
+ return __generator(this, function (_a) {
157
+ switch (_a.label) {
158
+ case 0: return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, timeout); })];
159
+ case 1:
160
+ _a.sent();
161
+ return [2 /*return*/];
162
+ }
163
+ });
164
+ }); };
165
+
166
+ /**
167
+ * @license
168
+ * memoize-promise.ts
169
+ * util
170
+ *
171
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-09-20
172
+ * Copyright © 2022 Monterosa. All rights reserved.
173
+ *
174
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
175
+ */
176
+ /**
177
+ * Creates a function that memoizes the result of `func`.
178
+ *
179
+ * @internal
180
+ *
181
+ * @param func - A function that returns a promise. The results of its work will be memoized.
182
+ * @param resolver - A function that determines the cache key.
183
+ * @param config - A configuration object with the following optional properties:
184
+ * `clearOnResolve` - Deletes memoized result upon promise resolve. Defaults to `false`.
185
+ * `clearOnReject` - Deletes memoized result upon promise reject. Defaults to `true`.
186
+ */
187
+ var memoizePromise = function (func, resolver, config) {
188
+ var _a, _b;
189
+ if (config === void 0) { config = {}; }
190
+ var clearOnResolve = (_a = config.clearOnResolve) !== null && _a !== void 0 ? _a : false;
191
+ var clearOnReject = (_b = config.clearOnReject) !== null && _b !== void 0 ? _b : true;
192
+ var cache = new Map();
193
+ var memoized = function () {
194
+ var args = [];
195
+ for (var _i = 0; _i < arguments.length; _i++) {
196
+ args[_i] = arguments[_i];
197
+ }
198
+ var key = resolver.apply(void 0, args);
199
+ if (cache.has(key)) {
200
+ return cache.get(key);
201
+ }
202
+ var promise = func.apply(void 0, args);
203
+ cache.set(key, promise);
204
+ promise.then(function () { return clearOnResolve && cache.delete(key); });
205
+ promise.catch(function () { return clearOnReject && cache.delete(key); });
206
+ return promise;
207
+ };
208
+ memoized.cache = cache;
209
+ return memoized;
210
+ };
211
+
212
+ /**
213
+ * @license
214
+ * global.ts
215
+ * util
216
+ *
217
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-04-21
218
+ * Copyright © 2022 Monterosa. All rights reserved.
219
+ *
220
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
221
+ */
222
+ /* eslint no-restricted-globals: "off" */
223
+ /**
224
+ * Global object polyfill.
225
+ * Based on MDN article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
226
+ *
227
+ * @internal
228
+ *
229
+ * @returns typeof globalThis
230
+ */
231
+ function getGlobal() {
232
+ if (typeof self !== 'undefined') {
233
+ return self;
234
+ }
235
+ if (typeof globalThis !== 'undefined') {
236
+ return globalThis;
237
+ }
238
+ if (typeof window !== 'undefined') {
239
+ return window;
240
+ }
241
+ if (typeof global !== 'undefined') {
242
+ return global;
243
+ }
244
+ throw new Error('Unable to locate global object.');
245
+ }
246
+
247
+ /**
248
+ * @license
249
+ * storage.ts
250
+ * util
251
+ *
252
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-04-21
253
+ * Copyright © 2022 Monterosa. All rights reserved.
254
+ *
255
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
256
+ */
257
+ var PREFIX = 'monterosa_sdk_';
258
+ var BAIT = 'bait';
259
+ var globals = getGlobal();
260
+ /**
261
+ * @internal
262
+ */
263
+ var getKey = function (name) { return "" + PREFIX + name; };
264
+ /**
265
+ * @internal
266
+ */
267
+ function getItem(key) {
268
+ return globals.localStorage.getItem(getKey(key));
269
+ }
270
+ /**
271
+ * @internal
272
+ */
273
+ function setItem(key, value) {
274
+ return globals.localStorage.setItem(getKey(key), value);
275
+ }
276
+ /**
277
+ * @internal
278
+ */
279
+ function removeItem(key) {
280
+ return globals.localStorage.removeItem(getKey(key));
281
+ }
282
+ /**
283
+ * @internal
284
+ */
285
+ function clear() {
286
+ return globals.localStorage.clear();
287
+ }
288
+ /**
289
+ * Checks locastorage availability.
290
+ * Based on MDN article: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
291
+ * and Paul Irish gists: https://gist.github.com/paulirish/5558557
292
+ *
293
+ * @internal
294
+ *
295
+ * @returns boolean
296
+ */
297
+ function checkAvailability() {
298
+ try {
299
+ setItem(BAIT, BAIT);
300
+ getItem(BAIT);
301
+ removeItem(BAIT);
302
+ return true;
303
+ }
304
+ catch (e) {
305
+ return false;
306
+ }
307
+ }
308
+
309
+ /**
310
+ * @license
311
+ * error.ts
312
+ * util
313
+ *
314
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2022-03-31
315
+ * Copyright © 2022 Monterosa. All rights reserved.
316
+ *
317
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
318
+ */
319
+ /* eslint max-classes-per-file: ["error", 2] */
320
+ /**
321
+ * MonterosaError extends the standard JavaScript `Error` object. It has
322
+ * an error code so that user can identify the error. Also it has it's own
323
+ * specific `name` "MonterosaError"
324
+ */
325
+ var MonterosaError = /** @class */ (function (_super) {
326
+ __extends(MonterosaError, _super);
327
+ /**
328
+ * @param code - Error code string
329
+ * @param message - A descriptive message for the error
330
+ */
331
+ function MonterosaError(code, message) {
332
+ var _this = _super.call(this, message) || this;
333
+ /**
334
+ * The name property represents a name for the type of error.
335
+ */
336
+ _this.name = 'MonterosaError';
337
+ _this.code = code;
338
+ // Fix For ES5
339
+ // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
340
+ Object.setPrototypeOf(_this, MonterosaError.prototype);
341
+ return _this;
342
+ }
343
+ return MonterosaError;
344
+ }(Error));
345
+ /**
346
+ * @internal
347
+ */
348
+ function createError(code, messages) {
349
+ var params = [];
350
+ for (var _i = 2; _i < arguments.length; _i++) {
351
+ params[_i - 2] = arguments[_i];
352
+ }
353
+ var message = messages[code].apply(messages, params);
354
+ return new MonterosaError(code, message);
355
+ }
356
+
357
+ /**
358
+ * @license
359
+ * throttle.ts
360
+ * util
361
+ *
362
+ * Created by Josep Rodriguez <josep.rodriguez@monterosa.co.uk> on 2022-07-13
363
+ * Copyright © 2022 Monterosa. All rights reserved.
364
+ *
365
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
366
+ */
367
+ /* eslint-disable */
368
+ // @ts-nocheck
369
+ /**
370
+ * lodash (Custom Build) <https://lodash.com/>
371
+ * Build: `lodash modularize exports="npm" -o ./`
372
+ * Copyright jQuery Foundation and other contributors <https://jquery.org/>
373
+ * Released under MIT license <https://lodash.com/license>
374
+ * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
375
+ * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
376
+ */
377
+ /** Used as the `TypeError` message for "Functions" methods. */
378
+ var FUNC_ERROR_TEXT = 'Expected a function';
379
+ /** Used as references for various `Number` constants. */
380
+ var NAN = 0 / 0;
381
+ /** `Object#toString` result references. */
382
+ var symbolTag = '[object Symbol]';
383
+ /** Used to match leading and trailing whitespace. */
384
+ var reTrim = /^\s+|\s+$/g;
385
+ /** Used to detect bad signed hexadecimal string values. */
386
+ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
387
+ /** Used to detect binary string values. */
388
+ var reIsBinary = /^0b[01]+$/i;
389
+ /** Used to detect octal string values. */
390
+ var reIsOctal = /^0o[0-7]+$/i;
391
+ /** Built-in method references without a dependency on `root`. */
392
+ var freeParseInt = parseInt;
393
+ /** Detect free variable `global` from Node.js. */
394
+ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
395
+ /** Detect free variable `self`. */
396
+ var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
397
+ /** Used as a reference to the global object. */
398
+ var root = freeGlobal || freeSelf || Function('return this')();
399
+ /** Used for built-in method references. */
400
+ var objectProto = Object.prototype;
401
+ /**
402
+ * Used to resolve the
403
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
404
+ * of values.
405
+ */
406
+ var objectToString = objectProto.toString;
407
+ /* Built-in method references for those with the same name as other `lodash` methods. */
408
+ var nativeMax = Math.max, nativeMin = Math.min;
409
+ /**
410
+ * Gets the timestamp of the number of milliseconds that have elapsed since
411
+ * the Unix epoch (1 January 1970 00:00:00 UTC).
412
+ *
413
+ * @static
414
+ * @memberOf _
415
+ * @since 2.4.0
416
+ * @category Date
417
+ * @returns {number} Returns the timestamp.
418
+ * @example
419
+ *
420
+ * _.defer(function(stamp) {
421
+ * console.log(_.now() - stamp);
422
+ * }, _.now());
423
+ * // => Logs the number of milliseconds it took for the deferred invocation.
424
+ */
425
+ var now$1 = function () {
426
+ return root.Date.now();
427
+ };
428
+ /**
429
+ * Creates a debounced function that delays invoking `func` until after `wait`
430
+ * milliseconds have elapsed since the last time the debounced function was
431
+ * invoked. The debounced function comes with a `cancel` method to cancel
432
+ * delayed `func` invocations and a `flush` method to immediately invoke them.
433
+ * Provide `options` to indicate whether `func` should be invoked on the
434
+ * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
435
+ * with the last arguments provided to the debounced function. Subsequent
436
+ * calls to the debounced function return the result of the last `func`
437
+ * invocation.
438
+ *
439
+ * **Note:** If `leading` and `trailing` options are `true`, `func` is
440
+ * invoked on the trailing edge of the timeout only if the debounced function
441
+ * is invoked more than once during the `wait` timeout.
442
+ *
443
+ * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
444
+ * until to the next tick, similar to `setTimeout` with a timeout of `0`.
445
+ *
446
+ * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
447
+ * for details over the differences between `_.debounce` and `_.throttle`.
448
+ *
449
+ * @static
450
+ * @memberOf _
451
+ * @since 0.1.0
452
+ * @category Function
453
+ * @param {Function} func The function to debounce.
454
+ * @param {number} [wait=0] The number of milliseconds to delay.
455
+ * @param {Object} [options={}] The options object.
456
+ * @param {boolean} [options.leading=false]
457
+ * Specify invoking on the leading edge of the timeout.
458
+ * @param {number} [options.maxWait]
459
+ * The maximum time `func` is allowed to be delayed before it's invoked.
460
+ * @param {boolean} [options.trailing=true]
461
+ * Specify invoking on the trailing edge of the timeout.
462
+ * @returns {Function} Returns the new debounced function.
463
+ * @example
464
+ *
465
+ * // Avoid costly calculations while the window size is in flux.
466
+ * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
467
+ *
468
+ * // Invoke `sendMail` when clicked, debouncing subsequent calls.
469
+ * jQuery(element).on('click', _.debounce(sendMail, 300, {
470
+ * 'leading': true,
471
+ * 'trailing': false
472
+ * }));
473
+ *
474
+ * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
475
+ * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
476
+ * var source = new EventSource('/stream');
477
+ * jQuery(source).on('message', debounced);
478
+ *
479
+ * // Cancel the trailing debounced invocation.
480
+ * jQuery(window).on('popstate', debounced.cancel);
481
+ */
482
+ function debounce(func, wait, options) {
483
+ var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
484
+ if (typeof func != 'function') {
485
+ throw new TypeError(FUNC_ERROR_TEXT);
486
+ }
487
+ wait = toNumber(wait) || 0;
488
+ if (isObject(options)) {
489
+ leading = !!options.leading;
490
+ maxing = 'maxWait' in options;
491
+ maxWait = maxing
492
+ ? nativeMax(toNumber(options.maxWait) || 0, wait)
493
+ : maxWait;
494
+ trailing = 'trailing' in options ? !!options.trailing : trailing;
495
+ }
496
+ function invokeFunc(time) {
497
+ var args = lastArgs, thisArg = lastThis;
498
+ lastArgs = lastThis = undefined;
499
+ lastInvokeTime = time;
500
+ result = func.apply(thisArg, args);
501
+ return result;
502
+ }
503
+ function leadingEdge(time) {
504
+ // Reset any `maxWait` timer.
505
+ lastInvokeTime = time;
506
+ // Start the timer for the trailing edge.
507
+ timerId = setTimeout(timerExpired, wait);
508
+ // Invoke the leading edge.
509
+ return leading ? invokeFunc(time) : result;
510
+ }
511
+ function remainingWait(time) {
512
+ var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result = wait - timeSinceLastCall;
513
+ return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;
514
+ }
515
+ function shouldInvoke(time) {
516
+ var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
517
+ // Either this is the first call, activity has stopped and we're at the
518
+ // trailing edge, the system time has gone backwards and we're treating
519
+ // it as the trailing edge, or we've hit the `maxWait` limit.
520
+ return (lastCallTime === undefined ||
521
+ timeSinceLastCall >= wait ||
522
+ timeSinceLastCall < 0 ||
523
+ (maxing && timeSinceLastInvoke >= maxWait));
524
+ }
525
+ function timerExpired() {
526
+ var time = now$1();
527
+ if (shouldInvoke(time)) {
528
+ return trailingEdge(time);
529
+ }
530
+ // Restart the timer.
531
+ timerId = setTimeout(timerExpired, remainingWait(time));
532
+ }
533
+ function trailingEdge(time) {
534
+ timerId = undefined;
535
+ // Only invoke if we have `lastArgs` which means `func` has been
536
+ // debounced at least once.
537
+ if (trailing && lastArgs) {
538
+ return invokeFunc(time);
539
+ }
540
+ lastArgs = lastThis = undefined;
541
+ return result;
542
+ }
543
+ function cancel() {
544
+ if (timerId !== undefined) {
545
+ clearTimeout(timerId);
546
+ }
547
+ lastInvokeTime = 0;
548
+ lastArgs = lastCallTime = lastThis = timerId = undefined;
549
+ }
550
+ function flush() {
551
+ return timerId === undefined ? result : trailingEdge(now$1());
552
+ }
553
+ function debounced() {
554
+ var time = now$1(), isInvoking = shouldInvoke(time);
555
+ lastArgs = arguments;
556
+ lastThis = this;
557
+ lastCallTime = time;
558
+ if (isInvoking) {
559
+ if (timerId === undefined) {
560
+ return leadingEdge(lastCallTime);
561
+ }
562
+ if (maxing) {
563
+ // Handle invocations in a tight loop.
564
+ timerId = setTimeout(timerExpired, wait);
565
+ return invokeFunc(lastCallTime);
566
+ }
567
+ }
568
+ if (timerId === undefined) {
569
+ timerId = setTimeout(timerExpired, wait);
570
+ }
571
+ return result;
572
+ }
573
+ debounced.cancel = cancel;
574
+ debounced.flush = flush;
575
+ return debounced;
576
+ }
577
+ /**
578
+ * Creates a throttled function that only invokes `func` at most once per
579
+ * every `wait` milliseconds. The throttled function comes with a `cancel`
580
+ * method to cancel delayed `func` invocations and a `flush` method to
581
+ * immediately invoke them. Provide `options` to indicate whether `func`
582
+ * should be invoked on the leading and/or trailing edge of the `wait`
583
+ * timeout. The `func` is invoked with the last arguments provided to the
584
+ * throttled function. Subsequent calls to the throttled function return the
585
+ * result of the last `func` invocation.
586
+ *
587
+ * **Note:** If `leading` and `trailing` options are `true`, `func` is
588
+ * invoked on the trailing edge of the timeout only if the throttled function
589
+ * is invoked more than once during the `wait` timeout.
590
+ *
591
+ * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
592
+ * until to the next tick, similar to `setTimeout` with a timeout of `0`.
593
+ *
594
+ * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
595
+ * for details over the differences between `_.throttle` and `_.debounce`.
596
+ *
597
+ * @internal
598
+ *
599
+ * @static
600
+ * @memberOf _
601
+ * @since 0.1.0
602
+ * @category Function
603
+ * @param {Function} func The function to throttle.
604
+ * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
605
+ * @param {Object} [options={}] The options object.
606
+ * @param {boolean} [options.leading=true]
607
+ * Specify invoking on the leading edge of the timeout.
608
+ * @param {boolean} [options.trailing=true]
609
+ * Specify invoking on the trailing edge of the timeout.
610
+ * @returns {Function} Returns the new throttled function.
611
+ * @example
612
+ *
613
+ * // Avoid excessively updating the position while scrolling.
614
+ * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
615
+ *
616
+ * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
617
+ * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
618
+ * jQuery(element).on('click', throttled);
619
+ *
620
+ * // Cancel the trailing throttled invocation.
621
+ * jQuery(window).on('popstate', throttled.cancel);
622
+ */
623
+ function throttle(func, wait, options) {
624
+ var leading = true, trailing = true;
625
+ if (typeof func != 'function') {
626
+ throw new TypeError(FUNC_ERROR_TEXT);
627
+ }
628
+ if (isObject(options)) {
629
+ leading = 'leading' in options ? !!options.leading : leading;
630
+ trailing = 'trailing' in options ? !!options.trailing : trailing;
631
+ }
632
+ return debounce(func, wait, {
633
+ leading: leading,
634
+ maxWait: wait,
635
+ trailing: trailing,
636
+ });
637
+ }
638
+ /**
639
+ * Checks if `value` is the
640
+ * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
641
+ * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
642
+ *
643
+ * @static
644
+ * @memberOf _
645
+ * @since 0.1.0
646
+ * @category Lang
647
+ * @param {*} value The value to check.
648
+ * @returns {boolean} Returns `true` if `value` is an object, else `false`.
649
+ * @example
650
+ *
651
+ * _.isObject({});
652
+ * // => true
653
+ *
654
+ * _.isObject([1, 2, 3]);
655
+ * // => true
656
+ *
657
+ * _.isObject(_.noop);
658
+ * // => true
659
+ *
660
+ * _.isObject(null);
661
+ * // => false
662
+ */
663
+ function isObject(value) {
664
+ var type = typeof value;
665
+ return !!value && (type == 'object' || type == 'function');
666
+ }
667
+ /**
668
+ * Checks if `value` is object-like. A value is object-like if it's not `null`
669
+ * and has a `typeof` result of "object".
670
+ *
671
+ * @static
672
+ * @memberOf _
673
+ * @since 4.0.0
674
+ * @category Lang
675
+ * @param {*} value The value to check.
676
+ * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
677
+ * @example
678
+ *
679
+ * _.isObjectLike({});
680
+ * // => true
681
+ *
682
+ * _.isObjectLike([1, 2, 3]);
683
+ * // => true
684
+ *
685
+ * _.isObjectLike(_.noop);
686
+ * // => false
687
+ *
688
+ * _.isObjectLike(null);
689
+ * // => false
690
+ */
691
+ function isObjectLike(value) {
692
+ return !!value && typeof value == 'object';
693
+ }
694
+ /**
695
+ * Checks if `value` is classified as a `Symbol` primitive or object.
696
+ *
697
+ * @static
698
+ * @memberOf _
699
+ * @since 4.0.0
700
+ * @category Lang
701
+ * @param {*} value The value to check.
702
+ * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
703
+ * @example
704
+ *
705
+ * _.isSymbol(Symbol.iterator);
706
+ * // => true
707
+ *
708
+ * _.isSymbol('abc');
709
+ * // => false
710
+ */
711
+ function isSymbol(value) {
712
+ return (typeof value == 'symbol' ||
713
+ (isObjectLike(value) && objectToString.call(value) == symbolTag));
714
+ }
715
+ /**
716
+ * Converts `value` to a number.
717
+ *
718
+ * @static
719
+ * @memberOf _
720
+ * @since 4.0.0
721
+ * @category Lang
722
+ * @param {*} value The value to process.
723
+ * @returns {number} Returns the number.
724
+ * @example
725
+ *
726
+ * _.toNumber(3.2);
727
+ * // => 3.2
728
+ *
729
+ * _.toNumber(Number.MIN_VALUE);
730
+ * // => 5e-324
731
+ *
732
+ * _.toNumber(Infinity);
733
+ * // => Infinity
734
+ *
735
+ * _.toNumber('3.2');
736
+ * // => 3.2
737
+ */
738
+ function toNumber(value) {
739
+ if (typeof value == 'number') {
740
+ return value;
741
+ }
742
+ if (isSymbol(value)) {
743
+ return NAN;
744
+ }
745
+ if (isObject(value)) {
746
+ var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
747
+ value = isObject(other) ? other + '' : other;
748
+ }
749
+ if (typeof value != 'string') {
750
+ return value === 0 ? value : +value;
751
+ }
752
+ value = value.replace(reTrim, '');
753
+ var isBinary = reIsBinary.test(value);
754
+ return isBinary || reIsOctal.test(value)
755
+ ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
756
+ : reIsBadHex.test(value)
757
+ ? NAN
758
+ : +value;
759
+ }
760
+
761
+ /**
762
+ * @license
763
+ * time.ts
764
+ * util
765
+ *
766
+ * Created by Rygor Kharytanovich <rygor@monterosa.co.uk> on 2025-03-24
767
+ * Copyright © 2025 Monterosa. All rights reserved.
768
+ *
769
+ * More details on the license can be found at https://www.monterosa.co/sdk/license
770
+ */
771
+ var emitter = new Emitter();
772
+ var serverTimestamp = 0;
773
+ var lastTickTimestamp = 0;
774
+ var tickTimeoutId;
775
+ /**
776
+ * Returns local timestamp in seconds
777
+ */
778
+ function getCurrentTimestamp() {
779
+ return Date.now() / 1000;
780
+ }
781
+ /**
782
+ * Normalizes the timestamp to reduce fluctuations due to `setTimeout` delays.
783
+ * Ensures the fractional part is around 0.5 to avoid skipping a second.
784
+ *
785
+ * Returns half-second timestamp. It is used to be sure that timestamp will not
786
+ * fluctuate more than in 1 second after each tick due to longer delays.
787
+ * https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#reasons_for_delays_longer_than_specified
788
+ *
789
+ * For example if the initial timestamp has a fractional part 0.9999 then with
790
+ * the setTimeout (tick) longer than specified we might jump over a one second.
791
+ * Lets imaging setTimeout took 1.0002 second, then our timestamp will be 2.0001.
792
+ * Thats why we are trying to keep fractional part in the middle of the second.
793
+ */
794
+ function getMiddleTimestamp(timestamp) {
795
+ return Math.floor(timestamp) + 0.5;
796
+ }
797
+ /**
798
+ * Calculates the delay for the next tick to keep timestamps stable.
799
+ */
800
+ function calculateNextTickDelay() {
801
+ var expectedNextTick = getMiddleTimestamp(serverTimestamp) + 1;
802
+ return (expectedNextTick - serverTimestamp) * 1000;
803
+ }
804
+ /**
805
+ * Main function that maintains current timestamp
806
+ */
807
+ function tick() {
808
+ clearTimeout(tickTimeoutId);
809
+ var currentTimestamp = getCurrentTimestamp();
810
+ var timeSinceLastTick = currentTimestamp - lastTickTimestamp;
811
+ serverTimestamp += timeSinceLastTick;
812
+ lastTickTimestamp = currentTimestamp;
813
+ tickTimeoutId = setTimeout(tick, calculateNextTickDelay());
814
+ emitter.emit('tick', serverTimestamp);
815
+ }
816
+ /**
817
+ * @internal
818
+ *
819
+ * Sets or updates current timestamp
820
+ *
821
+ * @param timestamp - Current timestamp in seconds
822
+ */
823
+ function setTimestamp(timestamp) {
824
+ lastTickTimestamp = getCurrentTimestamp();
825
+ serverTimestamp = getMiddleTimestamp(timestamp);
826
+ }
827
+ /**
828
+ * Returns current timestamp that is preserved by `tick()` function
829
+ *
830
+ * @returns Current timestamp in seconds
831
+ */
832
+ function now() {
833
+ return Math.floor(serverTimestamp);
834
+ }
835
+ /**
836
+ * Subscribes listener to the timestamp increment
837
+ *
838
+ * @param callback - A handler that executes when the timestamp is incremented
839
+ *
840
+ * @returns A function that unsubscribes the listener
841
+ */
842
+ function onTick(callback) {
843
+ return subscribe(emitter, 'tick', callback);
844
+ }
845
+ // Initially timestamp is set based on a local date
846
+ // Later on it can be overriden outside at any moment
847
+ // in our case it is populated with the server timestamp
848
+ // which comes from Enmasse session handshake message
849
+ setTimestamp(getCurrentTimestamp());
850
+ // Kicking in timestamp maintaining
851
+ tick();
852
+
853
+ exports.Emitter = Emitter;
854
+ exports.MonterosaError = MonterosaError;
855
+ exports.checkAvailability = checkAvailability;
856
+ exports.clear = clear;
857
+ exports.createError = createError;
858
+ exports.delay = delay;
859
+ exports.getGlobal = getGlobal;
860
+ exports.getItem = getItem;
861
+ exports.getKey = getKey;
862
+ exports.memoizePromise = memoizePromise;
863
+ exports.now = now;
864
+ exports.onTick = onTick;
865
+ exports.removeItem = removeItem;
866
+ exports.setItem = setItem;
867
+ exports.setTimestamp = setTimestamp;
868
+ exports.subscribe = subscribe;
869
+ exports.throttle = throttle;
870
+ exports.tick = tick;
871
+ //# sourceMappingURL=index.cjs.js.map