index.cjs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. function clamp(n, min, max) {
  4. return Math.min(max, Math.max(min, n));
  5. }
  6. function sum(...args) {
  7. return flattenArrayable(args).reduce((a, b) => a + b, 0);
  8. }
  9. function toArray(array) {
  10. array = array || [];
  11. if (Array.isArray(array))
  12. return array;
  13. return [array];
  14. }
  15. function flattenArrayable(array) {
  16. return toArray(array).flat(1);
  17. }
  18. function mergeArrayable(...args) {
  19. return args.flatMap((i) => toArray(i));
  20. }
  21. function partition(array, ...filters) {
  22. const result = new Array(filters.length + 1).fill(null).map(() => []);
  23. array.forEach((e, idx, arr) => {
  24. let i = 0;
  25. for (const filter of filters) {
  26. if (filter(e, idx, arr)) {
  27. result[i].push(e);
  28. return;
  29. }
  30. i += 1;
  31. }
  32. result[i].push(e);
  33. });
  34. return result;
  35. }
  36. function uniq(array) {
  37. return Array.from(new Set(array));
  38. }
  39. function last(array) {
  40. return at(array, -1);
  41. }
  42. function remove(array, value) {
  43. if (!array)
  44. return false;
  45. const index = array.indexOf(value);
  46. if (index >= 0) {
  47. array.splice(index, 1);
  48. return true;
  49. }
  50. return false;
  51. }
  52. function at(array, index) {
  53. const len = array.length;
  54. if (!len)
  55. return void 0;
  56. if (index < 0)
  57. index += len;
  58. return array[index];
  59. }
  60. function range(...args) {
  61. let start, stop, step;
  62. if (args.length === 1) {
  63. start = 0;
  64. step = 1;
  65. [stop] = args;
  66. } else {
  67. [start, stop, step = 1] = args;
  68. }
  69. const arr = [];
  70. let current = start;
  71. while (current < stop) {
  72. arr.push(current);
  73. current += step || 1;
  74. }
  75. return arr;
  76. }
  77. function move(arr, from, to) {
  78. arr.splice(to, 0, arr.splice(from, 1)[0]);
  79. return arr;
  80. }
  81. function clampArrayRange(n, arr) {
  82. return clamp(n, 0, arr.length - 1);
  83. }
  84. function sample(arr, count) {
  85. return Array.from({ length: count }, (_) => arr[Math.round(Math.random() * (arr.length - 1))]);
  86. }
  87. function shuffle(array) {
  88. for (let i = array.length - 1; i > 0; i--) {
  89. const j = Math.floor(Math.random() * (i + 1));
  90. [array[i], array[j]] = [array[j], array[i]];
  91. }
  92. return array;
  93. }
  94. const assert = (condition, message) => {
  95. if (!condition)
  96. throw new Error(message);
  97. };
  98. const toString = (v) => Object.prototype.toString.call(v);
  99. const noop = () => {
  100. };
  101. function notNullish(v) {
  102. return v != null;
  103. }
  104. function noNull(v) {
  105. return v !== null;
  106. }
  107. function notUndefined(v) {
  108. return v !== void 0;
  109. }
  110. function isTruthy(v) {
  111. return Boolean(v);
  112. }
  113. const isDef = (val) => typeof val !== "undefined";
  114. const isBoolean = (val) => typeof val === "boolean";
  115. const isFunction = (val) => typeof val === "function";
  116. const isNumber = (val) => typeof val === "number";
  117. const isString = (val) => typeof val === "string";
  118. const isObject = (val) => toString(val) === "[object Object]";
  119. const isWindow = (val) => typeof window !== "undefined" && toString(val) === "[object Window]";
  120. const isBrowser = typeof window !== "undefined";
  121. function slash(str) {
  122. return str.replace(/\\/g, "/");
  123. }
  124. function ensurePrefix(prefix, str) {
  125. if (!str.startsWith(prefix))
  126. return prefix + str;
  127. return str;
  128. }
  129. function ensureSuffix(suffix, str) {
  130. if (!str.endsWith(suffix))
  131. return str + suffix;
  132. return str;
  133. }
  134. function template(str, ...args) {
  135. return str.replace(/{(\d+)}/g, (match, key) => {
  136. const index = Number(key);
  137. if (Number.isNaN(index))
  138. return match;
  139. return args[index];
  140. });
  141. }
  142. const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
  143. function randomStr(size = 16, dict = urlAlphabet) {
  144. let id = "";
  145. let i = size;
  146. const len = dict.length;
  147. while (i--)
  148. id += dict[Math.random() * len | 0];
  149. return id;
  150. }
  151. const timestamp = () => +Date.now();
  152. function batchInvoke(functions) {
  153. functions.forEach((fn) => fn && fn());
  154. }
  155. function invoke(fn) {
  156. return fn();
  157. }
  158. function tap(value, callback) {
  159. callback(value);
  160. return value;
  161. }
  162. function objectMap(obj, fn) {
  163. return Object.fromEntries(Object.entries(obj).map(([k, v]) => fn(k, v)).filter(notNullish));
  164. }
  165. function isKeyOf(obj, k) {
  166. return k in obj;
  167. }
  168. function objectKeys(obj) {
  169. return Object.keys(obj);
  170. }
  171. function objectEntries(obj) {
  172. return Object.entries(obj);
  173. }
  174. function deepMerge(target, ...sources) {
  175. if (!sources.length)
  176. return target;
  177. const source = sources.shift();
  178. if (source === void 0)
  179. return target;
  180. if (isMergableObject(target) && isMergableObject(source)) {
  181. objectKeys(source).forEach((key) => {
  182. if (isMergableObject(source[key])) {
  183. if (!target[key])
  184. target[key] = {};
  185. deepMerge(target[key], source[key]);
  186. } else {
  187. target[key] = source[key];
  188. }
  189. });
  190. }
  191. return deepMerge(target, ...sources);
  192. }
  193. function isMergableObject(item) {
  194. return isObject(item) && !Array.isArray(item);
  195. }
  196. function objectPick(obj, keys, omitUndefined = false) {
  197. return keys.reduce((n, k) => {
  198. if (k in obj) {
  199. if (!omitUndefined || obj[k] !== void 0)
  200. n[k] = obj[k];
  201. }
  202. return n;
  203. }, {});
  204. }
  205. function clearUndefined(obj) {
  206. Object.keys(obj).forEach((key) => obj[key] === void 0 ? delete obj[key] : {});
  207. return obj;
  208. }
  209. function hasOwnProperty(obj, v) {
  210. if (obj == null)
  211. return false;
  212. return Object.prototype.hasOwnProperty.call(obj, v);
  213. }
  214. function createSingletonPromise(fn) {
  215. let _promise;
  216. function wrapper() {
  217. if (!_promise)
  218. _promise = fn();
  219. return _promise;
  220. }
  221. wrapper.reset = async () => {
  222. const _prev = _promise;
  223. _promise = void 0;
  224. if (_prev)
  225. await _prev;
  226. };
  227. return wrapper;
  228. }
  229. function sleep(ms, callback) {
  230. return new Promise((resolve) => setTimeout(async () => {
  231. await (callback == null ? void 0 : callback());
  232. resolve();
  233. }, ms));
  234. }
  235. function createPromiseLock() {
  236. const locks = [];
  237. return {
  238. async run(fn) {
  239. const p = fn();
  240. locks.push(p);
  241. try {
  242. return await p;
  243. } finally {
  244. remove(locks, p);
  245. }
  246. },
  247. async wait() {
  248. await Promise.allSettled(locks);
  249. },
  250. isWaiting() {
  251. return Boolean(locks.length);
  252. },
  253. clear() {
  254. locks.length = 0;
  255. }
  256. };
  257. }
  258. function createControlledPromise() {
  259. let resolve, reject;
  260. const promise = new Promise((_resolve, _reject) => {
  261. resolve = _resolve;
  262. reject = _reject;
  263. });
  264. promise.resolve = resolve;
  265. promise.reject = reject;
  266. return promise;
  267. }
  268. /* eslint-disable no-undefined,no-param-reassign,no-shadow */
  269. /**
  270. * Throttle execution of a function. Especially useful for rate limiting
  271. * execution of handlers on events like resize and scroll.
  272. *
  273. * @param {number} delay - A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
  274. * @param {boolean} [noTrailing] - Optional, defaults to false. If noTrailing is true, callback will only execute every `delay` milliseconds while the
  275. * throttled-function is being called. If noTrailing is false or unspecified, callback will be executed one final time
  276. * after the last throttled-function call. (After the throttled-function has not been called for `delay` milliseconds,
  277. * the internal counter is reset).
  278. * @param {Function} callback - A function to be executed after delay milliseconds. The `this` context and all arguments are passed through, as-is,
  279. * to `callback` when the throttled-function is executed.
  280. * @param {boolean} [debounceMode] - If `debounceMode` is true (at begin), schedule `clear` to execute after `delay` ms. If `debounceMode` is false (at end),
  281. * schedule `callback` to execute after `delay` ms.
  282. *
  283. * @returns {Function} A new, throttled, function.
  284. */
  285. function throttle (delay, noTrailing, callback, debounceMode) {
  286. /*
  287. * After wrapper has stopped being called, this timeout ensures that
  288. * `callback` is executed at the proper times in `throttle` and `end`
  289. * debounce modes.
  290. */
  291. var timeoutID;
  292. var cancelled = false; // Keep track of the last time `callback` was executed.
  293. var lastExec = 0; // Function to clear existing timeout
  294. function clearExistingTimeout() {
  295. if (timeoutID) {
  296. clearTimeout(timeoutID);
  297. }
  298. } // Function to cancel next exec
  299. function cancel() {
  300. clearExistingTimeout();
  301. cancelled = true;
  302. } // `noTrailing` defaults to falsy.
  303. if (typeof noTrailing !== 'boolean') {
  304. debounceMode = callback;
  305. callback = noTrailing;
  306. noTrailing = undefined;
  307. }
  308. /*
  309. * The `wrapper` function encapsulates all of the throttling / debouncing
  310. * functionality and when executed will limit the rate at which `callback`
  311. * is executed.
  312. */
  313. function wrapper() {
  314. for (var _len = arguments.length, arguments_ = new Array(_len), _key = 0; _key < _len; _key++) {
  315. arguments_[_key] = arguments[_key];
  316. }
  317. var self = this;
  318. var elapsed = Date.now() - lastExec;
  319. if (cancelled) {
  320. return;
  321. } // Execute `callback` and update the `lastExec` timestamp.
  322. function exec() {
  323. lastExec = Date.now();
  324. callback.apply(self, arguments_);
  325. }
  326. /*
  327. * If `debounceMode` is true (at begin) this is used to clear the flag
  328. * to allow future `callback` executions.
  329. */
  330. function clear() {
  331. timeoutID = undefined;
  332. }
  333. if (debounceMode && !timeoutID) {
  334. /*
  335. * Since `wrapper` is being called for the first time and
  336. * `debounceMode` is true (at begin), execute `callback`.
  337. */
  338. exec();
  339. }
  340. clearExistingTimeout();
  341. if (debounceMode === undefined && elapsed > delay) {
  342. /*
  343. * In throttle mode, if `delay` time has been exceeded, execute
  344. * `callback`.
  345. */
  346. exec();
  347. } else if (noTrailing !== true) {
  348. /*
  349. * In trailing throttle mode, since `delay` time has not been
  350. * exceeded, schedule `callback` to execute `delay` ms after most
  351. * recent execution.
  352. *
  353. * If `debounceMode` is true (at begin), schedule `clear` to execute
  354. * after `delay` ms.
  355. *
  356. * If `debounceMode` is false (at end), schedule `callback` to
  357. * execute after `delay` ms.
  358. */
  359. timeoutID = setTimeout(debounceMode ? clear : exec, debounceMode === undefined ? delay - elapsed : delay);
  360. }
  361. }
  362. wrapper.cancel = cancel; // Return the wrapper function.
  363. return wrapper;
  364. }
  365. /* eslint-disable no-undefined */
  366. /**
  367. * Debounce execution of a function. Debouncing, unlike throttling,
  368. * guarantees that a function is only executed a single time, either at the
  369. * very beginning of a series of calls, or at the very end.
  370. *
  371. * @param {number} delay - A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
  372. * @param {boolean} [atBegin] - Optional, defaults to false. If atBegin is false or unspecified, callback will only be executed `delay` milliseconds
  373. * after the last debounced-function call. If atBegin is true, callback will be executed only at the first debounced-function call.
  374. * (After the throttled-function has not been called for `delay` milliseconds, the internal counter is reset).
  375. * @param {Function} callback - A function to be executed after delay milliseconds. The `this` context and all arguments are passed through, as-is,
  376. * to `callback` when the debounced-function is executed.
  377. *
  378. * @returns {Function} A new, debounced function.
  379. */
  380. function debounce (delay, atBegin, callback) {
  381. return callback === undefined ? throttle(delay, atBegin, false) : throttle(delay, callback, atBegin !== false);
  382. }
  383. /*
  384. How it works:
  385. `this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.
  386. */
  387. class Node {
  388. value;
  389. next;
  390. constructor(value) {
  391. this.value = value;
  392. }
  393. }
  394. class Queue {
  395. #head;
  396. #tail;
  397. #size;
  398. constructor() {
  399. this.clear();
  400. }
  401. enqueue(value) {
  402. const node = new Node(value);
  403. if (this.#head) {
  404. this.#tail.next = node;
  405. this.#tail = node;
  406. } else {
  407. this.#head = node;
  408. this.#tail = node;
  409. }
  410. this.#size++;
  411. }
  412. dequeue() {
  413. const current = this.#head;
  414. if (!current) {
  415. return;
  416. }
  417. this.#head = this.#head.next;
  418. this.#size--;
  419. return current.value;
  420. }
  421. clear() {
  422. this.#head = undefined;
  423. this.#tail = undefined;
  424. this.#size = 0;
  425. }
  426. get size() {
  427. return this.#size;
  428. }
  429. * [Symbol.iterator]() {
  430. let current = this.#head;
  431. while (current) {
  432. yield current.value;
  433. current = current.next;
  434. }
  435. }
  436. }
  437. function pLimit(concurrency) {
  438. if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {
  439. throw new TypeError('Expected `concurrency` to be a number from 1 and up');
  440. }
  441. const queue = new Queue();
  442. let activeCount = 0;
  443. const next = () => {
  444. activeCount--;
  445. if (queue.size > 0) {
  446. queue.dequeue()();
  447. }
  448. };
  449. const run = async (fn, resolve, args) => {
  450. activeCount++;
  451. const result = (async () => fn(...args))();
  452. resolve(result);
  453. try {
  454. await result;
  455. } catch {}
  456. next();
  457. };
  458. const enqueue = (fn, resolve, args) => {
  459. queue.enqueue(run.bind(undefined, fn, resolve, args));
  460. (async () => {
  461. // This function needs to wait until the next microtask before comparing
  462. // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
  463. // when the run function is dequeued and called. The comparison in the if-statement
  464. // needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
  465. await Promise.resolve();
  466. if (activeCount < concurrency && queue.size > 0) {
  467. queue.dequeue()();
  468. }
  469. })();
  470. };
  471. const generator = (fn, ...args) => new Promise(resolve => {
  472. enqueue(fn, resolve, args);
  473. });
  474. Object.defineProperties(generator, {
  475. activeCount: {
  476. get: () => activeCount,
  477. },
  478. pendingCount: {
  479. get: () => queue.size,
  480. },
  481. clearQueue: {
  482. value: () => {
  483. queue.clear();
  484. },
  485. },
  486. });
  487. return generator;
  488. }
  489. const VOID = Symbol("p-void");
  490. class PInstance extends Promise {
  491. constructor(items = [], options) {
  492. super(() => {
  493. });
  494. this.items = items;
  495. this.options = options;
  496. this.promises = /* @__PURE__ */ new Set();
  497. }
  498. get promise() {
  499. var _a;
  500. let batch;
  501. const items = [...Array.from(this.items), ...Array.from(this.promises)];
  502. if ((_a = this.options) == null ? void 0 : _a.concurrency) {
  503. const limit = pLimit(this.options.concurrency);
  504. batch = Promise.all(items.map((p2) => limit(() => p2)));
  505. } else {
  506. batch = Promise.all(items);
  507. }
  508. return batch.then((l) => l.filter((i) => i !== VOID));
  509. }
  510. add(...args) {
  511. args.forEach((i) => {
  512. this.promises.add(i);
  513. });
  514. }
  515. map(fn) {
  516. return new PInstance(Array.from(this.items).map(async (i, idx) => {
  517. const v = await i;
  518. if (v === VOID)
  519. return VOID;
  520. return fn(v, idx);
  521. }), this.options);
  522. }
  523. filter(fn) {
  524. return new PInstance(Array.from(this.items).map(async (i, idx) => {
  525. const v = await i;
  526. const r = await fn(v, idx);
  527. if (!r)
  528. return VOID;
  529. return v;
  530. }), this.options);
  531. }
  532. forEach(fn) {
  533. return this.map(fn).then();
  534. }
  535. reduce(fn, initialValue) {
  536. return this.promise.then((array) => array.reduce(fn, initialValue));
  537. }
  538. clear() {
  539. this.promises.clear();
  540. }
  541. then(fn) {
  542. const p2 = this.promise;
  543. if (fn)
  544. return p2.then(fn);
  545. else
  546. return p2;
  547. }
  548. catch(fn) {
  549. return this.promise.catch(fn);
  550. }
  551. finally(fn) {
  552. return this.promise.finally(fn);
  553. }
  554. }
  555. function p(items, options) {
  556. return new PInstance(items, options);
  557. }
  558. exports.assert = assert;
  559. exports.at = at;
  560. exports.batchInvoke = batchInvoke;
  561. exports.clamp = clamp;
  562. exports.clampArrayRange = clampArrayRange;
  563. exports.clearUndefined = clearUndefined;
  564. exports.createControlledPromise = createControlledPromise;
  565. exports.createPromiseLock = createPromiseLock;
  566. exports.createSingletonPromise = createSingletonPromise;
  567. exports.debounce = debounce;
  568. exports.deepMerge = deepMerge;
  569. exports.ensurePrefix = ensurePrefix;
  570. exports.ensureSuffix = ensureSuffix;
  571. exports.flattenArrayable = flattenArrayable;
  572. exports.hasOwnProperty = hasOwnProperty;
  573. exports.invoke = invoke;
  574. exports.isBoolean = isBoolean;
  575. exports.isBrowser = isBrowser;
  576. exports.isDef = isDef;
  577. exports.isFunction = isFunction;
  578. exports.isKeyOf = isKeyOf;
  579. exports.isNumber = isNumber;
  580. exports.isObject = isObject;
  581. exports.isString = isString;
  582. exports.isTruthy = isTruthy;
  583. exports.isWindow = isWindow;
  584. exports.last = last;
  585. exports.mergeArrayable = mergeArrayable;
  586. exports.move = move;
  587. exports.noNull = noNull;
  588. exports.noop = noop;
  589. exports.notNullish = notNullish;
  590. exports.notUndefined = notUndefined;
  591. exports.objectEntries = objectEntries;
  592. exports.objectKeys = objectKeys;
  593. exports.objectMap = objectMap;
  594. exports.objectPick = objectPick;
  595. exports.p = p;
  596. exports.partition = partition;
  597. exports.randomStr = randomStr;
  598. exports.range = range;
  599. exports.remove = remove;
  600. exports.sample = sample;
  601. exports.shuffle = shuffle;
  602. exports.slash = slash;
  603. exports.sleep = sleep;
  604. exports.sum = sum;
  605. exports.tap = tap;
  606. exports.template = template;
  607. exports.throttle = throttle;
  608. exports.timestamp = timestamp;
  609. exports.toArray = toArray;
  610. exports.toString = toString;
  611. exports.uniq = uniq;