@twin.org/core 0.0.1-next.8 → 0.0.1

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.
Files changed (79) hide show
  1. package/dist/cjs/index.cjs +1677 -809
  2. package/dist/esm/index.mjs +1673 -810
  3. package/dist/types/encoding/base58.d.ts +18 -0
  4. package/dist/types/errors/baseError.d.ts +2 -1
  5. package/dist/types/factories/factory.d.ts +20 -1
  6. package/dist/types/helpers/arrayHelper.d.ts +13 -0
  7. package/dist/types/helpers/envHelper.d.ts +16 -0
  8. package/dist/types/helpers/errorHelper.d.ts +2 -1
  9. package/dist/types/helpers/jsonHelper.d.ts +30 -0
  10. package/dist/types/helpers/objectHelper.d.ts +25 -0
  11. package/dist/types/helpers/uint8ArrayHelper.d.ts +11 -0
  12. package/dist/types/index.d.ts +7 -0
  13. package/dist/types/models/IComponent.d.ts +12 -3
  14. package/dist/types/models/II18nShared.d.ts +29 -0
  15. package/dist/types/models/coerceType.d.ts +49 -0
  16. package/dist/types/models/compressionType.d.ts +1 -1
  17. package/dist/types/models/objectOrArray.d.ts +4 -0
  18. package/dist/types/utils/asyncCache.d.ts +10 -1
  19. package/dist/types/utils/coerce.d.ts +22 -0
  20. package/dist/types/utils/converter.d.ts +12 -0
  21. package/dist/types/utils/guards.d.ts +35 -0
  22. package/dist/types/utils/is.d.ts +12 -0
  23. package/dist/types/utils/sharedStore.d.ts +23 -0
  24. package/dist/types/utils/validation.d.ts +2 -0
  25. package/docs/changelog.md +230 -1
  26. package/docs/reference/classes/AlreadyExistsError.md +77 -27
  27. package/docs/reference/classes/ArrayHelper.md +79 -5
  28. package/docs/reference/classes/AsyncCache.md +75 -13
  29. package/docs/reference/classes/Base32.md +9 -5
  30. package/docs/reference/classes/Base58.md +61 -0
  31. package/docs/reference/classes/Base64.md +12 -6
  32. package/docs/reference/classes/Base64Url.md +9 -5
  33. package/docs/reference/classes/BaseError.md +79 -29
  34. package/docs/reference/classes/BitString.md +23 -11
  35. package/docs/reference/classes/Coerce.md +110 -12
  36. package/docs/reference/classes/Compression.md +19 -11
  37. package/docs/reference/classes/ConflictError.md +80 -28
  38. package/docs/reference/classes/Converter.md +110 -26
  39. package/docs/reference/classes/EnvHelper.md +45 -0
  40. package/docs/reference/classes/ErrorHelper.md +19 -7
  41. package/docs/reference/classes/Factory.md +95 -17
  42. package/docs/reference/classes/FilenameHelper.md +6 -4
  43. package/docs/reference/classes/GeneralError.md +75 -27
  44. package/docs/reference/classes/GuardError.md +80 -28
  45. package/docs/reference/classes/Guards.md +398 -80
  46. package/docs/reference/classes/HexHelper.md +18 -8
  47. package/docs/reference/classes/I18n.md +46 -20
  48. package/docs/reference/classes/Is.md +179 -51
  49. package/docs/reference/classes/JsonHelper.md +146 -10
  50. package/docs/reference/classes/NotFoundError.md +77 -27
  51. package/docs/reference/classes/NotImplementedError.md +71 -25
  52. package/docs/reference/classes/NotSupportedError.md +74 -26
  53. package/docs/reference/classes/ObjectHelper.md +197 -39
  54. package/docs/reference/classes/RandomHelper.md +6 -4
  55. package/docs/reference/classes/SharedStore.md +94 -0
  56. package/docs/reference/classes/StringHelper.md +54 -20
  57. package/docs/reference/classes/Uint8ArrayHelper.md +35 -0
  58. package/docs/reference/classes/UnauthorizedError.md +74 -26
  59. package/docs/reference/classes/UnprocessableError.md +75 -27
  60. package/docs/reference/classes/Url.md +37 -17
  61. package/docs/reference/classes/Urn.md +63 -27
  62. package/docs/reference/classes/Validation.md +349 -135
  63. package/docs/reference/classes/ValidationError.md +74 -26
  64. package/docs/reference/index.md +8 -0
  65. package/docs/reference/interfaces/IComponent.md +30 -8
  66. package/docs/reference/interfaces/IError.md +2 -2
  67. package/docs/reference/interfaces/II18nShared.md +47 -0
  68. package/docs/reference/interfaces/IKeyValue.md +3 -1
  69. package/docs/reference/interfaces/ILabelledValue.md +3 -1
  70. package/docs/reference/interfaces/ILocaleDictionary.md +1 -1
  71. package/docs/reference/interfaces/IPatchOperation.md +1 -1
  72. package/docs/reference/interfaces/IValidationFailure.md +1 -1
  73. package/docs/reference/type-aliases/CoerceType.md +5 -0
  74. package/docs/reference/type-aliases/CompressionType.md +1 -1
  75. package/docs/reference/type-aliases/ObjectOrArray.md +11 -0
  76. package/docs/reference/variables/CoerceType.md +67 -0
  77. package/docs/reference/variables/CompressionType.md +1 -1
  78. package/locales/en.json +23 -1
  79. package/package.json +7 -7
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var intlMessageformat = require('intl-messageformat');
4
3
  var rfc6902 = require('rfc6902');
4
+ var intlMessageformat = require('intl-messageformat');
5
5
 
6
6
  // Copyright 2024 IOTA Stiftung.
7
7
  // SPDX-License-Identifier: Apache-2.0.
@@ -113,7 +113,12 @@ class Is {
113
113
  }
114
114
  try {
115
115
  const json = JSON.parse(value);
116
- return typeof json === "object";
116
+ return (Is.object(json) ||
117
+ Is.array(json) ||
118
+ Is.string(json) ||
119
+ Is.number(json) ||
120
+ Is.boolean(json) ||
121
+ Is.null(json));
117
122
  }
118
123
  catch {
119
124
  return false;
@@ -137,7 +142,17 @@ class Is {
137
142
  static stringBase64Url(value) {
138
143
  return (Is.stringValue(value) &&
139
144
  // eslint-disable-next-line unicorn/better-regex
140
- /^(?:[A-Za-z0-9-_]{4})*(?:[A-Za-z0-9-_]{2}==|[A-Za-z0-9-_]{3}=)?$/.test(value));
145
+ /^([A-Za-z0-9-_])*$/.test(value));
146
+ }
147
+ /**
148
+ * Is the value a base58 string.
149
+ * @param value The value to test.
150
+ * @returns True if the value is a base58 string.
151
+ */
152
+ static stringBase58(value) {
153
+ return (Is.stringValue(value) &&
154
+ // eslint-disable-next-line unicorn/better-regex
155
+ /^[A-HJ-NP-Za-km-z1-9]*$/.test(value));
141
156
  }
142
157
  /**
143
158
  * Is the value a hex string.
@@ -351,6 +366,14 @@ class Is {
351
366
  static promise(value) {
352
367
  return value instanceof Promise;
353
368
  }
369
+ /**
370
+ * Is the value a regexp.
371
+ * @param value The value to test.
372
+ * @returns True if the value is a regexp.
373
+ */
374
+ static regexp(value) {
375
+ return value instanceof RegExp;
376
+ }
354
377
  }
355
378
 
356
379
  // Copyright 2024 IOTA Stiftung.
@@ -646,7 +669,10 @@ class BaseError extends Error {
646
669
  let properties;
647
670
  let inner;
648
671
  let stack;
649
- if (Is.object(err)) {
672
+ if (Is.object(err) && Is.stringValue(err.error)) {
673
+ message = err.error;
674
+ }
675
+ else if (Is.object(err)) {
650
676
  if (Is.stringValue(err.name)) {
651
677
  name = err.name;
652
678
  }
@@ -666,9 +692,6 @@ class BaseError extends Error {
666
692
  stack = err.stack;
667
693
  }
668
694
  }
669
- else if (Is.object(err) && Is.stringValue(err.error)) {
670
- message = err.error;
671
- }
672
695
  else if (Is.stringValue(err)) {
673
696
  message = err;
674
697
  }
@@ -686,7 +709,7 @@ class BaseError extends Error {
686
709
  */
687
710
  static flatten(err) {
688
711
  const flattened = [];
689
- let e = BaseError.fromError(err).toJsonObject();
712
+ let e = BaseError.fromError(err).toJsonObject(true);
690
713
  while (e) {
691
714
  const inner = e.inner;
692
715
  e.inner = undefined;
@@ -782,9 +805,10 @@ class BaseError extends Error {
782
805
  }
783
806
  /**
784
807
  * Serialize the error to the error model.
808
+ * @param includeStackTrace Whether to include the error stack in the model, defaults to false.
785
809
  * @returns The error model.
786
810
  */
787
- toJsonObject() {
811
+ toJsonObject(includeStackTrace) {
788
812
  const err = {};
789
813
  if (Is.stringValue(this.name)) {
790
814
  err.name = this.name;
@@ -798,11 +822,11 @@ class BaseError extends Error {
798
822
  if (Is.object(this.properties)) {
799
823
  err.properties = this.properties;
800
824
  }
801
- if (Is.stringValue(this.stack)) {
825
+ if ((includeStackTrace ?? false) && Is.stringValue(this.stack)) {
802
826
  err.stack = this.stack;
803
827
  }
804
828
  if (Is.notEmpty(this.inner)) {
805
- err.inner = BaseError.fromError(this.inner).toJsonObject();
829
+ err.inner = BaseError.fromError(this.inner).toJsonObject(includeStackTrace);
806
830
  }
807
831
  return err;
808
832
  }
@@ -900,6 +924,127 @@ class Base32 {
900
924
  }
901
925
  }
902
926
 
927
+ /**
928
+ * Class to help with base58 Encoding/Decoding.
929
+ */
930
+ class Base58 {
931
+ /**
932
+ * Runtime name for the class.
933
+ * @internal
934
+ */
935
+ static _CLASS_NAME = "Base58";
936
+ /**
937
+ * Alphabet table for encoding.
938
+ * @internal
939
+ */
940
+ static _ALPHABET =
941
+ // cspell:disable-next-line
942
+ "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
943
+ /**
944
+ * Reverse map for decoding.
945
+ * @internal
946
+ */
947
+ static _ALPHABET_REVERSE = [
948
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
949
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
950
+ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -1, -1, -1, -1, -1, -1, -1, 9, 10, 11, 12, 13, 14, 15, 16, -1,
951
+ 17, 18, 19, 20, 21, -1, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1, -1, 33,
952
+ 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, -1, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
953
+ 57, -1, -1, -1, -1, -1
954
+ ];
955
+ /**
956
+ * Convert the base 58 string to a byte array.
957
+ * @param base58 The base58 string to convert.
958
+ * @returns The byte array.
959
+ * @throws If the input string contains a character not in the Base58 alphabet.
960
+ */
961
+ static decode(base58) {
962
+ let zeroes = 0;
963
+ for (let i = 0; i < base58.length; i++) {
964
+ if (base58[i] !== "1") {
965
+ break;
966
+ }
967
+ zeroes += 1;
968
+ }
969
+ const size = Math.trunc((base58.length * 733) / 1000) + 1;
970
+ const b256 = new Uint8Array(size).fill(0);
971
+ let length = 0;
972
+ for (let i = zeroes; i < base58.length; i++) {
973
+ const ch = base58.charCodeAt(i);
974
+ if (ch & 0xff80) {
975
+ throw new GeneralError(Base58._CLASS_NAME, "invalidCharacter", { invalidCharacter: ch });
976
+ }
977
+ const val = Base58._ALPHABET_REVERSE[ch];
978
+ if (val === -1) {
979
+ throw new GeneralError(Base58._CLASS_NAME, "invalidCharacter", { invalidCharacter: ch });
980
+ }
981
+ let carry = val;
982
+ let j = 0;
983
+ for (let k = size - 1; k >= 0; k--, j++) {
984
+ if (carry === 0 && j >= length) {
985
+ break;
986
+ }
987
+ carry += b256[k] * 58;
988
+ b256[k] = carry;
989
+ carry >>>= 8;
990
+ }
991
+ length = j;
992
+ }
993
+ const out = new Uint8Array(zeroes + length);
994
+ let j;
995
+ for (j = 0; j < zeroes; j++) {
996
+ out[j] = 0;
997
+ }
998
+ let i = size - length;
999
+ while (i < size) {
1000
+ out[j++] = b256[i++];
1001
+ }
1002
+ return out;
1003
+ }
1004
+ /**
1005
+ * Convert a byte array to base 58.
1006
+ * @param bytes The byte array to encode.
1007
+ * @returns The data as base58 string.
1008
+ */
1009
+ static encode(bytes) {
1010
+ let zeroes = 0;
1011
+ for (let i = 0; i < bytes.length; i++) {
1012
+ if (bytes[i] !== 0) {
1013
+ break;
1014
+ }
1015
+ zeroes += 1;
1016
+ }
1017
+ const size = Math.trunc(((bytes.length - zeroes) * 138) / 100) + 1;
1018
+ const b58 = new Uint8Array(size).fill(0);
1019
+ let length = 0;
1020
+ for (let i = zeroes; i < bytes.length; i++) {
1021
+ let carry = bytes[i];
1022
+ let j = 0;
1023
+ for (let k = size - 1; k >= 0; k--, j++) {
1024
+ if (carry === 0 && j >= length) {
1025
+ break;
1026
+ }
1027
+ carry += b58[k] * 256;
1028
+ b58[k] = carry % 58;
1029
+ carry = Math.trunc(carry / 58);
1030
+ }
1031
+ length = j;
1032
+ }
1033
+ let i = size - length;
1034
+ while (i < size && b58[i] === 0) {
1035
+ i += 1;
1036
+ }
1037
+ let str = "";
1038
+ for (let j = 0; j < zeroes; j++) {
1039
+ str += "1";
1040
+ }
1041
+ while (i < size) {
1042
+ str += Base58._ALPHABET[b58[i++]];
1043
+ }
1044
+ return str;
1045
+ }
1046
+ }
1047
+
903
1048
  // Copyright 2024 IOTA Stiftung.
904
1049
  // SPDX-License-Identifier: Apache-2.0.
905
1050
  /* eslint-disable no-bitwise */
@@ -1054,7 +1199,7 @@ class Base64 {
1054
1199
  const maxChunkLength = 16383; // must be multiple of 3
1055
1200
  // go through the array every three bytes, we'll deal with trailing stuff later
1056
1201
  for (let i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
1057
- parts.push(Base64.encodeChunk(bytes, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
1202
+ parts.push(Base64.encodeChunk(bytes, i, Math.min(i + maxChunkLength, len2)));
1058
1203
  }
1059
1204
  // pad the end with zeros, but make sure to not forget the extra bytes
1060
1205
  if (extraBytes === 1) {
@@ -1350,6 +1495,49 @@ class ValidationError extends BaseError {
1350
1495
  }
1351
1496
  }
1352
1497
 
1498
+ /**
1499
+ * Class to help with arrays.
1500
+ */
1501
+ class ArrayHelper {
1502
+ /**
1503
+ * Do the two arrays match.
1504
+ * @param arr1 The first array.
1505
+ * @param arr2 The second array.
1506
+ * @returns True if both arrays are empty of have the same values.
1507
+ */
1508
+ static matches(arr1, arr2) {
1509
+ if (Is.empty(arr1) && Is.empty(arr2)) {
1510
+ return true;
1511
+ }
1512
+ if (!((Is.array(arr1) && Is.array(arr2)) || (Is.typedArray(arr1) && Is.typedArray(arr2)))) {
1513
+ return false;
1514
+ }
1515
+ if (arr1.length !== arr2.length) {
1516
+ return false;
1517
+ }
1518
+ for (let i = 0; i < arr1.length; i++) {
1519
+ if (arr1[i] !== arr2[i]) {
1520
+ return false;
1521
+ }
1522
+ }
1523
+ return true;
1524
+ }
1525
+ /**
1526
+ * Convert an object or array to an array.
1527
+ * @param value The object or array to convert.
1528
+ * @returns The array.
1529
+ */
1530
+ static fromObjectOrArray(value) {
1531
+ if (Is.empty(value)) {
1532
+ return undefined;
1533
+ }
1534
+ if (Is.array(value)) {
1535
+ return value;
1536
+ }
1537
+ return [value];
1538
+ }
1539
+ }
1540
+
1353
1541
  // Copyright 2024 IOTA Stiftung.
1354
1542
  // SPDX-License-Identifier: Apache-2.0.
1355
1543
  /**
@@ -1395,6 +1583,18 @@ class Guards {
1395
1583
  throw new GuardError(source, "guard.stringEmpty", property, value);
1396
1584
  }
1397
1585
  }
1586
+ /**
1587
+ * Is the property a JSON value.
1588
+ * @param source The source of the error.
1589
+ * @param property The name of the property.
1590
+ * @param value The value to test.
1591
+ * @throws GuardError If the value does not match the assertion.
1592
+ */
1593
+ static json(source, property, value) {
1594
+ if (!Is.json(value)) {
1595
+ throw new GuardError(source, "guard.stringJson", property, value);
1596
+ }
1597
+ }
1398
1598
  /**
1399
1599
  * Is the property a base64 string.
1400
1600
  * @param source The source of the error.
@@ -1419,6 +1619,18 @@ class Guards {
1419
1619
  throw new GuardError(source, "guard.base64Url", property, value);
1420
1620
  }
1421
1621
  }
1622
+ /**
1623
+ * Is the property a base58 string.
1624
+ * @param source The source of the error.
1625
+ * @param property The name of the property.
1626
+ * @param value The value to test.
1627
+ * @throws GuardError If the value does not match the assertion.
1628
+ */
1629
+ static stringBase58(source, property, value) {
1630
+ if (!Is.stringBase58(value)) {
1631
+ throw new GuardError(source, "guard.base58", property, value);
1632
+ }
1633
+ }
1422
1634
  /**
1423
1635
  * Is the property a string with a hex value.
1424
1636
  * @param source The source of the error.
@@ -1608,6 +1820,50 @@ class Guards {
1608
1820
  throw new GuardError(source, "guard.arrayOneOf", property, value, options.join(", "));
1609
1821
  }
1610
1822
  }
1823
+ /**
1824
+ * Does the array start with the specified data.
1825
+ * @param source The source of the error.
1826
+ * @param property The name of the property.
1827
+ * @param value The value to test.
1828
+ * @param startValues The values that must start the array.
1829
+ * @throws GuardError If the value does not match the assertion.
1830
+ */
1831
+ static arrayStartsWith(source, property, value, startValues) {
1832
+ if (!Is.arrayValue(value)) {
1833
+ throw new GuardError(source, "guard.array", property, value);
1834
+ }
1835
+ const startValuesArray = ArrayHelper.fromObjectOrArray(startValues);
1836
+ if (!Is.arrayValue(startValuesArray)) {
1837
+ throw new GuardError(source, "guard.array", property, startValuesArray);
1838
+ }
1839
+ for (let i = 0; i < startValuesArray.length; i++) {
1840
+ if (value[i] !== startValuesArray[i]) {
1841
+ throw new GuardError(source, "guard.arrayStartsWith", property, value, startValuesArray.join(", "));
1842
+ }
1843
+ }
1844
+ }
1845
+ /**
1846
+ * Does the array end with the specified data.
1847
+ * @param source The source of the error.
1848
+ * @param property The name of the property.
1849
+ * @param value The value to test.
1850
+ * @param endValues The values that must end the array.
1851
+ * @throws GuardError If the value does not match the assertion.
1852
+ */
1853
+ static arrayEndsWith(source, property, value, endValues) {
1854
+ if (!Is.arrayValue(value)) {
1855
+ throw new GuardError(source, "guard.array", property, value);
1856
+ }
1857
+ const endValuesArray = ArrayHelper.fromObjectOrArray(endValues);
1858
+ if (!Is.arrayValue(endValuesArray)) {
1859
+ throw new GuardError(source, "guard.array", property, endValuesArray);
1860
+ }
1861
+ for (let i = 0; i < endValuesArray.length; i++) {
1862
+ if (value[value.length - i - 1] !== endValuesArray[endValuesArray.length - i - 1]) {
1863
+ throw new GuardError(source, "guard.arrayEndsWith", property, value, endValuesArray.join(", "));
1864
+ }
1865
+ }
1866
+ }
1611
1867
  /**
1612
1868
  * Is the property a Uint8Array.
1613
1869
  * @param source The source of the error.
@@ -1648,6 +1904,53 @@ class Guards {
1648
1904
  }
1649
1905
  }
1650
1906
 
1907
+ // Copyright 2024 IOTA Stiftung.
1908
+ // SPDX-License-Identifier: Apache-2.0.
1909
+ /**
1910
+ * Provide a store for shared objects which can be accesses through multiple
1911
+ * instance loads of a packages.
1912
+ */
1913
+ class SharedStore {
1914
+ /**
1915
+ * Get a property from the shared store.
1916
+ * @param prop The name of the property to get.
1917
+ * @returns The property if it exists.
1918
+ */
1919
+ static get(prop) {
1920
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1921
+ const shared = globalThis.__TWIN_SHARED__;
1922
+ if (Is.undefined(shared)) {
1923
+ return;
1924
+ }
1925
+ return shared[prop];
1926
+ }
1927
+ /**
1928
+ * Set the property in the shared store.
1929
+ * @param prop The name of the property to set.
1930
+ * @param value The value to set.
1931
+ */
1932
+ static set(prop, value) {
1933
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1934
+ if (Is.undefined(globalThis.__TWIN_SHARED__)) {
1935
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1936
+ globalThis.__TWIN_SHARED__ = {};
1937
+ }
1938
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1939
+ globalThis.__TWIN_SHARED__[prop] = value;
1940
+ }
1941
+ /**
1942
+ * Remove a property from the shared store.
1943
+ * @param prop The name of the property to remove.
1944
+ */
1945
+ static remove(prop) {
1946
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1947
+ const shared = globalThis.__TWIN_SHARED__;
1948
+ if (!Is.undefined(shared)) {
1949
+ delete shared[prop];
1950
+ }
1951
+ }
1952
+ }
1953
+
1651
1954
  /**
1652
1955
  * Factory for creating implementation of generic types.
1653
1956
  */
@@ -1657,11 +1960,6 @@ class Factory {
1657
1960
  * @internal
1658
1961
  */
1659
1962
  static _CLASS_NAME = "Factory";
1660
- /**
1661
- * Store all the created factories.
1662
- * @internal
1663
- */
1664
- static _factories = {};
1665
1963
  /**
1666
1964
  * Type name for the instances.
1667
1965
  * @internal
@@ -1715,10 +2013,41 @@ class Factory {
1715
2013
  * @returns The factory instance.
1716
2014
  */
1717
2015
  static createFactory(typeName, autoInstance = false, matcher) {
1718
- if (Is.undefined(Factory._factories[typeName])) {
1719
- Factory._factories[typeName] = new Factory(typeName, autoInstance, matcher);
2016
+ const factories = Factory.getFactories();
2017
+ if (Is.undefined(factories[typeName])) {
2018
+ factories[typeName] = new Factory(typeName, autoInstance, matcher);
2019
+ }
2020
+ return factories[typeName];
2021
+ }
2022
+ /**
2023
+ * Get all the factories.
2024
+ * @returns All the factories.
2025
+ */
2026
+ static getFactories() {
2027
+ let factories = SharedStore.get("factories");
2028
+ if (Is.undefined(factories)) {
2029
+ factories = {};
2030
+ SharedStore.set("factories", factories);
2031
+ }
2032
+ return factories;
2033
+ }
2034
+ /**
2035
+ * Reset all the factories, which removes any created instances, but not the registrations.
2036
+ */
2037
+ static resetFactories() {
2038
+ const factories = Factory.getFactories();
2039
+ for (const typeName in factories) {
2040
+ factories[typeName].reset();
2041
+ }
2042
+ }
2043
+ /**
2044
+ * Clear all the factories, which removes anything registered with the factories.
2045
+ */
2046
+ static clearFactories() {
2047
+ const factories = Factory.getFactories();
2048
+ for (const typeName in factories) {
2049
+ factories[typeName].clear();
1720
2050
  }
1721
- return Factory._factories[typeName];
1722
2051
  }
1723
2052
  /**
1724
2053
  * Register a new generator.
@@ -1791,7 +2120,7 @@ class Factory {
1791
2120
  }
1792
2121
  }
1793
2122
  /**
1794
- * Reset all the instances.
2123
+ * Remove all the instances and leave the generators intact.
1795
2124
  */
1796
2125
  reset() {
1797
2126
  for (const name in this._generators) {
@@ -1799,6 +2128,14 @@ class Factory {
1799
2128
  }
1800
2129
  this._instances = {};
1801
2130
  }
2131
+ /**
2132
+ * Remove all the instances and the generators.
2133
+ */
2134
+ clear() {
2135
+ this._instances = {};
2136
+ this._generators = {};
2137
+ this._orderCounter = 0;
2138
+ }
1802
2139
  /**
1803
2140
  * Get all the instances as a map.
1804
2141
  * @returns The instances as a map.
@@ -1873,1003 +2210,1360 @@ const ComponentFactory = Factory.createFactory("component");
1873
2210
 
1874
2211
  // Copyright 2024 IOTA Stiftung.
1875
2212
  // SPDX-License-Identifier: Apache-2.0.
2213
+ /* eslint-disable no-bitwise */
1876
2214
  /**
1877
- * Class to help with arrays.
1878
- */
1879
- class ArrayHelper {
1880
- /**
1881
- * Do the two arrays match.
1882
- * @param arr1 The first array.
1883
- * @param arr2 The second array.
1884
- * @returns True if both arrays are empty of have the same values.
1885
- */
1886
- static matches(arr1, arr2) {
1887
- if (Is.empty(arr1) && Is.empty(arr2)) {
1888
- return true;
1889
- }
1890
- if (!((Is.array(arr1) && Is.array(arr2)) || (Is.typedArray(arr1) && Is.typedArray(arr2)))) {
1891
- return false;
1892
- }
1893
- if (arr1.length !== arr2.length) {
1894
- return false;
1895
- }
1896
- for (let i = 0; i < arr1.length; i++) {
1897
- if (arr1[i] !== arr2[i]) {
1898
- return false;
1899
- }
1900
- }
1901
- return true;
1902
- }
1903
- }
1904
-
1905
- // Copyright 2024 IOTA Stiftung.
1906
- // SPDX-License-Identifier: Apache-2.0.
1907
- /**
1908
- * Class to perform internationalization.
2215
+ * Convert arrays to and from different formats.
1909
2216
  */
1910
- class I18n {
1911
- /**
1912
- * The default translation.
1913
- */
1914
- static DEFAULT_LOCALE = "en";
2217
+ class Converter {
1915
2218
  /**
1916
- * Dictionaries for lookups.
2219
+ * Lookup table for encoding.
1917
2220
  * @internal
1918
2221
  */
1919
- static _localeDictionaries = {};
2222
+ static _ENCODE_LOOKUP;
1920
2223
  /**
1921
- * The current locale.
2224
+ * Lookup table for decoding.
1922
2225
  * @internal
1923
2226
  */
1924
- static _currentLocale = I18n.DEFAULT_LOCALE;
2227
+ static _DECODE_LOOKUP;
1925
2228
  /**
1926
- * Change handler for the locale being updated.
1927
- * @internal
2229
+ * Encode a raw array to UTF8 string.
2230
+ * @param array The bytes to encode.
2231
+ * @param startIndex The index to start in the bytes.
2232
+ * @param length The length of bytes to read.
2233
+ * @returns The array formatted as UTF8.
1928
2234
  */
1929
- static _localeChangedHandlers = {};
2235
+ static bytesToUtf8(array, startIndex, length) {
2236
+ const start = startIndex ?? 0;
2237
+ const len = length ?? array.length;
2238
+ let str = "";
2239
+ for (let i = start; i < start + len; i++) {
2240
+ const value = array[i];
2241
+ if (value < 0x80) {
2242
+ str += String.fromCharCode(value);
2243
+ }
2244
+ else if (value > 0xbf && value < 0xe0) {
2245
+ str += String.fromCharCode(((value & 0x1f) << 6) | (array[i + 1] & 0x3f));
2246
+ i += 1;
2247
+ }
2248
+ else if (value > 0xdf && value < 0xf0) {
2249
+ str += String.fromCharCode(((value & 0x0f) << 12) | ((array[i + 1] & 0x3f) << 6) | (array[i + 2] & 0x3f));
2250
+ i += 2;
2251
+ }
2252
+ else {
2253
+ // surrogate pair
2254
+ const charCode = (((value & 0x07) << 18) |
2255
+ ((array[i + 1] & 0x3f) << 12) |
2256
+ ((array[i + 2] & 0x3f) << 6) |
2257
+ (array[i + 3] & 0x3f)) -
2258
+ 0x010000;
2259
+ str += String.fromCharCode((charCode >> 10) | 0xd800, (charCode & 0x03ff) | 0xdc00);
2260
+ i += 3;
2261
+ }
2262
+ }
2263
+ return str;
2264
+ }
1930
2265
  /**
1931
- * Change handler for the dictionaries being updated.
1932
- * @internal
2266
+ * Convert a UTF8 string to raw array.
2267
+ * @param utf8 The text to decode.
2268
+ * @returns The array.
1933
2269
  */
1934
- static _dictionaryChangedHandlers = {};
2270
+ static utf8ToBytes(utf8) {
2271
+ const bytes = [];
2272
+ for (let i = 0; i < utf8.length; i++) {
2273
+ let charCode = utf8.charCodeAt(i);
2274
+ if (charCode < 0x80) {
2275
+ bytes.push(charCode);
2276
+ }
2277
+ else if (charCode < 0x800) {
2278
+ bytes.push(0xc0 | (charCode >> 6), 0x80 | (charCode & 0x3f));
2279
+ }
2280
+ else if (charCode < 0xd800 || charCode >= 0xe000) {
2281
+ bytes.push(0xe0 | (charCode >> 12), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
2282
+ }
2283
+ else {
2284
+ // surrogate pair
2285
+ i++;
2286
+ // UTF-16 encodes 0x10000-0x10FFFF by
2287
+ // subtracting 0x10000 and splitting the
2288
+ // 20 bits of 0x0-0xFFFFF into two halves
2289
+ charCode = 0x10000 + (((charCode & 0x3ff) << 10) | (utf8.charCodeAt(i) & 0x3ff));
2290
+ bytes.push(0xf0 | (charCode >> 18), 0x80 | ((charCode >> 12) & 0x3f), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
2291
+ }
2292
+ }
2293
+ return Uint8Array.from(bytes);
2294
+ }
1935
2295
  /**
1936
- * Set the locale.
1937
- * @param locale The new locale.
2296
+ * Encode a raw array to hex string.
2297
+ * @param array The bytes to encode.
2298
+ * @param includePrefix Include the 0x prefix on the returned hex.
2299
+ * @param startIndex The index to start in the bytes.
2300
+ * @param length The length of bytes to read.
2301
+ * @param reverse Reverse the combine direction.
2302
+ * @returns The array formatted as hex.
1938
2303
  */
1939
- static setLocale(locale) {
1940
- I18n._currentLocale = locale;
1941
- for (const callback in I18n._localeChangedHandlers) {
1942
- I18n._localeChangedHandlers[callback](I18n._currentLocale);
2304
+ static bytesToHex(array, includePrefix = false, startIndex, length, reverse) {
2305
+ let hex = "";
2306
+ this.buildHexLookups();
2307
+ if (Converter._ENCODE_LOOKUP) {
2308
+ const len = length ?? array.length;
2309
+ const start = startIndex ?? 0;
2310
+ if (reverse) {
2311
+ for (let i = 0; i < len; i++) {
2312
+ hex = Converter._ENCODE_LOOKUP[array[start + i]] + hex;
2313
+ }
2314
+ }
2315
+ else {
2316
+ for (let i = 0; i < len; i++) {
2317
+ hex += Converter._ENCODE_LOOKUP[array[start + i]];
2318
+ }
2319
+ }
1943
2320
  }
2321
+ return includePrefix ? HexHelper.addPrefix(hex) : hex;
1944
2322
  }
1945
2323
  /**
1946
- * Get the locale.
1947
- * @returns The current locale.
2324
+ * Decode a hex string to raw array.
2325
+ * @param hex The hex to decode.
2326
+ * @param reverse Store the characters in reverse.
2327
+ * @returns The array.
1948
2328
  */
1949
- static getLocale() {
1950
- return I18n._currentLocale;
2329
+ static hexToBytes(hex, reverse) {
2330
+ const strippedHex = HexHelper.stripPrefix(hex);
2331
+ const sizeof = strippedHex.length >> 1;
2332
+ const length = sizeof << 1;
2333
+ const array = new Uint8Array(sizeof);
2334
+ this.buildHexLookups();
2335
+ if (Converter._DECODE_LOOKUP) {
2336
+ let i = 0;
2337
+ let n = 0;
2338
+ while (i < length) {
2339
+ array[n++] =
2340
+ (Converter._DECODE_LOOKUP[strippedHex.charCodeAt(i++)] << 4) |
2341
+ Converter._DECODE_LOOKUP[strippedHex.charCodeAt(i++)];
2342
+ }
2343
+ if (reverse) {
2344
+ array.reverse();
2345
+ }
2346
+ }
2347
+ return array;
1951
2348
  }
1952
2349
  /**
1953
- * Add a locale dictionary.
1954
- * @param locale The locale.
1955
- * @param dictionary The dictionary to add.
2350
+ * Convert the UTF8 to hex.
2351
+ * @param utf8 The text to convert.
2352
+ * @param includePrefix Include the 0x prefix on the returned hex.
2353
+ * @returns The hex version of the bytes.
1956
2354
  */
1957
- static addDictionary(locale, dictionary) {
1958
- const mergedKeys = {};
1959
- I18n.flattenTranslationKeys(dictionary, "", mergedKeys);
1960
- I18n._localeDictionaries[locale] = mergedKeys;
1961
- for (const callback in I18n._dictionaryChangedHandlers) {
1962
- I18n._dictionaryChangedHandlers[callback](I18n._currentLocale);
1963
- }
2355
+ static utf8ToHex(utf8, includePrefix = false) {
2356
+ const hex = Converter.bytesToHex(Converter.utf8ToBytes(utf8));
2357
+ return includePrefix ? HexHelper.addPrefix(hex) : hex;
1964
2358
  }
1965
2359
  /**
1966
- * Get a locale dictionary.
1967
- * @param locale The locale.
1968
- * @returns The dictionary of undefined if it does not exist.
2360
+ * Convert the hex text to text.
2361
+ * @param hex The hex to convert.
2362
+ * @returns The UTF8 version of the bytes.
1969
2363
  */
1970
- static getDictionary(locale) {
1971
- return I18n._localeDictionaries[locale];
2364
+ static hexToUtf8(hex) {
2365
+ return Converter.bytesToUtf8(Converter.hexToBytes(HexHelper.stripPrefix(hex)));
1972
2366
  }
1973
2367
  /**
1974
- * Get all the locale dictionaries.
1975
- * @returns The dictionaries.
2368
+ * Convert bytes to binary string.
2369
+ * @param bytes The bytes to convert.
2370
+ * @returns A binary string of the bytes.
1976
2371
  */
1977
- static getAllDictionaries() {
1978
- return I18n._localeDictionaries;
2372
+ static bytesToBinary(bytes) {
2373
+ const b = [];
2374
+ for (let i = 0; i < bytes.length; i++) {
2375
+ b.push(bytes[i].toString(2).padStart(8, "0"));
2376
+ }
2377
+ return b.join("");
1979
2378
  }
1980
2379
  /**
1981
- * Add a locale changed handler.
1982
- * @param id The id of the handler.
1983
- * @param handler The handler to add.
2380
+ * Convert a binary string to bytes.
2381
+ * @param binary The binary string.
2382
+ * @returns The bytes.
1984
2383
  */
1985
- static addLocaleHandler(id, handler) {
1986
- I18n._localeChangedHandlers[id] = handler;
2384
+ static binaryToBytes(binary) {
2385
+ const bytes = new Uint8Array(Math.ceil(binary.length / 8));
2386
+ for (let i = 0; i < bytes.length; i++) {
2387
+ bytes[i] = Number.parseInt(binary.slice(i * 8, (i + 1) * 8), 2);
2388
+ }
2389
+ return bytes;
1987
2390
  }
1988
2391
  /**
1989
- * Remove a locale changed handler.
1990
- * @param id The id of the handler.
2392
+ * Convert bytes to base64 string.
2393
+ * @param bytes The bytes to convert.
2394
+ * @returns A base64 string of the bytes.
1991
2395
  */
1992
- static removeLocaleHandler(id) {
1993
- delete I18n._localeChangedHandlers[id];
2396
+ static bytesToBase64(bytes) {
2397
+ return Base64.encode(bytes);
1994
2398
  }
1995
2399
  /**
1996
- * Add a dictionary changed handler.
1997
- * @param id The id of the handler.
1998
- * @param handler The handler to add.
2400
+ * Convert a base64 string to bytes.
2401
+ * @param base64 The base64 string.
2402
+ * @returns The bytes.
1999
2403
  */
2000
- static addDictionaryHandler(id, handler) {
2001
- I18n._dictionaryChangedHandlers[id] = handler;
2404
+ static base64ToBytes(base64) {
2405
+ return Base64.decode(base64);
2002
2406
  }
2003
2407
  /**
2004
- * Remove a dictionary changed handler.
2005
- * @param id The id of the handler.
2408
+ * Convert bytes to base64 url string.
2409
+ * @param bytes The bytes to convert.
2410
+ * @returns A base64 url string of the bytes.
2006
2411
  */
2007
- static removeDictionaryHandler(id) {
2008
- delete I18n._dictionaryChangedHandlers[id];
2412
+ static bytesToBase64Url(bytes) {
2413
+ return Base64Url.encode(bytes);
2009
2414
  }
2010
2415
  /**
2011
- * Format a message.
2012
- * @param key The key of the message to format.
2013
- * @param values The values to substitute into the message.
2014
- * @param overrideLocale Override the locale.
2015
- * @returns The formatted string.
2416
+ * Convert a base64 url string to bytes.
2417
+ * @param base64Url The base64 url string.
2418
+ * @returns The bytes.
2016
2419
  */
2017
- static formatMessage(key, values, overrideLocale) {
2018
- let cl = overrideLocale ?? I18n._currentLocale;
2019
- if (cl.startsWith("debug-")) {
2020
- cl = I18n.DEFAULT_LOCALE;
2021
- }
2022
- if (!I18n._localeDictionaries[cl]) {
2023
- return `!!Missing ${cl}`;
2024
- }
2025
- if (!I18n._localeDictionaries[cl][key]) {
2026
- return `!!Missing ${cl}.${key}`;
2027
- }
2028
- if (I18n._currentLocale === "debug-k") {
2029
- return key;
2030
- }
2031
- let ret = new intlMessageformat.IntlMessageFormat(I18n._localeDictionaries[cl][key], cl).format(values);
2032
- if (I18n._currentLocale === "debug-x") {
2033
- ret = ret.replace(/[a-z]/g, "x").replace(/[A-Z]/g, "x").replace(/\d/g, "n");
2034
- }
2035
- return ret;
2420
+ static base64UrlToBytes(base64Url) {
2421
+ return Base64Url.decode(base64Url);
2036
2422
  }
2037
2423
  /**
2038
- * Check if the dictionaries have a message for the given key.
2039
- * @param key The key to check for existence.
2040
- * @returns True if the key exists.
2424
+ * Convert bytes to base58 string.
2425
+ * @param bytes The bytes to convert.
2426
+ * @returns A base58 string of the bytes.
2041
2427
  */
2042
- static hasMessage(key) {
2043
- return Is.string(I18n._localeDictionaries[I18n._currentLocale]?.[key]);
2428
+ static bytesToBase58(bytes) {
2429
+ return Base58.encode(bytes);
2044
2430
  }
2045
2431
  /**
2046
- * Flatten the translation property paths for faster lookup.
2047
- * @param translation The translation to merge.
2048
- * @param propertyPath The current root path.
2049
- * @param mergedKeys The merged keys dictionary to populate.
2432
+ * Convert a base58 string to bytes.
2433
+ * @param base58 The base58 string.
2434
+ * @returns The bytes.
2435
+ */
2436
+ static base58ToBytes(base58) {
2437
+ return Base58.decode(base58);
2438
+ }
2439
+ /**
2440
+ * Build the static lookup tables.
2050
2441
  * @internal
2051
2442
  */
2052
- static flattenTranslationKeys(translation, propertyPath, mergedKeys) {
2053
- for (const key in translation) {
2054
- const val = translation[key];
2055
- const mergedPath = propertyPath.length > 0 ? `${propertyPath}.${key}` : key;
2056
- if (Is.string(val)) {
2057
- mergedKeys[mergedPath] = val;
2058
- }
2059
- else if (Is.object(val)) {
2060
- I18n.flattenTranslationKeys(val, mergedPath, mergedKeys);
2443
+ static buildHexLookups() {
2444
+ if (!Converter._ENCODE_LOOKUP || !Converter._DECODE_LOOKUP) {
2445
+ const alphabet = "0123456789abcdef";
2446
+ Converter._ENCODE_LOOKUP = [];
2447
+ Converter._DECODE_LOOKUP = [];
2448
+ for (let i = 0; i < 256; i++) {
2449
+ Converter._ENCODE_LOOKUP[i] = alphabet[(i >> 4) & 0xf] + alphabet[i & 0xf];
2450
+ if (i < 16) {
2451
+ if (i < 10) {
2452
+ Converter._DECODE_LOOKUP[0x30 + i] = i;
2453
+ }
2454
+ else {
2455
+ Converter._DECODE_LOOKUP[0x61 - 10 + i] = i;
2456
+ }
2457
+ }
2061
2458
  }
2062
2459
  }
2063
2460
  }
2064
2461
  }
2065
2462
 
2066
- // Copyright 2024 IOTA Stiftung.
2067
- // SPDX-License-Identifier: Apache-2.0.
2068
2463
  /**
2069
- * Error helper functions.
2464
+ * Helpers methods for JSON objects.
2070
2465
  */
2071
- class ErrorHelper {
2466
+ class JsonHelper {
2072
2467
  /**
2073
- * Format Errors and returns just their messages.
2074
- * @param error The error to format.
2075
- * @returns The error formatted including any inner errors.
2468
+ * Runtime name for the class.
2469
+ * @internal
2076
2470
  */
2077
- static formatErrors(error) {
2078
- return ErrorHelper.localizeErrors(error).map(e => e.message);
2079
- }
2471
+ static _CLASS_NAME = "JsonHelper";
2080
2472
  /**
2081
- * Localize the content of an error and any inner errors.
2082
- * @param error The error to format.
2083
- * @returns The localized version of the errors flattened.
2473
+ * Serializes in canonical format.
2474
+ * Based on https://www.rfc-editor.org/rfc/rfc8785.
2475
+ * @param object The object to be serialized.
2476
+ * @returns The serialized object.
2084
2477
  */
2085
- static localizeErrors(error) {
2086
- const formattedErrors = [];
2087
- if (Is.notEmpty(error)) {
2088
- const errors = BaseError.flatten(error);
2089
- for (const err of errors) {
2090
- const errorNameKey = `errorNames.${StringHelper.camelCase(err.name)}`;
2091
- const errorMessageKey = `error.${err.message}`;
2092
- // If there is no error message then it is probably
2093
- // from a 3rd party lib, so don't format it just display
2094
- const hasErrorName = I18n.hasMessage(errorNameKey);
2095
- const hasErrorMessage = I18n.hasMessage(errorMessageKey);
2096
- const localizedError = {
2097
- name: I18n.formatMessage(hasErrorName ? errorNameKey : "errorNames.error"),
2098
- message: hasErrorMessage
2099
- ? I18n.formatMessage(errorMessageKey, err.properties)
2100
- : err.message
2101
- };
2102
- if (Is.stringValue(err.source)) {
2103
- localizedError.source = err.source;
2104
- }
2105
- if (Is.stringValue(err.stack)) {
2106
- // Remove the first line from the stack traces as they
2107
- // just have the error type and message duplicated
2108
- const lines = err.stack.split("\n");
2109
- lines.shift();
2110
- localizedError.stack = lines.join("\n");
2478
+ static canonicalize(object) {
2479
+ const buffer = [];
2480
+ if (object === null ||
2481
+ typeof object !== "object" ||
2482
+ ("toJSON" in object && object.toJSON instanceof Function)) {
2483
+ // Primitive data type
2484
+ buffer.push(JSON.stringify(object));
2485
+ }
2486
+ else if (Array.isArray(object)) {
2487
+ // Array maintain element order
2488
+ const parts = [];
2489
+ for (const element of object) {
2490
+ if (element === undefined) {
2491
+ parts.push("null");
2111
2492
  }
2112
- const additional = ErrorHelper.formatValidationErrors(err);
2113
- if (Is.stringValue(additional)) {
2114
- localizedError.additional = additional;
2493
+ else {
2494
+ parts.push(JsonHelper.canonicalize(element));
2115
2495
  }
2116
- formattedErrors.push(localizedError);
2117
2496
  }
2497
+ buffer.push(`[${parts.join(",")}]`);
2118
2498
  }
2119
- return formattedErrors;
2499
+ else {
2500
+ // Object sort properties
2501
+ const props = [];
2502
+ const keys = Object.keys(object).sort();
2503
+ const o = object;
2504
+ for (const key of keys) {
2505
+ if (o[key] !== undefined) {
2506
+ props.push(`${JSON.stringify(key)}:${JsonHelper.canonicalize(o[key])}`);
2507
+ }
2508
+ }
2509
+ buffer.push(`{${props.join(",")}}`);
2510
+ }
2511
+ return buffer.join("");
2120
2512
  }
2121
2513
  /**
2122
- * Localize the content of an error and any inner errors.
2123
- * @param error The error to format.
2124
- * @returns The localized version of the errors flattened.
2514
+ * Creates a RFC 6902 diff set.
2515
+ * Based on https://www.rfc-editor.org/rfc/rfc6902.
2516
+ * @param object1 The first object.
2517
+ * @param object2 The second object.
2518
+ * @returns The list of patches.
2125
2519
  */
2126
- static formatValidationErrors(error) {
2127
- if (Is.object(error.properties) &&
2128
- Object.keys(error.properties).length > 0 &&
2129
- Is.object(error.properties) &&
2130
- Is.arrayValue(error.properties.validationFailures)) {
2131
- const validationErrors = [];
2132
- for (const validationFailure of error.properties.validationFailures) {
2133
- const errorI18n = `error.${validationFailure.reason}`;
2134
- const errorMessage = I18n.hasMessage(errorI18n)
2135
- ? I18n.formatMessage(errorI18n, validationFailure.properties)
2136
- : errorI18n;
2137
- let v = `${validationFailure.property}: ${errorMessage}`;
2138
- if (Is.object(validationFailure.properties) &&
2139
- Is.notEmpty(validationFailure.properties.value)) {
2140
- v += ` = ${JSON.stringify(validationFailure.properties.value)}`;
2141
- }
2142
- validationErrors.push(v);
2520
+ static diff(object1, object2) {
2521
+ const operations = rfc6902.createPatch(object1, object2);
2522
+ return operations;
2523
+ }
2524
+ /**
2525
+ * Applies a RFC 6902 diff set to an object.
2526
+ * Based on https://www.rfc-editor.org/rfc/rfc6902.
2527
+ * @param object The object to patch.
2528
+ * @param patches The second object.
2529
+ * @returns The updated object.
2530
+ * @throws GeneralError if the patch fails.
2531
+ */
2532
+ static patch(object, patches) {
2533
+ const clone = ObjectHelper.clone(object);
2534
+ const result = rfc6902.applyPatch(clone, patches);
2535
+ for (let i = 0; i < result.length; i++) {
2536
+ if (!Is.empty(result[i])) {
2537
+ throw new GeneralError(JsonHelper._CLASS_NAME, "failedPatch", { index: i }, result[i]);
2538
+ }
2539
+ }
2540
+ return clone;
2541
+ }
2542
+ /**
2543
+ * Stringify the JSON with support for extended data types date/bigint/uint8array.
2544
+ * @param object The object to stringify.
2545
+ * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
2546
+ * @returns The stringified object.
2547
+ */
2548
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2549
+ static stringifyEx(object, space) {
2550
+ // We want to keep the 'this' intact for the replacer
2551
+ // eslint-disable-next-line @typescript-eslint/unbound-method
2552
+ return JSON.stringify(object, JsonHelper.stringifyExReplacer, space);
2553
+ }
2554
+ /**
2555
+ * Parse the JSON string with support for extended data types date/bigint/uint8array.
2556
+ * @param json The object to pause.
2557
+ * @returns The object.
2558
+ */
2559
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2560
+ static parseEx(json) {
2561
+ // We want to keep the 'this' intact for the reviver
2562
+ // eslint-disable-next-line @typescript-eslint/unbound-method
2563
+ return JSON.parse(json, JsonHelper.parseExReviver);
2564
+ }
2565
+ /**
2566
+ * Replacer function to handle extended data types.
2567
+ * @param this The object.
2568
+ * @param key The key.
2569
+ * @param value The value.
2570
+ * @returns The value.
2571
+ */
2572
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2573
+ static stringifyExReplacer(key, value) {
2574
+ const rawValue = this[key];
2575
+ if (Is.bigint(rawValue)) {
2576
+ return {
2577
+ "@ext": "bigint",
2578
+ value: rawValue.toString()
2579
+ };
2580
+ }
2581
+ else if (Is.date(rawValue)) {
2582
+ return {
2583
+ "@ext": "date",
2584
+ value: rawValue.getTime()
2585
+ };
2586
+ }
2587
+ else if (Is.uint8Array(rawValue)) {
2588
+ return {
2589
+ "@ext": "uint8array",
2590
+ value: Converter.bytesToBase64(rawValue)
2591
+ };
2592
+ }
2593
+ return value;
2594
+ }
2595
+ /**
2596
+ * Reviver function to handle extended data types.
2597
+ * @param this The object.
2598
+ * @param key The key.
2599
+ * @param value The value.
2600
+ * @returns The value.
2601
+ */
2602
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2603
+ static parseExReviver(key, value) {
2604
+ if (Is.object(value)) {
2605
+ if (value["@ext"] === "bigint") {
2606
+ return BigInt(value.value);
2607
+ }
2608
+ else if (value["@ext"] === "date") {
2609
+ return new Date(value.value);
2610
+ }
2611
+ else if (value["@ext"] === "uint8array") {
2612
+ return Converter.base64ToBytes(value.value);
2143
2613
  }
2144
- return validationErrors.join("\n");
2145
2614
  }
2615
+ return value;
2146
2616
  }
2147
2617
  }
2148
2618
 
2149
- // Copyright 2024 IOTA Stiftung.
2150
- // SPDX-License-Identifier: Apache-2.0.
2151
2619
  /**
2152
- * Coerce an object from one type to another.
2620
+ * Class to help with objects.
2153
2621
  */
2154
- class Coerce {
2622
+ class ObjectHelper {
2155
2623
  /**
2156
- * Coerce the value to a string.
2157
- * @param value The value to coerce.
2158
- * @throws TypeError If the value can not be coerced.
2159
- * @returns The value if it can be coerced.
2624
+ * Runtime name for the class.
2625
+ * @internal
2160
2626
  */
2161
- static string(value) {
2162
- if (Is.undefined(value)) {
2163
- return value;
2164
- }
2165
- if (Is.string(value)) {
2166
- return value;
2167
- }
2168
- if (Is.number(value)) {
2169
- return value.toString();
2170
- }
2171
- if (Is.boolean(value)) {
2172
- return value ? "true" : "false";
2173
- }
2174
- if (Is.date(value)) {
2175
- return value.toISOString();
2627
+ static _CLASS_NAME = "ObjectHelper";
2628
+ /**
2629
+ * Convert an object to bytes.
2630
+ * @param obj The object to convert.
2631
+ * @param format Format the JSON content.
2632
+ * @returns The object as bytes.
2633
+ */
2634
+ static toBytes(obj, format = false) {
2635
+ if (obj === undefined) {
2636
+ return new Uint8Array();
2176
2637
  }
2638
+ const json = format ? JSON.stringify(obj, undefined, "\t") : JSON.stringify(obj);
2639
+ return Converter.utf8ToBytes(json);
2177
2640
  }
2178
2641
  /**
2179
- * Coerce the value to a number.
2180
- * @param value The value to coerce.
2181
- * @throws TypeError If the value can not be coerced.
2182
- * @returns The value if it can be coerced.
2642
+ * Convert a bytes to an object.
2643
+ * @param bytes The bytes to convert to an object.
2644
+ * @returns The object.
2645
+ * @throws GeneralError if there was an error parsing the JSON.
2183
2646
  */
2184
- static number(value) {
2185
- if (Is.undefined(value)) {
2186
- return value;
2187
- }
2188
- if (Is.number(value)) {
2189
- return value;
2190
- }
2191
- if (Is.string(value)) {
2192
- const parsed = Number.parseFloat(value);
2193
- if (Is.number(parsed)) {
2194
- return parsed;
2195
- }
2647
+ static fromBytes(bytes) {
2648
+ if (Is.empty(bytes) || bytes.length === 0) {
2649
+ return undefined;
2196
2650
  }
2197
- if (Is.boolean(value)) {
2198
- return value ? 1 : 0;
2651
+ try {
2652
+ const utf8 = Converter.bytesToUtf8(bytes);
2653
+ return JSON.parse(utf8);
2199
2654
  }
2200
- if (Is.date(value)) {
2201
- return value.getTime();
2655
+ catch (err) {
2656
+ throw new GeneralError(ObjectHelper._CLASS_NAME, "failedBytesToJSON", undefined, err);
2202
2657
  }
2203
2658
  }
2204
2659
  /**
2205
- * Coerce the value to a bigint.
2206
- * @param value The value to coerce.
2207
- * @throws TypeError If the value can not be coerced.
2208
- * @returns The value if it can be coerced.
2660
+ * Make a deep clone of an object.
2661
+ * @param obj The object to clone.
2662
+ * @returns The objects clone.
2209
2663
  */
2210
- static bigint(value) {
2211
- if (Is.undefined(value)) {
2212
- return value;
2664
+ static clone(obj) {
2665
+ if (Is.undefined(obj)) {
2666
+ return undefined;
2213
2667
  }
2214
- if (Is.bigint(value)) {
2215
- return value;
2668
+ return structuredClone(obj);
2669
+ }
2670
+ /**
2671
+ * Deep merge objects.
2672
+ * @param obj1 The first object to merge.
2673
+ * @param obj2 The second object to merge.
2674
+ * @returns The combined deep merge of the objects.
2675
+ */
2676
+ static merge(obj1, obj2) {
2677
+ if (Is.empty(obj1)) {
2678
+ return ObjectHelper.clone(obj2);
2216
2679
  }
2217
- if (Is.number(value)) {
2218
- return BigInt(value);
2680
+ if (Is.empty(obj2)) {
2681
+ return ObjectHelper.clone(obj1);
2219
2682
  }
2220
- if (Is.string(value)) {
2221
- const parsed = Number.parseFloat(value);
2222
- if (Is.integer(parsed)) {
2223
- return BigInt(parsed);
2683
+ const obj1Clone = ObjectHelper.clone(obj1);
2684
+ if (Is.object(obj1Clone) && Is.object(obj2)) {
2685
+ const keys = Object.keys(obj2);
2686
+ for (const key of keys) {
2687
+ if (Is.object(obj1Clone[key]) && Is.object(obj2[key])) {
2688
+ ObjectHelper.propertySet(obj1Clone, key, ObjectHelper.merge(obj1Clone[key], obj2[key]));
2689
+ }
2690
+ else {
2691
+ ObjectHelper.propertySet(obj1Clone, key, obj2[key]);
2692
+ }
2224
2693
  }
2225
2694
  }
2226
- if (Is.boolean(value)) {
2227
- return value ? 1n : 0n;
2228
- }
2695
+ return obj1Clone;
2229
2696
  }
2230
2697
  /**
2231
- * Coerce the value to a boolean.
2232
- * @param value The value to coerce.
2233
- * @throws TypeError If the value can not be coerced.
2234
- * @returns The value if it can be coerced.
2698
+ * Does one object equal another.
2699
+ * @param obj1 The first object to compare.
2700
+ * @param obj2 The second object to compare.
2701
+ * @param strictPropertyOrder Should the properties be in the same order, defaults to true.
2702
+ * @returns True is the objects are equal.
2235
2703
  */
2236
- static boolean(value) {
2237
- if (Is.undefined(value)) {
2238
- return value;
2239
- }
2240
- if (Is.boolean(value)) {
2241
- return value;
2242
- }
2243
- if (Is.number(value)) {
2244
- // eslint-disable-next-line no-unneeded-ternary
2245
- return value ? true : false;
2704
+ static equal(obj1, obj2, strictPropertyOrder) {
2705
+ if (strictPropertyOrder ?? true) {
2706
+ return JSON.stringify(obj1) === JSON.stringify(obj2);
2246
2707
  }
2247
- if (Is.string(value)) {
2248
- if (/true/i.test(value)) {
2249
- return true;
2708
+ return JsonHelper.canonicalize(obj1) === JsonHelper.canonicalize(obj2);
2709
+ }
2710
+ /**
2711
+ * Get the property of an unknown object.
2712
+ * @param obj The object to get the property from.
2713
+ * @param property The property to get, can be separated by dots for nested path.
2714
+ * @returns The property.
2715
+ */
2716
+ static propertyGet(obj, property) {
2717
+ const pathParts = property.split(".");
2718
+ let pathValue = obj;
2719
+ for (const pathPart of pathParts) {
2720
+ // Is the path part numeric i.e. an array index.
2721
+ const arrayMatch = /^(\d+)$/.exec(pathPart);
2722
+ if (arrayMatch) {
2723
+ const arrayIndex = Number.parseInt(arrayMatch[1], 10);
2724
+ if (Is.arrayValue(pathValue) && arrayIndex < pathValue.length) {
2725
+ // There is no prop name so this is a direct array index on the current object
2726
+ pathValue = pathValue[arrayIndex];
2727
+ }
2728
+ else {
2729
+ // Array index for non array object so return
2730
+ return undefined;
2731
+ }
2250
2732
  }
2251
- if (/false/i.test(value)) {
2252
- return false;
2733
+ else if (Is.object(pathValue)) {
2734
+ // No array part in path so assume object sub property
2735
+ pathValue = pathValue[pathPart];
2736
+ }
2737
+ else {
2738
+ return undefined;
2253
2739
  }
2254
2740
  }
2741
+ return pathValue;
2255
2742
  }
2256
2743
  /**
2257
- * Coerce the value to a date.
2258
- * @param value The value to coerce.
2259
- * @throws TypeError If the value can not be coerced.
2260
- * @returns The value if it can be coerced.
2261
- */
2262
- static date(value) {
2263
- if (Is.undefined(value)) {
2264
- return value;
2265
- }
2266
- if (Is.date(value)) {
2267
- return value;
2268
- }
2269
- if (Is.number(value)) {
2270
- return new Date(value);
2271
- }
2272
- if (Is.string(value)) {
2273
- const dt = new Date(value);
2274
- if (!Number.isNaN(dt.getTime())) {
2275
- const utc = Date.UTC(dt.getUTCFullYear(), dt.getUTCMonth(), dt.getUTCDate());
2276
- return new Date(utc);
2744
+ * Set the property of an unknown object.
2745
+ * @param obj The object to set the property from.
2746
+ * @param property The property to set.
2747
+ * @param value The value to set.
2748
+ * @throws GeneralError if the property target is not an object.
2749
+ */
2750
+ static propertySet(obj, property, value) {
2751
+ const pathParts = property.split(".");
2752
+ let pathValue = obj;
2753
+ let parentObj;
2754
+ for (let i = 0; i < pathParts.length; i++) {
2755
+ const pathPart = pathParts[i];
2756
+ // Is the path part numeric i.e. an array index.
2757
+ const arrayMatch = /^(\d+)$/.exec(pathPart);
2758
+ const arrayIndex = arrayMatch ? Number.parseInt(arrayMatch[1], 10) : -1;
2759
+ if (i === pathParts.length - 1) {
2760
+ // Last part of path so set the value
2761
+ if (arrayIndex >= 0) {
2762
+ if (Is.array(pathValue)) {
2763
+ pathValue[arrayIndex] = value;
2764
+ }
2765
+ else if (Is.object(pathValue)) {
2766
+ pathValue[arrayIndex] = value;
2767
+ }
2768
+ else {
2769
+ throw new GeneralError(ObjectHelper._CLASS_NAME, "cannotSetArrayIndex", {
2770
+ property,
2771
+ index: arrayIndex
2772
+ });
2773
+ }
2774
+ }
2775
+ else if (Is.object(pathValue)) {
2776
+ pathValue[pathPart] = value;
2777
+ }
2778
+ else {
2779
+ throw new GeneralError(ObjectHelper._CLASS_NAME, "cannotSetProperty", { property });
2780
+ }
2781
+ }
2782
+ else {
2783
+ parentObj = pathValue;
2784
+ if (Is.object(pathValue)) {
2785
+ pathValue = pathValue[pathPart];
2786
+ }
2787
+ else if (Is.array(pathValue)) {
2788
+ pathValue = pathValue[arrayIndex];
2789
+ }
2790
+ if (Is.empty(pathValue)) {
2791
+ const nextArrayMatch = /^(\d+)$/.exec(pathParts[i + 1]);
2792
+ const nextArrayIndex = nextArrayMatch ? Number.parseInt(nextArrayMatch[1], 10) : -1;
2793
+ if (nextArrayIndex >= 0) {
2794
+ pathValue = [];
2795
+ }
2796
+ else {
2797
+ pathValue = {};
2798
+ }
2799
+ if (Is.object(parentObj)) {
2800
+ parentObj[pathPart] = pathValue;
2801
+ }
2802
+ else if (Is.array(parentObj)) {
2803
+ parentObj[arrayIndex] = pathValue;
2804
+ }
2805
+ }
2277
2806
  }
2278
2807
  }
2279
2808
  }
2280
2809
  /**
2281
- * Coerce the value to a date/time.
2282
- * @param value The value to coerce.
2283
- * @throws TypeError If the value can not be coerced.
2284
- * @returns The value if it can be coerced.
2810
+ * Delete the property of an unknown object.
2811
+ * @param obj The object to set the property from.
2812
+ * @param property The property to set
2285
2813
  */
2286
- static dateTime(value) {
2287
- if (Is.undefined(value)) {
2288
- return value;
2289
- }
2290
- if (Is.date(value)) {
2291
- return value;
2292
- }
2293
- if (Is.number(value)) {
2294
- return new Date(value);
2814
+ static propertyDelete(obj, property) {
2815
+ if (Is.object(obj)) {
2816
+ delete obj[property];
2295
2817
  }
2296
- if (Is.string(value)) {
2297
- const dt = new Date(value);
2298
- if (!Number.isNaN(dt.getTime())) {
2299
- const utc = Date.UTC(dt.getUTCFullYear(), dt.getUTCMonth(), dt.getUTCDate(), dt.getUTCHours(), dt.getUTCMinutes(), dt.getUTCSeconds(), dt.getUTCMilliseconds());
2300
- return new Date(utc);
2818
+ }
2819
+ /**
2820
+ * Extract a property from the object, providing alternative names.
2821
+ * @param obj The object to extract from.
2822
+ * @param propertyNames The possible names for the property.
2823
+ * @param removeProperties Remove the properties from the object, defaults to true.
2824
+ * @returns The property if available.
2825
+ */
2826
+ static extractProperty(obj, propertyNames, removeProperties = true) {
2827
+ let retVal;
2828
+ if (Is.object(obj)) {
2829
+ const names = Is.string(propertyNames) ? [propertyNames] : propertyNames;
2830
+ for (const prop of names) {
2831
+ retVal ??= ObjectHelper.propertyGet(obj, prop);
2832
+ if (removeProperties) {
2833
+ ObjectHelper.propertyDelete(obj, prop);
2834
+ }
2301
2835
  }
2302
2836
  }
2837
+ return retVal;
2303
2838
  }
2304
2839
  /**
2305
- * Coerce the value to a time.
2306
- * @param value The value to coerce.
2307
- * @throws TypeError If the value can not be coerced.
2308
- * @returns The value if it can be coerced.
2840
+ * Pick a subset of properties from an object.
2841
+ * @param obj The object to pick the properties from.
2842
+ * @param keys The property keys to pick.
2843
+ * @returns The partial object.
2309
2844
  */
2310
- static time(value) {
2311
- if (Is.undefined(value)) {
2312
- return value;
2313
- }
2314
- if (Is.date(value)) {
2315
- return value;
2316
- }
2317
- if (Is.number(value)) {
2318
- const dt = new Date(value);
2319
- dt.setFullYear(1970, 0, 1);
2320
- return dt;
2321
- }
2322
- if (Is.string(value)) {
2323
- const dt = new Date(value);
2324
- if (!Number.isNaN(dt.getTime())) {
2325
- const utc = Date.UTC(1970, 0, 1, dt.getUTCHours(), dt.getUTCMinutes(), dt.getUTCSeconds(), dt.getUTCMilliseconds());
2326
- return new Date(utc);
2845
+ static pick(obj, keys) {
2846
+ if (Is.object(obj) && Is.arrayValue(keys)) {
2847
+ const result = {};
2848
+ for (const key of keys) {
2849
+ result[key] = obj[key];
2327
2850
  }
2851
+ return result;
2328
2852
  }
2853
+ return obj;
2329
2854
  }
2330
2855
  /**
2331
- * Coerce the value to an object.
2332
- * @param value The value to coerce.
2333
- * @throws TypeError If the value can not be coerced.
2334
- * @returns The value if it can be coerced.
2856
+ * Omit a subset of properties from an object.
2857
+ * @param obj The object to omit the properties from.
2858
+ * @param keys The property keys to omit.
2859
+ * @returns The partial object.
2335
2860
  */
2336
- static object(value) {
2337
- if (Is.undefined(value)) {
2338
- return value;
2861
+ static omit(obj, keys) {
2862
+ if (Is.object(obj) && Is.arrayValue(keys)) {
2863
+ const result = { ...obj };
2864
+ for (const key of keys) {
2865
+ delete result[key];
2866
+ }
2867
+ return result;
2339
2868
  }
2340
- if (Is.object(value)) {
2341
- return value;
2869
+ return obj;
2870
+ }
2871
+ /**
2872
+ * Converter the non JSON primitives to extended types.
2873
+ * @param obj The object to convert.
2874
+ * @returns The object with extended properties.
2875
+ */
2876
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2877
+ static toExtended(obj) {
2878
+ const jsonExtended = JsonHelper.stringifyEx(obj);
2879
+ return JSON.parse(jsonExtended);
2880
+ }
2881
+ /**
2882
+ * Converter the extended types to non JSON primitives.
2883
+ * @param obj The object to convert.
2884
+ * @returns The object with regular properties.
2885
+ */
2886
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2887
+ static fromExtended(obj) {
2888
+ const jsonExtended = JsonHelper.stringifyEx(obj);
2889
+ return JsonHelper.parseEx(jsonExtended);
2890
+ }
2891
+ /**
2892
+ * Remove empty properties from an object.
2893
+ * @param obj The object to remove the empty properties from.
2894
+ * @param options The options for the removal.
2895
+ * @param options.removeUndefined Remove undefined properties, defaults to true.
2896
+ * @param options.removeNull Remove null properties, defaults to false.
2897
+ * @returns The object with empty properties removed.
2898
+ */
2899
+ static removeEmptyProperties(obj, options) {
2900
+ if (Is.object(obj)) {
2901
+ const removeUndefined = options?.removeUndefined ?? true;
2902
+ const removeNull = options?.removeNull ?? false;
2903
+ const newObj = {};
2904
+ const keys = Object.keys(obj);
2905
+ for (const key of keys) {
2906
+ if (!((removeUndefined && Is.undefined(obj[key])) || (removeNull && Is.null(obj[key])))) {
2907
+ newObj[key] = ObjectHelper.removeEmptyProperties(obj[key], options);
2908
+ }
2909
+ }
2910
+ return newObj;
2342
2911
  }
2343
- if (Is.stringValue(value)) {
2344
- try {
2345
- return JSON.parse(value);
2912
+ else if (Is.array(obj)) {
2913
+ const arr = [];
2914
+ for (const element of obj) {
2915
+ arr.push(ObjectHelper.removeEmptyProperties(element, options));
2346
2916
  }
2347
- catch { }
2917
+ return arr;
2348
2918
  }
2919
+ return obj;
2349
2920
  }
2350
2921
  }
2351
2922
 
2352
2923
  // Copyright 2024 IOTA Stiftung.
2353
2924
  // SPDX-License-Identifier: Apache-2.0.
2354
2925
  /**
2355
- * Class to help with filenames.
2926
+ * Environment variable helper.
2356
2927
  */
2357
- class FilenameHelper {
2358
- /**
2359
- * Replaces any unsafe characters in the filename.
2360
- * @param filename The filename to make safe.
2361
- * @returns The safe filename.
2362
- */
2363
- static safeFilename(filename) {
2364
- let safe = Coerce.string(filename);
2365
- if (Is.empty(safe)) {
2366
- return "";
2928
+ class EnvHelper {
2929
+ /**
2930
+ * Get the environment variable as an object with camel cased names.
2931
+ * @param envVars The environment variables.
2932
+ * @param prefix The prefix of the environment variables, if not provided gets all.
2933
+ * @returns The object with camel cased names.
2934
+ */
2935
+ static envToJson(envVars, prefix) {
2936
+ const result = {};
2937
+ if (!Is.empty(envVars)) {
2938
+ if (Is.empty(prefix)) {
2939
+ for (const envVar in envVars) {
2940
+ if (Is.stringValue(envVars[envVar])) {
2941
+ const camelCaseName = StringHelper.camelCase(envVar.toLowerCase());
2942
+ ObjectHelper.propertySet(result, camelCaseName, envVars[envVar]);
2943
+ }
2944
+ }
2945
+ }
2946
+ else {
2947
+ for (const envVar in envVars) {
2948
+ if (envVar.startsWith(prefix) && Is.stringValue(envVars[envVar])) {
2949
+ const camelCaseName = StringHelper.camelCase(envVar.replace(prefix, "").toLowerCase());
2950
+ ObjectHelper.propertySet(result, camelCaseName, envVars[envVar]);
2951
+ }
2952
+ }
2953
+ }
2367
2954
  }
2368
- // Common non filename characters
2369
- safe = safe.replace(/["*/:<>?\\|]/g, "_");
2370
- // Windows non filename characters
2371
- safe = safe.replace(/^(con|prn|aux|nul|com\d|lpt\d)$/i, "_");
2372
- // Control characters
2373
- safe = safe.replace(/[\u0000-\u001F\u0080-\u009F]/g, "_");
2374
- // Relative paths
2375
- safe = safe.replace(/^\.+/, "_");
2376
- // Trailing periods
2377
- safe = safe.replace(/\.+$/, "");
2378
- return safe;
2955
+ return result;
2379
2956
  }
2380
2957
  }
2381
2958
 
2382
2959
  // Copyright 2024 IOTA Stiftung.
2383
2960
  // SPDX-License-Identifier: Apache-2.0.
2384
2961
  /**
2385
- * Helpers methods for JSON objects.
2962
+ * Class to perform internationalization.
2386
2963
  */
2387
- class JsonHelper {
2964
+ class I18n {
2388
2965
  /**
2389
- * Serializes in canonical format.
2390
- * Based on https://www.rfc-editor.org/rfc/rfc8785.
2391
- * @param object The object to be serialized.
2392
- * @returns The serialized object.
2966
+ * The default translation.
2393
2967
  */
2394
- static canonicalize(object) {
2395
- const buffer = [];
2396
- if (object === null ||
2397
- typeof object !== "object" ||
2398
- ("toJSON" in object && object.toJSON instanceof Function)) {
2399
- // Primitive data type
2400
- buffer.push(JSON.stringify(object));
2401
- }
2402
- else if (Array.isArray(object)) {
2403
- // Array maintain element order
2404
- const parts = [];
2405
- for (const element of object) {
2406
- if (element === undefined) {
2407
- parts.push("null");
2408
- }
2409
- else {
2410
- parts.push(JsonHelper.canonicalize(element));
2411
- }
2412
- }
2413
- buffer.push(`[${parts.join(",")}]`);
2968
+ static DEFAULT_LOCALE = "en";
2969
+ /**
2970
+ * Set the locale.
2971
+ * @param locale The new locale.
2972
+ */
2973
+ static setLocale(locale) {
2974
+ const i18nShared = I18n.getI18nShared();
2975
+ i18nShared.currentLocale = locale;
2976
+ for (const callback in i18nShared.localeChangedHandlers) {
2977
+ i18nShared.localeChangedHandlers[callback](i18nShared.currentLocale);
2414
2978
  }
2415
- else {
2416
- // Object sort properties
2417
- const props = [];
2418
- const keys = Object.keys(object).sort();
2419
- const o = object;
2420
- for (const key of keys) {
2421
- if (o[key] !== undefined) {
2422
- props.push(`${JSON.stringify(key)}:${JsonHelper.canonicalize(o[key])}`);
2423
- }
2424
- }
2425
- buffer.push(`{${props.join(",")}}`);
2979
+ }
2980
+ /**
2981
+ * Get the locale.
2982
+ * @returns The current locale.
2983
+ */
2984
+ static getLocale() {
2985
+ const i18nShared = I18n.getI18nShared();
2986
+ return i18nShared.currentLocale;
2987
+ }
2988
+ /**
2989
+ * Add a locale dictionary.
2990
+ * @param locale The locale.
2991
+ * @param dictionary The dictionary to add.
2992
+ */
2993
+ static addDictionary(locale, dictionary) {
2994
+ const i18nShared = I18n.getI18nShared();
2995
+ const mergedKeys = {};
2996
+ I18n.flattenTranslationKeys(dictionary, "", mergedKeys);
2997
+ i18nShared.localeDictionaries[locale] = mergedKeys;
2998
+ for (const callback in i18nShared.dictionaryChangedHandlers) {
2999
+ i18nShared.dictionaryChangedHandlers[callback](i18nShared.currentLocale);
2426
3000
  }
2427
- return buffer.join("");
2428
3001
  }
2429
3002
  /**
2430
- * Creates a RFC 6902 diff set.
2431
- * Based on https://www.rfc-editor.org/rfc/rfc6902.
2432
- * @param object1 The first object.
2433
- * @param object2 The second object.
2434
- * @returns The list of patches.
3003
+ * Get a locale dictionary.
3004
+ * @param locale The locale.
3005
+ * @returns The dictionary of undefined if it does not exist.
2435
3006
  */
2436
- static diff(object1, object2) {
2437
- const operations = rfc6902.createPatch(object1, object2);
2438
- return operations;
3007
+ static getDictionary(locale) {
3008
+ const i18nShared = I18n.getI18nShared();
3009
+ return i18nShared.localeDictionaries[locale];
2439
3010
  }
2440
3011
  /**
2441
- * Applies a RFC 6902 diff set to an object.
2442
- * Based on https://www.rfc-editor.org/rfc/rfc6902.
2443
- * @param object The object to patch.
2444
- * @param patches The second object.
2445
- * @returns The updated object.
3012
+ * Get all the locale dictionaries.
3013
+ * @returns The dictionaries.
2446
3014
  */
2447
- static patch(object, patches) {
2448
- return rfc6902.applyPatch(object, patches);
3015
+ static getAllDictionaries() {
3016
+ const i18nShared = I18n.getI18nShared();
3017
+ return i18nShared.localeDictionaries;
2449
3018
  }
2450
- }
2451
-
2452
- // Copyright 2024 IOTA Stiftung.
2453
- // SPDX-License-Identifier: Apache-2.0.
2454
- /* eslint-disable no-bitwise */
2455
- /**
2456
- * Convert arrays to and from different formats.
2457
- */
2458
- class Converter {
2459
3019
  /**
2460
- * Lookup table for encoding.
2461
- * @internal
3020
+ * Add a locale changed handler.
3021
+ * @param id The id of the handler.
3022
+ * @param handler The handler to add.
2462
3023
  */
2463
- static _ENCODE_LOOKUP;
3024
+ static addLocaleHandler(id, handler) {
3025
+ const i18nShared = I18n.getI18nShared();
3026
+ i18nShared.localeChangedHandlers[id] = handler;
3027
+ }
2464
3028
  /**
2465
- * Lookup table for decoding.
2466
- * @internal
3029
+ * Remove a locale changed handler.
3030
+ * @param id The id of the handler.
2467
3031
  */
2468
- static _DECODE_LOOKUP;
3032
+ static removeLocaleHandler(id) {
3033
+ const i18nShared = I18n.getI18nShared();
3034
+ delete i18nShared.localeChangedHandlers[id];
3035
+ }
2469
3036
  /**
2470
- * Encode a raw array to UTF8 string.
2471
- * @param array The bytes to encode.
2472
- * @param startIndex The index to start in the bytes.
2473
- * @param length The length of bytes to read.
2474
- * @returns The array formatted as UTF8.
3037
+ * Add a dictionary changed handler.
3038
+ * @param id The id of the handler.
3039
+ * @param handler The handler to add.
2475
3040
  */
2476
- static bytesToUtf8(array, startIndex, length) {
2477
- const start = startIndex ?? 0;
2478
- const len = length ?? array.length;
2479
- let str = "";
2480
- for (let i = start; i < start + len; i++) {
2481
- const value = array[i];
2482
- if (value < 0x80) {
2483
- str += String.fromCharCode(value);
2484
- }
2485
- else if (value > 0xbf && value < 0xe0) {
2486
- str += String.fromCharCode(((value & 0x1f) << 6) | (array[i + 1] & 0x3f));
2487
- i += 1;
2488
- }
2489
- else if (value > 0xdf && value < 0xf0) {
2490
- str += String.fromCharCode(((value & 0x0f) << 12) | ((array[i + 1] & 0x3f) << 6) | (array[i + 2] & 0x3f));
2491
- i += 2;
2492
- }
2493
- else {
2494
- // surrogate pair
2495
- const charCode = (((value & 0x07) << 18) |
2496
- ((array[i + 1] & 0x3f) << 12) |
2497
- ((array[i + 2] & 0x3f) << 6) |
2498
- (array[i + 3] & 0x3f)) -
2499
- 0x010000;
2500
- str += String.fromCharCode((charCode >> 10) | 0xd800, (charCode & 0x03ff) | 0xdc00);
2501
- i += 3;
2502
- }
3041
+ static addDictionaryHandler(id, handler) {
3042
+ const i18nShared = I18n.getI18nShared();
3043
+ i18nShared.dictionaryChangedHandlers[id] = handler;
3044
+ }
3045
+ /**
3046
+ * Remove a dictionary changed handler.
3047
+ * @param id The id of the handler.
3048
+ */
3049
+ static removeDictionaryHandler(id) {
3050
+ const i18nShared = I18n.getI18nShared();
3051
+ delete i18nShared.dictionaryChangedHandlers[id];
3052
+ }
3053
+ /**
3054
+ * Format a message.
3055
+ * @param key The key of the message to format.
3056
+ * @param values The values to substitute into the message.
3057
+ * @param overrideLocale Override the locale.
3058
+ * @returns The formatted string.
3059
+ */
3060
+ static formatMessage(key, values, overrideLocale) {
3061
+ const i18nShared = I18n.getI18nShared();
3062
+ let cl = overrideLocale ?? i18nShared.currentLocale;
3063
+ if (cl.startsWith("debug-")) {
3064
+ cl = I18n.DEFAULT_LOCALE;
2503
3065
  }
2504
- return str;
3066
+ if (!i18nShared.localeDictionaries[cl]) {
3067
+ return `!!Missing ${cl}`;
3068
+ }
3069
+ if (!i18nShared.localeDictionaries[cl][key]) {
3070
+ return `!!Missing ${cl}.${key}`;
3071
+ }
3072
+ if (i18nShared.currentLocale === "debug-k") {
3073
+ return key;
3074
+ }
3075
+ let ret = new intlMessageformat.IntlMessageFormat(i18nShared.localeDictionaries[cl][key], cl).format(values);
3076
+ if (i18nShared.currentLocale === "debug-x") {
3077
+ ret = ret.replace(/[a-z]/g, "x").replace(/[A-Z]/g, "x").replace(/\d/g, "n");
3078
+ }
3079
+ return ret;
2505
3080
  }
2506
3081
  /**
2507
- * Convert a UTF8 string to raw array.
2508
- * @param utf8 The text to decode.
2509
- * @returns The array.
3082
+ * Check if the dictionaries have a message for the given key.
3083
+ * @param key The key to check for existence.
3084
+ * @returns True if the key exists.
2510
3085
  */
2511
- static utf8ToBytes(utf8) {
2512
- const bytes = [];
2513
- for (let i = 0; i < utf8.length; i++) {
2514
- let charCode = utf8.charCodeAt(i);
2515
- if (charCode < 0x80) {
2516
- bytes.push(charCode);
2517
- }
2518
- else if (charCode < 0x800) {
2519
- bytes.push(0xc0 | (charCode >> 6), 0x80 | (charCode & 0x3f));
3086
+ static hasMessage(key) {
3087
+ const i18nShared = I18n.getI18nShared();
3088
+ return Is.string(i18nShared.localeDictionaries[i18nShared.currentLocale]?.[key]);
3089
+ }
3090
+ /**
3091
+ * Flatten the translation property paths for faster lookup.
3092
+ * @param translation The translation to merge.
3093
+ * @param propertyPath The current root path.
3094
+ * @param mergedKeys The merged keys dictionary to populate.
3095
+ * @internal
3096
+ */
3097
+ static flattenTranslationKeys(translation, propertyPath, mergedKeys) {
3098
+ for (const key in translation) {
3099
+ const val = translation[key];
3100
+ const mergedPath = propertyPath.length > 0 ? `${propertyPath}.${key}` : key;
3101
+ if (Is.string(val)) {
3102
+ mergedKeys[mergedPath] = val;
2520
3103
  }
2521
- else if (charCode < 0xd800 || charCode >= 0xe000) {
2522
- bytes.push(0xe0 | (charCode >> 12), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
3104
+ else if (Is.object(val)) {
3105
+ I18n.flattenTranslationKeys(val, mergedPath, mergedKeys);
2523
3106
  }
2524
- else {
2525
- // surrogate pair
2526
- i++;
2527
- // UTF-16 encodes 0x10000-0x10FFFF by
2528
- // subtracting 0x10000 and splitting the
2529
- // 20 bits of 0x0-0xFFFFF into two halves
2530
- charCode = 0x10000 + (((charCode & 0x3ff) << 10) | (utf8.charCodeAt(i) & 0x3ff));
2531
- bytes.push(0xf0 | (charCode >> 18), 0x80 | ((charCode >> 12) & 0x3f), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
3107
+ }
3108
+ }
3109
+ /**
3110
+ * Get the I18n shared data.
3111
+ * @returns The I18n shared data.
3112
+ * @internal
3113
+ */
3114
+ static getI18nShared() {
3115
+ let i18nShared = SharedStore.get("i18n");
3116
+ if (Is.undefined(i18nShared)) {
3117
+ i18nShared = {
3118
+ localeDictionaries: {},
3119
+ currentLocale: I18n.DEFAULT_LOCALE,
3120
+ localeChangedHandlers: {},
3121
+ dictionaryChangedHandlers: {}
3122
+ };
3123
+ SharedStore.set("i18n", i18nShared);
3124
+ }
3125
+ return i18nShared;
3126
+ }
3127
+ }
3128
+
3129
+ // Copyright 2024 IOTA Stiftung.
3130
+ // SPDX-License-Identifier: Apache-2.0.
3131
+ /**
3132
+ * Error helper functions.
3133
+ */
3134
+ class ErrorHelper {
3135
+ /**
3136
+ * Format Errors and returns just their messages.
3137
+ * @param error The error to format.
3138
+ * @param includeDetails Whether to include error details, defaults to false.
3139
+ * @returns The error formatted including any inner errors.
3140
+ */
3141
+ static formatErrors(error, includeDetails) {
3142
+ const localizedErrors = ErrorHelper.localizeErrors(error);
3143
+ if (includeDetails ?? false) {
3144
+ const output = [];
3145
+ for (const err of localizedErrors) {
3146
+ let detailedError = err.message;
3147
+ if (Is.stringValue(err.stack)) {
3148
+ detailedError += `\n${err.stack}`;
3149
+ }
3150
+ output.push(detailedError);
2532
3151
  }
3152
+ return output;
2533
3153
  }
2534
- return Uint8Array.from(bytes);
3154
+ return localizedErrors.map(e => e.message);
2535
3155
  }
2536
3156
  /**
2537
- * Encode a raw array to hex string.
2538
- * @param array The bytes to encode.
2539
- * @param includePrefix Include the 0x prefix on the returned hex.
2540
- * @param startIndex The index to start in the bytes.
2541
- * @param length The length of bytes to read.
2542
- * @param reverse Reverse the combine direction.
2543
- * @returns The array formatted as hex.
3157
+ * Localize the content of an error and any inner errors.
3158
+ * @param error The error to format.
3159
+ * @returns The localized version of the errors flattened.
2544
3160
  */
2545
- static bytesToHex(array, includePrefix = false, startIndex, length, reverse) {
2546
- let hex = "";
2547
- this.buildHexLookups();
2548
- if (Converter._ENCODE_LOOKUP) {
2549
- const len = length ?? array.length;
2550
- const start = startIndex ?? 0;
2551
- if (reverse) {
2552
- for (let i = 0; i < len; i++) {
2553
- hex = Converter._ENCODE_LOOKUP[array[start + i]] + hex;
3161
+ static localizeErrors(error) {
3162
+ const formattedErrors = [];
3163
+ if (Is.notEmpty(error)) {
3164
+ const errors = BaseError.flatten(error);
3165
+ for (const err of errors) {
3166
+ const errorNameKey = `errorNames.${StringHelper.camelCase(err.name)}`;
3167
+ const errorMessageKey = `error.${err.message}`;
3168
+ // If there is no error message then it is probably
3169
+ // from a 3rd party lib, so don't format it just display
3170
+ const hasErrorName = I18n.hasMessage(errorNameKey);
3171
+ const hasErrorMessage = I18n.hasMessage(errorMessageKey);
3172
+ const localizedError = {
3173
+ name: I18n.formatMessage(hasErrorName ? errorNameKey : "errorNames.error"),
3174
+ message: hasErrorMessage
3175
+ ? I18n.formatMessage(errorMessageKey, err.properties)
3176
+ : err.message
3177
+ };
3178
+ if (Is.stringValue(err.source)) {
3179
+ localizedError.source = err.source;
2554
3180
  }
3181
+ if (Is.stringValue(err.stack)) {
3182
+ // Remove the first line from the stack traces as they
3183
+ // just have the error type and message duplicated
3184
+ const lines = err.stack.split("\n");
3185
+ lines.shift();
3186
+ localizedError.stack = lines.join("\n");
3187
+ }
3188
+ const additional = ErrorHelper.formatValidationErrors(err);
3189
+ if (Is.stringValue(additional)) {
3190
+ localizedError.additional = additional;
3191
+ }
3192
+ formattedErrors.push(localizedError);
2555
3193
  }
2556
- else {
2557
- for (let i = 0; i < len; i++) {
2558
- hex += Converter._ENCODE_LOOKUP[array[start + i]];
3194
+ }
3195
+ return formattedErrors;
3196
+ }
3197
+ /**
3198
+ * Localize the content of an error and any inner errors.
3199
+ * @param error The error to format.
3200
+ * @returns The localized version of the errors flattened.
3201
+ */
3202
+ static formatValidationErrors(error) {
3203
+ if (Is.object(error.properties) &&
3204
+ Object.keys(error.properties).length > 0 &&
3205
+ Is.object(error.properties) &&
3206
+ Is.arrayValue(error.properties.validationFailures)) {
3207
+ const validationErrors = [];
3208
+ for (const validationFailure of error.properties.validationFailures) {
3209
+ const errorI18n = `error.${validationFailure.reason}`;
3210
+ const errorMessage = I18n.hasMessage(errorI18n)
3211
+ ? I18n.formatMessage(errorI18n, validationFailure.properties)
3212
+ : errorI18n;
3213
+ let v = `${validationFailure.property}: ${errorMessage}`;
3214
+ if (Is.object(validationFailure.properties) &&
3215
+ Is.notEmpty(validationFailure.properties.value)) {
3216
+ v += ` = ${JSON.stringify(validationFailure.properties.value)}`;
2559
3217
  }
3218
+ validationErrors.push(v);
2560
3219
  }
3220
+ return validationErrors.join("\n");
2561
3221
  }
2562
- return includePrefix ? HexHelper.addPrefix(hex) : hex;
2563
3222
  }
3223
+ }
3224
+
3225
+ // Copyright 2024 IOTA Stiftung.
3226
+ // SPDX-License-Identifier: Apache-2.0.
3227
+ /**
3228
+ * The types the extracted data can be coerced to.
3229
+ */
3230
+ // eslint-disable-next-line @typescript-eslint/naming-convention
3231
+ const CoerceType = {
2564
3232
  /**
2565
- * Decode a hex string to raw array.
2566
- * @param hex The hex to decode.
2567
- * @param reverse Store the characters in reverse.
2568
- * @returns The array.
3233
+ * String.
2569
3234
  */
2570
- static hexToBytes(hex, reverse) {
2571
- const strippedHex = HexHelper.stripPrefix(hex);
2572
- const sizeof = strippedHex.length >> 1;
2573
- const length = sizeof << 1;
2574
- const array = new Uint8Array(sizeof);
2575
- this.buildHexLookups();
2576
- if (Converter._DECODE_LOOKUP) {
2577
- let i = 0;
2578
- let n = 0;
2579
- while (i < length) {
2580
- array[n++] =
2581
- (Converter._DECODE_LOOKUP[strippedHex.charCodeAt(i++)] << 4) |
2582
- Converter._DECODE_LOOKUP[strippedHex.charCodeAt(i++)];
2583
- }
2584
- if (reverse) {
2585
- array.reverse();
2586
- }
2587
- }
2588
- return array;
2589
- }
3235
+ String: "string",
2590
3236
  /**
2591
- * Convert the UTF8 to hex.
2592
- * @param utf8 The text to convert.
2593
- * @param includePrefix Include the 0x prefix on the returned hex.
2594
- * @returns The hex version of the bytes.
3237
+ * Number.
2595
3238
  */
2596
- static utf8ToHex(utf8, includePrefix = false) {
2597
- const hex = Converter.bytesToHex(Converter.utf8ToBytes(utf8));
2598
- return includePrefix ? HexHelper.addPrefix(hex) : hex;
2599
- }
3239
+ Number: "number",
2600
3240
  /**
2601
- * Convert the hex text to text.
2602
- * @param hex The hex to convert.
2603
- * @returns The UTF8 version of the bytes.
3241
+ * Integer.
2604
3242
  */
2605
- static hexToUtf8(hex) {
2606
- return Converter.bytesToUtf8(Converter.hexToBytes(HexHelper.stripPrefix(hex)));
2607
- }
3243
+ Integer: "integer",
2608
3244
  /**
2609
- * Convert bytes to binary string.
2610
- * @param bytes The bytes to convert.
2611
- * @returns A binary string of the bytes.
3245
+ * Boolean.
2612
3246
  */
2613
- static bytesToBinary(bytes) {
2614
- const b = [];
2615
- for (let i = 0; i < bytes.length; i++) {
2616
- b.push(bytes[i].toString(2).padStart(8, "0"));
2617
- }
2618
- return b.join("");
2619
- }
3247
+ Boolean: "boolean",
2620
3248
  /**
2621
- * Convert a binary string to bytes.
2622
- * @param binary The binary string.
2623
- * @returns The bytes.
3249
+ * Big Integer.
2624
3250
  */
2625
- static binaryToBytes(binary) {
2626
- const bytes = new Uint8Array(Math.ceil(binary.length / 8));
2627
- for (let i = 0; i < bytes.length; i++) {
2628
- bytes[i] = Number.parseInt(binary.slice(i * 8, (i + 1) * 8), 2);
2629
- }
2630
- return bytes;
2631
- }
3251
+ BigInt: "bigint",
2632
3252
  /**
2633
- * Convert bytes to base64 string.
2634
- * @param bytes The bytes to convert.
2635
- * @returns A base64 string of the bytes.
3253
+ * Date.
2636
3254
  */
2637
- static bytesToBase64(bytes) {
2638
- return Base64.encode(bytes);
2639
- }
3255
+ Date: "date",
2640
3256
  /**
2641
- * Convert a base64 string to bytes.
2642
- * @param base64 The base64 string.
2643
- * @returns The bytes.
3257
+ * Date Time.
2644
3258
  */
2645
- static base64ToBytes(base64) {
2646
- return Base64.decode(base64);
2647
- }
3259
+ DateTime: "datetime",
2648
3260
  /**
2649
- * Convert bytes to base64 url string.
2650
- * @param bytes The bytes to convert.
2651
- * @returns A base64 url string of the bytes.
3261
+ * Time.
2652
3262
  */
2653
- static bytesToBase64Url(bytes) {
2654
- return Base64Url.encode(bytes);
2655
- }
3263
+ Time: "time",
2656
3264
  /**
2657
- * Convert a base64 url string to bytes.
2658
- * @param base64Url The base64 url string.
2659
- * @returns The bytes.
3265
+ * Object.
2660
3266
  */
2661
- static base64UrlToBytes(base64Url) {
2662
- return Base64Url.decode(base64Url);
2663
- }
3267
+ Object: "object",
2664
3268
  /**
2665
- * Build the static lookup tables.
2666
- * @internal
3269
+ * Uint8Array.
2667
3270
  */
2668
- static buildHexLookups() {
2669
- if (!Converter._ENCODE_LOOKUP || !Converter._DECODE_LOOKUP) {
2670
- const alphabet = "0123456789abcdef";
2671
- Converter._ENCODE_LOOKUP = [];
2672
- Converter._DECODE_LOOKUP = [];
2673
- for (let i = 0; i < 256; i++) {
2674
- Converter._ENCODE_LOOKUP[i] = alphabet[(i >> 4) & 0xf] + alphabet[i & 0xf];
2675
- if (i < 16) {
2676
- if (i < 10) {
2677
- Converter._DECODE_LOOKUP[0x30 + i] = i;
2678
- }
2679
- else {
2680
- Converter._DECODE_LOOKUP[0x61 - 10 + i] = i;
2681
- }
2682
- }
2683
- }
2684
- }
2685
- }
2686
- }
3271
+ Uint8Array: "uint8array"
3272
+ };
2687
3273
 
3274
+ // Copyright 2024 IOTA Stiftung.
3275
+ // SPDX-License-Identifier: Apache-2.0.
2688
3276
  /**
2689
- * Class to help with objects.
3277
+ * Coerce an object from one type to another.
2690
3278
  */
2691
- class ObjectHelper {
2692
- /**
2693
- * Runtime name for the class.
2694
- * @internal
2695
- */
2696
- static _CLASS_NAME = "ObjectHelper";
3279
+ class Coerce {
2697
3280
  /**
2698
- * Convert an object to bytes.
2699
- * @param obj The object to convert.
2700
- * @param format Format the JSON content.
2701
- * @returns The object as bytes.
3281
+ * Coerce the value to a string.
3282
+ * @param value The value to coerce.
3283
+ * @throws TypeError If the value can not be coerced.
3284
+ * @returns The value if it can be coerced.
2702
3285
  */
2703
- static toBytes(obj, format = false) {
2704
- if (obj === undefined) {
2705
- return new Uint8Array();
3286
+ static string(value) {
3287
+ if (Is.undefined(value)) {
3288
+ return value;
3289
+ }
3290
+ if (Is.string(value)) {
3291
+ return value;
3292
+ }
3293
+ if (Is.number(value)) {
3294
+ return value.toString();
3295
+ }
3296
+ if (Is.boolean(value)) {
3297
+ return value ? "true" : "false";
3298
+ }
3299
+ if (Is.date(value)) {
3300
+ return value.toISOString();
2706
3301
  }
2707
- const json = format ? JSON.stringify(obj, undefined, "\t") : JSON.stringify(obj);
2708
- return Converter.utf8ToBytes(json);
2709
3302
  }
2710
3303
  /**
2711
- * Convert a bytes to an object.
2712
- * @param bytes The bytes to convert to an object.
2713
- * @returns The object.
2714
- * @throws GeneralError if there was an error parsing the JSON.
3304
+ * Coerce the value to a number.
3305
+ * @param value The value to coerce.
3306
+ * @throws TypeError If the value can not be coerced.
3307
+ * @returns The value if it can be coerced.
2715
3308
  */
2716
- static fromBytes(bytes) {
2717
- if (Is.empty(bytes) || bytes.length === 0) {
2718
- return undefined;
3309
+ static number(value) {
3310
+ if (Is.undefined(value)) {
3311
+ return value;
2719
3312
  }
2720
- try {
2721
- const utf8 = Converter.bytesToUtf8(bytes);
2722
- return JSON.parse(utf8);
3313
+ if (Is.number(value)) {
3314
+ return value;
2723
3315
  }
2724
- catch (err) {
2725
- throw new GeneralError(ObjectHelper._CLASS_NAME, "failedBytesToJSON", undefined, err);
3316
+ if (Is.string(value)) {
3317
+ const parsed = Number.parseFloat(value);
3318
+ if (Is.number(parsed)) {
3319
+ return parsed;
3320
+ }
3321
+ }
3322
+ if (Is.boolean(value)) {
3323
+ return value ? 1 : 0;
3324
+ }
3325
+ if (Is.date(value)) {
3326
+ return value.getTime();
2726
3327
  }
2727
3328
  }
2728
3329
  /**
2729
- * Make a deep clone of an object.
2730
- * @param obj The object to clone.
2731
- * @returns The objects clone.
3330
+ * Coerce the value to an integer.
3331
+ * @param value The value to coerce.
3332
+ * @throws TypeError If the value can not be coerced.
3333
+ * @returns The value if it can be coerced.
2732
3334
  */
2733
- static clone(obj) {
2734
- if (Is.undefined(obj)) {
2735
- return undefined;
3335
+ static integer(value) {
3336
+ const num = Coerce.number(value);
3337
+ if (!Is.undefined(num)) {
3338
+ return Math.trunc(num);
2736
3339
  }
2737
- return structuredClone(obj);
2738
3340
  }
2739
3341
  /**
2740
- * Deep merge objects.
2741
- * @param obj1 The first object to merge.
2742
- * @param obj2 The second object to merge.
2743
- * @returns The combined deep merge of the objects.
3342
+ * Coerce the value to a bigint.
3343
+ * @param value The value to coerce.
3344
+ * @throws TypeError If the value can not be coerced.
3345
+ * @returns The value if it can be coerced.
2744
3346
  */
2745
- static merge(obj1, obj2) {
2746
- if (Is.empty(obj1)) {
2747
- return ObjectHelper.clone(obj2);
3347
+ static bigint(value) {
3348
+ if (Is.undefined(value)) {
3349
+ return value;
2748
3350
  }
2749
- if (Is.empty(obj2)) {
2750
- return ObjectHelper.clone(obj1);
3351
+ if (Is.bigint(value)) {
3352
+ return value;
2751
3353
  }
2752
- const obj1Clone = ObjectHelper.clone(obj1);
2753
- if (Is.object(obj1Clone) && Is.object(obj2)) {
2754
- const keys = Object.keys(obj2);
2755
- for (const key of keys) {
2756
- if (Is.object(obj1Clone[key]) && Is.object(obj2[key])) {
2757
- ObjectHelper.propertySet(obj1Clone, key, ObjectHelper.merge(obj1Clone[key], obj2[key]));
2758
- }
2759
- else {
2760
- ObjectHelper.propertySet(obj1Clone, key, obj2[key]);
2761
- }
3354
+ if (Is.number(value)) {
3355
+ return BigInt(value);
3356
+ }
3357
+ if (Is.string(value)) {
3358
+ const parsed = Number.parseFloat(value);
3359
+ if (Is.integer(parsed)) {
3360
+ return BigInt(parsed);
3361
+ }
3362
+ }
3363
+ if (Is.boolean(value)) {
3364
+ return value ? 1n : 0n;
3365
+ }
3366
+ }
3367
+ /**
3368
+ * Coerce the value to a boolean.
3369
+ * @param value The value to coerce.
3370
+ * @throws TypeError If the value can not be coerced.
3371
+ * @returns The value if it can be coerced.
3372
+ */
3373
+ static boolean(value) {
3374
+ if (Is.undefined(value)) {
3375
+ return value;
3376
+ }
3377
+ if (Is.boolean(value)) {
3378
+ return value;
3379
+ }
3380
+ if (Is.number(value)) {
3381
+ // eslint-disable-next-line no-unneeded-ternary
3382
+ return value ? true : false;
3383
+ }
3384
+ if (Is.string(value)) {
3385
+ if (/true/i.test(value)) {
3386
+ return true;
3387
+ }
3388
+ if (/false/i.test(value)) {
3389
+ return false;
2762
3390
  }
2763
3391
  }
2764
- return obj1Clone;
2765
3392
  }
2766
3393
  /**
2767
- * Does one object equal another.
2768
- * @param obj1 The first object to compare.
2769
- * @param obj2 The second object to compare.
2770
- * @param strictPropertyOrder Should the properties be in the same order, defaults to true.
2771
- * @returns True is the objects are equal.
3394
+ * Coerce the value to a date.
3395
+ * @param value The value to coerce.
3396
+ * @throws TypeError If the value can not be coerced.
3397
+ * @returns The value if it can be coerced.
2772
3398
  */
2773
- static equal(obj1, obj2, strictPropertyOrder) {
2774
- if (strictPropertyOrder ?? true) {
2775
- return JSON.stringify(obj1) === JSON.stringify(obj2);
3399
+ static date(value) {
3400
+ if (Is.undefined(value)) {
3401
+ return value;
3402
+ }
3403
+ if (Is.date(value)) {
3404
+ return value;
3405
+ }
3406
+ if (Is.number(value)) {
3407
+ return new Date(value);
3408
+ }
3409
+ if (Is.string(value)) {
3410
+ const dt = new Date(value);
3411
+ if (!Number.isNaN(dt.getTime())) {
3412
+ const utc = Date.UTC(dt.getUTCFullYear(), dt.getUTCMonth(), dt.getUTCDate());
3413
+ return new Date(utc);
3414
+ }
2776
3415
  }
2777
- return JsonHelper.canonicalize(obj1) === JsonHelper.canonicalize(obj2);
2778
3416
  }
2779
3417
  /**
2780
- * Get the property of an unknown object.
2781
- * @param obj The object to get the property from.
2782
- * @param property The property to get, can be separated by dots for nested path.
2783
- * @returns The property.
3418
+ * Coerce the value to a date/time.
3419
+ * @param value The value to coerce.
3420
+ * @throws TypeError If the value can not be coerced.
3421
+ * @returns The value if it can be coerced.
2784
3422
  */
2785
- static propertyGet(obj, property) {
2786
- if (property.includes(".")) {
2787
- const parts = property.split(".");
2788
- let value = obj;
2789
- for (const part of parts) {
2790
- if (Is.object(value)) {
2791
- value = value[part];
2792
- }
2793
- else {
2794
- return undefined;
2795
- }
2796
- }
3423
+ static dateTime(value) {
3424
+ if (Is.undefined(value)) {
2797
3425
  return value;
2798
3426
  }
2799
- return Is.object(obj) ? obj[property] : undefined;
3427
+ if (Is.date(value)) {
3428
+ return value;
3429
+ }
3430
+ if (Is.number(value)) {
3431
+ return new Date(value);
3432
+ }
3433
+ if (Is.string(value)) {
3434
+ const dt = new Date(value);
3435
+ if (!Number.isNaN(dt.getTime())) {
3436
+ const utc = Date.UTC(dt.getUTCFullYear(), dt.getUTCMonth(), dt.getUTCDate(), dt.getUTCHours(), dt.getUTCMinutes(), dt.getUTCSeconds(), dt.getUTCMilliseconds());
3437
+ return new Date(utc);
3438
+ }
3439
+ }
2800
3440
  }
2801
3441
  /**
2802
- * Set the property of an unknown object.
2803
- * @param obj The object to set the property from.
2804
- * @param property The property to set.
2805
- * @param value The value to set.
3442
+ * Coerce the value to a time.
3443
+ * @param value The value to coerce.
3444
+ * @throws TypeError If the value can not be coerced.
3445
+ * @returns The value if it can be coerced.
2806
3446
  */
2807
- static propertySet(obj, property, value) {
2808
- if (Is.object(obj)) {
2809
- obj[property] = value;
3447
+ static time(value) {
3448
+ if (Is.undefined(value)) {
3449
+ return value;
3450
+ }
3451
+ if (Is.date(value)) {
3452
+ return value;
3453
+ }
3454
+ if (Is.number(value)) {
3455
+ const dt = new Date(value);
3456
+ dt.setFullYear(1970, 0, 1);
3457
+ return dt;
3458
+ }
3459
+ if (Is.string(value)) {
3460
+ const dt = new Date(value);
3461
+ if (!Number.isNaN(dt.getTime())) {
3462
+ const utc = Date.UTC(1970, 0, 1, dt.getUTCHours(), dt.getUTCMinutes(), dt.getUTCSeconds(), dt.getUTCMilliseconds());
3463
+ return new Date(utc);
3464
+ }
2810
3465
  }
2811
3466
  }
2812
3467
  /**
2813
- * Delete the property of an unknown object.
2814
- * @param obj The object to set the property from.
2815
- * @param property The property to set
3468
+ * Coerce the value to an object.
3469
+ * @param value The value to coerce.
3470
+ * @throws TypeError If the value can not be coerced.
3471
+ * @returns The value if it can be coerced.
2816
3472
  */
2817
- static propertyDelete(obj, property) {
2818
- if (Is.object(obj)) {
2819
- delete obj[property];
3473
+ static object(value) {
3474
+ if (Is.undefined(value)) {
3475
+ return value;
3476
+ }
3477
+ if (Is.object(value)) {
3478
+ return value;
3479
+ }
3480
+ if (Is.stringValue(value)) {
3481
+ try {
3482
+ return JSON.parse(value);
3483
+ }
3484
+ catch { }
2820
3485
  }
2821
3486
  }
2822
3487
  /**
2823
- * Extract a property from the object, providing alternative names.
2824
- * @param obj The object to extract from.
2825
- * @param propertyNames The possible names for the property.
2826
- * @param removeProperties Remove the properties from the object, defaults to true.
2827
- * @returns The property if available.
3488
+ * Coerce the value to a Uint8Array.
3489
+ * @param value The value to coerce.
3490
+ * @throws TypeError If the value can not be coerced.
3491
+ * @returns The value if it can be coerced.
2828
3492
  */
2829
- static extractProperty(obj, propertyNames, removeProperties = true) {
2830
- let retVal;
2831
- if (Is.object(obj)) {
2832
- const names = Is.string(propertyNames) ? [propertyNames] : propertyNames;
2833
- for (const prop of names) {
2834
- retVal ??= ObjectHelper.propertyGet(obj, prop);
2835
- if (removeProperties) {
2836
- ObjectHelper.propertyDelete(obj, prop);
2837
- }
3493
+ static uint8Array(value) {
3494
+ if (Is.undefined(value)) {
3495
+ return value;
3496
+ }
3497
+ if (Is.string(value)) {
3498
+ if (Is.stringHex(value.toLowerCase(), true)) {
3499
+ return Converter.hexToBytes(value.toLowerCase());
3500
+ }
3501
+ if (Is.stringBase64(value)) {
3502
+ return Converter.base64ToBytes(value);
2838
3503
  }
2839
3504
  }
2840
- return retVal;
2841
3505
  }
2842
3506
  /**
2843
- * Pick a subset of properties from an object.
2844
- * @param obj The object to pick the properties from.
2845
- * @param keys The property keys to pick.
2846
- * @returns The partial object.
2847
- */
2848
- static pick(obj, keys) {
2849
- if (Is.object(obj) && Is.arrayValue(keys)) {
2850
- const result = {};
2851
- for (const key of keys) {
2852
- result[key] = obj[key];
2853
- }
2854
- return result;
3507
+ * Coerces a value based on the coercion type.
3508
+ * @param value The value to coerce.
3509
+ * @param type The coercion type to perform.
3510
+ * @returns The coerced value.
3511
+ */
3512
+ static byType(value, type) {
3513
+ switch (type) {
3514
+ case CoerceType.String:
3515
+ return Coerce.string(value);
3516
+ case CoerceType.Number:
3517
+ return Coerce.number(value);
3518
+ case CoerceType.Integer:
3519
+ return Coerce.integer(value);
3520
+ case CoerceType.BigInt:
3521
+ return Coerce.bigint(value);
3522
+ case CoerceType.Boolean:
3523
+ return Coerce.boolean(value);
3524
+ case CoerceType.Date:
3525
+ return Coerce.date(value);
3526
+ case CoerceType.DateTime:
3527
+ return Coerce.dateTime(value);
3528
+ case CoerceType.Time:
3529
+ return Coerce.time(value);
3530
+ case CoerceType.Object:
3531
+ return Coerce.object(value);
3532
+ case CoerceType.Uint8Array:
3533
+ return Coerce.uint8Array(value);
3534
+ default:
3535
+ return value;
2855
3536
  }
2856
- return obj;
2857
3537
  }
3538
+ }
3539
+
3540
+ // Copyright 2024 IOTA Stiftung.
3541
+ // SPDX-License-Identifier: Apache-2.0.
3542
+ /**
3543
+ * Class to help with filenames.
3544
+ */
3545
+ class FilenameHelper {
2858
3546
  /**
2859
- * Omit a subset of properties from an object.
2860
- * @param obj The object to omit the properties from.
2861
- * @param keys The property keys to omit.
2862
- * @returns The partial object.
3547
+ * Replaces any unsafe characters in the filename.
3548
+ * @param filename The filename to make safe.
3549
+ * @returns The safe filename.
2863
3550
  */
2864
- static omit(obj, keys) {
2865
- if (Is.object(obj) && Is.arrayValue(keys)) {
2866
- const result = { ...obj };
2867
- for (const key of keys) {
2868
- delete result[key];
2869
- }
2870
- return result;
3551
+ static safeFilename(filename) {
3552
+ let safe = Coerce.string(filename);
3553
+ if (Is.empty(safe)) {
3554
+ return "";
2871
3555
  }
2872
- return obj;
3556
+ // Common non filename characters
3557
+ safe = safe.replace(/["*/:<>?\\|]/g, "_");
3558
+ // Windows non filename characters
3559
+ safe = safe.replace(/^(con|prn|aux|nul|com\d|lpt\d)$/i, "_");
3560
+ // Control characters
3561
+ safe = safe.replace(/[\u0000-\u001F\u0080-\u009F]/g, "_");
3562
+ // Relative paths
3563
+ safe = safe.replace(/^\.+/, "_");
3564
+ // Trailing periods
3565
+ safe = safe.replace(/\.+$/, "");
3566
+ return safe;
2873
3567
  }
2874
3568
  }
2875
3569
 
@@ -2891,6 +3585,32 @@ class RandomHelper {
2891
3585
  }
2892
3586
  }
2893
3587
 
3588
+ // Copyright 2024 IOTA Stiftung.
3589
+ // SPDX-License-Identifier: Apache-2.0.
3590
+ /**
3591
+ * Class to help with uint8 arrays.
3592
+ */
3593
+ class Uint8ArrayHelper {
3594
+ /**
3595
+ * Concatenate multiple arrays.
3596
+ * @param arrays The array to concatenate.
3597
+ * @returns The combined array.
3598
+ */
3599
+ static concat(arrays) {
3600
+ let totalLength = 0;
3601
+ for (const array of arrays) {
3602
+ totalLength += array.length;
3603
+ }
3604
+ const concatBytes = new Uint8Array(totalLength);
3605
+ let offset = 0;
3606
+ for (const array of arrays) {
3607
+ concatBytes.set(array, offset);
3608
+ offset += array.length;
3609
+ }
3610
+ return concatBytes;
3611
+ }
3612
+ }
3613
+
2894
3614
  // Copyright 2024 IOTA Stiftung.
2895
3615
  // SPDX-License-Identifier: Apache-2.0.
2896
3616
  /**
@@ -2903,7 +3623,7 @@ const CompressionType = {
2903
3623
  */
2904
3624
  Gzip: "gzip",
2905
3625
  /**
2906
- * deflate.
3626
+ * Deflate.
2907
3627
  */
2908
3628
  Deflate: "deflate"
2909
3629
  };
@@ -3354,29 +4074,93 @@ class Urn {
3354
4074
  * Cache the results from asynchronous requests.
3355
4075
  */
3356
4076
  class AsyncCache {
3357
- /**
3358
- * Cache for the fetch requests.
3359
- * @internal
3360
- */
3361
- static _cache = {};
3362
4077
  /**
3363
4078
  * Execute an async request and cache the result.
3364
4079
  * @param key The key for the entry in the cache.
3365
4080
  * @param ttlMs The TTL of the entry in the cache.
3366
4081
  * @param requestMethod The method to call if not cached.
4082
+ * @param cacheFailures Cache failure results, defaults to false.
3367
4083
  * @returns The response.
3368
4084
  */
3369
- static exec(key, ttlMs, requestMethod) {
4085
+ static exec(key, ttlMs, requestMethod, cacheFailures) {
3370
4086
  const cacheEnabled = Is.integer(ttlMs) && ttlMs >= 0;
3371
4087
  if (cacheEnabled) {
3372
4088
  AsyncCache.cleanupExpired();
3373
- if (!this._cache[key]) {
3374
- this._cache[key] = {
3375
- response: requestMethod(),
3376
- expires: ttlMs === 0 ? 0 : Date.now() + ttlMs
3377
- };
4089
+ const cache = AsyncCache.getSharedCache();
4090
+ // Do we have a cache entry for the key
4091
+ if (cache[key]) {
4092
+ if (!Is.empty(cache[key].result)) {
4093
+ // If the cache has already resulted in a value, resolve it
4094
+ return Promise.resolve(cache[key].result);
4095
+ }
4096
+ else if (!Is.empty(cache[key].error)) {
4097
+ // If the cache has already resulted in an error, reject it
4098
+ return Promise.reject(cache[key].error);
4099
+ }
4100
+ // Otherwise create a promise to return and store the resolver
4101
+ // and rejector in the cache entry, so that we can call then
4102
+ // when the request is done
4103
+ let storedResolve;
4104
+ let storedReject;
4105
+ const wait = new Promise((resolve, reject) => {
4106
+ storedResolve = resolve;
4107
+ storedReject = reject;
4108
+ });
4109
+ if (!Is.empty(storedResolve) && !Is.empty(storedReject)) {
4110
+ cache[key].promiseQueue.push({
4111
+ requestMethod,
4112
+ resolve: storedResolve,
4113
+ reject: storedReject
4114
+ });
4115
+ }
4116
+ return wait;
3378
4117
  }
3379
- return this._cache[key].response;
4118
+ // If we don't have a cache entry, create a new one
4119
+ cache[key] = {
4120
+ promiseQueue: [],
4121
+ expires: ttlMs === 0 ? 0 : Date.now() + ttlMs
4122
+ };
4123
+ // Return a promise that wraps the original request method
4124
+ // so that we can store any results or errors in the cache
4125
+ return new Promise((resolve, reject) => {
4126
+ // Call the request method and store the result
4127
+ requestMethod()
4128
+ // eslint-disable-next-line promise/prefer-await-to-then
4129
+ .then(res => {
4130
+ // If the request was successful, store the result
4131
+ cache[key].result = res;
4132
+ // and resolve both this promise and all the waiters
4133
+ resolve(res);
4134
+ for (const wait of cache[key].promiseQueue) {
4135
+ wait.resolve(res);
4136
+ }
4137
+ return res;
4138
+ })
4139
+ // eslint-disable-next-line promise/prefer-await-to-then
4140
+ .catch((err) => {
4141
+ // Reject the promise
4142
+ reject(err);
4143
+ // Handle the waiters based on the cacheFailures flag
4144
+ if (cacheFailures ?? false) {
4145
+ // If we are caching failures, store the error and reject the waiters
4146
+ cache[key].error = err;
4147
+ for (const wait of cache[key].promiseQueue) {
4148
+ wait.reject(err);
4149
+ }
4150
+ // Clear the waiters so we don't call them again
4151
+ cache[key].promiseQueue = [];
4152
+ }
4153
+ else {
4154
+ // If not caching failures for any queued requests we
4155
+ // have no value to either resolve or reject, so we
4156
+ // just resolve with the original request method
4157
+ for (const wait of cache[key].promiseQueue) {
4158
+ wait.resolve(wait.requestMethod());
4159
+ }
4160
+ delete cache[key];
4161
+ }
4162
+ });
4163
+ });
3380
4164
  }
3381
4165
  }
3382
4166
  /**
@@ -3385,41 +4169,80 @@ class AsyncCache {
3385
4169
  * @returns The item from the cache if it exists.
3386
4170
  */
3387
4171
  static async get(key) {
3388
- return AsyncCache._cache[key]?.response;
4172
+ const cache = AsyncCache.getSharedCache();
4173
+ if (!Is.empty(cache[key].result)) {
4174
+ // If the cache has already resulted in a value, resolve it
4175
+ return cache[key].result;
4176
+ }
4177
+ else if (!Is.empty(cache[key].error)) {
4178
+ // If the cache has already resulted in an error, reject it
4179
+ throw cache[key].error;
4180
+ }
4181
+ }
4182
+ /**
4183
+ * Set an entry into the cache.
4184
+ * @param key The key to set in the cache.
4185
+ * @param value The value to set in the cache.
4186
+ * @param ttlMs The TTL of the entry in the cache in ms, defaults to 1s.
4187
+ * @returns Nothing.
4188
+ */
4189
+ static async set(key, value, ttlMs) {
4190
+ const cache = AsyncCache.getSharedCache();
4191
+ cache[key] = {
4192
+ result: value,
4193
+ promiseQueue: [],
4194
+ expires: Date.now() + (ttlMs ?? 1000)
4195
+ };
3389
4196
  }
3390
4197
  /**
3391
4198
  * Remove an entry from the cache.
3392
4199
  * @param key The key to remove from the cache.
3393
4200
  */
3394
4201
  static remove(key) {
3395
- delete AsyncCache._cache[key];
4202
+ const cache = AsyncCache.getSharedCache();
4203
+ delete cache[key];
3396
4204
  }
3397
4205
  /**
3398
4206
  * Clear the cache.
3399
4207
  * @param prefix Optional prefix to clear only entries with that prefix.
3400
4208
  */
3401
4209
  static clearCache(prefix) {
4210
+ const cache = AsyncCache.getSharedCache();
3402
4211
  if (Is.stringValue(prefix)) {
3403
- for (const entry in this._cache) {
4212
+ for (const entry in cache) {
3404
4213
  if (entry.startsWith(prefix)) {
3405
- delete this._cache[entry];
4214
+ delete cache[entry];
3406
4215
  }
3407
4216
  }
3408
4217
  }
3409
4218
  else {
3410
- AsyncCache._cache = {};
4219
+ SharedStore.set("asyncCache", {});
3411
4220
  }
3412
4221
  }
3413
4222
  /**
3414
4223
  * Perform a cleanup of the expired entries in the cache.
3415
4224
  */
3416
4225
  static cleanupExpired() {
3417
- for (const entry in this._cache) {
3418
- if (AsyncCache._cache[entry].expires > 0 && AsyncCache._cache[entry].expires < Date.now()) {
3419
- delete this._cache[entry];
4226
+ const cache = AsyncCache.getSharedCache();
4227
+ for (const entry in cache) {
4228
+ if (cache[entry].expires > 0 && cache[entry].expires < Date.now()) {
4229
+ delete cache[entry];
3420
4230
  }
3421
4231
  }
3422
4232
  }
4233
+ /**
4234
+ * Get the shared cache.
4235
+ * @returns The shared cache.
4236
+ * @internal
4237
+ */
4238
+ static getSharedCache() {
4239
+ let sharedCache = SharedStore.get("asyncCache");
4240
+ if (Is.undefined(sharedCache)) {
4241
+ sharedCache = {};
4242
+ SharedStore.set("asyncCache", sharedCache);
4243
+ }
4244
+ return sharedCache;
4245
+ }
3423
4246
  }
3424
4247
 
3425
4248
  /**
@@ -3441,15 +4264,14 @@ class Compression {
3441
4264
  Guards.uint8Array(Compression._CLASS_NAME, "bytes", bytes);
3442
4265
  Guards.arrayOneOf(Compression._CLASS_NAME, "type", type, Object.values(CompressionType));
3443
4266
  const blob = new Blob([bytes]);
3444
- const ds = new CompressionStream(type);
3445
- const compressedStream = blob.stream().pipeThrough(ds);
3446
- const compressedBlob = await new Response(compressedStream).blob();
3447
- const ab = await compressedBlob.arrayBuffer();
3448
- const compressedBytes = new Uint8Array(ab);
4267
+ const compressionStream = new CompressionStream(type);
4268
+ const compressionPipe = blob.stream().pipeThrough(compressionStream);
4269
+ const compressedBlob = await new Response(compressionPipe).blob();
4270
+ const compressedBytes = new Uint8Array(await compressedBlob.arrayBuffer());
3449
4271
  // GZIP header contains a byte which specifies the OS the
3450
4272
  // compression was performed on. We set this to 3 (Unix) to ensure
3451
4273
  // that we produce consistent results.
3452
- if (type === "gzip" && compressedBytes.length >= 10) {
4274
+ if (type === CompressionType.Gzip && compressedBytes.length >= 10) {
3453
4275
  compressedBytes[9] = 3;
3454
4276
  }
3455
4277
  return compressedBytes;
@@ -3464,11 +4286,10 @@ class Compression {
3464
4286
  Guards.uint8Array(Compression._CLASS_NAME, "compressedBytes", compressedBytes);
3465
4287
  Guards.arrayOneOf(Compression._CLASS_NAME, "type", type, Object.values(CompressionType));
3466
4288
  const blob = new Blob([compressedBytes]);
3467
- const ds = new DecompressionStream(type);
3468
- const decompressedStream = blob.stream().pipeThrough(ds);
3469
- const decompressedBlob = await new Response(decompressedStream).blob();
3470
- const ab = await decompressedBlob.arrayBuffer();
3471
- return new Uint8Array(ab);
4289
+ const decompressionStream = new DecompressionStream(type);
4290
+ const decompressionPipe = blob.stream().pipeThrough(decompressionStream);
4291
+ const decompressedBlob = await new Response(decompressionPipe).blob();
4292
+ return new Uint8Array(await decompressedBlob.bytes());
3472
4293
  }
3473
4294
  }
3474
4295
 
@@ -3526,6 +4347,7 @@ class Validation {
3526
4347
  * @param options Additional options for the validation.
3527
4348
  * @param options.minLength The minimum length of the string.
3528
4349
  * @param options.maxLength The maximum length of the string.
4350
+ * @param options.format Specific format to check.
3529
4351
  * @returns True if the value is a valid string.
3530
4352
  */
3531
4353
  static string(property, value, failures, fieldNameResource, options) {
@@ -3544,6 +4366,47 @@ class Validation {
3544
4366
  const maxLimitDefined = Is.integer(maxLength);
3545
4367
  const belowMin = minLimitDefined && value.length < minLength;
3546
4368
  const aboveMax = maxLimitDefined && value.length > maxLength;
4369
+ if (options?.format === "base58" && !Is.stringBase58(value)) {
4370
+ failures.push({
4371
+ property,
4372
+ reason: "validation.beTextBase58",
4373
+ properties: {
4374
+ fieldName: fieldNameResource ?? "validation.defaultFieldName",
4375
+ value
4376
+ }
4377
+ });
4378
+ }
4379
+ else if (options?.format === "base64" && !Is.stringBase64(value)) {
4380
+ failures.push({
4381
+ property,
4382
+ reason: "validation.beTextBase64",
4383
+ properties: {
4384
+ fieldName: fieldNameResource ?? "validation.defaultFieldName",
4385
+ value
4386
+ }
4387
+ });
4388
+ }
4389
+ else if (options?.format === "hex" && !Is.stringHex(value)) {
4390
+ failures.push({
4391
+ property,
4392
+ reason: "validation.beTextHex",
4393
+ properties: {
4394
+ fieldName: fieldNameResource ?? "validation.defaultFieldName",
4395
+ value
4396
+ }
4397
+ });
4398
+ }
4399
+ else if (Is.regexp(options?.format) && !options.format.test(value)) {
4400
+ failures.push({
4401
+ property,
4402
+ reason: "validation.beTextRegExp",
4403
+ properties: {
4404
+ fieldName: fieldNameResource ?? "validation.defaultFieldName",
4405
+ value,
4406
+ format: options?.format
4407
+ }
4408
+ });
4409
+ }
3547
4410
  if (minLimitDefined && maxLimitDefined && (belowMin || aboveMax)) {
3548
4411
  failures.push({
3549
4412
  property,
@@ -4207,16 +5070,19 @@ exports.AlreadyExistsError = AlreadyExistsError;
4207
5070
  exports.ArrayHelper = ArrayHelper;
4208
5071
  exports.AsyncCache = AsyncCache;
4209
5072
  exports.Base32 = Base32;
5073
+ exports.Base58 = Base58;
4210
5074
  exports.Base64 = Base64;
4211
5075
  exports.Base64Url = Base64Url;
4212
5076
  exports.BaseError = BaseError;
4213
5077
  exports.BitString = BitString;
4214
5078
  exports.Coerce = Coerce;
5079
+ exports.CoerceType = CoerceType;
4215
5080
  exports.ComponentFactory = ComponentFactory;
4216
5081
  exports.Compression = Compression;
4217
5082
  exports.CompressionType = CompressionType;
4218
5083
  exports.ConflictError = ConflictError;
4219
5084
  exports.Converter = Converter;
5085
+ exports.EnvHelper = EnvHelper;
4220
5086
  exports.ErrorHelper = ErrorHelper;
4221
5087
  exports.Factory = Factory;
4222
5088
  exports.FilenameHelper = FilenameHelper;
@@ -4232,7 +5098,9 @@ exports.NotImplementedError = NotImplementedError;
4232
5098
  exports.NotSupportedError = NotSupportedError;
4233
5099
  exports.ObjectHelper = ObjectHelper;
4234
5100
  exports.RandomHelper = RandomHelper;
5101
+ exports.SharedStore = SharedStore;
4235
5102
  exports.StringHelper = StringHelper;
5103
+ exports.Uint8ArrayHelper = Uint8ArrayHelper;
4236
5104
  exports.UnauthorizedError = UnauthorizedError;
4237
5105
  exports.UnprocessableError = UnprocessableError;
4238
5106
  exports.Url = Url;