@twin.org/core 0.0.1-next.6 → 0.0.1-next.60

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