'use strict'; /** * Generates a random string using the UUID library. * * @returns A randomly generated string. */ var randomString = function () { return (Math.random() + 1).toString(36).substring(7); }; /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { 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); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { 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; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; 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); 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); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; /** * Compares the full text in a given data object with a search term. * * @template T - The generic type for the data object. * @param data - The data object to compare. * @param search - The search term to compare against the data object. * @param keys - The keys in the data object to compare against. * @returns - Returns true if the full text in the data object contains the search term, false otherwise. */ var compareFulltext = function (data, search) { var e_1, _a; var keys = []; for (var _i = 2; _i < arguments.length; _i++) { keys[_i - 2] = arguments[_i]; } var target = String(search || "") .toLowerCase() .split(" "); var filterFn = function (key) { var source = String(data[key] || "") .toLowerCase() .split(" "); return target.every(function (term) { return source.some(function (word) { return word.includes(term); }); }); }; var isOk = false; try { for (var keys_1 = __values(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) { var key = keys_1_1.value; isOk = isOk || filterFn(key); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return)) _a.call(keys_1); } finally { if (e_1) throw e_1.error; } } return isOk; }; /** * A function that compares two values and returns a numeric value based on their comparison. * * @param a - The first value to compare. * @param b - The second value to compare. * @returns - A numeric value indicating the result of the comparison. */ var compareFn = function (a, b) { if (typeof a === 'number' && typeof b === 'number') { return a - b; } else if (typeof a === 'boolean' && typeof b === 'boolean') { return (a ? 1 : 0) - (b ? 1 : 0); } else if (typeof a === 'string' && typeof b === 'string') { return a.localeCompare(b); } else { return 0; } }; /** * Compares two arrays and determines if they are equal. * * @param a_arr - The first array to compare. * @param b_arr - The second array to compare. * @returns - Returns `true` if the arrays are equal, otherwise `false`. */ var compareArray = function (a_arr, b_arr) { if (Array.isArray(a_arr) && Array.isArray(b_arr)) { if (a_arr.length !== b_arr.length) { return false; } var a_sort = __spreadArray([], __read(a_arr), false).sort(compareFn); var b_sort_1 = __spreadArray([], __read(b_arr), false).sort(compareFn); return a_sort.every(function (value, index) { return value === b_sort_1[index]; }); } return false; }; /** * Check if a given value is an object. * * @param obj - The value to check. * @returns - Returns `true` if the value is an object, else `false`. */ var isObject = function (obj) { if (typeof obj === 'object' && obj !== null) { return Object.getPrototypeOf(obj) === Object.prototype; } else { return false; } }; /** * Formats a raw string using a template and optional parameters. * * @param raw - The raw string to be formatted. * @param template - The template string used for formatting. * @param [params] - Optional parameters for customization. * @param [params.symbol='0'] - The symbol used in the template to indicate characters to be replaced. * @param [params.allowed] - A function or regular expression used to filter characters in the raw string. * @param [params.replace] - A function used to replace characters in the raw string. * @returns The formatted string. */ var formatText = function (raw, template, _a) { var e_1, _b; var _c = _a === void 0 ? {} : _a, _d = _c.symbol, symbol = _d === void 0 ? '0' : _d, allowed = _c.allowed, replace = _c.replace; if (!template || !raw) { return raw; } if (replace) { var tempRaw = raw.split(''); for (var i = 0; i !== raw.length; i++) { var pendingChar = replace(raw[i]) || null; if (pendingChar !== null) { tempRaw[i] = pendingChar; } } raw = tempRaw.join(''); } if (allowed) { var pendingRemoveIdx_1 = new Set(); if (typeof allowed === 'function') { for (var i = 0; i !== raw.length; i++) { var lastChar = raw[i]; if (!allowed(lastChar, i)) { pendingRemoveIdx_1.add(i); } } } else { for (var i = 0; i !== raw.length; i++) { var lastChar = raw[i]; if (!lastChar.match(allowed)) { pendingRemoveIdx_1.add(i); } } } raw = raw.split('').filter(function (_, idx) { return !pendingRemoveIdx_1.has(idx); }).join(''); } var idx = 0; var result = ''; try { for (var template_1 = __values(template), template_1_1 = template_1.next(); !template_1_1.done; template_1_1 = template_1.next()) { var char = template_1_1.value; if (idx === raw.length) { break; } else if (char === symbol || char === raw[idx]) { result += raw[idx]; idx++; } else { result += char; } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (template_1_1 && !template_1_1.done && (_b = template_1.return)) _b.call(template_1); } finally { if (e_1) throw e_1.error; } } return result; }; /** * Delays the execution for the specified amount of time. * * @param [timeout=1000] - The duration to wait in milliseconds. * @returns A promise that resolves once the timeout has elapsed. */ var sleep = function (timeout) { if (timeout === void 0) { timeout = 1000; } return new Promise(function (res) { return setTimeout(function () { return res(); }, timeout); }); }; var TIMEOUT_SYMBOL = Symbol('timeout'); var timeout = function (run, delay) { if (delay === void 0) { delay = 30000; } var wrappedFn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return __awaiter(void 0, void 0, void 0, function () { var result; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, Promise.race([ run.apply(void 0, __spreadArray([], __read(args), false)), sleep(delay).then(function () { return TIMEOUT_SYMBOL; }), ])]; case 1: result = _a.sent(); return [2 /*return*/, result]; } }); }); }; return wrappedFn; }; /** * Creates an awaiter object along with a promise. * * @template T - The type of the value to be resolved. * * @function * @returns An array containing the promise and the awaiter object. */ var createAwaiter = function () { var resolveRef = null; var rejectRef = null; var awaiter = new Promise(function (resolve, reject) { var _a; _a = __read([resolve, reject], 2), resolveRef = _a[0], rejectRef = _a[1]; }); var resolve = function (value) { return resolveRef && resolveRef(value); }; var reject = function (value) { return rejectRef && rejectRef(value); }; return [awaiter, { resolve: resolve, reject: reject }]; }; var waitForNext = function (subject_1, condition_1) { var args_1 = []; for (var _i = 2; _i < arguments.length; _i++) { args_1[_i - 2] = arguments[_i]; } return __awaiter(void 0, __spreadArray([subject_1, condition_1], __read(args_1), false), void 0, function (subject, condition, delay) { var unsubscribeRef, isFinished, _a, promise, _b, resolve; if (delay === void 0) { delay = 0; } return __generator(this, function (_c) { isFinished = false; _a = __read(createAwaiter(), 2), promise = _a[0], _b = _a[1], resolve = _b.resolve, _b.reject; unsubscribeRef = subject.subscribe(function (value) { if (condition(value)) { unsubscribeRef && unsubscribeRef(); isFinished = true; resolve(value); } }); delay && sleep(delay).then(function () { if (isFinished) { return; } unsubscribeRef && unsubscribeRef(); resolve(TIMEOUT_SYMBOL); }); return [2 /*return*/, promise]; }); }); }; /** * Creates a function that is only executed once, and then memoizes and returns the result. * * @template T - The type of the function to be executed once. * @param run - The function to be executed once. * @returns - The executed function with additional "clear" method to reset the execution state. */ var singleshot = function (run) { var hasRunned = false; var result = null; /** * Runs a function once and caches the result for subsequent calls. * * @param args - Arguments passed to the function. * @returns - The result of the function. */ var fn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (!hasRunned) { hasRunned = true; result = run.apply(void 0, __spreadArray([], __read(args), false)); } return result; }; /** * Clears the given array or object by removing all its properties or elements. * * @param target - The array or object to be cleared. * @throws If the target is not an array or an object. * */ fn.clear = function () { hasRunned = false; }; return fn; }; /** * A class representing a task. * * @class */ var Task = /** @class */ (function () { /** * Constructor for creating an instance of the class. * * @param target - The target promise to be handled. * * @return - This method does not return any value. */ function Task(target) { var _this = this; this.target = target; this._status = "pending"; target.then(function () { return _this._status = "fulfilled"; }); target.catch(function () { return _this._status = "rejected"; }); } Object.defineProperty(Task.prototype, "status", { /** * Retrieves the current status value. * * @return The value of the status. */ get: function () { return this._status; }, enumerable: false, configurable: true }); return Task; }()); /** * Represents a higher-order function that runs a task only once and provides a way to clear the result. * @template T - The function type. * @param run - The function to be executed. * @returns - The wrapped function with additional clear functionality. */ var singlerun = function (run) { var result = undefined; /** * Executes the given `run` function with the provided arguments and returns the result. * * If the `result` status is not "pending", a new `Task` is created with the `run` function. * * @param args - The arguments to be passed to the `run` function. * @returns - The target property of the `result` object, if available. */ var fn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if ((result === null || result === void 0 ? void 0 : result.status) !== "pending") { result = new Task(run.apply(void 0, __spreadArray([], __read(args), false))); } return result === null || result === void 0 ? void 0 : result.target; }; /** * Clears the content of the given input field. * * @param input - The input field to be cleared. * @returns */ fn.clear = function () { result = undefined; }; /** * Gets the running task status * @returns */ fn.getStatus = function () { return (result === null || result === void 0 ? void 0 : result.status) || "ready"; }; return fn; }; /** * Symbol representing cancellation status. * * @type {Symbol} * @name CANCELED_SYMBOL */ var CANCELED_SYMBOL = Symbol('cancelable-canceled'); /** * Wraps a promise function and provides cancellation functionality. * * @param promise - The promise function to wrap. * @returns The wrapped function with cancellation capability. * @template T - The type of the promise's resolved value. * @template P - The type of the promise function's arguments. */ var cancelable = function (promise) { var cancelRef; /** * A function that wraps a given promise with cancellation functionality. * * @template P - The type of the arguments passed to the wrapped function. * @template T - The type of the resolved value of the promise. * @param promise - The promise to be wrapped. * @returns A promise that resolves with the resolved value of the given promise, or with the symbol `CANCELED_SYMBOL` if the wrapped function's * cancellation is triggered. */ var wrappedFn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return new Promise(function (resolve, reject) { var hasCanceled = false; cancelRef && cancelRef(); cancelRef = function () { hasCanceled = true; resolve(CANCELED_SYMBOL); }; var result = promise.apply(void 0, __spreadArray([], __read(args), false)); result.then(function (val) { if (!hasCanceled) { resolve(val); return; } }); result.catch(function (error) { if (!hasCanceled) { reject(error); return; } }); }); }; /** * Cancels the execution of the wrapped function. * * @function * @name wrappedFn.cancel * @returns */ wrappedFn.cancel = function () { cancelRef && cancelRef(); }; return wrappedFn; }; var REQUEST_ANIMATION_FRAME_FN = "requestAnimationFrame" in globalThis ? globalThis.requestAnimationFrame : setTimeout; var CANCEL_ANIMATION_FRAME_FN = "cancelAnimationFrame" in globalThis ? globalThis.cancelAnimationFrame : clearTimeout; var REQUEST_ANIMATION_FRAME = function (fn) { return REQUEST_ANIMATION_FRAME_FN(fn); }; var CANCEL_ANIMATION_FRAME = function (id) { return CANCEL_ANIMATION_FRAME_FN(id); }; /** * Creates a debounced version of a function. * * @template T - The type of the original function. * @param run - The function to debounce. * @param [delay=1000] - The delay in milliseconds before executing the debounced function. * @returns - The debounced function with additional methods for clearing and flushing. */ var debounce = function (run, delay) { if (delay === void 0) { delay = 1000; } var timeout; var lastRun = null; var on = delay ? setTimeout : REQUEST_ANIMATION_FRAME; var un = delay ? clearTimeout : CANCEL_ANIMATION_FRAME; /** * Wrapper function that delays the execution of a given function * * @param run - The function to be executed * @param delay - The delay in milliseconds * @returns */ var wrappedFn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } timeout !== null && un(timeout); var exec = function () { lastRun = null; timeout = null; run.apply(void 0, __spreadArray([], __read(args), false)); }; lastRun = exec; timeout = on(exec, delay); }; /** * Clears the wrapped function from any saved state or implementation. * * @memberof wrappedFn */ wrappedFn.clear = function () { timeout !== null && un(timeout); timeout = null; lastRun = null; }; /** * Flushes any queued functions within the wrapped function. * * @param wrappedFn - The wrapped function that may have queued functions. * @returns */ wrappedFn.flush = function () { timeout !== null && un(timeout); lastRun && lastRun(); timeout = null; lastRun = null; }; wrappedFn.pending = function () { return !!lastRun; }; return wrappedFn; }; /** * Compose multiple functions together to create a new function that applies the given functions from right to left. * If no functions are given, the composed function will simply return the input argument. * If only one function is given, the composed function will simply return the output of that function. * * @param funcs - The functions to be composed. * @returns - The composed function. */ var compose = function () { var funcs = []; for (var _i = 0; _i < arguments.length; _i++) { funcs[_i] = arguments[_i]; } if (funcs.length === 0) { return function (arg) { return arg; }; } if (funcs.length === 1) { return funcs[0]; } return funcs.reduce(function (a, b) { return function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return a(b.apply(void 0, __spreadArray([], __read(args), false))); }; }); }; /** * Creates a wrapper function for a Promise that allows for cancellation and clearing of queued Promises. * * @template T - The resolved value of the Promise. * @template P - The types of the arguments passed to the promise function. * @param promise - The promise function to be wrapped. * @returns - The wrapped function. */ var queued = function (promise) { var lastPromise = Promise.resolve(); var cancelFn = undefined; /** * Executes a promise function with the given arguments, allowing cancellation and clearing. * @template P - The tuple type of the arguments passed to the promise function. * @param promise - The promise function to be executed. * @param args - The arguments to be passed to the promise function. * @returns - A promise that resolves with the result of the promise function or CANCELED_SYMBOL if canceled. */ var wrappedFn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var isCanceled = false; var cancel = function () { isCanceled = true; }; cancelFn = cancelFn ? compose(cancelFn, cancel) : cancel; lastPromise = lastPromise .then(function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: if (!!isCanceled) return [3 /*break*/, 2]; return [4 /*yield*/, promise.apply(void 0, __spreadArray([], __read(args), false))]; case 1: return [2 /*return*/, _a.sent()]; case 2: return [2 /*return*/, CANCELED_SYMBOL]; } }); }); }) .finally(function () { wrappedFn.clear(); cancelFn = undefined; }); return lastPromise; }; /** * Clears any existing wrapped function stored in the wrappedFn variable. * This function is used to reset the wrapped function to its initial state. * * @function clear */ wrappedFn.clear = function () { lastPromise = Promise.resolve(); cancelFn = undefined; }; /** * Cancels the execution of the wrapped function. * Once called, the wrapped function will not be executed. * * @function cancel * @memberof wrappedFn * */ wrappedFn.cancel = function () { lastPromise = Promise.resolve(); cancelFn && cancelFn(); cancelFn = undefined; }; return wrappedFn; }; /** * Creates an execution pool for asynchronous functions with a limited concurrency. * * @template T - The type of the result of the wrapped function. * @template P - The types of the parameters of the wrapped function. * * @function * @param run - The function to be executed in the pool. * @param options - Optional configuration options for the execution pool. * @returns A wrapped function that executes asynchronously within the execution pool. */ var execpool = function (run, _a) { var _b = _a === void 0 ? {} : _a, _c = _b.maxExec, maxExec = _c === void 0 ? 3 : _c, _d = _b.delay, delay = _d === void 0 ? 10 : _d; var execSet = new Set(); var execStack = []; /** * Executes a function with arguments and adds it to the execution pool. * * @function * @param awaiter - The awaiter to resolve the function execution. * @param args - The arguments to pass to the function. */ var execute = function (awaiter) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } var exec = run.apply(void 0, __spreadArray([], __read(args), false)); execSet.add(exec); exec.finally(function () { execSet.delete(exec); }); awaiter.resolve(exec); }; /** * Initializes the execution loop for the execution pool. * * @function */ var initLoop = singlerun(function () { return __awaiter(void 0, void 0, void 0, function () { var _a, args, awaiter; return __generator(this, function (_b) { switch (_b.label) { case 0: if (!execStack.length) return [3 /*break*/, 5]; if (!execSet.size) return [3 /*break*/, 2]; return [4 /*yield*/, Promise.race(execSet)]; case 1: _b.sent(); _b.label = 2; case 2: if (!(execSet.size >= maxExec)) return [3 /*break*/, 4]; return [4 /*yield*/, sleep(delay)]; case 3: _b.sent(); return [3 /*break*/, 0]; case 4: _a = execStack.pop(), args = _a.args, awaiter = _a.awaiter; execute.apply(void 0, __spreadArray([awaiter], __read(args), false)); return [3 /*break*/, 0]; case 5: return [2 /*return*/]; } }); }); }); /** * The wrapped function that executes within the execution pool. * * @function * @param args - The arguments to pass to the wrapped function. * @returns A promise that resolves with the result of the wrapped function. */ var wrappedFn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return __awaiter(void 0, void 0, void 0, function () { var _a, result, awaiter; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = __read(createAwaiter(), 2), result = _a[0], awaiter = _a[1]; if (execSet.size < maxExec) { execute.apply(void 0, __spreadArray([awaiter], __read(args), false)); } else { execStack.unshift({ awaiter: awaiter, args: args, }); initLoop(); } return [4 /*yield*/, result]; case 1: return [2 /*return*/, _b.sent()]; } }); }); }; /** * Clears all pending executions in the execution pool. * * @function */ wrappedFn.clear = function () { while (execStack.length) { execStack.pop(); } execSet.clear(); initLoop.clear(); }; return wrappedFn; }; /** * Retries a function multiple times until it succeeds or reaches the maximum number of retries. * * @param run - The function to run. * @param count - The maximum number of retries (default is 5). * @returns - The wrapped function that can be canceled. */ var retry = function (run, count) { if (count === void 0) { count = 5; } var wrappedFn = queued(function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return __awaiter(void 0, void 0, void 0, function () { var total, call; return __generator(this, function (_a) { switch (_a.label) { case 0: total = count; call = function () { return __awaiter(void 0, void 0, void 0, function () { var error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 4]); return [4 /*yield*/, run.apply(void 0, __spreadArray([], __read(args), false))]; case 1: return [2 /*return*/, _a.sent()]; case 2: error_1 = _a.sent(); if (--total === 0) { throw error_1; } return [4 /*yield*/, call()]; case 3: return [2 /*return*/, _a.sent()]; case 4: return [2 /*return*/]; } }); }); }; return [4 /*yield*/, call()]; case 1: return [2 /*return*/, _a.sent()]; } }); }); }); return wrappedFn; }; /** * Caches the result of a function based on the change of arguments. * @template T - The type of the function to be cached. * @template A - The type of the arguments of the function. * @param changed - Function to determine if the arguments have changed. * @param run - The function to be cached. * @returns - The cached function with additional clear method. */ var cached = function (changed, run) { var lastArgs = null; var initial = true; var lastValue; /** * Clears the value of the lastArgs variable. * @function * @name clear * @returns */ var clear = function () { lastArgs = null; }; /** * Executes a function with given arguments and caches the result. * * @param args - The arguments to be passed to the function. * @returns - The result of the executed function. */ var executeFn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (!initial) { if (!changed(lastArgs, args)) { return lastValue; } } lastArgs = args; initial = false; return lastValue = run.apply(void 0, __spreadArray([], __read(args), false)); }; executeFn.clear = clear; return executeFn; }; /** * Defines the GET_VALUE_MAP constant. * * This symbol is used to uniquely identify the 'get-value-map' property in an object or map. * It can be used as a key to retrieve or set a value from a map. * * @const {symbol} GET_VALUE_MAP - The symbol representing the 'get-value-map' property. */ var GET_VALUE_MAP = Symbol('get-value-map'); /** * A memoization function that caches the result of a function based on its arguments. * * @template T - The function type that will be memoized * @template A - The argument types of the function * @template K - The key type used to store the memoized results * @param key - A function that generates a unique key based on the arguments of the original function * @param run - The original function to be memoized * @returns - A memoized version of the original function with the ability to clear the cache */ var memoize = function (key, run) { /** * A map that associates keys of type K with values of type IRefMemoize>. * * @template K - The type of the keys in the valueMap. * @template T - The type of the values in the valueMap. */ var valueMap = new Map(); /** * Clears the value map. * If a key is provided, it deletes the corresponding value from the map. * If no key is provided, it clears the entire map. * * @param [key] - The key of the value to delete from the map. * @returns */ var clear = function (key) { if (key) { valueMap.delete(key); return; } valueMap.clear(); }; /** * Executes a function with the given arguments and caches the result. * Implements the `IClearableMemoize` interface. * * @template A - The argument types of the function. * @template T - The return type of the function. * @param args - The arguments to pass to the function. * @returns - The cached result of the function. */ var executeFn = function () { var _a; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var k = key(args); var value = (_a = valueMap.get(k)) === null || _a === void 0 ? void 0 : _a.current; if (value === undefined) { var ref = { current: undefined }; valueMap.set(k, ref); value = ref.current = run.apply(void 0, __spreadArray([], __read(args), false)); } return value; }; /** * Executes the GET_VALUE_MAP function by symbol. Works like a friend classes in C++ * * @return The value map containing key-value pairs. */ executeFn[GET_VALUE_MAP] = function () { return valueMap; }; /** * Clears the executeFn function. * * @function clear * @memberof executeFn * @returns */ executeFn.clear = clear; executeFn.add = function (key, value) { var ref = valueMap.get(key); if (ref === undefined) { ref = { current: value }; } else { ref.current = value; } valueMap.set(key, ref); }; executeFn.remove = function (key) { return valueMap.delete(key); }; return executeFn; }; var CATCH_SYMBOL = Symbol("default"); /** * Asynchronously waits for a promise to resolve and handles any errors that occur. * * @param value - The promise to await. * @param config - The configuration options. * @param config.fallback - The fallback function to call if an error occurs. * @param config.defaultValue - The default value to return if an error occurs. * @returns - A promise that resolves to the resolved value of the input promise, or the defaultValue if an error occurs. * */ var awaiter = function (value_1, _a) { return __awaiter(void 0, [value_1, _a], void 0, function (value, _b) { var error_1; var fallback = _b.fallback, defaultValue = _b.defaultValue; return __generator(this, function (_c) { switch (_c.label) { case 0: _c.trys.push([0, 2, , 3]); return [4 /*yield*/, value]; case 1: return [2 /*return*/, _c.sent()]; case 2: error_1 = _c.sent(); fallback && fallback(error_1); return [2 /*return*/, defaultValue]; case 3: return [2 /*return*/]; } }); }); }; /** * A higher-order function that wraps the provided function with a try-catch block. It catches any errors that occur during the execution of the function and handles them according to * the specified configuration. * * @template T - The type of the function being wrapped * @template A - An array of arguments that the function accepts * @template V - The type of the value returned by the function * @template D - The type of the default value to return in case of error * * @param run - The function to be wrapped * @param config - The configuration object * @param config.fallback - The fallback function to be called with the caught error (optional) * @param config.defaultValue - The default value to be returned if an error occurs * * @returns - The wrapped function that handles errors and returns the result or the default value */ var trycatch = function (run, _a) { var _b = _a === void 0 ? {} : _a, allowedErrors = _b.allowedErrors, fallback = _b.fallback, _c = _b.defaultValue, defaultValue = _c === void 0 ? CATCH_SYMBOL : _c; return function () { var e_1, _a; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } try { var result = run.apply(void 0, __spreadArray([], __read(args), false)); if (result instanceof Promise) { return awaiter(result, { fallback: fallback, defaultValue: defaultValue }); } return result; } catch (error) { fallback && fallback(error); if (allowedErrors) { try { for (var allowedErrors_1 = __values(allowedErrors), allowedErrors_1_1 = allowedErrors_1.next(); !allowedErrors_1_1.done; allowedErrors_1_1 = allowedErrors_1.next()) { var BaseError = allowedErrors_1_1.value; if (error instanceof BaseError) { return defaultValue; } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (allowedErrors_1_1 && !allowedErrors_1_1.done && (_a = allowedErrors_1.return)) _a.call(allowedErrors_1); } finally { if (e_1) throw e_1.error; } } throw error; } return defaultValue; } }; }; /** * Represents the default timeout value in milliseconds. * * @constant {number} DEFAULT_TIMEOUT - The value of the default timeout. */ var DEFAULT_TIMEOUT = 250; /** * A unique symbol representing a value that should never occur. * * @type {symbol} */ var NEVER_VALUE$6 = Symbol('never'); /** * Wrap a function with time-to-live (TTL) caching. * * @template T - The function type. * @template A - The argument types of the function. * @template K - The key type for caching. * @param run - The function to wrap. * @param options - The configuration options. * @param [options.key] - The key generator function that generates a key based on function arguments. * @param [options.timeout] - The TTL duration in milliseconds. * @returns - The wrapped function with caching capability. */ var ttl = function (run, _a) { var _b = _a === void 0 ? {} : _a, _c = _b.key, key = _c === void 0 ? function () { return NEVER_VALUE$6; } : _c, _d = _b.timeout, timeout = _d === void 0 ? DEFAULT_TIMEOUT : _d; /** * Creates a memoized function that caches the result of the * original function based on the provided key. * * @param key - The key used to cache the result of the function. * @param run - The original function to be memoized. * @returns - A memoized function that returns the cached value. */ var wrappedFn = memoize(key, function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return ({ value: run.apply(void 0, __spreadArray([], __read(args), false)), ttl: Date.now(), }); }); /** * Executes a wrapped function with a TTL (Time To Live). * @param args - The arguments for the wrapped function. * @returns - The return value of the wrapped function. */ var executeFn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var currentTtl = Date.now(); var _a = wrappedFn.apply(void 0, __spreadArray([], __read(args), false)), value = _a.value, ttl = _a.ttl; if (currentTtl - ttl > timeout) { var k = key(args); wrappedFn.clear(k); return executeFn.apply(void 0, __spreadArray([], __read(args), false)); } return value; }; /** * Clears the executeFn function. * * @function * @memberof executeFn * @name clear * * @returns */ executeFn.clear = function (key) { wrappedFn.clear(key); }; /** * Executes a garbage collection in the ttl storage. * * @function executeFn.gc * @returns */ executeFn.gc = function () { var e_1, _a; var valueMap = wrappedFn[GET_VALUE_MAP](); try { for (var _b = __values(valueMap.entries()), _c = _b.next(); !_c.done; _c = _b.next()) { var _d = __read(_c.value, 2), key_1 = _d[0], item = _d[1]; var currentTtl = Date.now(); if (currentTtl - item.current.ttl > timeout) { wrappedFn.clear(key_1); } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } }; executeFn.add = function (key, value) { return wrappedFn.add(key, { value: value, ttl: Date.now(), }); }; executeFn.remove = wrappedFn.remove; return executeFn; }; /** * Throttle function execution to a specific delay. * @template T - Function type * @param run - Function to be throttled * @param delay - Delay in milliseconds (default: 1000) * @returns - Throttled function with clear method */ var throttle = function (run, delay) { if (delay === void 0) { delay = 1000; } var lastExec = 0; /** * Clears the existing timeout. * * @function * @name clearExistingTimeout * @returns */ var clearExistingTimeout = function () { }; /** * A wrapper function that delays the execution of the given function * until a certain amount of time has passed since the last execution. * * @param args - Arguments to be passed to the wrapped function. * @returns */ var wrappedFn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var elapsed = Date.now() - lastExec; var exec = function () { lastExec = Date.now(); run.apply(void 0, __spreadArray([], __read(args), false)); }; { exec(); } if (elapsed > delay) { exec(); } }; /** * Clears the wrapped function. * This function removes any existing functionality from the wrapped function. * * @memberof wrappedFn * @function clear */ wrappedFn.clear = clearExistingTimeout; return wrappedFn; }; var RANDOM_CODE = randomString(); var OBSOLETE_PROMPT = "Method marked as obsolete. Type ".concat(RANDOM_CODE, " to continue"); var getMethodName = function (fn, self) { var e_1, _a; if (!self) { return "unknown"; } if (typeof self !== 'object') { return "unknown"; } try { for (var _b = __values(Object.keys(self)), _c = _b.next(); !_c.done; _c = _b.next()) { var key = _c.value; if (self[key] === fn) { return key; } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } return getMethodName(fn, Object.getPrototypeOf(self)); }; var obsolete = function (run) { var methodName = ""; var fn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: methodName = methodName || getMethodName(fn, this); console.log("react-declarative obsolete hof call method_name=".concat(methodName)); if (!('prompt' in globalThis)) return [3 /*break*/, 2]; if (!(globalThis.prompt(OBSOLETE_PROMPT) === RANDOM_CODE)) return [3 /*break*/, 2]; return [4 /*yield*/, run.apply(void 0, __spreadArray([], __read(args), false))]; case 1: return [2 /*return*/, _a.sent()]; case 2: throw new Error('react-declarative obsolete hof call'); } }); }); }; return fn; }; /** * Wraps a function with a single event loop ticking behavior. * * @param run - The function to be wrapped. * @returns A wrapped function that executes with a single ticking behavior. */ var singletick = function (run) { var timeout = null; var singleshotFn = singleshot(run); /** * This is a higher-order function that wraps another function and adds * a delay before invoking it. * * @param singleshotFn - The function to be wrapped. * @param singletick.delay - The delay in milliseconds before invoking the wrapped function. * @returns - The result of invoking the wrapped function. */ var wrappedFn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var result = singleshotFn.apply(void 0, __spreadArray([], __read(args), false)); timeout !== null && clearTimeout(timeout); timeout = setTimeout(function () { singleshotFn.clear(); timeout = null; }, singletick.delay); return result; }; return wrappedFn; }; singletick.delay = 0; /** * Creates a wrapped function that only executes the provided function after the initial call has completed. * The wrapped function can be cleared to allow subsequent calls to execute the provided function again. * * @template T The type of the promise resolved by the provided function. * @template P The type of the arguments passed to the provided function. * @param run The function to be wrapped. * @returns The wrapped function. */ var afterinit = function (run) { var hasComplete = false; /** * A wrapper function that either resolves a Promise or calls the inner function 'run' depending on its state. * * @param args - The arguments to be passed to the inner function 'run'. * @returns - A Promise that resolves to 'undefined' if 'hasComplete' is false, otherwise calls the inner function 'run'. */ var wrappedFn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (!hasComplete) { hasComplete = true; return Promise.resolve(); } return run.apply(void 0, __spreadArray([], __read(args), false)); }; /** * Clears the function wrapped in a wrapper function. * This function removes any previously set function and resets it to null. * * @param wrappedFn - The wrapped function to be cleared. * @returns */ wrappedFn.clear = function () { hasComplete = false; }; return wrappedFn; }; /** * Returns the first element of an array. * * @template T - The type of array elements. * @param arr - The input array. * @returns - The first element of the array, or null if the array is null or empty. */ var first = function (arr) { if (Array.isArray(arr)) { var _a = __read(arr, 1), first_1 = _a[0]; return first_1 || null; } return null; }; /** * Checks if an object is empty. * * @param obj - The object to check for emptiness. * @returns - Returns true if the object is empty, otherwise returns false. */ function isEmpty(obj) { if (Object.getOwnPropertySymbols(obj).length !== 0) { return false; } if (Object.getOwnPropertyNames(obj).length !== 0) { return false; } return true; } /** * Class representing an event emitter. * @class */ var EventEmitter = /** @class */ (function () { function EventEmitter() { var _this = this; this._events = {}; /** * Retrieves the listeners associated with the given event key. * * @param key - The event key to retrieve the listeners for. * @returns An array of listeners associated with the given event key. */ this.getListeners = function (key) { return _this._events[key] || []; }; /** * Subscribes a callback function to the specified event name. * * @param eventName - The key of the event. * @param callback - The callback function to be executed when the event is triggered. * @returns */ this.subscribe = function (eventName, callback) { !_this._events[eventName] && (_this._events[eventName] = []); _this._events[eventName].push(callback); }; /** * Removes a callback function from the list of event listeners for the specified event. * * @param eventName - The key of the event to unsubscribe from. * @param callback - The callback function to remove from the event listeners. * @returns */ this.unsubscribe = function (eventName, callback) { !_this._events[eventName] && (_this._events[eventName] = []); _this._events[eventName] = _this._events[eventName].filter(function (eventCallback) { return callback !== eventCallback; }); }; /** * Clears all event handlers registered for the current object. * @function * @returns */ this.unsubscribeAll = function () { _this._events = {}; }; /** * Subscribes a callback function to the given event name. The callback function will be triggered only once when the event is emitted. * * @param eventName - The name of the event to subscribe to. * @param callback - The callback function to be executed when the event is emitted. * @returns - A function that can be called to unsubscribe the callback function from the event. */ this.once = function (eventName, callback) { var subscriber = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, callback.apply(void 0, __spreadArray([], __read(args), false))]; case 1: _a.sent(); this.unsubscribe(eventName, subscriber); return [2 /*return*/]; } }); }); }; _this.subscribe(eventName, subscriber); return function () { _this.unsubscribe(eventName, subscriber); }; }; /** * Emits the given event with the specified arguments. * * @param eventName - The name of the event to emit. * @param args - The arguments to pass to the event listeners. * @returns - A promise that resolves when all event listeners have completed. */ this.emit = function (eventName) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } return __awaiter(_this, void 0, void 0, function () { var event, i; return __generator(this, function (_a) { switch (_a.label) { case 0: event = __spreadArray([], __read(this._events && this._events[eventName] || []), false); i = 0; _a.label = 1; case 1: if (!(i !== event.length)) return [3 /*break*/, 4]; return [4 /*yield*/, event[i].apply(event, __spreadArray([], __read(args), false))]; case 2: _a.sent(); _a.label = 3; case 3: i++; return [3 /*break*/, 1]; case 4: return [2 /*return*/]; } }); }); }; } Object.defineProperty(EventEmitter.prototype, "hasListeners", { /** * Check if the object has any listeners attached to it. * * @return True if the object has listeners, false otherwise. */ get: function () { return !isEmpty(this._events); }, enumerable: false, configurable: true }); return EventEmitter; }()); var OBSERVER_EVENT = Symbol('observer-subscribe'); var CONNECT_EVENT = Symbol('observer-connect'); var DISCONNECT_EVENT = Symbol('observer-disconnect'); var LISTEN_CONNECT = Symbol('observer-connect-listen'); var LISTEN_DISCONNECT = Symbol('observer-disconnect-listen'); /** * A class representing an Observer. * * @template Data - The type of data to observe. */ var Observer = /** @class */ (function () { function Observer(dispose) { var _this = this; this.dispose = dispose; this.broadcast = new EventEmitter(); this._isShared = false; /** * Subscribe a given observer to the global broadcast event. * * @param observer - The observer subscribing to the event. * @param callback - The callback function to be executed when the event is triggered. * @returns */ this._subscribe = function (observer, callback) { _this.broadcast.subscribe(OBSERVER_EVENT, callback); observer[LISTEN_CONNECT](function () { _this.broadcast.emit(CONNECT_EVENT); }); observer[LISTEN_DISCONNECT](function () { if (!_this.hasListeners) { _this.broadcast.emit(DISCONNECT_EVENT); } }); }; /** * Unsubscribes a callback function from the observer event. * * @param callback - The callback function to unsubscribe. * @returns */ this._unsubscribe = function (callback) { _this.broadcast.unsubscribe(OBSERVER_EVENT, callback); }; /** * Tries to dispose the object if it has no listeners and is not shared. * If disposed successfully, emits the DISCONNECT_EVENT. */ this.tryDispose = function () { if (!_this.hasListeners && !_this._isShared) { _this.dispose(); _this.broadcast.emit(DISCONNECT_EVENT); } }; /** * Creates a new Observer. * @template T - The type of the value emitted by the observer. * @param callbackfn - A function to apply to each value emitted by the observer. * @returns - The created Observer. */ this.map = function (callbackfn) { var unsubscribeRef; var dispose = compose(function () { return _this.tryDispose(); }, function () { return unsubscribeRef(); }); var observer = new Observer(dispose); var handler = function (value) { var pendingValue = callbackfn(value); observer.emit(pendingValue); }; _this._subscribe(observer, handler); unsubscribeRef = function () { return _this._unsubscribe(handler); }; return observer; }; /** * Applies a callback function to each value emitted by the Observable and flattens the resulting values into a new Observable. * * @template T - The type of values emitted by the Observable. * * @param callbackfn - A callback function that accepts a value emitted by the Observable and returns an array of values or a single value. * * @returns - A new Observer that emits the flattened values. */ this.flatMap = function (callbackfn) { var unsubscribeRef; var dispose = compose(function () { return _this.tryDispose(); }, function () { return unsubscribeRef(); }); var observer = new Observer(dispose); var handler = function (value) { var pendingValue = callbackfn(value); if (Array.isArray(pendingValue)) { pendingValue.forEach(function (value) { observer.emit(value); }); } else { observer.emit(pendingValue); } }; _this._subscribe(observer, handler); unsubscribeRef = function () { return _this._unsubscribe(handler); }; return observer; }; /** * Operator function to create a new observer with a transformed data type. * * @template T - The type of the transformed data. * @param callbackfn - A callback function that takes the target observer and returns a new observer with transformed data. * @returns - A new observer with the transformed data type. */ this.operator = function (callbackfn) { return callbackfn(_this); }; /** * Reduces the data emitted by an Observer using a callback function and an initial value. * * @template T - The type of the accumulator and the return value. * @param callbackfn - The callback function to execute on each emitted value. * It takes an accumulator value and the current value being emitted, and returns the new accumulator value. * @param begin - The initial value of the accumulator. * @returns - An Observer that emits the accumulated value after each emission. */ this.reduce = function (callbackfn, begin) { var unsubscribeRef; var acm = begin; var dispose = compose(function () { return _this.tryDispose(); }, function () { return unsubscribeRef(); }); var observer = new Observer(dispose); var handler = function (value) { var pendingValue = callbackfn(acm, value); acm = pendingValue; observer.emit(pendingValue); }; _this._subscribe(observer, handler); unsubscribeRef = function () { return _this._unsubscribe(handler); }; return observer; }; /** * Creates and returns an observer function that splits an array of data * into a nested array of a specified length. * * @returns The split observer function. */ this.split = function () { var unsubscribeRef; var dispose = compose(function () { return _this.tryDispose(); }, function () { return unsubscribeRef(); }); var observer = new Observer(dispose); var handler = function (data) { if (Array.isArray(data)) { data.flat(Number.POSITIVE_INFINITY).forEach(function (item) { observer.emit(item); }); } else { observer.emit(data); } }; _this._subscribe(observer, handler); unsubscribeRef = function () { return _this._unsubscribe(handler); }; return observer; }; /** * Creates an Observer with asynchronous mapping functionality. * * @template T - The type of the result of the mapping function. * @param callbackfn - The function used to map the incoming data. * @param [fallbackfn] - An optional fallback function to handle error cases. If not provided, the error will be rethrown. * @returns - The created Observer. */ this.mapAsync = function (callbackfn, fallbackfn) { var unsubscribeRef; var dispose = compose(function () { return _this.tryDispose(); }, function () { return unsubscribeRef(); }); var observer = new Observer(dispose); var iteraction = queued(callbackfn); var handler = function (value) { return __awaiter(_this, void 0, void 0, function () { var pendingValue, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, iteraction(value)]; case 1: pendingValue = _a.sent(); if (pendingValue !== CANCELED_SYMBOL) { observer.emit(pendingValue); } return [3 /*break*/, 3]; case 2: e_1 = _a.sent(); if (fallbackfn) { fallbackfn(e_1); } else { throw e_1; } return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }; _this._subscribe(observer, handler); unsubscribeRef = compose(function () { return _this._unsubscribe(handler); }, function () { return iteraction.clear(); }); return observer; }; /** * Creates a filtered observer. * * @param callbackfn - The filter callback function. * @returns The filtered observer. */ this.filter = function (callbackfn) { var unsubscribeRef; var dispose = compose(function () { return _this.tryDispose(); }, function () { return unsubscribeRef(); }); var observer = new Observer(dispose); var handler = function (value) { var delegate = callbackfn(value); if (delegate) { observer.emit(value); } }; _this._subscribe(observer, handler); unsubscribeRef = function () { return _this._unsubscribe(handler); }; return observer; }; /** * Attaches a callback function to the tap observer. The callback function will be called with a value of type `Data` when the tap observer is triggered. * * @param callbackfn - A callback function that takes a value of type `Data` as an argument. * @returns - An observer object that can be used to manage the tap subscription. */ this.tap = function (callbackfn) { var unsubscribeRef; var dispose = compose(function () { return _this.tryDispose(); }, function () { return unsubscribeRef(); }); var observer = new Observer(dispose); var handler = function (value) { callbackfn(value); observer.emit(value); }; _this._subscribe(observer, handler); unsubscribeRef = function () { return _this._unsubscribe(handler); }; return observer; }; /** * Creates a debounced observer that emits values at a specified delay. * * @param delay - The delay (in milliseconds) between value emissions. * @returns The debounced observer. */ this.debounce = function (delay) { var unsubscribeRef; var dispose = compose(function () { return _this.tryDispose(); }, function () { return unsubscribeRef(); }); var observer = new Observer(dispose); var handler = debounce(function (value) { observer.emit(value); }, delay); _this._subscribe(observer, handler); unsubscribeRef = compose(function () { return handler.clear(); }, function () { return _this._unsubscribe(handler); }); return observer; }; /** * Creates a delayed observer that emits values at a specified delay. * * @param delay - The delay (in milliseconds) between value emissions. * @returns The debounced observer. */ this.delay = function (delay) { var unsubscribeRef; var dispose = compose(function () { return _this.tryDispose(); }, function () { return unsubscribeRef(); }); var observer = new Observer(dispose); var isCanceled = false; var handler = queued(function (value) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, sleep(delay)]; case 1: _a.sent(); if (!!isCanceled) return [3 /*break*/, 3]; return [4 /*yield*/, observer.emit(value)]; case 2: _a.sent(); _a.label = 3; case 3: return [2 /*return*/]; } }); }); }); _this._subscribe(observer, handler); unsubscribeRef = compose(function () { return handler.clear(); }, function () { return _this._unsubscribe(handler); }, function () { isCanceled = true; }); return observer; }; /** * Emits the specified data to all observers. * * @param data - The data to be emitted. */ this.emit = function (data) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.broadcast.emit(OBSERVER_EVENT, data)]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Subscribes to the `OBSERVER_EVENT` and invokes the provided callback function. * Emits the `CONNECT_EVENT`. * Returns a composed function that will try to dispose and unsubscribe the callback. * * @param callbackfn - The callback function to be invoked when `OBSERVER_EVENT` is emitted. * @returns - The composed function that will try to dispose and unsubscribe the callback. */ this.connect = function (callbackfn) { _this.broadcast.subscribe(OBSERVER_EVENT, callbackfn); _this.broadcast.emit(CONNECT_EVENT); return compose(function () { return _this.tryDispose(); }, function () { return _this._unsubscribe(callbackfn); }); }; /** * Executes a callback function once and provides a way to unsubscribe from further executions. * * @param callbackfn - The callback function to be executed once. * @returns - A function that can be called to unsubscribe from further executions of the callback. */ this.once = function (callbackfn) { var unsubscribeRef; var handler = function (value) { callbackfn(value); unsubscribeRef(); }; unsubscribeRef = _this.connect(handler); return unsubscribeRef; }; /** * Marks a variable as shared. * * @returns The shared variable object. */ this.share = function () { _this._isShared = true; return _this; }; /** * Creates an observable sequence that emits values at specified intervals. * @param [interval=1000] - The time interval between emissions in milliseconds. * @returns The observer object to subscribe to. */ this.repeat = function (interval) { if (interval === void 0) { interval = 1000; } var unsubscribeRef; var timeout; var dispose = compose(function () { return _this.tryDispose(); }, function () { return unsubscribeRef(); }, function () { return timeout !== undefined && clearTimeout(timeout); }); var observer = new Observer(dispose); var handler = function (value) { if (timeout !== undefined) { clearTimeout(timeout); } observer.emit(value); if (_this.hasListeners) { timeout = setTimeout(handler, interval, value); } }; _this._subscribe(observer, handler); unsubscribeRef = function () { return _this._unsubscribe(handler); }; return observer; }; /** * Merges an observer with the given observer, returning a new observer that emits values from both observers. * * @template T - The type of value emitted by the observer. * @param observer - The observer to merge with. * @returns - The merged observer. */ this.merge = function (observer) { var unsubscribeRef; var dispose = compose(function () { return _this.tryDispose(); }, function () { return unsubscribeRef(); }); var merged = new Observer(dispose); var handler = function (value) { merged.emit(value); }; _this._subscribe(merged, handler); var unsubscribe = function () { return undefined; }; merged[LISTEN_CONNECT](function () { unsubscribe = observer.connect(handler) || (function () { return undefined; }); }); unsubscribeRef = compose(function () { return _this._unsubscribe(handler); }, function () { return unsubscribe(); }); return merged; }; /** * Unsubscribes from all events and performs cleanup. * * @function * @name unsubscribe * @memberOf undefined * * @returns */ this.unsubscribe = function () { _this.broadcast.unsubscribeAll(); _this.broadcast.emit(DISCONNECT_EVENT); _this.dispose(); }; /** * Converts the current instance to a Promise that resolves with the data. * * @returns A Promise that resolves with the data. */ this.toPromise = function () { return new Promise(function (res) { _this.once(function (data) { return res(data); }); }); }; /** * Creates a context for iterating asynchronously using a generator function. * * @returns The iterator context object. * @property iterate - The generator function that can be used to iterate over the values. * @property done - Marks the iteration as complete. */ this.toIteratorContext = function () { var self = _this; var isDone = false; var iterate = function () { return __asyncGenerator(this, arguments, function () { var next; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!!isDone) return [3 /*break*/, 4]; return [4 /*yield*/, __await(self.toPromise())]; case 1: next = _a.sent(); return [4 /*yield*/, __await(next)]; case 2: return [4 /*yield*/, _a.sent()]; case 3: _a.sent(); return [3 /*break*/, 0]; case 4: return [2 /*return*/]; } }); }); }; return { iterate: iterate, done: function () { isDone = true; }, }; }; } Object.defineProperty(Observer.prototype, "isShared", { /** * Returns the current value of the 'isShared' property. * * @returns - The value of the 'isShared' property. */ get: function () { return this._isShared; }, enumerable: false, configurable: true }); Object.defineProperty(Observer.prototype, "hasListeners", { /** * Returns whether the given event has any listeners. * * @returns True if there are listeners for the event, otherwise false. */ get: function () { return !!this.broadcast.getListeners(OBSERVER_EVENT).length; }, enumerable: false, configurable: true }); /** * Sets up a listener for the connect event on the broadcast channel. * * @param fn - The callback function to be executed once the connect event is triggered. * @returns */ Observer.prototype[LISTEN_CONNECT] = function (fn) { this.broadcast.once(CONNECT_EVENT, fn); }; /** * Adds a listener for the DISCONNECT_EVENT. * * @param fn - The function to be executed when the event occurs. */ Observer.prototype[LISTEN_DISCONNECT] = function (fn) { this.broadcast.once(DISCONNECT_EVENT, fn); }; return Observer; }()); var SUBJECT_EVENT = Symbol('rn-declarative-subject'); /** * Represents a subject that can emit data and be subscribed to. * @class * @implements {TSubject} * @implements {TObservable} * @template Data - The type of data that the subject emits. */ var Subject = /** @class */ (function () { function Subject() { var _this = this; this._emitter = new EventEmitter(); /** * Maps the values of the observer using the given callback function. * * @template T - The type of the mapped values. * @param callbackfn - A function that maps each value of the observer. * @returns - An observer with the mapped values. */ this.map = function (callbackfn) { var unsubscribeRef; var observer = new Observer(function () { return unsubscribeRef(); }); unsubscribeRef = _this.subscribe(observer.emit); return observer.map(callbackfn); }; /** * Applies a transformation function to each value emitted by the observer and flattens the result into a single observer. * @template T - The type of values emitted by the observer. * @param callbackfn - The transformation function to apply to each value emitted by the observer. * @returns - The observer that emits the flattened values. */ this.flatMap = function (callbackfn) { var unsubscribeRef; var observer = new Observer(function () { return unsubscribeRef(); }); unsubscribeRef = _this.subscribe(observer.emit); return observer.flatMap(callbackfn); }; /** * Applies a reducer function to each value emitted by the observer and returns a single accumulated value. * * @template T - The type of the accumulated value and emitted values * @param callbackfn - A function that accepts the accumulated value and the current emitted value, and returns the new accumulated value * @param begin - The initial value for the accumulator * @returns - An observer that emits the accumulated value when the original observer completes */ this.reduce = function (callbackfn, begin) { var unsubscribeRef; var observer = new Observer(function () { return unsubscribeRef(); }); unsubscribeRef = _this.subscribe(observer.emit); return observer.reduce(callbackfn, begin); }; /** * Asynchronously maps the emitted values of the observer using the provided callback function. * * @template T - The type of the mapped values. * @param callbackfn - The callback function that maps the emitted values of the observer. * @param [fallbackfn] - The optional fallback function that handles errors during mapping. * @returns - Returns a new observer that emits the mapped values. */ this.mapAsync = function (callbackfn, fallbackfn) { var unsubscribeRef; var observer = new Observer(function () { return unsubscribeRef(); }); unsubscribeRef = _this.subscribe(observer.emit); return observer.mapAsync(callbackfn, fallbackfn); }; /** * Applies a filtering function to the observer and returns a new observer with filtered values. * * @param callbackfn - A function that tests each value in the observer. Should return true or false. * @returns - A new observer with filtered values. */ this.filter = function (callbackfn) { var unsubscribeRef; var observer = new Observer(function () { return unsubscribeRef(); }); unsubscribeRef = _this.subscribe(observer.emit); return observer.filter(callbackfn); }; /** * The tap function allows you to perform side effects without modifying the observed data. * */ this.tap = function (callbackfn) { var unsubscribeRef; var observer = new Observer(function () { return unsubscribeRef(); }); unsubscribeRef = _this.subscribe(observer.emit); return observer.tap(callbackfn); }; /** * Applies a callback function to the values emitted by an observer. * * @param callbackfn - The callback function to apply to the emitted values. * @returns - An observer with the applied operator. * * @template T - The type of values emitted by the observer. * * @category Observables */ this.operator = function (callbackfn) { var unsubscribeRef; var observer = new Observer(function () { return unsubscribeRef(); }); unsubscribeRef = _this.subscribe(observer.emit); return observer.operator(callbackfn); }; /** * Splits the observed data into batches of arrays. * * @returns - The observer that emits batches of arrays. */ this.split = function () { var unsubscribeRef; var observer = new Observer(function () { return unsubscribeRef(); }); unsubscribeRef = _this.subscribe(observer.emit); return observer.split(); }; /** * Creates a debounced observer with an optional delay. * @param [delay] - The delay in milliseconds before emitting the data. * @returns - The debounced observer. */ this.debounce = function (delay) { var unsubscribeRef; var observer = new Observer(function () { return unsubscribeRef(); }); unsubscribeRef = _this.subscribe(observer.emit); return observer.debounce(delay); }; /** * Creates a delayed observer with an optional delay. * @param [delay] - The delay in milliseconds before emitting the data. * @returns - The delayed observer. */ this.delay = function (delay) { var unsubscribeRef; var observer = new Observer(function () { return unsubscribeRef(); }); unsubscribeRef = _this.subscribe(observer.emit); return observer.delay(delay); }; /** * Creates an observer that repeats emitting values at a specified interval. * * @param [interval] - The time interval at which to repeat emitting values. * @returns - The created observer. */ this.repeat = function (interval) { var unsubscribeRef; var observer = new Observer(function () { return unsubscribeRef(); }); unsubscribeRef = _this.subscribe(observer.emit); return observer.repeat(interval); }; /** * Merges the provided observer with the current observer instance. * Returns a new observer that emits values from both observers. * * @param observer - The observer to merge with the current observer. * @returns - A new observer that emits values from both observers. */ this.merge = function (observer) { var unsubscribeRef; var merged = new Observer(function () { return unsubscribeRef(); }); unsubscribeRef = _this.subscribe(merged.emit); return merged.merge(observer); }; /** * Subscribes to an event. * * @param callback - The callback function to be invoked when the event is triggered. * @returns - A function to unsubscribe from the event. */ this.subscribe = function (callback) { _this._emitter.subscribe(SUBJECT_EVENT, callback); return function () { _this._emitter.unsubscribe(SUBJECT_EVENT, callback); }; }; /** * Unsubscribes all event listeners. * * @function unsubscribeAll * @instance * @returns - No return value. */ this.unsubscribeAll = function () { _this._emitter.unsubscribeAll(); }; /** * Executes the provided callback function only once. * The callback function will be invoked when the specified event occurs for the first time. * * @param callback - The function to be executed only once. * @returns - A function that removes the registered event listener. */ this.once = function (callback) { return _this._emitter.once(SUBJECT_EVENT, callback); }; /** * Converts an observer-based asynchronous operation into a promise-based asynchronous operation. * * @function toPromise * @instance * @returns A promise representing the completion or failure of the asynchronous operation. */ this.toPromise = function () { return _this.toObserver().toPromise(); }; /** * Converts the current object to an iterator context. * * @function * @returns The iterator context representing the current object. */ this.toIteratorContext = function () { return _this.toObserver().toIteratorContext(); }; this.next = this.next.bind(this); this.toObserver = this.toObserver.bind(this); this.toIteratorContext = this.toIteratorContext.bind(this); } /** * Calls the next method to emit the specified data using the SUBJECT_EVENT event. * * @param data - The data to be emitted. * @return - Resolves when the emission is complete. */ Subject.prototype.next = function (data) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this._emitter.emit(SUBJECT_EVENT, data)]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Creates a new observer to observe the data emitted by a source. * * @template TObserver - The type of observer. * @template Data - The type of data emitted by the source. * @returns - The created observer. */ Subject.prototype.toObserver = function () { var unsubscribeRef; var observer = new Observer(function () { return unsubscribeRef(); }); unsubscribeRef = this.subscribe(observer.emit); return observer; }; return Subject; }()); /** * Represents a BehaviorSubject that extends the Subject class and provides the functionality of an observable and an observer. * * @template Data - The type of the data that the BehaviorSubject holds. */ var BehaviorSubject = /** @class */ (function (_super) { __extends(BehaviorSubject, _super); function BehaviorSubject(_data) { if (_data === void 0) { _data = null; } var _this = _super.call(this) || this; _this._data = _data; /** * Sets the given data and calls the next method of the super class asynchronously. * * @param data - The data to be set. * @return Resolves when super class's next method is called. */ _this.next = function (data) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: this._data = data; return [4 /*yield*/, _super.prototype.next.call(this, data)]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Creates a new observer. * * @returns The observer instance. */ _this.toObserver = function () { var unsubscribeRef; var observer = new Observer(function () { return unsubscribeRef(); }); observer[LISTEN_CONNECT](function () { _this._data && observer.emit(_this._data); }); unsubscribeRef = _this.subscribe(observer.emit); return observer; }; return _this; } Object.defineProperty(BehaviorSubject.prototype, "data", { /** * Retrieves the data stored in the instance. * * @return The data stored in the instance. */ get: function () { return this._data; }, enumerable: false, configurable: true }); return BehaviorSubject; }(Subject)); /** * A special symbol representing a value that should never be used or returned. * * @type {symbol} */ var NEVER_VALUE$5 = Symbol('never'); /** * Wraps a promise function with lock functionality. * * @param promise - The promise function to be wrapped. * @returns The wrapped function with lock functionality. */ var lock = function (promise) { var lockCount = 0; var lockSubject = new BehaviorSubject(lockCount); /** * Waits for the lock to be unlocked. * @returns - Resolves when the lock is unlocked. */ var waitForUnlock = function () { return new Promise(function (resolve) { var handler = function () { if (lockSubject.data === 0) { resolve(); return; } lockSubject.once(handler); }; handler(); }); }; /** * Executes a function, after waiting for the unlock signal. * * @function * @param args - The arguments to pass to the function. * @returns - A promise that resolves to the value returned by the function. */ var executeFn = queued(function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, waitForUnlock()]; case 1: _a.sent(); if (first(args) === NEVER_VALUE$5) { return [2 /*return*/, null]; } return [4 /*yield*/, promise.apply(void 0, __spreadArray([], __read(args), false))]; case 2: return [2 /*return*/, _a.sent()]; } }); }); }); /** * Asynchronous function wrapper. * @param args - Arguments to be passed to the wrapped function. * @returns - A promise that resolves to the result of the wrapped function. */ var wrappedFn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, executeFn.apply(void 0, __spreadArray([], __read(args), false))]; case 1: return [2 /*return*/, _a.sent()]; } }); }); }; /** * Removes all the wrapped functions that are stored in the wrappedFn collection. * @function wrappedFn.clear * @returns */ wrappedFn.clear = function () { lockSubject.next(0); lockCount = 0; lockSubject = new BehaviorSubject(lockCount); executeFn.clear(); }; /** * Cancels the execution of a wrapped function. * * @function cancel * @memberof wrappedFn * */ wrappedFn.cancel = function () { wrappedFn.clear(); executeFn.cancel(); }; /** * Begins a lock for the wrapped function. * * @function beginLock * @memberof wrappedFn */ wrappedFn.beginLock = function () { lockCount += 1; lockSubject.next(lockCount); }; /** * Releases the lock after the wrapped function has completed execution. * * @param wrappedFn - The function that is wrapped and needs the lock released. * @returns - The result of executing the wrapped function. */ wrappedFn.endLock = function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: lockCount = Math.max(lockCount - 1, 0); lockSubject.next(lockCount); return [4 /*yield*/, executeFn(NEVER_VALUE$5)]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; return wrappedFn; }; /** * A utility function to deep flatten an array of objects. * * @param arr - The input array to be deep flattened. * @returns - The deep flattened array. * @template T - The type of elements in the input array. */ var deepFlat = function (arr) { if (arr === void 0) { arr = []; } var result = []; var process = function (entries) { if (entries === void 0) { entries = []; } return entries === null || entries === void 0 ? void 0 : entries.forEach(function (entry) { var fields = entry['fields'] || []; var child = entry['child'] ? [entry['child']] : []; process(__spreadArray(__spreadArray([], __read(fields), false), __read(child), false)); result.push(entry); }); }; process(arr); return result; }; var NEVER_VALUE$4 = Symbol('never'); /** * Counts the occurrences of each value emitted by the target observer. * * @template T - The type of values emitted by the target observer. * @param target - The target observer to count the occurrences for. * @returns - An observer that emits {@link ICounted} objects containing the value and count. */ var count = function () { return function (target) { return target .reduce(function (acm, cur) { if (acm.value === cur) { return { value: cur, count: acm.count + 1, }; } return { value: cur, count: 0, }; }, { value: NEVER_VALUE$4, count: 0, }); }; }; var NEVER_VALUE$3 = Symbol('never'); /** * Filters out duplicate values in an observable stream based on a specified compare value. * * @template T - The type of the values in the observable stream. * @template V - The type of the compare value. * @param getCompareValue - A function that takes a value of type T and returns its compare value of type V. * @param target - The observable stream to filter. * @returns - An observable stream with distinct values. */ var distinct = function (getCompareValue) { if (getCompareValue === void 0) { getCompareValue = function (value) { return value; }; } return function (target) { var prevValue = NEVER_VALUE$3; return target .map(function (value) { return ({ value: value, compare: getCompareValue(value) }); }) .filter(function (_a) { var value = _a.compare; return value !== prevValue; }) .tap(function (_a) { var compare = _a.compare; return prevValue = compare; }) .map(function (_a) { var value = _a.value; return value; }); }; }; /** * Groups the elements of an array in chunks of a specified size. * * @template T - The type of the elements in the array, or 'any' if not specified * @param by - The size of each group * @returns - A function that takes an array and returns a new array with the elements grouped by the specified size */ var group = function (by) { return function (target) { return target .reduce(function (acm, cur) { if (acm.length === by) { return [cur]; } else { return __spreadArray(__spreadArray([], __read(acm), false), [cur], false); } }, []) .filter(function (acm) { return acm.length === by; }); }; }; /** * Creates an observer that emits a value after a specified delay. * * @param delay - The delay in milliseconds. * @returns - The observer that emits values after the specified delay. */ var fromInterval = function (delay) { var timeout; var iterationIdx = 0; var observer = new Observer(function () { if (timeout !== undefined) { clearTimeout(timeout); } }); var process = function () { observer.emit(iterationIdx); iterationIdx++; timeout = setTimeout(process, delay); }; observer[LISTEN_CONNECT](function () { process(); }); return observer; }; /** * Creates an observable that emits the result of a given promise callback function. * * @param callbackfn - The callback function that returns a promise. * @param [fallbackfn] - The fallback function to handle errors if the promise rejects. * @returns - The observable observer. * * @template Data - The type of data emitted by the observer. */ var fromPromise = function (callbackfn, fallbackfn) { var isCanceled = false; var observer = new Observer(function () { isCanceled = true; }); var process = function () { return __awaiter(void 0, void 0, void 0, function () { var result, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, callbackfn()]; case 1: result = _a.sent(); if (!isCanceled) { observer.emit(result); } return [3 /*break*/, 3]; case 2: e_1 = _a.sent(); if (fallbackfn) { fallbackfn(e_1); } else { throw e_1; } return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }; observer[LISTEN_CONNECT](function () { process(); }); return observer; }; /** * Creates a delayed observer that emits a void value after a specified delay. * * @param delay - The delay in milliseconds before emitting the value. * @returns - The delayed observer instance. */ var fromDelay = function (delay) { var timeout; var observer = new Observer(function () { if (timeout !== undefined) { clearTimeout(timeout); } }); var process = function () { timeout = undefined; observer.emit(); }; observer[LISTEN_CONNECT](function () { setTimeout(process, delay); }); return observer; }; /** * Creates an observer that emits a flattened and filtered array of data. * * @template Data - The type of data being observed. * @param data - The data to observe. * @returns - The observer that emits the flattened and filtered array of data. */ var fromArray = function (data) { var observer = new Observer(function () { return undefined; }); var process = function () { if (Array.isArray(data)) { data.flat(Number.POSITIVE_INFINITY).forEach(function (item) { observer.emit(item); }); } else { observer.emit(data); } }; observer[LISTEN_CONNECT](function () { process(); }); return observer; }; /** * A utility function for creating observer objects that can be chained * with multiple operators. * * @template Data The type of data emitted by the observer. * * @param factory A function that returns an observer. * * @returns The created observer object. */ var createObserver = function (factory) { return ({ tap: function (callbackfn) { return factory().tap(callbackfn); }, debounce: function (delay) { return factory().debounce(delay); }, delay: function (delay) { return factory().delay(delay); }, repeat: function (interval) { return factory().repeat(interval); }, filter: function (callbackfn) { return factory().filter(callbackfn); }, map: function (callbackfn) { return factory().map(callbackfn); }, flatMap: function (callbackfn) { return factory().flatMap(callbackfn); }, operator: function (callbackfn) { return factory().operator(callbackfn); }, reduce: function (callbackfn, begin) { return factory().reduce(callbackfn, begin); }, mapAsync: function (callbackfn, fallbackfn) { return factory().mapAsync(callbackfn, fallbackfn); }, merge: function (observer) { return factory().merge(observer); }, split: function () { return factory().split(); }, connect: function (callbackfn) { return factory().connect(callbackfn); }, once: function (callbackfn) { return factory().once(callbackfn); }, unsubscribe: function () { return factory().unsubscribe(); }, share: function () { return factory().share(); }, toPromise: function () { return factory().toPromise(); }, toIteratorContext: function () { return factory().toIteratorContext(); }, }); }; /** * The Source class provides utility functions for creating and manipulating Observers. */ var Source = /** @class */ (function () { function Source() { } var _a; _a = Source; /** * Merges multiple observers into a single observer. * * @template A - The type of observer A. * @template B - The type of observer B. * @template C - The type of observer C. * @template D - The type of observer D. * @template E - The type of observer E. * @template F - The type of observer F. * @template G - The type of observer G. * @template H - The type of observer H. * @template I - The type of observer I. * @template J - The type of observer J. * * @param observers - An array of observers to merge. * * @returns - The merged observer. */ Source.merge = function (observers) { var root = new Subject().toObserver(); observers.forEach(function (observer) { if (observer) { root = root.merge(observer); } }); return root; }; /** * Creates a join observer that combines the values emitted by multiple Observers into a single Observable. * * @template A - The type of the value emitted by the first Observer. * @template B - The type of the value emitted by the second Observer. * @template C - The type of the value emitted by the third Observer. * @template D - The type of the value emitted by the fourth Observer. * @template E - The type of the value emitted by the fifth Observer. * @template F - The type of the value emitted by the sixth Observer. * @template G - The type of the value emitted by the seventh Observer. * @template H - The type of the value emitted by the eighth Observer. * @template I - The type of the value emitted by the ninth Observer. * @template J - The type of the value emitted by the tenth Observer. * * @param observers - An array of Observers to join. * @param options - Optional parameters for the join operation, including a buffer and a race flag. * @param options.buffer - An array to store the latest emitted values from each Observer. Defaults to an empty array. * @param options.race - A boolean flag indicating whether to emit the combined values immediately or wait for all Observers to emit a value. Defaults to false. * * @returns An Observer that emits an array of values, each value being the latest emitted value from the corresponding Observer. */ Source.join = function (observers, _b) { var _c = _b === void 0 ? {} : _b, _d = _c.race, race = _d === void 0 ? false : _d, _e = _c.buffer, buffer = _e === void 0 ? [] : _e; var disposeRef = function () { return undefined; }; var observer = new Observer(function () { return disposeRef(); }); observers = observers.filter(function (value) { return !!value; }); buffer = __spreadArray([], __read(new Array(observers.length)), false).map(function (_, idx) { return buffer[idx]; }); var subscriptions = []; var next = function () { if (buffer.every(function (value) { return value !== undefined; })) { observer.emit(__spreadArray([], __read(buffer), false)); !race && buffer.fill(undefined); } }; observer[LISTEN_CONNECT](function () { observers.forEach(function (observer, idx) { if (observer) { var unsubscribe_1 = observer.connect(function (value) { buffer[idx] = value; next(); }); subscriptions.push(function () { return unsubscribe_1(); }); } }); disposeRef = compose.apply(void 0, __spreadArray([], __read(subscriptions), false)); }); return observer; }; /** * @typedef Unicast * @template Data - The type of data the observer handles. * * @property factory - A factory function to create the observer. * @property isUnicasted - Indicates whether the observer is unicast. * * @returns - A unicast observer instance. */ Source.unicast = function (factory) { return (__assign(__assign({}, createObserver(factory)), { isUnicasted: true })); }; /** * Creates a multicast observer. * * @template Data - The type of data being observed. * @param factory - A factory function that creates the observer. * @returns - The multicast observer. */ Source.multicast = function (factory) { var observer; return __assign(__assign({}, createObserver(function () { if (!observer) { observer = factory(); observer[LISTEN_DISCONNECT](function () { observer = undefined; }); } return observer; })), { getRef: function () { return observer; }, isMulticasted: true }); }; /** * Creates a hot observable that emits data as it is received from the given emitter. * * @template Data The type of data emitted by the observable. * @param emitter The function that receives a callback to emit data. It should return a cleanup function or `undefined`. * @returns The observer that allows subscribing to and unsubscribing from the emitted data. */ Source.createHot = function (emitter) { var unsubscribeRef; var observer = new Observer(function () { return unsubscribeRef(); }); unsubscribeRef = emitter(observer.emit) || (function () { return undefined; }); return observer; }; /** * Creates a cold observable. * * @param emitter - The emitter function which is called when a subscriber is added. * It should return a function that is called when the subscription is unsubscribed, * or return `undefined` if no cleanup is needed. * @returns - The created observer. */ Source.createCold = function (emitter) { var unsubscribeRef = function () { return undefined; }; var observer = new Observer(function () { return unsubscribeRef(); }); observer[LISTEN_CONNECT](function () { unsubscribeRef = emitter(observer.emit) || (function () { return undefined; }); }); return observer; }; /** * Creates a new instance of the Cold object. */ Source.create = _a.createCold; /** * Creates a pipe that connects an observer to a subject and emits output values based on a given emitter function. * * @param target - The observer that will receive output values. * @param emitter - A function that takes a subject and a next function and returns an unsubscribe function. * @returns The observer that is connected to the subject and emits output values. * @template Data - The type of data that will be observed. * @template Output - The type of output that will be emitted. */ Source.pipe = function (target, emitter) { var unsubscribeRef = function () { return undefined; }; var observer = new Observer(function () { return unsubscribeRef(); }); observer[LISTEN_CONNECT](function () { var subject = new Subject(); var unsubscribeTarget = target.connect(subject.next); var unsubscribeEmitter = emitter(subject, observer.emit) || (function () { return undefined; }); unsubscribeRef = compose(function () { return unsubscribeEmitter(); }, function () { return unsubscribeTarget(); }); }); return observer; }; Source.fromInterval = fromInterval; Source.fromPromise = fromPromise; Source.fromDelay = fromDelay; Source.fromArray = fromArray; /** * Creates a new observer that emits a value from the given data or function. * * @param data - The data or function to emit from the observer. * @returns - The created observer. */ Source.fromValue = function (data) { var observer = new Observer(function () { return undefined; }); observer[LISTEN_CONNECT](function () { if (typeof data === 'function') { observer.emit(data()); } else { observer.emit(data); } }); return observer; }; /** * Creates an observer from the given subject and returns it. * * @template Data - The type of data emitted by the observer. * @param subject - The subject to create the observer from. * @returns - The observer created from the subject. */ Source.fromSubject = function (subject) { var unsubscribeRef; var observer = new Observer(function () { return unsubscribeRef(); }); unsubscribeRef = subject.subscribe(observer.emit); return observer; }; /** * Creates an observer from a BehaviorSubject. * * @template Data The type of data emitted by the BehaviorSubject. * @param subject - The BehaviorSubject to create the observer from. * @returns The observer created from the BehaviorSubject. */ Source.fromBehaviorSubject = function (subject) { var unsubscribeRef; var observer = new Observer(function () { return unsubscribeRef(); }); observer[LISTEN_CONNECT](function () { subject.data && observer.emit(subject.data); }); unsubscribeRef = subject.subscribe(observer.emit); return observer; }; return Source; }()); /* Source.join([ Source.create((next) => next("1")), Source.create((next) => next(2)), Source.create((next) => next(false)), ]).split().connect((value) => console.log(value)); */ /* const { Source } = require('.') const multicast = Source.multicast(() => Source.create(() => { console.log('ctor'); return () => console.log('dtor'); })); const c1 = multicast.connect((v) => console.log(v)) const c2 = multicast.connect((v) => console.log(v)) c1() c2() const c3 = multicast.connect((v) => console.log(v)) */ var NEVER_VALUE$2 = Symbol('never'); /** * Takes a count number as an input and returns a higher-order function * that accepts a target TObserver. The higher-order function returns a TObserver * that filters the values emitted by the target TObserver based on the count. * Only values with an index less than or equal to the count will be emitted. * * @typeparam T - The type of values emitted by the target TObserver. * @param count - The maximum index of values to be emitted. * @returns A higher-order function that accepts a target TObserver and returns * a TObserver that filters values based on the count. */ var take = function (count) { return function (target) { return target .reduce(function (acm, cur) { return ({ value: cur, idx: acm.idx + 1, }); }, { value: NEVER_VALUE$2, idx: 0 }) .filter(function (_a) { var idx = _a.idx; return idx <= count; }) .map(function (_a) { var value = _a.value; return value; }); }; }; var NEVER_VALUE$1 = Symbol('never'); /** * Adds liveness functionality to a given observer stream. * * @template T - The type of values in the observer stream. * @param fallbackfn - The fallback function to be called when liveness times out. * @param waitFor - The time period in milliseconds to wait for liveness before calling the fallback function. Default is 5000 milliseconds. * @param target - The observer stream to add liveness functionality to. * @returns - The modified observer stream with liveness functionality. */ var liveness = function (fallbackfn, waitFor) { if (waitFor === void 0) { waitFor = 5000; } return function (target) { var isOk = true; var stream = Source.merge([ Source.fromInterval(waitFor) .filter(function () { var isOkPrev = isOk; isOk = false; return !isOkPrev; }) .operator(take(1)) .tap(fallbackfn) .map(function () { return NEVER_VALUE$1; }), target.tap(function () { isOk = true; }) ]); return stream.filter(function (value) { return value !== NEVER_VALUE$1; }); }; }; /** * Applies a pairwise transformation to an observer. * * @template T - The type of value observed by the original observer. * @param [by=2] - The number of values in each pair. * @returns - A function that takes an observer and returns a new observer that emits pairs of values. */ var pair = function (by) { if (by === void 0) { by = 2; } return function (target) { return target .reduce(function (acm, cur) { return __spreadArray(__spreadArray([], __read(acm), false), [cur], false).slice(-by); }, []) .filter(function (acm) { return acm.length === by; }); }; }; var NEVER_VALUE = Symbol('never'); /** * Skips the first n elements emitted by an observer. * * @typeparam T - The type of elements emitted by the observer. * @param the - The number of elements to skip. * @returns A new observer that skips the first n elements of the original observer. */ var skip = function (the) { return function (target) { return target .reduce(function (acm, cur) { return ({ value: cur, idx: acm.idx + 1, }); }, { value: NEVER_VALUE, idx: 0 }) .filter(function (_a) { var idx = _a.idx; return idx > the; }) .map(function (_a) { var value = _a.value; return value; }); }; }; /** * Applies stride tricks to a given target observer. * @template T The type of elements in the target observer. * @param strideSize The size of each stride. * @param [step=Math.floor(strideSize / 2)] The step size between each stride. * @returns The transformed observer that emits strided data. * @throws If the strideSize or step is too big, or if the data is unshaped. */ var strideTricks = function (strideSize, step) { if (step === void 0) { step = Math.floor(strideSize / 2); } return function (target) { var windowSize = -1; var totalSteps = -1; var resultSize = -1; var needExtraStep = false; return target .tap(function (buffer) { if (windowSize === -1) { windowSize = buffer.length; totalSteps = Math.ceil((windowSize - strideSize) / step); needExtraStep = totalSteps * strideSize !== windowSize; resultSize = totalSteps + (needExtraStep ? 1 : 0); if (strideSize > windowSize || step > strideSize) throw new Error('rn-declarative strideTricks too big stride'); } }) .flatMap(function (buffer) { if (buffer.length !== windowSize) { throw new Error('rn-declarative strideTricks unshaped data'); } var strides = []; for (var i = 0; i !== totalSteps; i++) { var startPos = i * step; strides.push(buffer.slice(startPos, startPos + strideSize)); } if (needExtraStep) { var lastStep = buffer.slice(windowSize - strideSize, windowSize); lastStep["lastStep"] = true; strides.push(lastStep); } return strides.flat(1); }) .reduce(function (acm, cur) { if (acm.length === strideSize) { return [cur]; } else { return __spreadArray(__spreadArray([], __read(acm), false), [cur], false); } }, []) .filter(function (acm) { return acm.length === strideSize; }) .reduce(function (acm, cur) { if (acm.length === resultSize) { return [cur]; } else { return __spreadArray(__spreadArray([], __read(acm), false), [cur], false); } }, []) .filter(function (acm) { return acm.length === resultSize; }); }; }; /** * Represents a collection of static operator functions. */ var Operator = /** @class */ (function () { function Operator() { } Operator.take = take; Operator.skip = skip; Operator.pair = pair; Operator.group = group; Operator.strideTricks = strideTricks; Operator.distinct = distinct; Operator.liveness = liveness; Operator.count = count; return Operator; }()); /* const { Source, Operator } = require('.') Source.fromInterval(1_000).operator(Operator.take(5)).connect(console.log) Source.fromInterval(1_000).operator(Operator.pair()).connect(console.log) Source.fromInterval(1_000).operator(Operator.group(3)).connect(console.log) Source.fromInterval(1_000).operator(Operator.skip(3)).connect(console.log) Source.fromValue([1,2,3,4,5,6,7,8,9,10,11,12,13]).operator(Operator.strideTricks(3, 3)).connect(console.log) */ /** * A function that picks a subset of documents from an array of documents, given a limit and offset. * * @template T - The type of the documents in the array. * @param limit - The maximum number of documents to pick. * @param offset - The number of documents to skip before picking. * @returns - A function that takes an array of documents and returns an object with `rows` and `done` properties. * The `rows` property contains the picked documents, and `done` property indicates if the picking is finished. */ var pickDocuments = function (limit, offset) { var result = []; return function (rows) { var e_1, _a; if (rows === void 0) { rows = []; } try { for (var rows_1 = __values(rows), rows_1_1 = rows_1.next(); !rows_1_1.done; rows_1_1 = rows_1.next()) { var row = rows_1_1.value; if (offset > 0) { offset -= 1; continue; } if (limit > 0) { result.push(row); limit -= 1; continue; } break; } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (rows_1_1 && !rows_1_1.done && (_a = rows_1.return)) _a.call(rows_1); } finally { if (e_1) throw e_1.error; } } return { rows: result, done: limit <= 0, }; }; }; /** * Resolves the documents from an async generator and paginates them. * * @param iterator - The async generator to resolve documents from. * @returns - A promise that resolves to the flattened array of documents. */ var paginateDocuments = function (iterator, limit, offset) { return __awaiter(void 0, void 0, void 0, function () { var iter, chunk, rows, e_1_1; var _a, iterator_1, iterator_1_1; var _b, e_1, _c, _d; return __generator(this, function (_e) { switch (_e.label) { case 0: iter = pickDocuments(limit, offset); _e.label = 1; case 1: _e.trys.push([1, 6, 7, 12]); _a = true, iterator_1 = __asyncValues(iterator); _e.label = 2; case 2: return [4 /*yield*/, iterator_1.next()]; case 3: if (!(iterator_1_1 = _e.sent(), _b = iterator_1_1.done, !_b)) return [3 /*break*/, 5]; _d = iterator_1_1.value; _a = false; chunk = _d; rows = [chunk].flatMap(function (v) { return v; }); if (iter(rows).done) { return [3 /*break*/, 5]; } _e.label = 4; case 4: _a = true; return [3 /*break*/, 2]; case 5: return [3 /*break*/, 12]; case 6: e_1_1 = _e.sent(); e_1 = { error: e_1_1 }; return [3 /*break*/, 12]; case 7: _e.trys.push([7, , 10, 11]); if (!(!_a && !_b && (_c = iterator_1.return))) return [3 /*break*/, 9]; return [4 /*yield*/, _c.call(iterator_1)]; case 8: _e.sent(); _e.label = 9; case 9: return [3 /*break*/, 11]; case 10: if (e_1) throw e_1.error; return [7 /*endfinally*/]; case 11: return [7 /*endfinally*/]; case 12: return [2 /*return*/, iter().rows]; } }); }); }; /** * Resolves the documents from an async generator and distincts them. * * @param iterator - The async generator to resolve documents from. * @returns - A promise that resolves to the flattened array of documents. */ function distinctDocuments(iterator_1) { return __asyncGenerator(this, arguments, function distinctDocuments_1(iterator, getId) { var duplicateSet, _a, iterator_2, iterator_2_1, chunk, rows, rows_1, rows_1_1, row, id, e_1_1, e_2_1; var e_1, _b; var _c, e_2, _d, _e; if (getId === void 0) { getId = function (data) { return data["id"]; }; } return __generator(this, function (_f) { switch (_f.label) { case 0: duplicateSet = new Set(); _f.label = 1; case 1: _f.trys.push([1, 14, 15, 20]); _a = true, iterator_2 = __asyncValues(iterator); _f.label = 2; case 2: return [4 /*yield*/, __await(iterator_2.next())]; case 3: if (!(iterator_2_1 = _f.sent(), _c = iterator_2_1.done, !_c)) return [3 /*break*/, 13]; _e = iterator_2_1.value; _a = false; chunk = _e; rows = [chunk].flatMap(function (v) { return v; }); _f.label = 4; case 4: _f.trys.push([4, 10, 11, 12]); rows_1 = (e_1 = void 0, __values(rows)), rows_1_1 = rows_1.next(); _f.label = 5; case 5: if (!!rows_1_1.done) return [3 /*break*/, 9]; row = rows_1_1.value; id = getId(row); if (!!duplicateSet.has(id)) return [3 /*break*/, 8]; duplicateSet.add(id); return [4 /*yield*/, __await(row)]; case 6: return [4 /*yield*/, _f.sent()]; case 7: _f.sent(); _f.label = 8; case 8: rows_1_1 = rows_1.next(); return [3 /*break*/, 5]; case 9: return [3 /*break*/, 12]; case 10: e_1_1 = _f.sent(); e_1 = { error: e_1_1 }; return [3 /*break*/, 12]; case 11: try { if (rows_1_1 && !rows_1_1.done && (_b = rows_1.return)) _b.call(rows_1); } finally { if (e_1) throw e_1.error; } return [7 /*endfinally*/]; case 12: _a = true; return [3 /*break*/, 2]; case 13: return [3 /*break*/, 20]; case 14: e_2_1 = _f.sent(); e_2 = { error: e_2_1 }; return [3 /*break*/, 20]; case 15: _f.trys.push([15, , 18, 19]); if (!(!_a && !_c && (_d = iterator_2.return))) return [3 /*break*/, 17]; return [4 /*yield*/, __await(_d.call(iterator_2))]; case 16: _f.sent(); _f.label = 17; case 17: return [3 /*break*/, 19]; case 18: if (e_2) throw e_2.error; return [7 /*endfinally*/]; case 19: return [7 /*endfinally*/]; case 20: return [2 /*return*/]; } }); }); } /** * Resolves the documents from an async generator and returns them as a flattened array. * * @param iterator - The async generator to resolve documents from. * @returns - A promise that resolves to the flattened array of documents. */ var resolveDocuments = function (iterator) { return __awaiter(void 0, void 0, void 0, function () { var result, item, e_1_1; var _a, iterator_1, iterator_1_1; var _b, e_1, _c, _d; return __generator(this, function (_e) { switch (_e.label) { case 0: result = []; _e.label = 1; case 1: _e.trys.push([1, 6, 7, 12]); _a = true, iterator_1 = __asyncValues(iterator); _e.label = 2; case 2: return [4 /*yield*/, iterator_1.next()]; case 3: if (!(iterator_1_1 = _e.sent(), _b = iterator_1_1.done, !_b)) return [3 /*break*/, 5]; _d = iterator_1_1.value; _a = false; item = _d; result.push(item); _e.label = 4; case 4: _a = true; return [3 /*break*/, 2]; case 5: return [3 /*break*/, 12]; case 6: e_1_1 = _e.sent(); e_1 = { error: e_1_1 }; return [3 /*break*/, 12]; case 7: _e.trys.push([7, , 10, 11]); if (!(!_a && !_b && (_c = iterator_1.return))) return [3 /*break*/, 9]; return [4 /*yield*/, _c.call(iterator_1)]; case 8: _e.sent(); _e.label = 9; case 9: return [3 /*break*/, 11]; case 10: if (e_1) throw e_1.error; return [7 /*endfinally*/]; case 11: return [7 /*endfinally*/]; case 12: return [2 /*return*/, result.flatMap(function (v) { return v; })]; } }); }); }; /** * Filters the documents from an async generator and yield them by the condition * * @param iterator - The async generator to resolve documents from. * @returns - A promise that resolves to the flattened array of documents. */ function filterDocuments(iterator, predicate) { return __asyncGenerator(this, arguments, function filterDocuments_1() { var _a, iterator_1, iterator_1_1, chunk, rows, rows_1, rows_1_1, row, e_1_1, e_2_1; var e_1, _b; var _c, e_2, _d, _e; return __generator(this, function (_f) { switch (_f.label) { case 0: _f.trys.push([0, 14, 15, 20]); _a = true, iterator_1 = __asyncValues(iterator); _f.label = 1; case 1: return [4 /*yield*/, __await(iterator_1.next())]; case 2: if (!(iterator_1_1 = _f.sent(), _c = iterator_1_1.done, !_c)) return [3 /*break*/, 13]; _e = iterator_1_1.value; _a = false; chunk = _e; rows = [chunk].flatMap(function (v) { return v; }); _f.label = 3; case 3: _f.trys.push([3, 10, 11, 12]); rows_1 = (e_1 = void 0, __values(rows)), rows_1_1 = rows_1.next(); _f.label = 4; case 4: if (!!rows_1_1.done) return [3 /*break*/, 9]; row = rows_1_1.value; return [4 /*yield*/, __await(predicate(row))]; case 5: if (!_f.sent()) return [3 /*break*/, 8]; return [4 /*yield*/, __await(row)]; case 6: return [4 /*yield*/, _f.sent()]; case 7: _f.sent(); _f.label = 8; case 8: rows_1_1 = rows_1.next(); return [3 /*break*/, 4]; case 9: return [3 /*break*/, 12]; case 10: e_1_1 = _f.sent(); e_1 = { error: e_1_1 }; return [3 /*break*/, 12]; case 11: try { if (rows_1_1 && !rows_1_1.done && (_b = rows_1.return)) _b.call(rows_1); } finally { if (e_1) throw e_1.error; } return [7 /*endfinally*/]; case 12: _a = true; return [3 /*break*/, 1]; case 13: return [3 /*break*/, 20]; case 14: e_2_1 = _f.sent(); e_2 = { error: e_2_1 }; return [3 /*break*/, 20]; case 15: _f.trys.push([15, , 18, 19]); if (!(!_a && !_c && (_d = iterator_1.return))) return [3 /*break*/, 17]; return [4 /*yield*/, __await(_d.call(iterator_1))]; case 16: _f.sent(); _f.label = 17; case 17: return [3 /*break*/, 19]; case 18: if (e_2) throw e_2.error; return [7 /*endfinally*/]; case 19: return [7 /*endfinally*/]; case 20: return [2 /*return*/]; } }); }); } /** * Maps the documents from an async generator and yield them * * @param iterator - The async generator to resolve documents from. * @returns - A promise that resolves to the flattened array of documents. */ function mapDocuments(iterator, callbackfn) { return __asyncGenerator(this, arguments, function mapDocuments_1() { var _a, iterator_1, iterator_1_1, chunk, rows, rows_1, rows_1_1, row, e_1_1, e_2_1; var e_1, _b; var _c, e_2, _d, _e; return __generator(this, function (_f) { switch (_f.label) { case 0: _f.trys.push([0, 14, 15, 20]); _a = true, iterator_1 = __asyncValues(iterator); _f.label = 1; case 1: return [4 /*yield*/, __await(iterator_1.next())]; case 2: if (!(iterator_1_1 = _f.sent(), _c = iterator_1_1.done, !_c)) return [3 /*break*/, 13]; _e = iterator_1_1.value; _a = false; chunk = _e; rows = [chunk].flatMap(function (v) { return v; }); _f.label = 3; case 3: _f.trys.push([3, 10, 11, 12]); rows_1 = (e_1 = void 0, __values(rows)), rows_1_1 = rows_1.next(); _f.label = 4; case 4: if (!!rows_1_1.done) return [3 /*break*/, 9]; row = rows_1_1.value; return [4 /*yield*/, __await(callbackfn(row))]; case 5: return [4 /*yield*/, __await.apply(void 0, [_f.sent()])]; case 6: return [4 /*yield*/, _f.sent()]; case 7: _f.sent(); _f.label = 8; case 8: rows_1_1 = rows_1.next(); return [3 /*break*/, 4]; case 9: return [3 /*break*/, 12]; case 10: e_1_1 = _f.sent(); e_1 = { error: e_1_1 }; return [3 /*break*/, 12]; case 11: try { if (rows_1_1 && !rows_1_1.done && (_b = rows_1.return)) _b.call(rows_1); } finally { if (e_1) throw e_1.error; } return [7 /*endfinally*/]; case 12: _a = true; return [3 /*break*/, 1]; case 13: return [3 /*break*/, 20]; case 14: e_2_1 = _f.sent(); e_2 = { error: e_2_1 }; return [3 /*break*/, 20]; case 15: _f.trys.push([15, , 18, 19]); if (!(!_a && !_c && (_d = iterator_1.return))) return [3 /*break*/, 17]; return [4 /*yield*/, __await(_d.call(iterator_1))]; case 16: _f.sent(); _f.label = 17; case 17: return [3 /*break*/, 19]; case 18: if (e_2) throw e_2.error; return [7 /*endfinally*/]; case 19: return [7 /*endfinally*/]; case 20: return [2 /*return*/]; } }); }); } var TOTAL_DOCUMENTS = 10000; var REQUEST_LIMIT = 5000; var REQUEST_DELAY = 100; /** * Asynchronous generator function that iterates over documents. * * @template Data - The type of the row data in the documents. * * @param config - The configuration object. * @param [config.totalDocuments=TOTAL_DOCUMENTS] - The total number of documents to iterate over. * @param [config.limit=REQUEST_LIMIT] - The number of documents to fetch in each request. * @param [config.delay=REQUEST_DELAY] - The delay between each request. * @param [config.createRequest=() => []] - The function used to create the request. * * @returns An asynchronous generator that yields an array of documents. * * @throws If the response length is greater than the specified limit. */ var iterateDocuments = function (_a) { return __asyncGenerator(this, arguments, function (_b) { var request, counter, lastId, lastQuery, response; var _this = this; var _c = _b.totalDocuments, totalDocuments = _c === void 0 ? TOTAL_DOCUMENTS : _c, _d = _b.limit, limit = _d === void 0 ? REQUEST_LIMIT : _d, _e = _b.delay, delay = _e === void 0 ? REQUEST_DELAY : _e, _f = _b.getId, getId = _f === void 0 ? function (data) { return data["id"]; } : _f, _g = _b.createRequest, createRequest = _g === void 0 ? function () { return []; } : _g; return __generator(this, function (_h) { switch (_h.label) { case 0: request = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return __awaiter(_this, void 0, void 0, function () { var _a, result; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, Promise.all([ createRequest.apply(void 0, __spreadArray([], __read(args), false)), sleep(delay), ])]; case 1: _a = __read.apply(void 0, [_b.sent(), 1]), result = _a[0]; return [2 /*return*/, result]; } }); }); }; counter = 0; lastId = null; lastQuery = request({ lastId: null, offset: 0, page: 0, limit: limit, }); _h.label = 1; case 1: if (!(counter < totalDocuments)) return [3 /*break*/, 8]; return [4 /*yield*/, __await(lastQuery)]; case 2: response = _h.sent(); if (!(response.length < limit)) return [3 /*break*/, 5]; return [4 /*yield*/, __await(response)]; case 3: return [4 /*yield*/, _h.sent()]; case 4: _h.sent(); return [3 /*break*/, 8]; case 5: if (response.length > limit) { throw new Error('functool-kit iterateDocuments response.length > limit'); } lastId = getId(response[response.length - 1]) || null; counter += limit; /** * Represents the last query made by the user. * @class */ lastQuery = request({ lastId: lastId, offset: counter, page: Math.ceil(counter / limit), limit: limit, }); return [4 /*yield*/, __await(response)]; case 6: return [4 /*yield*/, _h.sent()]; case 7: _h.sent(); return [3 /*break*/, 1]; case 8: return [2 /*return*/]; } }); }); }; function iteratePromise(fn) { return __asyncGenerator(this, arguments, function iteratePromise_1() { var _a, _b, row, e_1_1; var e_1, _c; return __generator(this, function (_d) { switch (_d.label) { case 0: _d.trys.push([0, 7, 8, 9]); return [4 /*yield*/, __await(fn())]; case 1: _a = __values.apply(void 0, [_d.sent()]), _b = _a.next(); _d.label = 2; case 2: if (!!_b.done) return [3 /*break*/, 6]; row = _b.value; return [4 /*yield*/, __await(row)]; case 3: return [4 /*yield*/, _d.sent()]; case 4: _d.sent(); _d.label = 5; case 5: _b = _a.next(); return [3 /*break*/, 2]; case 6: return [3 /*break*/, 9]; case 7: e_1_1 = _d.sent(); e_1 = { error: e_1_1 }; return [3 /*break*/, 9]; case 8: try { if (_b && !_b.done && (_c = _a.return)) _c.call(_a); } finally { if (e_1) throw e_1.error; } return [7 /*endfinally*/]; case 9: return [2 /*return*/]; } }); }); } var iterateUnion = function (iterators, getId) { if (getId === void 0) { getId = function (data) { return data["id"]; }; } return function (limit, offset) { return __asyncGenerator(this, arguments, function () { var duplicateSet, iterators_1, iterators_1_1, iterator, _a, iterator_1, iterator_1_1, chunk, rows, rows_1, rows_1_1, row, id, e_1_1, e_2_1, e_3_1; var e_3, _b, e_1, _c; var _d, e_2, _e, _f; return __generator(this, function (_g) { switch (_g.label) { case 0: duplicateSet = new Set(); _g.label = 1; case 1: _g.trys.push([1, 26, 27, 28]); iterators_1 = __values(iterators), iterators_1_1 = iterators_1.next(); _g.label = 2; case 2: if (!!iterators_1_1.done) return [3 /*break*/, 25]; iterator = iterators_1_1.value; _g.label = 3; case 3: _g.trys.push([3, 18, 19, 24]); _a = true, iterator_1 = (e_2 = void 0, __asyncValues(iterator)); _g.label = 4; case 4: return [4 /*yield*/, __await(iterator_1.next())]; case 5: if (!(iterator_1_1 = _g.sent(), _d = iterator_1_1.done, !_d)) return [3 /*break*/, 17]; _f = iterator_1_1.value; _a = false; chunk = _f; rows = [chunk].flatMap(function (v) { return v; }); _g.label = 6; case 6: _g.trys.push([6, 14, 15, 16]); rows_1 = (e_1 = void 0, __values(rows)), rows_1_1 = rows_1.next(); _g.label = 7; case 7: if (!!rows_1_1.done) return [3 /*break*/, 13]; row = rows_1_1.value; id = getId(row); if (duplicateSet.has(id)) { return [3 /*break*/, 12]; } if (offset > 0) { offset -= 1; return [3 /*break*/, 12]; } if (!(limit > 0)) return [3 /*break*/, 10]; duplicateSet.add(id); return [4 /*yield*/, __await(row)]; case 8: return [4 /*yield*/, _g.sent()]; case 9: _g.sent(); limit -= 1; return [3 /*break*/, 12]; case 10: return [4 /*yield*/, __await(void 0)]; case 11: return [2 /*return*/, _g.sent()]; case 12: rows_1_1 = rows_1.next(); return [3 /*break*/, 7]; case 13: return [3 /*break*/, 16]; case 14: e_1_1 = _g.sent(); e_1 = { error: e_1_1 }; return [3 /*break*/, 16]; case 15: try { if (rows_1_1 && !rows_1_1.done && (_c = rows_1.return)) _c.call(rows_1); } finally { if (e_1) throw e_1.error; } return [7 /*endfinally*/]; case 16: _a = true; return [3 /*break*/, 4]; case 17: return [3 /*break*/, 24]; case 18: e_2_1 = _g.sent(); e_2 = { error: e_2_1 }; return [3 /*break*/, 24]; case 19: _g.trys.push([19, , 22, 23]); if (!(!_a && !_d && (_e = iterator_1.return))) return [3 /*break*/, 21]; return [4 /*yield*/, __await(_e.call(iterator_1))]; case 20: _g.sent(); _g.label = 21; case 21: return [3 /*break*/, 23]; case 22: if (e_2) throw e_2.error; return [7 /*endfinally*/]; case 23: return [7 /*endfinally*/]; case 24: iterators_1_1 = iterators_1.next(); return [3 /*break*/, 2]; case 25: return [3 /*break*/, 28]; case 26: e_3_1 = _g.sent(); e_3 = { error: e_3_1 }; return [3 /*break*/, 28]; case 27: try { if (iterators_1_1 && !iterators_1_1.done && (_b = iterators_1.return)) _b.call(iterators_1); } finally { if (e_3) throw e_3.error; } return [7 /*endfinally*/]; case 28: return [2 /*return*/]; } }); }); }; }; function iterateList(rows_1) { return __asyncGenerator(this, arguments, function iterateList_1(rows, map) { var rows_2, rows_2_1, row, e_1_1; var e_1, _a; if (map === void 0) { map = function (row) { return Promise.resolve(row); }; } return __generator(this, function (_b) { switch (_b.label) { case 0: _b.trys.push([0, 7, 8, 9]); rows_2 = __values(rows), rows_2_1 = rows_2.next(); _b.label = 1; case 1: if (!!rows_2_1.done) return [3 /*break*/, 6]; row = rows_2_1.value; return [4 /*yield*/, __await(map(row))]; case 2: return [4 /*yield*/, __await.apply(void 0, [_b.sent()])]; case 3: return [4 /*yield*/, _b.sent()]; case 4: _b.sent(); _b.label = 5; case 5: rows_2_1 = rows_2.next(); return [3 /*break*/, 1]; case 6: return [3 /*break*/, 9]; case 7: e_1_1 = _b.sent(); e_1 = { error: e_1_1 }; return [3 /*break*/, 9]; case 8: try { if (rows_2_1 && !rows_2_1.done && (_a = rows_2.return)) _a.call(rows_2); } finally { if (e_1) throw e_1.error; } return [7 /*endfinally*/]; case 9: return [2 /*return*/]; } }); }); } var has = function (arr, value) { if (arr instanceof Array) { return arr.includes(value); } if (arr instanceof Set) { return arr.has(value); } if (arr instanceof Map) { return arr.has(value); } if (arr) { return arr === value; } return false; }; /** * Performs a logical AND operation on multiple values. * * @template T - The type of the values * @param args - The values to perform the logical AND operation on * @returns - The result of the logical AND operation */ var and = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (args.some(function (arg) { return arg instanceof Promise; })) { return new Promise(function (res, rej) { return __awaiter(void 0, void 0, void 0, function () { var items, result, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, Promise.all(args)]; case 1: items = _a.sent(); result = items.reduce(function (acm, cur) { return Boolean(acm && cur); }, true); res(result); return [3 /*break*/, 3]; case 2: error_1 = _a.sent(); rej(error_1); return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }); } return args.reduce(function (acm, cur) { return Boolean(acm && cur); }, true); }; /** * Returns a value of type T representing the logical OR operation on the given arguments. * * @param args - The arguments to be evaluated for the logical OR operation. * @returns A value of type T representing the result of the logical OR operation. * @throws If any of the arguments is a rejected promise. * @typeparam T - The type of the arguments and the return value. */ var or = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (args.some(function (arg) { return arg instanceof Promise; })) { return new Promise(function (res, rej) { return __awaiter(void 0, void 0, void 0, function () { var items, result, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, Promise.all(args)]; case 1: items = _a.sent(); result = items.reduce(function (acm, cur) { return Boolean(acm || cur); }, false); res(result); return [3 /*break*/, 3]; case 2: error_1 = _a.sent(); rej(error_1); return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }); } return args.reduce(function (acm, cur) { return Boolean(acm || cur); }, false); }; /** * Applies the logical negation operator to the given argument. * If the argument is a Promise, it returns a new Promise that resolves to the negation of the resolved value of the argument Promise. * If the argument is not a Promise, it returns the negation of the argument. * * @template T - The type of the argument and the return value. * @param arg - The argument to apply the logical negation operator. * @returns - The result of apply the logical negation operator to the argument. */ var not = function (arg) { if (arg instanceof Promise) { return new Promise(function (res, rej) { return __awaiter(void 0, void 0, void 0, function () { var result, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, arg]; case 1: result = _a.sent(); res(!result); return [3 /*break*/, 3]; case 2: error_1 = _a.sent(); rej(error_1); return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }); } return !arg; }; /** * Executes conditional branching based on the provided conditions and returns the appropriate value. * * @template A - Type of the condition value. * @template T - Type of the run value. * @template E - Type of the not value. * * @param params - The parameters object. * @param params.condition - The condition value or a function that returns the condition value. * @param params.run - The run value or a function that returns the run value. * @param [params.not=false] - The not value or a function that returns the not value. Defaults to false. * * @returns - The result of executing the condition and returning the appropriate value. */ var match = function (_a) { var condition = _a.condition, run = _a.run, _b = _a.not, not = _b === void 0 ? false : _b; var check = typeof condition === 'function' ? condition() : condition; var result = typeof run === 'function' ? run() : run; var fallback = typeof not === 'function' ? not : not; if (result instanceof Promise || check instanceof Promise || fallback instanceof Promise) { return new Promise(function (res, rej) { return __awaiter(void 0, void 0, void 0, function () { var _a, _b, error_1; return __generator(this, function (_c) { switch (_c.label) { case 0: _c.trys.push([0, 5, , 6]); return [4 /*yield*/, check]; case 1: if (!_c.sent()) return [3 /*break*/, 3]; _a = res; return [4 /*yield*/, result]; case 2: _a.apply(void 0, [_c.sent()]); return [2 /*return*/]; case 3: _b = res; return [4 /*yield*/, fallback]; case 4: _b.apply(void 0, [_c.sent()]); return [3 /*break*/, 6]; case 5: error_1 = _c.sent(); rej(error_1); return [3 /*break*/, 6]; case 6: return [2 /*return*/]; } }); }); }); } if (check) { return result; } return fallback; }; /** * Joins multiple arrays into a single array, removing duplicates and filtering out null values. * * @param arr - The arrays to join. * @returns - The joined array. * * @template T - The type of values in the array. */ var join = function () { var arr = []; for (var _i = 0; _i < arguments.length; _i++) { arr[_i] = arguments[_i]; } arr = arr.flat(1); return __spreadArray([], __read(new Set(arr.flatMap(function (item) { if (Array.isArray(item)) { return join(item); } return item; }).filter(Boolean))), false); }; /** * Returns the last element of an array or null if the array is empty or not an array. * * @param arr - The array from which to retrieve the last element. * @returns - The last element of the array or null. */ var last = function (arr) { if (Array.isArray(arr)) { var _a = __read(arr.slice(-1), 1), last_1 = _a[0]; return last_1 || null; } return null; }; /** * Filters an array and removes null values, casting the resulting array to a specific generic type if specified. * * @param arr - The input array containing values of type T or null. * @returns - The filtered array with null values removed. * * @template T - The generic type of the array elements. */ var truely = function (arr) { return ((arr === null || arr === void 0 ? void 0 : arr.filter(function (v) { return v; })) || []); }; /** * Extracts the enumerable properties from an Error object and returns them in a new object. * * @param error - The Error object. * @returns - An object containing the enumerable properties of the Error object. */ var errorData = function (error) { if (!error) { return {}; } var propertyNames = Object.getOwnPropertyNames(error); var result = {}; propertyNames.forEach(function (property) { var descriptor = Object.getOwnPropertyDescriptor(error, property) || {}; if ('value' in descriptor) { result[property] = descriptor.value; } }); return result; }; var FETCH_CONFIG = { useSymbolException: false, }; /** * Represents an error that occurs during a fetch request. * * @class * @extends Error */ var FetchError = /** @class */ (function (_super) { __extends(FetchError, _super); function FetchError(originalError, request, response) { var _this = _super.call(this, originalError.message || 'FetchError') || this; _this.originalError = originalError; _this.request = request; _this.response = response; return _this; } return FetchError; }(Error)); var PAYLOAD_METHODS = ['POST', 'PUT', 'PATCH']; /** * Makes an asynchronous HTTP request using the Fetch API. * * @param input - The resource URL or an instance of the URL class. * @param [init] - The request options. * @returns - The response data as a Promise. * @throws - If an error occurs during the request. */ var fetchApi = function (input, init) { return __awaiter(void 0, void 0, void 0, function () { var request, response, error_1; var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: request = input instanceof URL ? input.toString() : input; response = undefined; _b.label = 1; case 1: _b.trys.push([1, 4, , 5]); return [4 /*yield*/, fetch(request, __assign(__assign({}, init), { headers: __assign(__assign({}, (PAYLOAD_METHODS.includes((_a = init === null || init === void 0 ? void 0 : init.method) === null || _a === void 0 ? void 0 : _a.toUpperCase()) && { "Content-Type": "application/json", })), init === null || init === void 0 ? void 0 : init.headers) }))]; case 2: response = _b.sent(); if (!response.ok) { throw new Error('fetchApi response not ok'); } return [4 /*yield*/, response.json()]; case 3: return [2 /*return*/, _b.sent()]; case 4: error_1 = _b.sent(); if (FETCH_CONFIG.useSymbolException) { return [2 /*return*/, CATCH_SYMBOL]; } throw new FetchError(error_1, request, response); case 5: return [2 /*return*/]; } }); }); }; fetchApi.config = function (config) { Object.assign(FETCH_CONFIG, config); }; exports.BehaviorSubject = BehaviorSubject; exports.CANCELED_PROMISE_SYMBOL = CANCELED_SYMBOL; exports.CATCH_SYMBOL = CATCH_SYMBOL; exports.EventEmitter = EventEmitter; exports.FetchError = FetchError; exports.Observer = Observer; exports.Operator = Operator; exports.Source = Source; exports.Subject = Subject; exports.TIMEOUT_SYMBOL = TIMEOUT_SYMBOL; exports.Task = Task; exports.afterinit = afterinit; exports.and = and; exports.cached = cached; exports.cancelable = cancelable; exports.compareArray = compareArray; exports.compareFulltext = compareFulltext; exports.compose = compose; exports.createAwaiter = createAwaiter; exports.debounce = debounce; exports.deepFlat = deepFlat; exports.distinctDocuments = distinctDocuments; exports.errorData = errorData; exports.execpool = execpool; exports.fetchApi = fetchApi; exports.filterDocuments = filterDocuments; exports.first = first; exports.formatText = formatText; exports.has = has; exports.isObject = isObject; exports.iterateDocuments = iterateDocuments; exports.iterateList = iterateList; exports.iteratePromise = iteratePromise; exports.iterateUnion = iterateUnion; exports.join = join; exports.last = last; exports.lock = lock; exports.mapDocuments = mapDocuments; exports.match = match; exports.memoize = memoize; exports.not = not; exports.obsolete = obsolete; exports.or = or; exports.paginateDocuments = paginateDocuments; exports.pickDocuments = pickDocuments; exports.queued = queued; exports.randomString = randomString; exports.resolveDocuments = resolveDocuments; exports.retry = retry; exports.singlerun = singlerun; exports.singleshot = singleshot; exports.singletick = singletick; exports.sleep = sleep; exports.throttle = throttle; exports.timeout = timeout; exports.truely = truely; exports.trycatch = trycatch; exports.ttl = ttl; exports.waitForNext = waitForNext;