mcard-js 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +117 -0
  3. package/dist/__mocks__/better-sqlite3.js +20 -0
  4. package/dist/__mocks__/better-sqlite3.js.map +1 -0
  5. package/dist/config/config_constants.js +188 -0
  6. package/dist/config/config_constants.js.map +1 -0
  7. package/dist/config/env_parameters.js +62 -0
  8. package/dist/config/env_parameters.js.map +1 -0
  9. package/dist/content/model/content_type_detector.js +89 -0
  10. package/dist/content/model/content_type_detector.js.map +1 -0
  11. package/dist/core/card-collection.js +279 -0
  12. package/dist/core/card-collection.js.map +1 -0
  13. package/dist/core/event-producer.js +132 -0
  14. package/dist/core/event-producer.js.map +1 -0
  15. package/dist/core/g_time.js +201 -0
  16. package/dist/core/g_time.js.map +1 -0
  17. package/dist/core/hash/enums.js +19 -0
  18. package/dist/core/hash/enums.js.map +1 -0
  19. package/dist/core/hash/validator.js +260 -0
  20. package/dist/core/hash/validator.js.map +1 -0
  21. package/dist/core/mcard.js +205 -0
  22. package/dist/core/mcard.js.map +1 -0
  23. package/dist/engine/sqlite_engine.js +723 -0
  24. package/dist/engine/sqlite_engine.js.map +1 -0
  25. package/dist/index.js +10 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/middleware/mcardPersistenceMiddleware.js +45 -0
  28. package/dist/middleware/mcardPersistenceMiddleware.js.map +1 -0
  29. package/dist/models/database_schemas.js +31 -0
  30. package/dist/models/database_schemas.js.map +1 -0
  31. package/dist/services/logger.js +80 -0
  32. package/dist/services/logger.js.map +1 -0
  33. package/dist/services/mcardStorageService.js +36 -0
  34. package/dist/services/mcardStorageService.js.map +1 -0
  35. package/dist/utils/actionHelpers.js +25 -0
  36. package/dist/utils/actionHelpers.js.map +1 -0
  37. package/dist/utils/bufferContentHelper.js +393 -0
  38. package/dist/utils/bufferContentHelper.js.map +1 -0
  39. package/dist/utils/bufferPolyfill.js +198 -0
  40. package/dist/utils/bufferPolyfill.js.map +1 -0
  41. package/dist/utils/content-detection.js +74 -0
  42. package/dist/utils/content-detection.js.map +1 -0
  43. package/dist/utils/content-utils.js +269 -0
  44. package/dist/utils/content-utils.js.map +1 -0
  45. package/dist/utils/content_type_detector copy.js +480 -0
  46. package/dist/utils/content_type_detector copy.js.map +1 -0
  47. package/dist/utils/content_type_detector.js +480 -0
  48. package/dist/utils/content_type_detector.js.map +1 -0
  49. package/dist/utils/cryptoPolyfill.js +166 -0
  50. package/dist/utils/cryptoPolyfill.js.map +1 -0
  51. package/dist/utils/dotenv-browser.js +35 -0
  52. package/dist/utils/dotenv-browser.js.map +1 -0
  53. package/dist/utils/environmentDetector.js +93 -0
  54. package/dist/utils/environmentDetector.js.map +1 -0
  55. package/dist/utils/logWriter.js +27 -0
  56. package/dist/utils/logWriter.js.map +1 -0
  57. package/dist/utils/serviceWorkerManager.js +118 -0
  58. package/dist/utils/serviceWorkerManager.js.map +1 -0
  59. package/dist/utils/test-content-detection.js +79 -0
  60. package/dist/utils/test-content-detection.js.map +1 -0
  61. package/dist/utils/test-detection-fix.js +121 -0
  62. package/dist/utils/test-detection-fix.js.map +1 -0
  63. package/dist/utils/test-format-conversion.js +170 -0
  64. package/dist/utils/test-format-conversion.js.map +1 -0
  65. package/dist/utils/test-mov-viewer.js +57 -0
  66. package/dist/utils/test-mov-viewer.js.map +1 -0
  67. package/dist/utils/testDetection.js +21 -0
  68. package/dist/utils/testDetection.js.map +1 -0
  69. package/dist/utils/textEncoderPolyfill.js +87 -0
  70. package/dist/utils/textEncoderPolyfill.js.map +1 -0
  71. package/package.json +74 -0
  72. package/src/__mocks__/better-sqlite3.js +14 -0
  73. package/src/config/config_constants.js +227 -0
  74. package/src/config/env_parameters.js +69 -0
  75. package/src/content/model/content_type_detector.js +87 -0
  76. package/src/core/card-collection.js +300 -0
  77. package/src/core/event-producer.js +160 -0
  78. package/src/core/g_time.js +215 -0
  79. package/src/core/hash/enums.js +13 -0
  80. package/src/core/hash/validator.js +271 -0
  81. package/src/core/mcard.js +203 -0
  82. package/src/engine/sqlite_engine.js +755 -0
  83. package/src/index.js +10 -0
  84. package/src/middleware/mcardPersistenceMiddleware.js +45 -0
  85. package/src/models/database_schemas.js +26 -0
  86. package/src/services/logger.js +74 -0
  87. package/src/services/mcardStorageService.js +34 -0
  88. package/src/utils/actionHelpers.js +13 -0
  89. package/src/utils/bufferContentHelper.js +436 -0
  90. package/src/utils/bufferPolyfill.js +202 -0
  91. package/src/utils/cn.ts +6 -0
  92. package/src/utils/content-detection.js +66 -0
  93. package/src/utils/content-utils.js +250 -0
  94. package/src/utils/content_type_detector copy.js +501 -0
  95. package/src/utils/content_type_detector.js +501 -0
  96. package/src/utils/cryptoPolyfill.js +180 -0
  97. package/src/utils/dateUtils.ts +18 -0
  98. package/src/utils/dbInitializer.ts +27 -0
  99. package/src/utils/dotenv-browser.js +29 -0
  100. package/src/utils/environmentDetector.js +92 -0
  101. package/src/utils/logWriter.js +20 -0
  102. package/src/utils/serviceWorkerManager.js +122 -0
  103. package/src/utils/stateWatcher.ts +78 -0
  104. package/src/utils/storeAdapter copy.ts +157 -0
  105. package/src/utils/storeAdapter.ts +157 -0
  106. package/src/utils/test-content-detection.js +71 -0
  107. package/src/utils/test-detection-fix.js +136 -0
  108. package/src/utils/test-format-conversion.js +165 -0
  109. package/src/utils/test-mov-viewer.js +59 -0
  110. package/src/utils/testDetection.js +16 -0
  111. package/src/utils/textEncoderPolyfill.js +88 -0
@@ -0,0 +1,201 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = exports.GTime = void 0;
7
+ var _config_constants = require("../config/config_constants.js");
8
+ class GTime {
9
+ /**
10
+ * Get current timestamp in ISO format with hash function and region code
11
+ * @param {string|HashAlgorithm} hashFunction - Hash function to use
12
+ * @returns {string} Formatted timestamp string
13
+ */
14
+ static stampNow(hashFunction) {
15
+ // Use default hash algorithm if no function is provided
16
+ if (hashFunction === null || hashFunction === undefined) {
17
+ hashFunction = _config_constants.HashAlgorithm.DEFAULT;
18
+ }
19
+
20
+ // Convert string to HashAlgorithm if needed
21
+ let normalizedHashFunction = hashFunction;
22
+ if (typeof hashFunction === 'string') {
23
+ const trimmedFunc = hashFunction.toLowerCase().trim();
24
+ if (!Object.values(_config_constants.HashAlgorithm).filter(func => typeof func === 'string').map(func => func.toLowerCase()).includes(trimmedFunc)) {
25
+ throw new Error(`Invalid hash function: ${hashFunction}`);
26
+ }
27
+ try {
28
+ normalizedHashFunction = _config_constants.HashAlgorithm[trimmedFunc.toUpperCase()];
29
+ } catch (error) {
30
+ throw new Error(`Invalid hash function: ${hashFunction}`);
31
+ }
32
+ }
33
+ const now = new Date();
34
+ const year = now.getFullYear();
35
+ const month = String(now.getMonth() + 1).padStart(2, '0');
36
+ const day = String(now.getDate()).padStart(2, '0');
37
+ const hours = String(now.getHours()).padStart(2, '0');
38
+ const minutes = String(now.getMinutes()).padStart(2, '0');
39
+ const seconds = String(now.getSeconds()).padStart(2, '0');
40
+
41
+ // Ensure 6 decimal places for microseconds
42
+ const microseconds = String(Math.floor(performance.now() % 1 * 1000000)).padStart(6, '0').slice(0, 6);
43
+ const timestamp = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${microseconds}Z`;
44
+ const regionCode = Intl.DateTimeFormat().resolvedOptions().timeZone.split('/')[0].toUpperCase();
45
+ return `${normalizedHashFunction}|${timestamp}|${regionCode}`;
46
+ }
47
+
48
+ /**
49
+ * Alias for stampNow to maintain backwards compatibility
50
+ * @param {string|HashAlgorithm} hashFunction - Hash function to use
51
+ * @returns {string} Formatted timestamp string
52
+ */
53
+ static stamp_now(hashFunction) {
54
+ return this.stampNow(hashFunction);
55
+ }
56
+
57
+ /**
58
+ * Get the hash function from the formatted string
59
+ * @param {string} stringValue - Formatted timestamp string
60
+ * @returns {string} Hash function
61
+ */
62
+ static get_hash_function(stringValue) {
63
+ // Validate input is a non-empty string
64
+ if (!stringValue || typeof stringValue !== 'string' || stringValue.trim() === '') {
65
+ throw new Error('Invalid hash function: Empty or non-string input');
66
+ }
67
+
68
+ // Validate exact number of parts
69
+ const parts = stringValue.split('|');
70
+ if (parts.length !== 3) {
71
+ throw new Error('Invalid hash function: Incorrect number of components');
72
+ }
73
+
74
+ // Validate each part is non-empty and has no extra whitespace
75
+ const [hashFunctionStr, timestamp, regionCode] = parts;
76
+ if (!hashFunctionStr || !timestamp || !regionCode) {
77
+ throw new Error('Invalid hash function: Missing components');
78
+ }
79
+
80
+ // Validate hash function format (must be exactly lowercase, no extra whitespace)
81
+ const trimmedHashFunc = hashFunctionStr.trim();
82
+ const validLowercaseHashes = Object.values(_config_constants.HashAlgorithm).filter(func => typeof func === 'string').map(func => func.toLowerCase());
83
+ if (!validLowercaseHashes.includes(trimmedHashFunc) || trimmedHashFunc !== hashFunctionStr) {
84
+ throw new Error(`Invalid hash function: ${hashFunctionStr}`);
85
+ }
86
+
87
+ // Validate timestamp format (strict ISO 8601 with exactly 6 decimal places)
88
+ const timestampRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/;
89
+ const trimmedTimestamp = timestamp.trim();
90
+ if (!timestampRegex.test(trimmedTimestamp) || trimmedTimestamp !== timestamp) {
91
+ throw new Error('Invalid hash function: Incorrect timestamp format');
92
+ }
93
+
94
+ // Validate region code format (must be all uppercase letters, no extra whitespace)
95
+ const trimmedRegionCode = regionCode.trim();
96
+ if (!/^[A-Z]+$/.test(trimmedRegionCode) || trimmedRegionCode !== regionCode) {
97
+ throw new Error('Invalid hash function: Incorrect region code format');
98
+ }
99
+ try {
100
+ return _config_constants.HashAlgorithm[trimmedHashFunc.toUpperCase()];
101
+ } catch (error) {
102
+ throw new Error(`Invalid hash function: ${trimmedHashFunc}`);
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Get the timestamp from the formatted string
108
+ * @param {string} stringValue - Formatted timestamp string
109
+ * @returns {string} Timestamp in ISO format
110
+ */
111
+ static get_timestamp(stringValue) {
112
+ return stringValue.split('|')[1];
113
+ }
114
+
115
+ /**
116
+ * Get the region code from the formatted string
117
+ * @param {string} stringValue - Formatted timestamp string
118
+ * @returns {string} Region code
119
+ */
120
+ static get_region_code(stringValue) {
121
+ return stringValue.split('|')[2];
122
+ }
123
+
124
+ /**
125
+ * Check if the provided hash function is valid
126
+ * @param {string|HashAlgorithm} hashFunction - Hash function to validate
127
+ * @returns {boolean} Whether the hash function is valid
128
+ */
129
+ static is_valid_hash_function(hashFunction) {
130
+ // Strict validation for null or undefined
131
+ if (hashFunction === null || hashFunction === undefined) {
132
+ return false;
133
+ }
134
+
135
+ // Reject any non-string, non-object inputs
136
+ if (typeof hashFunction !== 'string' && typeof hashFunction !== 'object' && typeof hashFunction !== 'boolean') {
137
+ return false;
138
+ }
139
+
140
+ // Reject non-string objects
141
+ if (typeof hashFunction === 'object' && !(hashFunction instanceof String)) {
142
+ return false;
143
+ }
144
+
145
+ // Reject empty strings or whitespace
146
+ if (typeof hashFunction === 'string' && (hashFunction.trim() === '' || hashFunction !== hashFunction.trim())) {
147
+ return false;
148
+ }
149
+
150
+ // For string inputs, be extremely strict
151
+ if (typeof hashFunction === 'string' || hashFunction instanceof String) {
152
+ // Convert to string
153
+ const strFunc = String(hashFunction);
154
+
155
+ // All valid hash functions, lowercase
156
+ const validLowercaseHashes = Object.values(_config_constants.HashAlgorithm).filter(func => typeof func === 'string').map(func => func.toLowerCase());
157
+
158
+ // Reject any input that doesn't match exactly
159
+ const isValid = validLowercaseHashes.includes(strFunc) && strFunc === strFunc.toLowerCase() && strFunc.trim() === strFunc;
160
+
161
+ // Extra checks to reject inputs like 'md 5', 'md5 hash', 'SHA-256', 'MD5', etc.
162
+ if (!isValid || strFunc.includes(' ')) {
163
+ return false;
164
+ }
165
+ return true;
166
+ }
167
+
168
+ // If we reach here, it means the input is a valid HashAlgorithm value
169
+ return Object.values(_config_constants.HashAlgorithm).includes(hashFunction);
170
+ }
171
+
172
+ /**
173
+ * Check if the provided region code is valid
174
+ * @param {string} regionCode - Region code to validate
175
+ * @returns {boolean} Whether the region code is valid
176
+ */
177
+ static is_valid_region_code(regionCode) {
178
+ if (regionCode === null || regionCode === undefined) {
179
+ return false;
180
+ }
181
+ return typeof regionCode === 'string' && regionCode.trim().length > 0 && regionCode.trim() === regionCode.trim().toUpperCase() && regionCode.trim() === regionCode; // No extra whitespace
182
+ }
183
+
184
+ /**
185
+ * Check if the provided timestamp is in ISO format
186
+ * @param {string} timestamp - Timestamp to validate
187
+ * @returns {boolean} Whether the timestamp is in ISO format
188
+ */
189
+ /**
190
+ * Validate ISO 8601 format with 6 decimal places
191
+ * @param {string} timestamp
192
+ * @returns {boolean}
193
+ */
194
+ static is_iso_format(timestamp) {
195
+ const isoRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/;
196
+ return isoRegex.test(timestamp);
197
+ }
198
+ }
199
+ exports.GTime = GTime;
200
+ var _default = exports.default = GTime;
201
+ //# sourceMappingURL=g_time.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"g_time.js","names":["_config_constants","require","GTime","stampNow","hashFunction","undefined","HashAlgorithm","DEFAULT","normalizedHashFunction","trimmedFunc","toLowerCase","trim","Object","values","filter","func","map","includes","Error","toUpperCase","error","now","Date","year","getFullYear","month","String","getMonth","padStart","day","getDate","hours","getHours","minutes","getMinutes","seconds","getSeconds","microseconds","Math","floor","performance","slice","timestamp","regionCode","Intl","DateTimeFormat","resolvedOptions","timeZone","split","stamp_now","get_hash_function","stringValue","parts","length","hashFunctionStr","trimmedHashFunc","validLowercaseHashes","timestampRegex","trimmedTimestamp","test","trimmedRegionCode","get_timestamp","get_region_code","is_valid_hash_function","strFunc","isValid","is_valid_region_code","is_iso_format","isoRegex","exports","_default","default"],"sources":["../../src/core/g_time.js"],"sourcesContent":["import { HashAlgorithm } from '../config/config_constants.js';\n\nexport class GTime {\n /**\n * Get current timestamp in ISO format with hash function and region code\n * @param {string|HashAlgorithm} hashFunction - Hash function to use\n * @returns {string} Formatted timestamp string\n */\n static stampNow(hashFunction) {\n // Use default hash algorithm if no function is provided\n if (hashFunction === null || hashFunction === undefined) {\n hashFunction = HashAlgorithm.DEFAULT;\n }\n\n // Convert string to HashAlgorithm if needed\n let normalizedHashFunction = hashFunction;\n if (typeof hashFunction === 'string') {\n const trimmedFunc = hashFunction.toLowerCase().trim();\n if (!Object.values(HashAlgorithm).filter(func => typeof func === 'string').map(func => func.toLowerCase()).includes(trimmedFunc)) {\n throw new Error(`Invalid hash function: ${hashFunction}`);\n }\n try {\n normalizedHashFunction = HashAlgorithm[trimmedFunc.toUpperCase()];\n } catch (error) {\n throw new Error(`Invalid hash function: ${hashFunction}`);\n }\n }\n\n const now = new Date();\n const year = now.getFullYear();\n const month = String(now.getMonth() + 1).padStart(2, '0');\n const day = String(now.getDate()).padStart(2, '0');\n const hours = String(now.getHours()).padStart(2, '0');\n const minutes = String(now.getMinutes()).padStart(2, '0');\n const seconds = String(now.getSeconds()).padStart(2, '0');\n \n // Ensure 6 decimal places for microseconds\n const microseconds = String(Math.floor(performance.now() % 1 * 1000000)).padStart(6, '0').slice(0, 6);\n\n const timestamp = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${microseconds}Z`;\n const regionCode = Intl.DateTimeFormat().resolvedOptions().timeZone.split('/')[0].toUpperCase();\n\n return `${normalizedHashFunction}|${timestamp}|${regionCode}`;\n }\n\n /**\n * Alias for stampNow to maintain backwards compatibility\n * @param {string|HashAlgorithm} hashFunction - Hash function to use\n * @returns {string} Formatted timestamp string\n */\n static stamp_now(hashFunction) {\n return this.stampNow(hashFunction);\n }\n\n /**\n * Get the hash function from the formatted string\n * @param {string} stringValue - Formatted timestamp string\n * @returns {string} Hash function\n */\n static get_hash_function(stringValue) {\n // Validate input is a non-empty string\n if (!stringValue || typeof stringValue !== 'string' || stringValue.trim() === '') {\n throw new Error('Invalid hash function: Empty or non-string input');\n }\n\n // Validate exact number of parts\n const parts = stringValue.split('|');\n if (parts.length !== 3) {\n throw new Error('Invalid hash function: Incorrect number of components');\n }\n\n // Validate each part is non-empty and has no extra whitespace\n const [hashFunctionStr, timestamp, regionCode] = parts;\n if (!hashFunctionStr || !timestamp || !regionCode) {\n throw new Error('Invalid hash function: Missing components');\n }\n\n // Validate hash function format (must be exactly lowercase, no extra whitespace)\n const trimmedHashFunc = hashFunctionStr.trim();\n const validLowercaseHashes = Object.values(HashAlgorithm).filter(func => typeof func === 'string').map(func => func.toLowerCase());\n \n if (!validLowercaseHashes.includes(trimmedHashFunc) || \n trimmedHashFunc !== hashFunctionStr) {\n throw new Error(`Invalid hash function: ${hashFunctionStr}`);\n }\n\n // Validate timestamp format (strict ISO 8601 with exactly 6 decimal places)\n const timestampRegex = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{6}Z$/;\n const trimmedTimestamp = timestamp.trim();\n \n if (!timestampRegex.test(trimmedTimestamp) || \n trimmedTimestamp !== timestamp) {\n throw new Error('Invalid hash function: Incorrect timestamp format');\n }\n\n // Validate region code format (must be all uppercase letters, no extra whitespace)\n const trimmedRegionCode = regionCode.trim();\n if (!/^[A-Z]+$/.test(trimmedRegionCode) || \n trimmedRegionCode !== regionCode) {\n throw new Error('Invalid hash function: Incorrect region code format');\n }\n\n try {\n return HashAlgorithm[trimmedHashFunc.toUpperCase()];\n } catch (error) {\n throw new Error(`Invalid hash function: ${trimmedHashFunc}`);\n }\n }\n\n /**\n * Get the timestamp from the formatted string\n * @param {string} stringValue - Formatted timestamp string\n * @returns {string} Timestamp in ISO format\n */\n static get_timestamp(stringValue) {\n return stringValue.split('|')[1];\n }\n\n /**\n * Get the region code from the formatted string\n * @param {string} stringValue - Formatted timestamp string\n * @returns {string} Region code\n */\n static get_region_code(stringValue) {\n return stringValue.split('|')[2];\n }\n\n /**\n * Check if the provided hash function is valid\n * @param {string|HashAlgorithm} hashFunction - Hash function to validate\n * @returns {boolean} Whether the hash function is valid\n */\n static is_valid_hash_function(hashFunction) {\n // Strict validation for null or undefined\n if (hashFunction === null || hashFunction === undefined) {\n return false;\n }\n\n // Reject any non-string, non-object inputs\n if (typeof hashFunction !== 'string' && \n typeof hashFunction !== 'object' && \n typeof hashFunction !== 'boolean') {\n return false;\n }\n\n // Reject non-string objects\n if (typeof hashFunction === 'object' && \n !(hashFunction instanceof String)) {\n return false;\n }\n\n // Reject empty strings or whitespace\n if (typeof hashFunction === 'string' && \n (hashFunction.trim() === '' || hashFunction !== hashFunction.trim())) {\n return false;\n }\n\n // For string inputs, be extremely strict\n if (typeof hashFunction === 'string' || hashFunction instanceof String) {\n // Convert to string \n const strFunc = String(hashFunction);\n \n // All valid hash functions, lowercase\n const validLowercaseHashes = Object.values(HashAlgorithm).filter(func => typeof func === 'string').map(func => func.toLowerCase());\n \n // Reject any input that doesn't match exactly\n const isValid = validLowercaseHashes.includes(strFunc) && \n strFunc === strFunc.toLowerCase() && \n strFunc.trim() === strFunc;\n\n // Extra checks to reject inputs like 'md 5', 'md5 hash', 'SHA-256', 'MD5', etc.\n if (!isValid || strFunc.includes(' ')) {\n return false;\n }\n\n return true;\n }\n \n // If we reach here, it means the input is a valid HashAlgorithm value\n return Object.values(HashAlgorithm).includes(hashFunction);\n }\n\n /**\n * Check if the provided region code is valid\n * @param {string} regionCode - Region code to validate\n * @returns {boolean} Whether the region code is valid\n */\n static is_valid_region_code(regionCode) {\n if (regionCode === null || regionCode === undefined) {\n return false;\n }\n\n return typeof regionCode === 'string' && \n regionCode.trim().length > 0 && \n regionCode.trim() === regionCode.trim().toUpperCase() &&\n regionCode.trim() === regionCode; // No extra whitespace\n }\n\n /**\n * Check if the provided timestamp is in ISO format\n * @param {string} timestamp - Timestamp to validate\n * @returns {boolean} Whether the timestamp is in ISO format\n */\n /**\n * Validate ISO 8601 format with 6 decimal places\n * @param {string} timestamp\n * @returns {boolean}\n */\n static is_iso_format(timestamp) {\n const isoRegex =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UAAU,CAAC,CAAC;EAC3C;;EAEA;AACF;AACA;AACA;AACA;EACE;AACF;AACA;AACA;AACA;EACE,OAAOwB,aAAaA,CAACzB,SAAS,EAAE;IAC9B,MAAM0B,QAAQ,GAAG,+CAA+C;IAChE,OAAOA,QAAQ,CAACT,IAAI,CAACjB,SAAS,CAAC;EACjC;AACF;AAAC2B,OAAA,CAAAnE,KAAA,GAAAA,KAAA;AAAA,IAAAoE,QAAA,GAAAD,OAAA,CAAAE,OAAA,GAEcrE,KAAK","ignoreList":[]}
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = exports.HashAlgorithm = void 0;
7
+ // Hash algorithm enums
8
+ const HashAlgorithm = exports.HashAlgorithm = {
9
+ MD5: 'md5',
10
+ SHA1: 'sha1',
11
+ SHA224: 'sha224',
12
+ SHA256: 'sha256',
13
+ SHA384: 'sha384',
14
+ SHA512: 'sha512'
15
+ };
16
+ var _default = exports.default = {
17
+ HashAlgorithm
18
+ };
19
+ //# sourceMappingURL=enums.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enums.js","names":["HashAlgorithm","exports","MD5","SHA1","SHA224","SHA256","SHA384","SHA512","_default","default"],"sources":["../../../src/core/hash/enums.js"],"sourcesContent":["// Hash algorithm enums\nexport const HashAlgorithm = {\n MD5: 'md5',\n SHA1: 'sha1',\n SHA224: 'sha224',\n SHA256: 'sha256',\n SHA384: 'sha384',\n SHA512: 'sha512'\n};\n\nexport default {\n HashAlgorithm\n};\n"],"mappings":";;;;;;AAAA;AACO,MAAMA,aAAa,GAAAC,OAAA,CAAAD,aAAA,GAAG;EAC3BE,GAAG,EAAE,KAAK;EACVC,IAAI,EAAE,MAAM;EACZC,MAAM,EAAE,QAAQ;EAChBC,MAAM,EAAE,QAAQ;EAChBC,MAAM,EAAE,QAAQ;EAChBC,MAAM,EAAE;AACV,CAAC;AAAC,IAAAC,QAAA,GAAAP,OAAA,CAAAQ,OAAA,GAEa;EACbT;AACF,CAAC","ignoreList":[]}
@@ -0,0 +1,260 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ Object.defineProperty(exports, "HASH_ALGORITHM_HIERARCHY", {
7
+ enumerable: true,
8
+ get: function () {
9
+ return _config_constants.HASH_ALGORITHM_HIERARCHY;
10
+ }
11
+ });
12
+ Object.defineProperty(exports, "HashAlgorithm", {
13
+ enumerable: true,
14
+ get: function () {
15
+ return _config_constants.HashAlgorithm;
16
+ }
17
+ });
18
+ Object.defineProperty(exports, "VALID_HASH_FUNCTIONS", {
19
+ enumerable: true,
20
+ get: function () {
21
+ return _config_constants.VALID_HASH_FUNCTIONS;
22
+ }
23
+ });
24
+ exports.default = void 0;
25
+ var _textEncoderPolyfill = require("../../utils/textEncoderPolyfill.js");
26
+ var _bufferPolyfill = require("../../utils/bufferPolyfill.js");
27
+ var _cryptoPolyfill = require("../../utils/cryptoPolyfill.js");
28
+ var _config_constants = require("../../config/config_constants.js");
29
+ // Replace direct crypto import with environment-aware implementation
30
+
31
+ // Check if we're in a browser environment
32
+ const isBrowser = typeof window !== 'undefined';
33
+ class HashValidator {
34
+ /**
35
+ * Constructor for HashValidator
36
+ */
37
+ constructor(content, hashAlgorithm = _config_constants.HashAlgorithm.DEFAULT) {
38
+ // Convert content to Buffer/Uint8Array if it's a string
39
+ this.content = _bufferPolyfill.SafeBuffer.isBuffer(content) ? content : (0, _textEncoderPolyfill.encodeText)(content);
40
+ this.hashAlgorithm = this.normalizeHashAlgorithm(hashAlgorithm);
41
+
42
+ // In browser environments, we can't synchronously compute crypto hashes
43
+ if (isBrowser) {
44
+ this.hashValue = "computing...";
45
+ this._computeHashAsync().then(hash => {
46
+ this.hashValue = hash;
47
+ });
48
+ } else {
49
+ this.hashValue = this.computeHash();
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Async computation of hash for browser environments
55
+ * @private
56
+ */
57
+ async _computeHashAsync() {
58
+ const hash = (0, _cryptoPolyfill.createHash)(this.hashAlgorithm);
59
+ hash.update(this.content);
60
+ return await hash.digest('hex');
61
+ }
62
+
63
+ /**
64
+ * Normalizes the hash algorithm input
65
+ * @param {string|Object} hashAlgorithm - The hash algorithm to normalize
66
+ * @returns {string} Normalized hash algorithm
67
+ */
68
+ normalizeHashAlgorithm(hashAlgorithm) {
69
+ // Handle undefined or null input
70
+ if (hashAlgorithm === undefined || hashAlgorithm === null) {
71
+ return _config_constants.HashAlgorithm.DEFAULT || 'sha256';
72
+ }
73
+
74
+ // If input is an object, try to extract the type
75
+ if (typeof hashAlgorithm === 'object') {
76
+ hashAlgorithm = hashAlgorithm.type || hashAlgorithm.value || _config_constants.HashAlgorithm.DEFAULT || 'sha256';
77
+ }
78
+
79
+ // Convert to lowercase string and remove dashes for consistency
80
+ const normalizedAlgo = String(hashAlgorithm).toLowerCase().replace(/-/g, '');
81
+
82
+ // Validate the hash algorithm
83
+ if (!HashValidator.isValidHashFunction(normalizedAlgo)) {
84
+ console.warn(`Invalid hash algorithm: ${normalizedAlgo}, using default instead`);
85
+ return _config_constants.HashAlgorithm.DEFAULT || 'sha256';
86
+ }
87
+ return normalizedAlgo;
88
+ }
89
+
90
+ /**
91
+ * Validates a hash function
92
+ * @param {string} hashFunction - Hash function to validate
93
+ * @returns {boolean} Whether the hash function is valid
94
+ */
95
+ static isValidHashFunction(hashFunction) {
96
+ if (!hashFunction) return false;
97
+ const normalizedFunc = String(hashFunction).toLowerCase().trim();
98
+
99
+ // Accept both formats: with dashes (Web Crypto format) and without dashes (Node.js format)
100
+ const validAlgorithms = [
101
+ // Node.js format
102
+ 'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',
103
+ // Web Crypto format
104
+ 'sha-1', 'sha-256', 'sha-384', 'sha-512'];
105
+ return validAlgorithms.includes(normalizedFunc) || validAlgorithms.includes(normalizedFunc.replace(/-/g, ''));
106
+ }
107
+
108
+ /**
109
+ * Compute hash from content
110
+ * @returns {string|Promise<string>} Computed hash or promise to hash
111
+ */
112
+ computeHash() {
113
+ try {
114
+ const hash = (0, _cryptoPolyfill.createHash)(this.hashAlgorithm);
115
+ hash.update(this.content);
116
+ const result = hash.digest('hex');
117
+
118
+ // Handle the case where result is a Promise
119
+ if (result instanceof Promise) {
120
+ return "computing...";
121
+ }
122
+ return result;
123
+ } catch (e) {
124
+ console.error('Error computing hash:', e);
125
+ return '';
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Getter for hash value
131
+ * @returns {string} Hash value
132
+ */
133
+ getHashValue() {
134
+ return this.hashValue;
135
+ }
136
+
137
+ /**
138
+ * Getter for hash algorithm
139
+ * @returns {string} Hash algorithm
140
+ */
141
+ getHashAlgorithm() {
142
+ return this.hashAlgorithm;
143
+ }
144
+
145
+ /**
146
+ * Static method to compute hash
147
+ * @param {string|Buffer} content - Content to hash
148
+ * @param {string} hashAlgorithm - Algorithm to use
149
+ * @returns {string|Promise<string>} Computed hash or Promise of hash in browser
150
+ */
151
+ static computeHash(content, hashAlgorithm = _config_constants.HashAlgorithm.DEFAULT) {
152
+ const buffer = _bufferPolyfill.SafeBuffer.isBuffer(content) ? content : (0, _textEncoderPolyfill.encodeText)(content);
153
+ const hash = (0, _cryptoPolyfill.createHash)(hashAlgorithm);
154
+ hash.update(buffer);
155
+ return hash.digest('hex');
156
+ }
157
+
158
+ /**
159
+ * Validate hash against an expected hash
160
+ * @param {string} [expectedHash] - Expected hash value
161
+ * @returns {boolean|Promise<boolean>} True if hash matches, false otherwise
162
+ */
163
+ validate(expectedHash) {
164
+ if (!expectedHash) return false;
165
+ if (isBrowser) {
166
+ // In browser, we need to handle async validation
167
+ return this._computeHashAsync().then(computedHash => {
168
+ return computedHash === expectedHash;
169
+ });
170
+ }
171
+ return this.hashValue === expectedHash;
172
+ }
173
+
174
+ /**
175
+ * Return string representation
176
+ * @returns {string} String representation
177
+ */
178
+ toString() {
179
+ return `HashValidator(alg=${this.hashAlgorithm}, hash=${this.hashValue})`;
180
+ }
181
+
182
+ /**
183
+ * Gets the strength order of hash algorithms
184
+ * @returns {string[]} Ordered list of hash algorithms by strength
185
+ */
186
+ getHashAlgorithmStrengthOrder() {
187
+ return [_config_constants.HashAlgorithm.MD5, _config_constants.HashAlgorithm.SHA1, _config_constants.HashAlgorithm.SHA224, _config_constants.HashAlgorithm.SHA256, _config_constants.HashAlgorithm.SHA384, _config_constants.HashAlgorithm.SHA512];
188
+ }
189
+
190
+ /**
191
+ * Gets the strength index of a hash algorithm
192
+ * @param {string} algorithm - Hash algorithm
193
+ * @returns {number} Strength index
194
+ */
195
+ getHashAlgorithmStrength(algorithm) {
196
+ return this.getHashAlgorithmStrengthOrder().indexOf(algorithm);
197
+ }
198
+
199
+ /**
200
+ * Checks if one hash algorithm is stronger than another
201
+ * @param {string} current - Current hash algorithm
202
+ * @param {string} upgrade - Potential upgrade hash algorithm
203
+ * @returns {boolean} Whether the upgrade is stronger
204
+ */
205
+ isStrongerHashAlgorithm(current, upgrade) {
206
+ return this.getHashAlgorithmStrength(upgrade) > this.getHashAlgorithmStrength(current);
207
+ }
208
+
209
+ /**
210
+ * Determines the next hash algorithm in the upgrade path
211
+ * @param {string|Object} currentHashFunction - Current hash function
212
+ * @returns {string} Next hash algorithm
213
+ */
214
+ nextHashFunction(currentHashFunction) {
215
+ const strengthOrder = this.getHashAlgorithmStrengthOrder();
216
+
217
+ // Handle undefined or null input
218
+ if (currentHashFunction === undefined || currentHashFunction === null) {
219
+ return _config_constants.HashAlgorithm.MD5;
220
+ }
221
+
222
+ // Extract hash function value if it's an object
223
+ const currentHash = typeof currentHashFunction === 'object' ? currentHashFunction.value || currentHashFunction.type : currentHashFunction;
224
+
225
+ // Normalize to lowercase
226
+ const normalizedHash = (currentHash || '').toLowerCase();
227
+
228
+ // Find current index
229
+ const currentIndex = strengthOrder.indexOf(normalizedHash);
230
+
231
+ // Special case for SHA512 - wrap around to SHA1
232
+ if (normalizedHash === _config_constants.HashAlgorithm.SHA512) {
233
+ return _config_constants.HashAlgorithm.SHA1;
234
+ }
235
+
236
+ // If not found or last in order, return default (first hash function)
237
+ if (currentIndex === -1 || currentIndex === strengthOrder.length - 1) {
238
+ return _config_constants.HashAlgorithm[strengthOrder[0].toUpperCase()];
239
+ }
240
+
241
+ // Return the next hash function in the order as an enum
242
+ return _config_constants.HashAlgorithm[strengthOrder[currentIndex + 1].toUpperCase()];
243
+ }
244
+
245
+ /**
246
+ * Static method to get supported hash algorithms
247
+ * @returns {string[]} List of supported hash algorithms
248
+ */
249
+ static getSupportedAlgorithms() {
250
+ return [_config_constants.HashAlgorithm.MD5, _config_constants.HashAlgorithm.SHA1, _config_constants.HashAlgorithm.SHA256, _config_constants.HashAlgorithm.SHA512];
251
+ }
252
+ static compute_hash(content, hashAlgorithm = _config_constants.HashAlgorithm.DEFAULT) {
253
+ return HashValidator.computeHash(content, hashAlgorithm);
254
+ }
255
+ static HashAlgorithm = _config_constants.HashAlgorithm;
256
+ static HASH_ALGORITHM_HIERARCHY = _config_constants.HASH_ALGORITHM_HIERARCHY;
257
+ static VALID_HASH_FUNCTIONS = _config_constants.VALID_HASH_FUNCTIONS;
258
+ }
259
+ exports.default = HashValidator;
260
+ //# sourceMappingURL=validator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validator.js","names":["_textEncoderPolyfill","require","_bufferPolyfill","_cryptoPolyfill","_config_constants","isBrowser","window","HashValidator","constructor","content","hashAlgorithm","HashAlgorithm","DEFAULT","SafeBuffer","isBuffer","encodeText","normalizeHashAlgorithm","hashValue","_computeHashAsync","then","hash","computeHash","createHash","update","digest","undefined","type","value","normalizedAlgo","String","toLowerCase","replace","isValidHashFunction","console","warn","hashFunction","normalizedFunc","trim","validAlgorithms","includes","result","Promise","e","error","getHashValue","getHashAlgorithm","buffer","validate","expectedHash","computedHash","toString","getHashAlgorithmStrengthOrder","MD5","SHA1","SHA224","SHA256","SHA384","SHA512","getHashAlgorithmStrength","algorithm","indexOf","isStrongerHashAlgorithm","current","upgrade","nextHashFunction","currentHashFunction","strengthOrder","currentHash","normalizedHash","currentIndex","length","toUpperCase","getSupportedAlgorithms","compute_hash","HASH_ALGORITHM_HIERARCHY","VALID_HASH_FUNCTIONS","exports","default"],"sources":["../../../src/core/hash/validator.js"],"sourcesContent":["// Replace direct crypto import with environment-aware implementation\nimport { encodeText } from '../../utils/textEncoderPolyfill.js';\nimport { SafeBuffer } from '../../utils/bufferPolyfill.js';\nimport { createHash } from '../../utils/cryptoPolyfill.js';\nimport { \n HashAlgorithm, \n HASH_ALGORITHM_HIERARCHY, \n VALID_HASH_FUNCTIONS \n} from '../../config/config_constants.js';\n\n// Check if we're in a browser environment\nconst isBrowser = typeof window !== 'undefined';\n\nexport default class HashValidator {\n /**\n * Constructor for HashValidator\n */\n constructor(content, hashAlgorithm = HashAlgorithm.DEFAULT) {\n // Convert content to Buffer/Uint8Array if it's a string\n this.content = SafeBuffer.isBuffer(content) \n ? content \n : encodeText(content);\n \n this.hashAlgorithm = this.normalizeHashAlgorithm(hashAlgorithm);\n \n // In browser environments, we can't synchronously compute crypto hashes\n if (isBrowser) {\n this.hashValue = \"computing...\";\n this._computeHashAsync().then(hash => {\n this.hashValue = hash;\n });\n } else {\n this.hashValue = this.computeHash();\n }\n }\n \n /**\n * Async computation of hash for browser environments\n * @private\n */\n async _computeHashAsync() {\n const hash = createHash(this.hashAlgorithm);\n hash.update(this.content);\n return await hash.digest('hex');\n }\n\n /**\n * Normalizes the hash algorithm input\n * @param {string|Object} hashAlgorithm - The hash algorithm to normalize\n * @returns {string} Normalized hash algorithm\n */\n normalizeHashAlgorithm(hashAlgorithm) {\n // Handle undefined or null input\n if (hashAlgorithm === undefined || hashAlgorithm === null) {\n return HashAlgorithm.DEFAULT || 'sha256';\n }\n \n // If input is an object, try to extract the type\n if (typeof hashAlgorithm === 'object') {\n hashAlgorithm = hashAlgorithm.type || hashAlgorithm.value || HashAlgorithm.DEFAULT || 'sha256';\n }\n \n // Convert to lowercase string and remove dashes for consistency\n const normalizedAlgo = String(hashAlgorithm).toLowerCase().replace(/-/g, '');\n \n // Validate the hash algorithm\n if (!HashValidator.isValidHashFunction(normalizedAlgo)) {\n console.warn(`Invalid hash algorithm: ${normalizedAlgo}, using default instead`);\n return HashAlgorithm.DEFAULT || 'sha256';\n }\n \n return normalizedAlgo;\n }\n\n /**\n * Validates a hash function\n * @param {string} hashFunction - Hash function to validate\n * @returns {boolean} Whether the hash function is valid\n */\n static isValidHashFunction(hashFunction) {\n if (!hashFunction) return false;\n \n const normalizedFunc = String(hashFunction).toLowerCase().trim();\n \n // Accept both formats: with dashes (Web Crypto format) and without dashes (Node.js format)\n const validAlgorithms = [\n // Node.js format\n 'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',\n // Web Crypto format\n 'sha-1', 'sha-256', 'sha-384', 'sha-512'\n ];\n \n return validAlgorithms.includes(normalizedFunc) || \n validAlgorithms.includes(normalizedFunc.replace(/-/g, ''));\n }\n\n /**\n * Compute hash from content\n * @returns {string|Promise<string>} Computed hash or promise to hash\n */\n computeHash() {\n try {\n const hash = createHash(this.hashAlgorithm);\n hash.update(this.content);\n const result = hash.digest('hex');\n \n // Handle the case where result is a Promise\n if (result instanceof Promise) {\n return \"computing...\";\n }\n \n return result;\n } catch (e) {\n console.error('Error computing hash:', e);\n return '';\n }\n }\n\n /**\n * Getter for hash value\n * @returns {string} Hash value\n */\n getHashValue() {\n return this.hashValue;\n }\n\n /**\n * Getter for hash algorithm\n * @returns {string} Hash algorithm\n */\n getHashAlgorithm() {\n return this.hashAlgorithm;\n }\n\n /**\n * Static method to compute hash\n * @param {string|Buffer} content - Content to hash\n * @param {string} hashAlgorithm - Algorithm to use\n * @returns {string|Promise<string>} Computed hash or Promise of hash in browser\n */\n static computeHash(content, hashAlgorithm = HashAlgorithm.DEFAULT) {\n const buffer = SafeBuffer.isBuffer(content) \n ? content \n : encodeText(content);\n \n const hash = createHash(hashAlgorithm);\n hash.update(buffer);\n return hash.digest('hex');\n }\n\n /**\n * Validate hash against an expected hash\n * @param {string} [expectedHash] - Expected hash value\n * @returns {boolean|Promise<boolean>} True if hash matches, false otherwise\n */\n validate(expectedHash) {\n if (!expectedHash) return false;\n \n if (isBrowser) {\n // In browser, we need to handle async validation\n return this._computeHashAsync().then(computedHash => {\n return computedHash === expectedHash;\n });\n }\n \n return this.hashValue === expectedHash;\n }\n\n /**\n * Return string representation\n * @returns {string} String representation\n */\n toString() {\n return `HashValidator(alg=${this.hashAlgorithm}, hash=${this.hashValue})`;\n }\n\n /**\n * Gets the strength order of hash algorithms\n * @returns {string[]} Ordered list of hash algorithms by strength\n */\n getHashAlgorithmStrengthOrder() {\n return [\n HashAlgorithm.MD5,\n HashAlgorithm.SHA1,\n HashAlgorithm.SHA224,\n HashAlgorithm.SHA256,\n HashAlgorithm.SHA384,\n HashAlgorithm.SHA512\n ];\n }\n\n /**\n * Gets the strength index of a hash algorithm\n * @param {string} algorithm - Hash algorithm\n * @returns {number} Strength index\n */\n getHashAlgorithmStrength(algorithm) {\n return this.getHashAlgorithmStrengthOrder().indexOf(algorithm);\n }\n\n /**\n * Checks if one hash algorithm is stronger than another\n * @param {string} current - Current hash algorithm\n * @param {string} upgrade - Potential upgrade hash algorithm\n * @returns {boolean} Whether the upgrade is stronger\n */\n isStrongerHashAlgorithm(current, upgrade) {\n return this.getHashAlgorithmStrength(upgrade) > this.getHashAlgorithmStrength(current);\n }\n\n /**\n * Determines the next hash algorithm in the upgrade path\n * @param {string|Object} currentHashFunction - Current hash function\n * @returns {string} Next hash algorithm\n */\n nextHashFunction(currentHashFunction) {\n const strengthOrder = this.getHashAlgorithmStrengthOrder();\n\n // Handle undefined or null input\n if (currentHashFunction === undefined || currentHashFunction === null) {\n return HashAlgorithm.MD5;\n }\n\n // Extract hash function value if it's an object\n const currentHash = typeof currentHashFunction === 'object' \n ? currentHashFunction.value || currentHashFunction.type \n : currentHashFunction;\n\n // Normalize to lowercase\n const normalizedHash = (currentHash || '').toLowerCase();\n\n // Find current index\n const currentIndex = strengthOrder.indexOf(normalizedHash);\n\n // Special case for SHA512 - wrap around to SHA1\n if (normalizedHash === HashAlgorithm.SHA512) {\n return HashAlgorithm.SHA1;\n }\n\n // If not found or last in order, return default (first hash function)\n if (currentIndex === -1 || currentIndex === strengthOrder.length - 1) {\n return HashAlgorithm[strengthOrder[0].toUpperCase()];\n }\n\n // Return the next hash function in the order as an enum\n return HashAlgorithm[strengthOrder[currentIndex + 1].toUpperCase()];\n }\n\n /**\n * Static method to get supported hash algorithms\n * @returns {string[]} List of supported hash algorithms\n */\n static getSupportedAlgorithms() {\n return [\n HashAlgorithm.MD5,\n HashAlgorithm.SHA1,\n HashAlgorithm.SHA256,\n HashAlgorithm.SHA512\n ];\n }\n\n static compute_hash(content, hashAlgorithm = HashAlgorithm.DEFAULT) {\n return HashValidator.computeHash(content, hashAlgorithm);\n }\n\n static HashAlgorithm = HashAlgorithm;\n static HASH_ALGORITHM_HIERARCHY = HASH_ALGORITHM_HIERARCHY;\n static VALID_HASH_FUNCTIONS = VALID_HASH_FUNCTIONS;\n}\n\nexport { HashAlgorithm, HASH_ALGORITHM_HIERARCHY, VALID_HASH_FUNCTIONS };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AACA,IAAAA,oBAAA,GAAAC,OAAA;AACA,IAAAC,eAAA,GAAAD,OAAA;AACA,IAAAE,eAAA,GAAAF,OAAA;AACA,IAAAG,iBAAA,GAAAH,OAAA;AAJA;;AAUA;AACA,MAAMI,SAAS,GAAG,OAAOC,MAAM,KAAK,WAAW;AAEhC,MAAMC,aAAa,CAAC;EACjC;AACF;AACA;EACEC,WAAWA,CAACC,OAAO,EAAEC,aAAa,GAAGC,+BAAa,CAACC,OAAO,EAAE;IAC1D;IACA,IAAI,CAACH,OAAO,GAAGI,0BAAU,CAACC,QAAQ,CAACL,OAAO,CAAC,GACvCA,OAAO,GACP,IAAAM,+BAAU,EAACN,OAAO,CAAC;IAEvB,IAAI,CAACC,aAAa,GAAG,IAAI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