@talismn/util 2.1.1 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region \0rolldown/runtime.js
2
+ // \0rolldown/runtime.js
3
3
  var __create = Object.create;
4
4
  var __defProp = Object.defineProperty;
5
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -20,22 +20,19 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
20
20
  value: mod,
21
21
  enumerable: true
22
22
  }) : target, mod));
23
- //#endregion
24
23
  let bignumber_js = require("bignumber.js");
25
24
  bignumber_js = __toESM(bignumber_js);
26
25
  let lodash_es = require("lodash-es");
27
26
  let rxjs = require("rxjs");
28
- //#region src/configureBigNumber.ts
27
+ // src/configureBigNumber.ts
29
28
  bignumber_js.default.set({ STRICT: false });
30
29
  var configureBigNumber_default = bignumber_js.default;
31
- //#endregion
32
- //#region src/addTrailingSlash.ts
30
+ // src/addTrailingSlash.ts
33
31
  const addTrailingSlash = (url) => {
34
32
  if (url.endsWith("/")) return url;
35
33
  return `${url}/`;
36
34
  };
37
- //#endregion
38
- //#region src/assert.ts
35
+ // src/assert.ts
39
36
  /**
40
37
  * @name assert
41
38
  * @description Throws an Error with the given message if the condition is falsy.
@@ -46,8 +43,7 @@ function assert(condition, message) {
46
43
  if (condition) return;
47
44
  throw new Error(typeof message === "function" ? message() : message);
48
45
  }
49
- //#endregion
50
- //#region src/BigMath.ts
46
+ // src/BigMath.ts
51
47
  /**
52
48
  * Javascript's `Math` library for `BigInt`.
53
49
  * Taken from https://stackoverflow.com/questions/51867270/is-there-a-library-similar-to-math-that-supports-javascript-bigint/64953280#64953280
@@ -69,14 +65,12 @@ const BigMath = {
69
65
  return value;
70
66
  }
71
67
  };
72
- //#endregion
73
- //#region src/isHexString.ts
68
+ // src/isHexString.ts
74
69
  const REGEX_HEX_STRING = /^0x[0-9a-fA-F]*$/;
75
70
  const isHexString = (value) => {
76
71
  return typeof value === "string" && REGEX_HEX_STRING.test(value);
77
72
  };
78
- //#endregion
79
- //#region src/bytes.ts
73
+ // src/bytes.ts
80
74
  /**
81
75
  * Byte / hex primitives, drop-in equivalents of the `@polkadot/util` helpers we used to depend on.
82
76
  * Semantics intentionally match polkadot-js for migration safety.
@@ -158,14 +152,12 @@ const u8aUnwrapBytes = (value) => {
158
152
  const u8a = u8aToU8a(value);
159
153
  return u8aIsWrapped(u8a) ? u8a.subarray(U8A_WRAP_PREFIX.length, u8a.length - U8A_WRAP_POSTFIX.length) : u8a;
160
154
  };
161
- //#endregion
162
- //#region src/jsActivityHook.ts
155
+ // src/jsActivityHook.ts
163
156
  const reportJsActivity = (label, durationMs) => {
164
157
  const record = globalThis.__recordJsActivity;
165
158
  if (record) record(label, durationMs);
166
159
  };
167
- //#endregion
168
- //#region src/yieldToEventLoop.ts
160
+ // src/yieldToEventLoop.ts
169
161
  const yieldToEventLoop = () => {
170
162
  const { scheduler } = globalThis;
171
163
  if (typeof scheduler?.postTask === "function") return scheduler.postTask(() => {}, { priority: "background" });
@@ -182,8 +174,7 @@ const yieldToEventLoop = () => {
182
174
  });
183
175
  return new Promise((resolve) => setTimeout(resolve, 0));
184
176
  };
185
- //#endregion
186
- //#region src/timeSlicer.ts
177
+ // src/timeSlicer.ts
187
178
  /**
188
179
  * Default CPU budget for a single synchronous slice of chunked work.
189
180
  * ~50-60% of a 60fps frame, leaving the rest for the host (user interactions, rendering).
@@ -226,8 +217,7 @@ const createTimeSlicer = ({ budgetMs = 10, signal, now = defaultNow, label } = {
226
217
  throwIfAborted
227
218
  };
228
219
  };
229
- //#endregion
230
- //#region src/chunkedArray.ts
220
+ // src/chunkedArray.ts
231
221
  const getSlicer = (options) => options?.slicer ?? createTimeSlicer({
232
222
  budgetMs: options?.budgetMs,
233
223
  signal: options?.signal,
@@ -280,8 +270,7 @@ const arrayItemsEqualWithYield = async (a, b, options) => {
280
270
  }
281
271
  return true;
282
272
  };
283
- //#endregion
284
- //#region src/deferred.ts
273
+ // src/deferred.ts
285
274
  /**
286
275
  * In TypeScript, a deferred promise refers to a pattern that involves creating a promise that can be
287
276
  * resolved or rejected at a later point in time, typically by code outside of the current function scope.
@@ -315,8 +304,7 @@ function Deferred() {
315
304
  isRejected: () => isRejected
316
305
  };
317
306
  }
318
- //#endregion
319
- //#region src/firstThenDebounce.ts
307
+ // src/firstThenDebounce.ts
320
308
  /**
321
309
  * An rxjs operator which:
322
310
  *
@@ -324,8 +312,90 @@ function Deferred() {
324
312
  * 2. Debounces any future values by `timeout` ms.
325
313
  */
326
314
  const firstThenDebounce = (timeout) => (source) => (0, rxjs.concat)(source.pipe((0, rxjs.take)(1)), source.pipe((0, rxjs.skip)(1)).pipe((0, rxjs.debounceTime)(timeout)));
327
- //#endregion
328
- //#region src/formatDecimals.ts
315
+ // src/formatCurrency.ts
316
+ const INTL_CURRENCY_OVERRIDES = {
317
+ btc: {
318
+ symbol: "₿",
319
+ fractionDigits: 6
320
+ },
321
+ eth: {
322
+ symbol: "Ξ",
323
+ fractionDigits: 5
324
+ },
325
+ tao: {
326
+ symbol: "τ",
327
+ fractionDigits: 4
328
+ },
329
+ idr: { fractionDigits: 0 }
330
+ };
331
+ const INTL_MAX_FRACTION_DIGITS = 20;
332
+ const clampFractionDigits = (digits) => digits === void 0 ? void 0 : Math.min(digits, INTL_MAX_FRACTION_DIGITS);
333
+ const fractionDigitsByCurrency = /* @__PURE__ */ new Map();
334
+ const getCurrencyFractionDigits = (currency) => {
335
+ const currencyId = currency.toLowerCase();
336
+ const cached = fractionDigitsByCurrency.get(currencyId);
337
+ if (cached !== void 0) return cached;
338
+ const { maximumFractionDigits: intlFractionDigits = 2 } = new Intl.NumberFormat(void 0, {
339
+ style: "currency",
340
+ currency
341
+ }).resolvedOptions();
342
+ const fractionDigits = INTL_CURRENCY_OVERRIDES[currencyId]?.fractionDigits ?? intlFractionDigits;
343
+ fractionDigitsByCurrency.set(currencyId, fractionDigits);
344
+ return fractionDigits;
345
+ };
346
+ const getDefaultFractionDigits = (currencyId, options) => {
347
+ if ([
348
+ options.minimumFractionDigits,
349
+ options.maximumFractionDigits,
350
+ options.minimumSignificantDigits,
351
+ options.maximumSignificantDigits
352
+ ].some((digits) => digits !== void 0) || options.notation === "compact") return void 0;
353
+ return INTL_CURRENCY_OVERRIDES[currencyId]?.fractionDigits;
354
+ };
355
+ const isSpacing = (part) => part?.type === "literal" && part.value.trim() === "";
356
+ const withTrailingCode = (parts, code) => {
357
+ const currencyIndex = parts.findIndex((part) => part.type === "currency");
358
+ const number = parts.filter((part, index) => index !== currencyIndex && !(isSpacing(part) && Math.abs(index - currencyIndex) === 1));
359
+ while (isSpacing(number[0])) number.shift();
360
+ while (isSpacing(number.at(-1))) number.pop();
361
+ return [
362
+ ...number,
363
+ {
364
+ type: "literal",
365
+ value: " "
366
+ },
367
+ {
368
+ type: "currency",
369
+ value: code
370
+ }
371
+ ];
372
+ };
373
+ const formatCurrencyToParts = (amount, currency, options = {}) => {
374
+ const currencyId = currency.toLowerCase();
375
+ const currencyDisplay = options.currencyDisplay ?? (currencyId === "usd" ? "narrowSymbol" : "symbol");
376
+ const defaultFractionDigits = getDefaultFractionDigits(currencyId, options);
377
+ const intlOptions = {
378
+ ...options,
379
+ style: "currency",
380
+ currency,
381
+ currencyDisplay,
382
+ minimumFractionDigits: clampFractionDigits(options.minimumFractionDigits ?? defaultFractionDigits),
383
+ maximumFractionDigits: clampFractionDigits(options.maximumFractionDigits ?? defaultFractionDigits)
384
+ };
385
+ if (currencyDisplay === "code") return withTrailingCode(new Intl.NumberFormat(void 0, intlOptions).formatToParts(amount), currency.toUpperCase());
386
+ const symbol = currencyDisplay === "name" ? void 0 : INTL_CURRENCY_OVERRIDES[currencyId]?.symbol;
387
+ if (!symbol) return new Intl.NumberFormat(void 0, intlOptions).formatToParts(amount);
388
+ return new Intl.NumberFormat(void 0, {
389
+ ...intlOptions,
390
+ currency: "USD",
391
+ currencyDisplay: "narrowSymbol"
392
+ }).formatToParts(amount).map((part) => part.type === "currency" ? {
393
+ ...part,
394
+ value: symbol
395
+ } : part);
396
+ };
397
+ const formatCurrency = (amount, currency, options = {}) => formatCurrencyToParts(amount, currency, options).map((part) => part.value).join("");
398
+ // src/formatDecimals.ts
329
399
  const MIN_DIGITS = 4;
330
400
  const MAX_DECIMALS_FORMAT = 12;
331
401
  /**
@@ -357,28 +427,39 @@ const formatDecimals = (num, digits = MIN_DIGITS, options = {}, locale = "en-US"
357
427
  ...options
358
428
  }).format(truncatedValue.toNumber());
359
429
  };
360
- //#endregion
361
- //#region src/formatPrice.ts
362
- const formatPrice = (price, currency, compact) => {
363
- return Intl.NumberFormat(void 0, {
364
- style: "currency",
365
- currency,
366
- currencyDisplay: currency === "usd" ? "narrowSymbol" : "symbol",
367
- minimumSignificantDigits: 3,
368
- maximumSignificantDigits: compact ? price < 1 ? 3 : 4 : void 0,
369
- roundingPriority: compact ? "auto" : "morePrecision",
370
- notation: compact ? "compact" : "standard"
371
- }).format(price);
372
- };
373
- //#endregion
374
- //#region src/getErrorMessage.ts
430
+ // src/formatPrice.ts
431
+ const getPriceOptions = (price, compact) => ({
432
+ minimumSignificantDigits: 3,
433
+ maximumSignificantDigits: compact ? price < 1 ? 3 : 4 : void 0,
434
+ roundingPriority: compact ? "auto" : "morePrecision",
435
+ notation: compact ? "compact" : "standard"
436
+ });
437
+ const formatPrice = (price, currency, compact) => formatCurrency(price, currency, getPriceOptions(price, compact));
438
+ const MIN_COLLAPSED_ZEROS = 4;
439
+ const formatCompactPrice = (price, currency) => {
440
+ const parts = formatCurrencyToParts(price, currency, getPriceOptions(price, true));
441
+ const joinParts = (from, to) => parts.slice(from, to).map((part) => part.value).join("");
442
+ const fractionIndex = parts.findIndex((part) => part.type === "fraction");
443
+ const integer = parts.find((part) => part.type === "integer")?.value;
444
+ const match = /^(0+)([1-9]\d*?)0*$/.exec(parts[fractionIndex]?.value ?? "");
445
+ if (integer !== "0" || !match || match[1].length < MIN_COLLAPSED_ZEROS) return {
446
+ kind: "plain",
447
+ text: joinParts(0)
448
+ };
449
+ return {
450
+ kind: "collapsedZeros",
451
+ head: joinParts(0, fractionIndex),
452
+ zeroCount: match[1].length,
453
+ tail: match[2] + joinParts(fractionIndex + 1)
454
+ };
455
+ };
456
+ // src/getErrorMessage.ts
375
457
  const getErrorMessage = (error, fallback = "Unknown error") => {
376
458
  if (typeof error === "string") return error || fallback;
377
459
  if (error && typeof error === "object" && "message" in error && typeof error.message === "string") return error.message || fallback;
378
460
  return fallback;
379
461
  };
380
- //#endregion
381
- //#region src/getLoadable.ts
462
+ // src/getLoadable.ts
382
463
  function getLoadable$(factory, options = {}) {
383
464
  const { getError, refreshInterval } = options;
384
465
  const createLoadableStream = () => (0, rxjs.from)(factory()).pipe((0, rxjs.map)((data) => ({
@@ -394,8 +475,7 @@ const getGenericError = (error) => ({
394
475
  name: "Error",
395
476
  message: getErrorMessage(error)
396
477
  });
397
- //#endregion
398
- //#region src/getSharedObservable.ts
478
+ // src/getSharedObservable.ts
399
479
  const CACHE = /* @__PURE__ */ new Map();
400
480
  /**
401
481
  * How long an entry survives with no subscribers before being dropped. Long enough
@@ -455,8 +535,7 @@ const getSharedObservable = (namespace, args, createObservable, serializer = (ar
455
535
  scheduleCleanup(entry);
456
536
  return entry.observable;
457
537
  };
458
- //#endregion
459
- //#region src/getQuery.ts
538
+ // src/getQuery.ts
460
539
  /**
461
540
  * Creates a shared observable for executing queries with caching, loading states, and automatic refresh capabilities.
462
541
  *
@@ -521,8 +600,7 @@ const getQuery$ = ({ namespace, args, queryFn, defaultValue, refreshInterval, se
521
600
  bufferSize: 1
522
601
  })), serializer);
523
602
  };
524
- //#endregion
525
- //#region src/getLoadableQuery.ts
603
+ // src/getLoadableQuery.ts
526
604
  /**
527
605
  * Thin wrapper around getQuery$ that returns Loadable<T> and optionally
528
606
  * primes the stream with a loading state using the provided default value.
@@ -557,38 +635,31 @@ const getLoadableQuery$ = (params) => {
557
635
  }
558
636
  }), (0, rxjs.startWith)(...initial));
559
637
  };
560
- //#endregion
561
- //#region src/hasOwnProperty.ts
638
+ // src/hasOwnProperty.ts
562
639
  function hasOwnProperty(obj, prop) {
563
640
  if (typeof obj !== "object") return false;
564
641
  if (obj === null) return false;
565
642
  return prop in obj;
566
643
  }
567
- //#endregion
568
- //#region src/isAbortError.ts
644
+ // src/isAbortError.ts
569
645
  const isAbortError = (error) => {
570
646
  return error instanceof Error && error.name === "AbortError";
571
647
  };
572
- //#endregion
573
- //#region src/isArrayOf.ts
648
+ // src/isArrayOf.ts
574
649
  function isArrayOf(array, func) {
575
650
  if (array.length > 0 && array[0] instanceof func) return true;
576
651
  return false;
577
652
  }
578
- //#endregion
579
- //#region src/isAscii.ts
653
+ // src/isAscii.ts
580
654
  const isAscii = (str) => {
581
655
  return [...str].every((char) => char.charCodeAt(0) <= 127);
582
656
  };
583
- //#endregion
584
- //#region src/isBigInt.ts
657
+ // src/isBigInt.ts
585
658
  const isBigInt = (value) => typeof value === "bigint";
586
- //#endregion
587
- //#region src/isBooleanTrue.ts
659
+ // src/isBooleanTrue.ts
588
660
  /** @deprecated use isTruthy instead */
589
661
  const isBooleanTrue = (x) => !!x;
590
- //#endregion
591
- //#region src/isErrorOfName.ts
662
+ // src/isErrorOfName.ts
592
663
  /**
593
664
  * Robust replacement for `error instanceof SomeErrorClass` when the class comes from a
594
665
  * package that gets bundled into multiple chunks/contexts (e.g. viem, @solana/web3.js).
@@ -601,8 +672,7 @@ const isBooleanTrue = (x) => !!x;
601
672
  * duck-type the shape instead.
602
673
  */
603
674
  const isErrorOfName = (error, ...names) => error instanceof Error && names.includes(error.name);
604
- //#endregion
605
- //#region src/isNotNil.ts
675
+ // src/isNotNil.ts
606
676
  /**
607
677
  * WARNING: This function only checks against null or undefined, it does not coerce the value.
608
678
  * ie: false and 0 are considered not nil
@@ -612,11 +682,9 @@ const isErrorOfName = (error, ...names) => error instanceof Error && names.inclu
612
682
  * @returns whether the value is neither null nor undefined
613
683
  */
614
684
  const isNotNil = (value) => value !== null && value !== void 0;
615
- //#endregion
616
- //#region src/isPromise.ts
685
+ // src/isPromise.ts
617
686
  const isPromise = (value) => !!value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
618
- //#endregion
619
- //#region src/isSubject.ts
687
+ // src/isSubject.ts
620
688
  /**
621
689
  * Tests to see if an object is an RxJS {@link Subject}.
622
690
  */
@@ -637,11 +705,9 @@ function isFn(value) {
637
705
  function isBool(value) {
638
706
  return typeof value === "boolean";
639
707
  }
640
- //#endregion
641
- //#region src/isTruthy.ts
708
+ // src/isTruthy.ts
642
709
  const isTruthy = (value) => Boolean(value);
643
- //#endregion
644
- //#region src/keepAlive.ts
710
+ // src/keepAlive.ts
645
711
  /**
646
712
  * An RxJS operator that keeps the source observable alive for a specified duration
647
713
  * after all subscribers have unsubscribed. This prevents expensive re-subscriptions
@@ -675,8 +741,7 @@ const keepSourceSubscribed = (observable, ms) => {
675
741
  const sub = observable.subscribe();
676
742
  return () => setTimeout(() => sub.unsubscribe(), ms);
677
743
  };
678
- //#endregion
679
- //#region src/lruMap.ts
744
+ // src/lruMap.ts
680
745
  /**
681
746
  * A Map with a maximum size and least-recently-used eviction.
682
747
  *
@@ -720,8 +785,7 @@ var LruMap = class {
720
785
  return this.#map.size;
721
786
  }
722
787
  };
723
- //#endregion
724
- //#region src/mapChunked.ts
788
+ // src/mapChunked.ts
725
789
  const runChunkedProject = (project, options, value, index) => new rxjs.Observable((subscriber) => {
726
790
  const controller = new AbortController();
727
791
  project(value, {
@@ -758,15 +822,13 @@ const switchMapChunked = (project, options) => (0, rxjs.switchMap)((value, index
758
822
  * still aborts it).
759
823
  */
760
824
  const concatMapChunked = (project, options) => (0, rxjs.concatMap)((value, index) => runChunkedProject(project, options, value, index));
761
- //#endregion
762
- //#region src/planckToTokens.ts
825
+ // src/planckToTokens.ts
763
826
  function planckToTokens(planck, tokenDecimals) {
764
827
  if (typeof planck !== "string" || typeof tokenDecimals !== "number") return;
765
828
  const multiplier = 10 ** (-1 * tokenDecimals);
766
829
  return new configureBigNumber_default(planck).multipliedBy(multiplier).toString(10);
767
830
  }
768
- //#endregion
769
- //#region src/replaySubjectFrom.ts
831
+ // src/replaySubjectFrom.ts
770
832
  /**
771
833
  * Turns a value into a {@link ReplaySubject} of size 1.
772
834
  *
@@ -787,14 +849,12 @@ const replaySubjectFrom = (initialValue) => {
787
849
  subject.next(initialValue);
788
850
  return subject;
789
851
  };
790
- //#endregion
791
- //#region src/sleep.ts
852
+ // src/sleep.ts
792
853
  const sleep = (ms) => new Promise((resolve) => {
793
854
  if (process.env.NODE_ENV === "test") resolve();
794
855
  else setTimeout(resolve, ms);
795
856
  });
796
- //#endregion
797
- //#region src/splitSubject.ts
857
+ // src/splitSubject.ts
798
858
  /**
799
859
  * Takes a subject and splits it into two parts:
800
860
  *
@@ -808,8 +868,7 @@ function splitSubject(subject) {
808
868
  const next = (value) => subject.next(value);
809
869
  return [next, subject.asObservable()];
810
870
  }
811
- //#endregion
812
- //#region src/stripHexPrefix.ts
871
+ // src/stripHexPrefix.ts
813
872
  /**
814
873
  * @name stripHexPrefix
815
874
  * @description Removes a leading `0x` prefix from a string, if present.
@@ -820,18 +879,310 @@ function splitSubject(subject) {
820
879
  * stripHexPrefix("1234") // "1234"
821
880
  **/
822
881
  const stripHexPrefix = (str) => str.startsWith("0x") ? str.slice(2) : str;
823
- //#endregion
824
- //#region src/throwAfter.ts
882
+ // src/suspension.ts
883
+ /**
884
+ * Detects when the JS runtime has been suspended, and provides timeouts that count only the
885
+ * time it was running.
886
+ *
887
+ * A mobile OS freezes an app that goes to the background, its webviews included, and a
888
+ * browser can freeze a tab or put a laptop to sleep. No timer fires while the runtime is
889
+ * frozen, and on resume every timer that came due in the meantime fires at once, before the
890
+ * socket messages that arrived while it was frozen. A 30s request timeout armed shortly
891
+ * before a 90s suspension therefore fails its request the moment the runtime resumes,
892
+ * although the answer may already be waiting.
893
+ *
894
+ * A one-second ticker runs while anything is watching. A gap between two ticks longer than
895
+ * `SUSPENSION_GAP_MS` (`HOST_SUSPENSION_GAP_MS` once a host marks suspensions) is taken to be
896
+ * a suspension. Timer callbacks call `checkSuspension()` first, because on resume a due timer
897
+ * can run before the ticker does.
898
+ *
899
+ * A page that is hidden can't tell a freeze from timer throttling: browsers run the timers of
900
+ * a hidden tab once a second, and Chrome once a minute after five minutes. Both leave gaps
901
+ * between ticks while socket messages keep arriving. In a hidden page, the first gap starts a
902
+ * suspension that lasts until the page is shown again, or until its ticks run on time again
903
+ * (a frozen page that resumes while hidden, or an extension's background page, which is never
904
+ * shown). Taking each gap for a resume would restart every timeout once a minute, so that
905
+ * none ever fires.
906
+ *
907
+ * A runtime can also be cut off while it keeps running: a webview whose network traffic goes
908
+ * through its app's native code stays alive while the app is frozen in the background. Its
909
+ * host marks that time with `setSuspended()`. An app can mark its own runtime the same way
910
+ * from the OS's background and foreground events.
911
+ */
912
+ const TICK_MS = 1e3;
913
+ /**
914
+ * A gap between ticks longer than this is a suspension. Well above the longest stall the JS
915
+ * thread is expected to have while it runs, so that a busy thread is not taken for a frozen
916
+ * one.
917
+ */
918
+ const SUSPENSION_GAP_MS = 5e3;
919
+ /**
920
+ * A gap between ticks longer than this is a suspension once a host has marked suspensions
921
+ * (`setSuspended`). The marks cover the freezes the host knows of, and a gap only has to
922
+ * catch one whose mark arrived too late, such as a webview frozen before its app's message
923
+ * reached it. A stall of the JS thread under this long (a metadata parse on a slow phone)
924
+ * then doesn't restart the timeouts.
925
+ */
926
+ const HOST_SUSPENSION_GAP_MS = 15e3;
927
+ /**
928
+ * A tick that comes `TICK_MS / 2` to this long after the one before is on time. Browsers
929
+ * align a hidden page's timers to whole seconds, so its ticks can be up to two seconds apart.
930
+ */
931
+ const ON_TIME_TICK_GAP_MS = 3e3;
932
+ /** On-time ticks in a row that end a hidden page's suspension */
933
+ const ON_TIME_TICKS_TO_RESUME = 5;
934
+ const listeners = /* @__PURE__ */ new Set();
935
+ let holds = 0;
936
+ let ticker = null;
937
+ let lastRunAt = 0;
938
+ /** when the ticker last ran */
939
+ let lastTickAt = 0;
940
+ /** on-time ticks in a row since a hidden page's suspension started */
941
+ let onTimeTicks = 0;
942
+ /** how far the clock has moved back in all, for the timeouts to shift their start by */
943
+ let clockMovedBackMs = 0;
944
+ let lastResumedAt = Number.NEGATIVE_INFINITY;
945
+ /** when the host marked the runtime suspended (`setSuspended(true)`), or null */
946
+ let suspendedSince = null;
947
+ /** whether the page (when there is one) is hidden */
948
+ let pageHidden = false;
949
+ /** the longest gap between ticks since the page was hidden */
950
+ let hiddenGapMs = 0;
951
+ /** a suspension that has ended for the host or the page while the other still holds it */
952
+ let pending = null;
953
+ let watchingPage = false;
954
+ /** whether a host has marked suspensions (`setSuspended`) */
955
+ let hostMarksSuspensions = false;
956
+ const suspensionGapMs = () => hostMarksSuspensions ? HOST_SUSPENSION_GAP_MS : SUSPENSION_GAP_MS;
957
+ const getPage = () => {
958
+ const page = globalThis.document;
959
+ return typeof page?.addEventListener === "function" ? page : void 0;
960
+ };
961
+ const isHeld = () => suspendedSince !== null || pageHidden && hiddenGapMs > suspensionGapMs();
962
+ /** Ends the host's or the page's part of a suspension, and resumes once neither holds it */
963
+ const endHold = (now, ms, byHost) => {
964
+ pending = {
965
+ ms: Math.max(pending?.ms ?? 0, ms),
966
+ byHost: (pending?.byHost ?? false) || byHost
967
+ };
968
+ if (isHeld()) return;
969
+ const ended = pending;
970
+ pending = null;
971
+ lastRunAt = now;
972
+ if (ended.byHost || ended.ms > suspensionGapMs()) resume(now, ended.ms);
973
+ };
974
+ const handleVisibilityChange = () => {
975
+ const hidden = getPage()?.visibilityState === "hidden";
976
+ if (hidden === pageHidden) return;
977
+ if (hidden) {
978
+ checkSuspension();
979
+ pageHidden = true;
980
+ hiddenGapMs = 0;
981
+ onTimeTicks = 0;
982
+ return;
983
+ }
984
+ const now = Date.now();
985
+ followClock(now);
986
+ const ms = Math.max(hiddenGapMs, ticker ? now - lastRunAt : 0);
987
+ pageHidden = false;
988
+ endPageHold(now, ms);
989
+ };
990
+ const endPageHold = (now, ms) => {
991
+ hiddenGapMs = 0;
992
+ onTimeTicks = 0;
993
+ endHold(now, ms, false);
994
+ };
995
+ /**
996
+ * Ends a hidden page's suspension once its ticks have run on time for a while: its timers run
997
+ * at their normal pace again. A tick that runs right after another (the timers that came due
998
+ * during a freeze, run together) counts neither way.
999
+ */
1000
+ const tick = () => {
1001
+ const now = Date.now();
1002
+ const sinceLastTick = now - lastTickAt;
1003
+ lastTickAt = now;
1004
+ checkSuspension();
1005
+ if (!pageHidden || hiddenGapMs <= suspensionGapMs()) return;
1006
+ if (sinceLastTick > ON_TIME_TICK_GAP_MS) onTimeTicks = 0;
1007
+ else if (sinceLastTick >= TICK_MS / 2) onTimeTicks++;
1008
+ if (onTimeTicks >= ON_TIME_TICKS_TO_RESUME) endPageHold(now, hiddenGapMs);
1009
+ };
1010
+ const watchPage = () => {
1011
+ const page = getPage();
1012
+ if (watchingPage || !page) return;
1013
+ watchingPage = true;
1014
+ pageHidden = page.visibilityState === "hidden";
1015
+ page.addEventListener("visibilitychange", handleVisibilityChange);
1016
+ };
1017
+ const hold = () => {
1018
+ holds++;
1019
+ if (ticker) return;
1020
+ watchPage();
1021
+ const now = Date.now();
1022
+ followClock(now);
1023
+ lastRunAt = now;
1024
+ lastTickAt = now;
1025
+ ticker = setInterval(tick, TICK_MS);
1026
+ };
1027
+ const release = () => {
1028
+ holds--;
1029
+ if (holds > 0 || !ticker) return;
1030
+ clearInterval(ticker);
1031
+ ticker = null;
1032
+ };
1033
+ /**
1034
+ * Shifts the times kept here when the clock has moved back since the runtime last ran, so that
1035
+ * time since a resume, or since the host marked a suspension, keeps counting from where it was
1036
+ */
1037
+ const followClock = (now) => {
1038
+ if (now >= lastRunAt) return;
1039
+ const movedBackMs = lastRunAt - now;
1040
+ clockMovedBackMs += movedBackMs;
1041
+ lastRunAt = now;
1042
+ lastTickAt -= movedBackMs;
1043
+ lastResumedAt -= movedBackMs;
1044
+ if (suspendedSince !== null) suspendedSince -= movedBackMs;
1045
+ };
1046
+ /**
1047
+ * Records that the JS runtime is running now. When it last ran longer than
1048
+ * `SUSPENSION_GAP_MS` (or `HOST_SUSPENSION_GAP_MS`) ago, it was suspended in between, and the resume listeners run before
1049
+ * this returns. When the host or a hidden page holds the suspension, they run once it ends.
1050
+ * Cheap enough to call at the start of every timer callback that measures time.
1051
+ */
1052
+ const checkSuspension = () => {
1053
+ const now = Date.now();
1054
+ followClock(now);
1055
+ const suspendedMs = ticker ? now - lastRunAt : 0;
1056
+ lastRunAt = now;
1057
+ if (pageHidden) {
1058
+ hiddenGapMs = Math.max(hiddenGapMs, suspendedMs);
1059
+ return;
1060
+ }
1061
+ if (suspendedSince !== null || suspendedMs <= suspensionGapMs()) return;
1062
+ resume(now, suspendedMs);
1063
+ };
1064
+ const resume = (now, suspendedMs) => {
1065
+ lastResumedAt = now;
1066
+ for (const listener of [...listeners]) try {
1067
+ listener(suspendedMs);
1068
+ } catch (error) {
1069
+ queueMicrotask(() => {
1070
+ throw error;
1071
+ });
1072
+ }
1073
+ };
1074
+ /**
1075
+ * Marks the JS runtime suspended (`true`) or running again (`false`), for a host that knows
1076
+ * when the runtime is frozen or cut off (it may keep running). While suspended,
1077
+ * `setAwakeTimeout` timeouts don't fire. `setSuspended(false)` is a resume: the timeouts start
1078
+ * over, and the resume listeners run with the time since `setSuspended(true)`. When the page
1079
+ * is also held suspended (hidden, with a gap between ticks), the resume waits until it is
1080
+ * shown or its ticks run on time again.
1081
+ *
1082
+ * From the first call on, a gap between ticks counts as a suspension only from
1083
+ * `HOST_SUSPENSION_GAP_MS` (15s), so that a stall of the JS thread doesn't restart the
1084
+ * timeouts. A host calls it at startup with the runtime's state, for that to apply from then.
1085
+ *
1086
+ * The state is global to the module: the mark reaches the code that reads it (such as
1087
+ * `ChainConnectorDot`) only when both load the same copy of `@talismn/util`. A second copy in
1088
+ * the bundle, from mismatched `@talismn/*` versions or from CJS and ESM builds side by side,
1089
+ * keeps a state of its own, without an error.
1090
+ */
1091
+ const setSuspended = (suspended) => {
1092
+ hostMarksSuspensions = true;
1093
+ if (suspended) {
1094
+ checkSuspension();
1095
+ suspendedSince ??= Date.now();
1096
+ return;
1097
+ }
1098
+ if (suspendedSince === null) return;
1099
+ const now = Date.now();
1100
+ followClock(now);
1101
+ const suspendedMs = now - suspendedSince;
1102
+ suspendedSince = null;
1103
+ endHold(now, suspendedMs, true);
1104
+ };
1105
+ /**
1106
+ * Whether the runtime is held suspended until a later resume: marked by the host
1107
+ * (`setSuspended(true)`), or a hidden page whose timers have stopped or been throttled
1108
+ */
1109
+ const isSuspended = () => {
1110
+ checkSuspension();
1111
+ return isHeld();
1112
+ };
1113
+ /**
1114
+ * When the JS runtime last resumed from a suspension (`Date.now()` time), or -Infinity when
1115
+ * no suspension has been seen. A freeze is only seen while something is watching (an
1116
+ * `onResume` listener or a pending `setAwakeTimeout`); the end of a suspension the host
1117
+ * marked (`setSuspended(false)`) is a resume in any case.
1118
+ */
1119
+ const getLastResumedAt = () => {
1120
+ checkSuspension();
1121
+ return lastResumedAt;
1122
+ };
1123
+ /**
1124
+ * Calls `listener` each time the JS runtime resumes from a suspension, with how long it was
1125
+ * suspended for. Returns the function that removes it.
1126
+ */
1127
+ const onResume = (listener) => {
1128
+ listeners.add(listener);
1129
+ hold();
1130
+ let removed = false;
1131
+ return () => {
1132
+ if (removed) return;
1133
+ removed = true;
1134
+ listeners.delete(listener);
1135
+ release();
1136
+ };
1137
+ };
1138
+ /**
1139
+ * Like `setTimeout`, but time the JS runtime spends suspended does not count. When the runtime
1140
+ * resumes from a suspension before the timeout is up, the timeout starts over from the resume,
1141
+ * so the work it guards gets its full time again. Returns the function that cancels it.
1142
+ */
1143
+ const setAwakeTimeout = (callback, ms) => {
1144
+ hold();
1145
+ let startedAt = Date.now();
1146
+ let clockMovedBackAtStartMs = clockMovedBackMs;
1147
+ let token = null;
1148
+ let done = false;
1149
+ const finish = () => {
1150
+ if (done) return;
1151
+ done = true;
1152
+ if (token) clearTimeout(token);
1153
+ token = null;
1154
+ release();
1155
+ };
1156
+ const fire = () => {
1157
+ checkSuspension();
1158
+ if (done) return;
1159
+ if (isHeld()) {
1160
+ token = setTimeout(fire, ms);
1161
+ return;
1162
+ }
1163
+ startedAt -= clockMovedBackMs - clockMovedBackAtStartMs;
1164
+ clockMovedBackAtStartMs = clockMovedBackMs;
1165
+ const now = Date.now();
1166
+ const remaining = ms - (now - Math.min(now, Math.max(startedAt, lastResumedAt)));
1167
+ if (remaining > 0) {
1168
+ token = setTimeout(fire, remaining);
1169
+ return;
1170
+ }
1171
+ finish();
1172
+ callback();
1173
+ };
1174
+ token = setTimeout(fire, ms);
1175
+ return finish;
1176
+ };
1177
+ // src/throwAfter.ts
825
1178
  const throwAfter = (ms, reason) => new Promise((_, reject) => setTimeout(() => reject(new Error(reason)), ms));
826
- //#endregion
827
- //#region src/tokensToPlanck.ts
1179
+ // src/tokensToPlanck.ts
828
1180
  function tokensToPlanck(tokens, tokenDecimals) {
829
1181
  if (typeof tokens !== "string" || typeof tokenDecimals !== "number") return;
830
1182
  const multiplier = 10 ** tokenDecimals;
831
1183
  return new configureBigNumber_default(tokens).multipliedBy(multiplier).toString(10);
832
1184
  }
833
- //#endregion
834
- //#region src/validateArrayWithYield.ts
1185
+ // src/validateArrayWithYield.ts
835
1186
  /**
836
1187
  * Validates every item of an array within a cooperative time budget, yielding the thread
837
1188
  * to the host event loop whenever the budget for the current slice is exhausted.
@@ -859,8 +1210,7 @@ const validateArrayWithYield = async (items, parseItem, options) => {
859
1210
  data
860
1211
  };
861
1212
  };
862
- //#endregion
863
- //#region src/validateHexString.ts
1213
+ // src/validateHexString.ts
864
1214
  /**
865
1215
  * @name validateHexString
866
1216
  * @description Checks if a string is a hex string. Required to account for type differences between different polkadot libraries
@@ -876,7 +1226,6 @@ const validateHexString = (str) => {
876
1226
  if (str.startsWith("0x")) return str;
877
1227
  throw new Error("Expected a hex string");
878
1228
  };
879
- //#endregion
880
1229
  exports.BigMath = BigMath;
881
1230
  exports.DEFAULT_TIME_SLICE_BUDGET_MS = DEFAULT_TIME_SLICE_BUDGET_MS;
882
1231
  exports.Deferred = Deferred;
@@ -886,13 +1235,19 @@ exports.REGEX_HEX_STRING = REGEX_HEX_STRING;
886
1235
  exports.addTrailingSlash = addTrailingSlash;
887
1236
  exports.arrayItemsEqualWithYield = arrayItemsEqualWithYield;
888
1237
  exports.assert = assert;
1238
+ exports.checkSuspension = checkSuspension;
889
1239
  exports.concatMapChunked = concatMapChunked;
890
1240
  exports.createTimeSlicer = createTimeSlicer;
891
1241
  exports.firstThenDebounce = firstThenDebounce;
892
1242
  exports.forEachWithYield = forEachWithYield;
1243
+ exports.formatCompactPrice = formatCompactPrice;
1244
+ exports.formatCurrency = formatCurrency;
1245
+ exports.formatCurrencyToParts = formatCurrencyToParts;
893
1246
  exports.formatDecimals = formatDecimals;
894
1247
  exports.formatPrice = formatPrice;
1248
+ exports.getCurrencyFractionDigits = getCurrencyFractionDigits;
895
1249
  exports.getErrorMessage = getErrorMessage;
1250
+ exports.getLastResumedAt = getLastResumedAt;
896
1251
  exports.getLoadable$ = getLoadable$;
897
1252
  exports.getLoadableQuery$ = getLoadableQuery$;
898
1253
  exports.getQuery$ = getQuery$;
@@ -912,15 +1267,19 @@ exports.isHexString = isHexString;
912
1267
  exports.isNotNil = isNotNil;
913
1268
  exports.isPromise = isPromise;
914
1269
  exports.isSubject = isSubject;
1270
+ exports.isSuspended = isSuspended;
915
1271
  exports.isTruthy = isTruthy;
916
1272
  exports.keepAlive = keepAlive;
917
1273
  exports.keyByWithYield = keyByWithYield;
918
1274
  exports.mapWithYield = mapWithYield;
919
1275
  exports.newAbortError = newAbortError;
920
1276
  exports.numberToU8a = numberToU8a;
1277
+ exports.onResume = onResume;
921
1278
  exports.planckToTokens = planckToTokens;
922
1279
  exports.replaySubjectFrom = replaySubjectFrom;
923
1280
  exports.reportJsActivity = reportJsActivity;
1281
+ exports.setAwakeTimeout = setAwakeTimeout;
1282
+ exports.setSuspended = setSuspended;
924
1283
  exports.sleep = sleep;
925
1284
  exports.splitSubject = splitSubject;
926
1285
  exports.stringToU8a = stringToU8a;