@zohodesk/react-cli 1.1.29-exp.2 → 1.1.29-exp.3

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 (222) hide show
  1. package/README.md +18 -0
  2. package/lib/babel/babel-option-utils/babel-preset-react-option.js +3 -0
  3. package/lib/babel/cmjs-plugins-presets.js +13 -2
  4. package/lib/babel/es-plugins-presets.js +14 -3
  5. package/lib/common/buildEs.js +0 -1
  6. package/lib/common/getEntries.js +13 -2
  7. package/lib/common/getPublicPathConfig.js +6 -0
  8. package/lib/common/index.js +6 -1
  9. package/lib/common/runPreProcess.js +15 -6
  10. package/lib/common/splitChunks.js +21 -2
  11. package/lib/common/sslcertUpdater.js +18 -7
  12. package/lib/common/templateParameters.js +2 -0
  13. package/lib/common/testPattern.js +21 -10
  14. package/lib/common/valueReplacer.js +16 -1
  15. package/lib/configs/jest.config.js +11 -2
  16. package/lib/configs/libAlias.js +16 -10
  17. package/lib/configs/resolvers.js +16 -6
  18. package/lib/configs/webpack.component.umd.config.js +6 -1
  19. package/lib/configs/webpack.css.umd.config.js +14 -6
  20. package/lib/configs/webpack.dev.config.js +14 -1
  21. package/lib/configs/webpack.docs.config.js +9 -1
  22. package/lib/configs/webpack.impact.config.js +8 -1
  23. package/lib/configs/webpack.prod.config.js +17 -4
  24. package/lib/constants.js +18 -9
  25. package/lib/deprecationLogger.js +7 -0
  26. package/lib/hooks/docsProptypeHook.js +8 -4
  27. package/lib/jest/commitedFilesResult.js +46 -4
  28. package/lib/jest/coverageCollector.js +12 -1
  29. package/lib/jest/jsonMaker.js +6 -0
  30. package/lib/jest/preProcessors/cssPreprocessor.js +9 -1
  31. package/lib/jest/preProcessors/jsPreprocessor.js +11 -2
  32. package/lib/jest/preProcessors/otherFilesPreprocessor.js +4 -1
  33. package/lib/jest/result.js +23 -1
  34. package/lib/jest/run.js +18 -7
  35. package/lib/jest/setup.js +60 -8
  36. package/lib/loaderUtils/configsAssetsLoaders.js +12 -2
  37. package/lib/loaderUtils/getCSSLoaders.js +22 -10
  38. package/lib/loaderUtils/getDevJsLoaders.js +13 -4
  39. package/lib/loaderUtils/index.js +4 -1
  40. package/lib/loaderUtils/tests/windowsModification.test.js +1 -0
  41. package/lib/loaderUtils/windowsModification.js +3 -2
  42. package/lib/loaders/__test__/markdownLoader.spec.js +1 -0
  43. package/lib/loaders/composeLoader.js +37 -13
  44. package/lib/loaders/docsLoader.js +12 -1
  45. package/lib/loaders/docsPropsLoader.js +8 -4
  46. package/lib/loaders/enhancedReactLiveConverter.js +23 -2
  47. package/lib/loaders/fileBountryLoader.js +3 -1
  48. package/lib/loaders/fileLoader.js +23 -12
  49. package/lib/loaders/markdownLoader.js +19 -14
  50. package/lib/loaders/reactLiveConvertor.js +15 -5
  51. package/lib/loaders/scriptInstrumentLoader.js +16 -7
  52. package/lib/loaders/selectorMappingLoader.js +26 -7
  53. package/lib/loaders/workerLoader.js +24 -9
  54. package/lib/logger.js +4 -0
  55. package/lib/middlewares/HMRMiddleware.js +27 -13
  56. package/lib/middlewares/SSTMiddleware.js +5 -1
  57. package/lib/pluginUtils/configHtmlWebpackPlugins.js +24 -1
  58. package/lib/pluginUtils/getDevPlugins.js +42 -9
  59. package/lib/pluginUtils/getDocsPlugins.js +13 -3
  60. package/lib/pluginUtils/getLibraryImactPlugins.js +6 -5
  61. package/lib/pluginUtils/getLibraryPlugins.js +8 -2
  62. package/lib/pluginUtils/getProdPlugins.js +47 -8
  63. package/lib/pluginUtils/getServerPlugins.js +8 -2
  64. package/lib/pluginUtils/getUMDCSSPlugins.js +10 -2
  65. package/lib/pluginUtils/getUMDComponentPlugins.js +10 -2
  66. package/lib/pluginUtils/index.js +9 -1
  67. package/lib/plugins/CdnChangePlugin.js +18 -2
  68. package/lib/plugins/CleanupStatsPlugin.js +5 -0
  69. package/lib/plugins/CssOrderControlPlugin.js +6 -3
  70. package/lib/plugins/CustomAttributePlugin.js +19 -14
  71. package/lib/plugins/CustomScriptLoadingStrategyPlugin.js +23 -3
  72. package/lib/plugins/EFCPlugin.js +34 -20
  73. package/lib/plugins/EFCTemplatePlugin.js +30 -19
  74. package/lib/plugins/EfcResourceCleanupPlugin.js +3 -0
  75. package/lib/plugins/EventsHandlingPlugin.js +4 -2
  76. package/lib/plugins/I18NInjectIntoIndexPlugin.js +37 -14
  77. package/lib/plugins/I18nSplitPlugin/I18nDebugPlugin.js +15 -10
  78. package/lib/plugins/I18nSplitPlugin/I18nDependency.js +10 -4
  79. package/lib/plugins/I18nSplitPlugin/I18nDownlodLogic.js +155 -78
  80. package/lib/plugins/I18nSplitPlugin/I18nFilesEmitter.js +81 -198
  81. package/lib/plugins/I18nSplitPlugin/I18nKeysIdentifer.js +23 -12
  82. package/lib/plugins/I18nSplitPlugin/index.js +24 -13
  83. package/lib/plugins/I18nSplitPlugin/utils/collectI18nKeys.js +12 -2
  84. package/lib/plugins/I18nSplitPlugin/utils/getI18nFileUrlPathTemplate.js +1 -0
  85. package/lib/plugins/I18nSplitPlugin/utils/getI18nKeysFormModules.js +5 -0
  86. package/lib/plugins/I18nSplitPlugin/utils/hashUtils.js +8 -1
  87. package/lib/plugins/I18nSplitPlugin/utils/index.js +4 -0
  88. package/lib/plugins/I18nSplitPlugin/utils/propertiesUtils.js +20 -0
  89. package/lib/plugins/I18nSplitPlugin/utils/unicodeConversion.js +1 -0
  90. package/lib/plugins/ManifestPlugin.js +18 -1
  91. package/lib/plugins/MinifyPlugin.js +10 -1
  92. package/lib/plugins/ModuleStatsPlugin.js +24 -1
  93. package/lib/plugins/OptimizeJSPlugin.js +10 -2
  94. package/lib/plugins/PublicPathCallbackPlugin.js +12 -1
  95. package/lib/plugins/PublicPathChangePlugin.js +39 -6
  96. package/lib/plugins/ReportGeneratePlugin.js +32 -5
  97. package/lib/plugins/RequireVariablePublicPlugin.js +8 -1
  98. package/lib/plugins/ResourceHintsPlugin.js +13 -4
  99. package/lib/plugins/RtlSplitPlugin/OverwriteCssPathForRTL.js +17 -12
  100. package/lib/plugins/RtlSplitPlugin/RtlCssPlugin.js +17 -10
  101. package/lib/plugins/RtlSplitPlugin/replaceCssDirTemplate.js +5 -2
  102. package/lib/plugins/ScriptInstrumentPlugin.js +8 -1
  103. package/lib/plugins/SelectorPlugin.js +32 -6
  104. package/lib/plugins/ServiceWorkerPlugin.js +22 -5
  105. package/lib/plugins/ShadowDOMSupportPlugin.js +41 -4
  106. package/lib/plugins/SourceMapHookPlugin.js +12 -2
  107. package/lib/plugins/StatsPlugin.js +14 -0
  108. package/lib/plugins/TPHashMappingPlugin.js +18 -3
  109. package/lib/plugins/UnusedFilesFindPlugin.js +39 -4
  110. package/lib/plugins/VariableConversionCollector.js +42 -15
  111. package/lib/plugins/index.js +20 -1
  112. package/lib/plugins/libraryImpactPlugin.js +33 -1
  113. package/lib/plugins/utils/classHandling.js +6 -0
  114. package/lib/plugins/utils/fileHandling.js +15 -6
  115. package/lib/plugins/utils/tests/fileHandling.test.js +4 -0
  116. package/lib/plugins/variableConvertorUtils.js +29 -14
  117. package/lib/plugins/webpackwatchrunplugin.js +5 -0
  118. package/lib/postcss-plugins/EmptyPlugin.js +4 -3
  119. package/lib/postcss-plugins/ExcludePlugin.js +5 -1
  120. package/lib/postcss-plugins/IncludePlugin.js +5 -1
  121. package/lib/postcss-plugins/RTLSplitPlugin.js +27 -14
  122. package/lib/postcss-plugins/SelectorReplace.js +16 -1
  123. package/lib/postcss-plugins/ValueReplacer.js +6 -7
  124. package/lib/postcss-plugins/__test__/hoverActivePlugin.spec.js +3 -0
  125. package/lib/postcss-plugins/__test__/selectorReplace.test.js +3 -6
  126. package/lib/postcss-plugins/__test__/valueReplacer.spec.js +5 -2
  127. package/lib/postcss-plugins/hoverActivePlugin.js +67 -31
  128. package/lib/postcss-plugins/variableModificationPlugin/ErrorHandler.js +7 -0
  129. package/lib/postcss-plugins/variableModificationPlugin/index.js +49 -28
  130. package/lib/schemas/index.js +10 -3
  131. package/lib/servers/clusterHubServer.js +11 -1
  132. package/lib/servers/devBuild.js +26 -14
  133. package/lib/servers/docsServer.js +3 -1
  134. package/lib/servers/docsServerCore.js +22 -1
  135. package/lib/servers/getCliPath.js +9 -0
  136. package/lib/servers/helpServer.js +6 -1
  137. package/lib/servers/httpsOptions.js +8 -2
  138. package/lib/servers/impactServer.js +35 -3
  139. package/lib/servers/mockserver.js +10 -1
  140. package/lib/servers/nowatchserver.js +37 -12
  141. package/lib/servers/requireLocalOrGlobal.js +17 -6
  142. package/lib/servers/scrServer.js +21 -14
  143. package/lib/servers/server.js +36 -6
  144. package/lib/servers/ssServer.js +17 -1
  145. package/lib/templates/CoverageScriptTemplate.js +14 -0
  146. package/lib/templates/WMSTemplate.js +13 -7
  147. package/lib/templates/linterConstant.js +4 -2
  148. package/lib/utils/babelPresets.js +7 -3
  149. package/lib/utils/clean.js +9 -3
  150. package/lib/utils/copy.js +7 -1
  151. package/lib/utils/copyTimezones.js +9 -1
  152. package/lib/utils/createEventStream.js +6 -1
  153. package/lib/utils/cssClassNameGenerate.js +30 -10
  154. package/lib/utils/cssURLReplacer.js +22 -1
  155. package/lib/utils/dependencyPostPublish.js +10 -1
  156. package/lib/utils/deprecationSupport.js +32 -7
  157. package/lib/utils/fileUtils.js +28 -1
  158. package/lib/utils/folderIterator.js +13 -2
  159. package/lib/utils/getComponents.js +21 -0
  160. package/lib/utils/getCurrentBranch.js +5 -0
  161. package/lib/utils/getDependenciesImpactList.js +22 -1
  162. package/lib/utils/getFileType.js +10 -2
  163. package/lib/utils/getHash.js +8 -1
  164. package/lib/utils/getIp.js +2 -0
  165. package/lib/utils/getOptions.js +53 -16
  166. package/lib/utils/getServerURL.js +10 -1
  167. package/lib/utils/index.js +51 -4
  168. package/lib/utils/init.js +1 -0
  169. package/lib/utils/initPreCommitHook.js +30 -7
  170. package/lib/utils/jsonHelper.js +22 -3
  171. package/lib/utils/libraryImpactConfig.js +5 -2
  172. package/lib/utils/lint/addScripts.js +5 -2
  173. package/lib/utils/lint/checkExistingConfig.js +12 -3
  174. package/lib/utils/lint/copyConfigs.js +3 -0
  175. package/lib/utils/lint/index.js +9 -0
  176. package/lib/utils/lint/lintScripts.js +1 -0
  177. package/lib/utils/lint/lintSetup.js +4 -3
  178. package/lib/utils/lint/lintStagedPreCommitHook.js +1 -0
  179. package/lib/utils/lint/question.js +7 -0
  180. package/lib/utils/lintReporter.js +20 -0
  181. package/lib/utils/log.js +1 -0
  182. package/lib/utils/mailSender.js +8 -1
  183. package/lib/utils/object-manipulation.js +17 -1
  184. package/lib/utils/pullOrigin.js +4 -0
  185. package/lib/utils/reinstallDependencies.js +29 -1
  186. package/lib/utils/removeAttributes.js +8 -1
  187. package/lib/utils/repoClone.js +28 -3
  188. package/lib/utils/request.js +12 -0
  189. package/lib/utils/rtl.js +17 -5
  190. package/lib/utils/selectorReplacer.js +16 -10
  191. package/lib/utils/setEnvVariables.js +2 -0
  192. package/lib/utils/ssTestHack.js +11 -1
  193. package/lib/utils/switchBranch.js +5 -0
  194. package/lib/utils/typeCheck.js +1 -0
  195. package/lib/utils/urlConcat.js +4 -0
  196. package/lib/utils/useExitCleanup.js +10 -9
  197. package/lib/utils/variableConverter.js +31 -22
  198. package/{package-lock.json → npm-shrinkwrap.json} +2333 -2101
  199. package/package.json +3 -2
  200. package/lib/plugins/I18nSplitPlugin/utils/applyMetaManifest.js +0 -279
  201. package/lib/plugins/I18nSplitPlugin/utils/createMetaManifest.js +0 -51
  202. package/lib/plugins/I18nSplitPlugin/utils/createRegularManifest.js +0 -48
  203. package/lib/plugins/newi18nsplitplugin/18nPlugin1.js +0 -306
  204. package/lib/plugins/newi18nsplitplugin/18nPlugin2.js +0 -363
  205. package/lib/plugins/newi18nsplitplugin/18nPlugin3.js +0 -694
  206. package/lib/plugins/newi18nsplitplugin/18nPlugin_hashed.js +0 -1258
  207. package/lib/plugins/newi18nsplitplugin/18nPlugin_working.js +0 -542
  208. package/lib/plugins/newi18nsplitplugin/18nplugin.js +0 -974
  209. package/lib/plugins/newi18nsplitplugin/ChunkManager.js +0 -131
  210. package/lib/plugins/newi18nsplitplugin/GenerateModuleIdToKeysMapPlugin.js +0 -59
  211. package/lib/plugins/newi18nsplitplugin/I18nDiffPlugin.js +0 -262
  212. package/lib/plugins/newi18nsplitplugin/I18nDownloadLogic.js +0 -166
  213. package/lib/plugins/newi18nsplitplugin/I18nPropertiesPlugin.js +0 -111
  214. package/lib/plugins/newi18nsplitplugin/KeyCollector.js +0 -163
  215. package/lib/plugins/newi18nsplitplugin/ManifestGenerator.js +0 -88
  216. package/lib/plugins/newi18nsplitplugin/UnicodeConversionPlugin.js +0 -101
  217. package/lib/plugins/newi18nsplitplugin/constants.js +0 -162
  218. package/lib/plugins/newi18nsplitplugin/utils/I18nKeyHasher.js +0 -78
  219. package/lib/plugins/newi18nsplitplugin/utils/getJsResourceKeys.js +0 -22
  220. package/lib/plugins/newi18nsplitplugin/utils/i18nChunkUtils.js +0 -18
  221. package/lib/plugins/newi18nsplitplugin/utils/manifestGenerator.js +0 -580
  222. package/lib/plugins/newi18nsplitplugin/utils/propertiesUtils.js +0 -54
@@ -1,131 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.ChunkManager = void 0;
7
-
8
- // ChunkManager.js
9
- class ChunkManager {
10
- constructor(options) {
11
- this.maxChunkSize = options.maxChunkSize;
12
- this.minChunkSize = options.minChunkSize;
13
- this.chunkGroups = new Map(); // Track related keys
14
- }
15
- splitChunk(chunkId, keys, numChunks) {
16
- // Group related keys first
17
- const groups = this.groupRelatedKeys(keys);
18
- const newChunks = []; // Create new chunks
19
-
20
- for (let i = 0; i < numChunks; i++) {
21
- newChunks.push({
22
- id: `${chunkId}_${i}`,
23
- keys: [],
24
- size: 0
25
- });
26
- } // Distribute groups to chunks to maintain key locality
27
-
28
- groups.forEach(group => {
29
- const targetChunk = this.findBestChunkForGroup(newChunks, group);
30
- if (targetChunk) {
31
- targetChunk.keys.push(...group);
32
- targetChunk.size += group.length;
33
- }
34
- }); // Balance remaining individual keys
35
-
36
- const ungroupedKeys = this.getUngroupedKeys(keys, groups);
37
- this.distributeKeys(ungroupedKeys, newChunks);
38
- return newChunks;
39
- }
40
- groupRelatedKeys(keys) {
41
- const groups = [];
42
- const keyPrefix = new Map(); // Group by common prefixes first
43
-
44
- keys.forEach(key => {
45
- const prefix = key.split('.')[0];
46
- if (!keyPrefix.has(prefix)) {
47
- keyPrefix.set(prefix, []);
48
- }
49
- keyPrefix.get(prefix).push(key);
50
- }); // Create groups based on size constraints
51
-
52
- keyPrefix.forEach((prefixKeys, prefix) => {
53
- if (prefixKeys.length <= this.maxChunkSize) {
54
- groups.push(prefixKeys);
55
- } else {
56
- // Split large prefix groups
57
- const numSubgroups = Math.ceil(prefixKeys.length / this.maxChunkSize);
58
- const subgroupSize = Math.ceil(prefixKeys.length / numSubgroups);
59
- for (let i = 0; i < prefixKeys.length; i += subgroupSize) {
60
- groups.push(prefixKeys.slice(i, i + subgroupSize));
61
- }
62
- }
63
- });
64
- return groups;
65
- }
66
- findBestChunkForGroup(chunks, group) {
67
- let bestChunk = null;
68
- let bestScore = -1;
69
- chunks.forEach(chunk => {
70
- const score = this.calculateChunkScore(chunk, group);
71
- if (score > bestScore) {
72
- bestScore = score;
73
- bestChunk = chunk;
74
- }
75
- });
76
- return bestChunk;
77
- }
78
- calculateChunkScore(chunk, group) {
79
- // Score based on:
80
- // 1. Available space
81
- // 2. Related keys already in chunk
82
- // 3. Chunk balance
83
- const availableSpace = this.maxChunkSize - chunk.size;
84
- if (availableSpace < group.length) return -1;
85
- let score = 100 * (availableSpace / this.maxChunkSize); // Check for related keys
86
-
87
- const relatedKeys = this.countRelatedKeys(chunk.keys, group);
88
- score += relatedKeys * 10;
89
- return score;
90
- }
91
- countRelatedKeys(existingKeys, newKeys) {
92
- let count = 0;
93
- const prefixes = new Set(newKeys.map(key => key.split('.')[0]));
94
- existingKeys.forEach(key => {
95
- if (prefixes.has(key.split('.')[0])) count++;
96
- });
97
- return count;
98
- }
99
- distributeKeys(keys, chunks) {
100
- // Sort chunks by available space
101
- chunks.sort((a, b) => this.maxChunkSize - a.size - (this.maxChunkSize - b.size));
102
- keys.forEach(key => {
103
- const targetChunk = chunks.find(chunk => chunk.size < this.maxChunkSize);
104
- if (targetChunk) {
105
- targetChunk.keys.push(key);
106
- targetChunk.size++;
107
- }
108
- });
109
- }
110
- mergeChunks(chunk1Id, chunk2Id) {
111
- const chunk1 = this.chunkGroups.get(chunk1Id);
112
- const chunk2 = this.chunkGroups.get(chunk2Id);
113
- if (!chunk1 || !chunk2) return null;
114
- const combinedSize = chunk1.size + chunk2.size;
115
- if (combinedSize > this.maxChunkSize) return null;
116
- const mergedChunk = {
117
- id: `${chunk1Id}_${chunk2Id}_merged`,
118
- keys: [...chunk1.keys, ...chunk2.keys],
119
- size: combinedSize
120
- };
121
- this.chunkGroups.delete(chunk1Id);
122
- this.chunkGroups.delete(chunk2Id);
123
- this.chunkGroups.set(mergedChunk.id, mergedChunk);
124
- return mergedChunk;
125
- }
126
- getUngroupedKeys(allKeys, groups) {
127
- const groupedKeys = new Set(groups.flat());
128
- return allKeys.filter(key => !groupedKeys.has(key));
129
- }
130
- }
131
- exports.ChunkManager = ChunkManager;
@@ -1,59 +0,0 @@
1
- "use strict";
2
-
3
- // GenerateModuleIdToKeysMapPlugin.js (Updated)
4
- const fs = require('fs');
5
- const path = require('path');
6
- class GenerateModuleIdToKeysMapPlugin {
7
- constructor(options = {}) {
8
- this.moduleToKeysMapPath = options.moduleToKeysMapPath || 'module_to_keys_map.json';
9
- this.outputPath = options.outputPath || 'module_id_to_keys_map.json';
10
- }
11
- apply(compiler) {
12
- compiler.hooks.emit.tapAsync('GenerateModuleIdToKeysMapPlugin', (compilation, callback) => {
13
- console.log('[GenerateModuleIdToKeysMapPlugin] Plugin is running.'); // Load the existing module_to_keys_map.json
14
-
15
- let moduleToKeysMap;
16
- try {
17
- const data = fs.readFileSync(this.moduleToKeysMapPath, 'utf8');
18
- moduleToKeysMap = JSON.parse(data); // console.log('[GenerateModuleIdToKeysMapPlugin] moduleToKeysMap loaded.');
19
- } catch (error) {
20
- // console.error(`[GenerateModuleIdToKeysMapPlugin] Error reading ${this.moduleToKeysMapPath}:`, error);
21
- moduleToKeysMap = {};
22
- }
23
- const projectRoot = path.resolve(__dirname, '..'); // Adjust '..' as needed
24
- // Build a mapping from module relative paths to module IDs
25
-
26
- const modulePathToIdMap = new Map();
27
- for (const module of compilation.modules) {
28
- if (module.resource) {
29
- const moduleResource = module.resource;
30
- const relativeModuleResource = path.relative(projectRoot, moduleResource).replace(/\\/g, '/').toLowerCase();
31
- const moduleId = module.id;
32
- modulePathToIdMap.set(relativeModuleResource, moduleId);
33
- }
34
- } // console.log('[GenerateModuleIdToKeysMapPlugin] Available module paths and IDs:');
35
-
36
- for (const [modulePath, moduleId] of modulePathToIdMap.entries()) {// console.log(`Module Path: ${modulePath}, Module ID: ${moduleId}`);
37
- } // Transform module paths in moduleToKeysMap to module IDs
38
-
39
- const moduleIdToKeysMap = {};
40
- for (const [modulePath, keysData] of Object.entries(moduleToKeysMap)) {
41
- const normalizedModulePath = modulePath.replace(/\\/g, '/').toLowerCase();
42
- const moduleId = modulePathToIdMap.get(normalizedModulePath);
43
- if (moduleId == null) {
44
- // console.warn(`[GenerateModuleIdToKeysMapPlugin] Module ID not found for path: ${normalizedModulePath}`);
45
- continue;
46
- }
47
- const moduleIdString = String(moduleId);
48
- moduleIdToKeysMap[moduleIdString] = keysData;
49
- } // Write the module_id_to_keys_map.json
50
-
51
- try {
52
- fs.writeFileSync(this.outputPath, JSON.stringify(moduleIdToKeysMap, null, 2), 'utf8'); // console.log(`[GenerateModuleIdToKeysMapPlugin] Generated ${this.outputPath}`);
53
- } catch (error) {// console.error(`[GenerateModuleIdToKeysMapPlugin] Error writing ${this.outputPath}:`, error);
54
- }
55
- callback();
56
- });
57
- }
58
- }
59
- module.exports = GenerateModuleIdToKeysMapPlugin;
@@ -1,262 +0,0 @@
1
- "use strict";
2
-
3
- // const { RawSource } = require('webpack-sources');
4
- // const fs = require('fs');
5
- // const path = require('path');
6
- // //const axios = require('axios');
7
- // class I18nDiffPlugin {
8
- // constructor(options = {}) {
9
- // const {
10
- // localMetaManifestPath,
11
- // liveMetaManifestUrl,
12
- // i18nAssetsOutputPath,
13
- // i18nDataPath,
14
- // locales = [],
15
- // } = options;
16
- // if (!localMetaManifestPath || !liveMetaManifestUrl || !i18nDataPath) {
17
- // throw new Error('I18nDiffPlugin: Missing required options.');
18
- // }
19
- // this.localMetaManifestPath = localMetaManifestPath;
20
- // this.liveMetaManifestUrl = liveMetaManifestUrl;
21
- // this.i18nAssetsOutputPath = i18nAssetsOutputPath || 'dist/i18n-diff-chunks';
22
- // this.i18nDataPath = i18nDataPath;
23
- // this.locales = locales;
24
- // }
25
- // apply(compiler) {
26
- // compiler.hooks.emit.tapAsync('I18nDiffPlugin', async (compilation, callback) => {
27
- // try {
28
- // // Step 1: Fetch the live CDN meta manifest
29
- // // const liveManifest = await this.fetchLiveManifest();
30
- // const liveManifest = fs.readFileSync("./metaManifest.json", 'utf-8');
31
- // // Step 2: Read the local meta manifest
32
- // const localManifest = this.readLocalManifest();
33
- // // Step 3: Compare manifests to find new or moved keys
34
- // const diffKeys = this.compareManifests(localManifest, liveManifest);
35
- // if (diffKeys.length === 0) {
36
- // console.log('I18nDiffPlugin: No new or moved i18n keys detected.');
37
- // return callback();
38
- // }
39
- // console.log(`I18nDiffPlugin: Found ${diffKeys.length} new or moved i18n keys.`);
40
- // // Step 4: Generate i18n chunks for the diff keys
41
- // await this.generateI18nChunks(compilation, diffKeys);
42
- // // Step 5: Include chunks in build output (handled by emitting assets)
43
- // callback();
44
- // } catch (error) {
45
- // console.error('I18nDiffPlugin: Error during processing:', error);
46
- // callback(error);
47
- // }
48
- // });
49
- // }
50
- // // async fetchLiveManifest() {
51
- // // console.log('I18nDiffPlugin: Fetching live CDN meta manifest...');
52
- // // const response = await axios.get(this.liveMetaManifestUrl);
53
- // // return response.data;
54
- // // }
55
- // readLocalManifest() {
56
- // console.log('I18nDiffPlugin: Reading local meta manifest...');
57
- // const manifestContent = fs.readFileSync(this.localMetaManifestPath, 'utf-8');
58
- // return JSON.parse(manifestContent);
59
- // }
60
- // compareManifests(localManifest, liveManifest) {
61
- // const localKeys = new Set(Object.keys(localManifest));
62
- // const liveKeys = new Set(Object.keys(liveManifest));
63
- // // Identify keys that are in local but not in live (new or moved keys)
64
- // const diffKeys = [...localKeys].filter((key) => !liveKeys.has(key));
65
- // return diffKeys;
66
- // }
67
- // async generateI18nChunks(compilation, diffKeys) {
68
- // console.log('I18nDiffPlugin: Generating i18n chunks for new or moved keys...');
69
- // for (const locale of this.locales) {
70
- // const localeData = await this.loadLocaleData(locale);
71
- // const i18nData = {};
72
- // for (const key of diffKeys) {
73
- // if (localeData[key]) {
74
- // i18nData[key] = localeData[key];
75
- // } else {
76
- // console.warn(`I18nDiffPlugin: Key "${key}" not found in locale "${locale}" data.`);
77
- // }
78
- // }
79
- // const chunkContent = `window.loadI18nChunk(${JSON.stringify(i18nData)});`;
80
- // const chunkFilename = `${this.i18nAssetsOutputPath}/${locale}/i18n-diff-chunk.js`;
81
- // // Ensure the path exists
82
- // const outputPath = path.dirname(chunkFilename);
83
- // if (!fs.existsSync(outputPath)) {
84
- // fs.mkdirSync(outputPath, { recursive: true });
85
- // }
86
- // // Emit the chunk
87
- // compilation.assets[chunkFilename] = new RawSource(chunkContent);
88
- // }
89
- // }
90
- // async loadLocaleData(locale) {
91
- // const localeFilePath = path.join(this.i18nDataPath, `${locale}.json`);
92
- // if (!fs.existsSync(localeFilePath)) {
93
- // throw new Error(`I18nDiffPlugin: Locale data file not found for "${locale}" at "${localeFilePath}".`);
94
- // }
95
- // const content = fs.readFileSync(localeFilePath, 'utf-8');
96
- // return JSON.parse(content);
97
- // }
98
- // }
99
- // module.exports = I18nDiffPlugin;
100
- const {
101
- RawSource
102
- } = require('webpack-sources');
103
- const fs = require('fs');
104
- const path = require('path'); //const getI18nKeysFromModules = require('./utils/getI18nKeysFromModules');
105
-
106
- const {
107
- convertUnicode
108
- } = require('../I18nSplitPlugin/utils/unicodeConversion');
109
- const pluginName = 'I18nDiffPlugin';
110
- class I18nDiffPlugin {
111
- constructor(options = {}) {
112
- const {
113
- localMetaManifestPath,
114
- liveMetaManifestPath,
115
- i18nAssetsOutputPath,
116
- i18nDataPath,
117
- jsonpFunc
118
- } = options;
119
- if (!localMetaManifestPath || !liveMetaManifestPath || !i18nDataPath) {
120
- throw new Error('I18nDiffPlugin: Missing required options.');
121
- }
122
- this.localMetaManifestPath = localMetaManifestPath;
123
- this.liveMetaManifestPath = liveMetaManifestPath;
124
- this.i18nAssetsOutputPath = i18nAssetsOutputPath || 'dist/i18n-diff-chunks';
125
- this.i18nDataPath = i18nDataPath;
126
- this.jsonpFunc = jsonpFunc || 'window.loadI18nChunk';
127
- this.allI18nObject = {};
128
- this.locales = [];
129
- }
130
- apply(compiler) {
131
- compiler.hooks.emit.tapAsync(pluginName, (compilation, callback) => {
132
- try {
133
- // Step 1: Load the live CDN meta manifest
134
- // const liveManifest = this.loadManifest(this.liveMetaManifestPath);
135
- const liveManifest = this.loadManifest("./metaManifest.json"); // Step 2: Read the local meta manifest
136
-
137
- const localManifest = this.loadManifest(this.localMetaManifestPath); // Step 3: Compare manifests to find new or moved keys
138
-
139
- const {
140
- newKeys,
141
- movedKeys
142
- } = this.compareManifests(localManifest, liveManifest);
143
- const diffKeys = [...new Set([...newKeys, ...movedKeys])];
144
- if (diffKeys.length === 0) {
145
- console.log('I18nDiffPlugin: No new or moved i18n keys detected.');
146
- return callback();
147
- }
148
- console.log(`I18nDiffPlugin: Found ${diffKeys.length} new or moved i18n keys.`);
149
- console.log(`New keys: ${newKeys.join(', ')}`);
150
- console.log(`Moved keys: ${movedKeys.join(', ')}`); // Step 4: Load all i18n data
151
-
152
- this.loadAllI18nData(); // Step 5: Generate i18n chunks for the diff keys
153
-
154
- this.generateI18nChunks(compilation, diffKeys);
155
- callback();
156
- } catch (error) {
157
- console.error('I18nDiffPlugin: Error during processing:', error);
158
- callback(error);
159
- }
160
- });
161
- }
162
- loadManifest(manifestPath) {
163
- console.log(`I18nDiffPlugin: Loading manifest from ${manifestPath}...`);
164
- const manifestContent = fs.readFileSync(manifestPath, 'utf-8');
165
- return JSON.parse(manifestContent);
166
- }
167
- compareManifests(localManifest, liveManifest) {
168
- const localKeys = Object.keys(localManifest.keyToCacheGroupMap);
169
- const liveKeys = Object.keys(liveManifest.keyToCacheGroupMap);
170
- const newKeys = localKeys.filter(key => !liveKeys.includes(key));
171
- const movedKeys = localKeys.filter(key => {
172
- if (liveKeys.includes(key)) {
173
- const localGroups = localManifest.keyToCacheGroupMap[key];
174
- const liveGroups = liveManifest.keyToCacheGroupMap[key];
175
- return JSON.stringify(localGroups) !== JSON.stringify(liveGroups);
176
- }
177
- return false;
178
- });
179
- return {
180
- newKeys,
181
- movedKeys
182
- };
183
- } // loadAllI18nData() {
184
- // console.log('I18nDiffPlugin: Loading all i18n data...');
185
- // const files = fs.readdirSync(this.i18nDataPath);
186
- // files.forEach((file) => {
187
- // const locale = path.basename(file, path.extname(file));
188
- // const localeFilePath = path.join(this.i18nDataPath, file);
189
- // const content = fs.readFileSync(localeFilePath, 'utf-8');
190
- // this.allI18nObject[locale] = JSON.parse(content);
191
- // this.locales.push(locale);
192
- // });
193
- // console.log(`I18nDiffPlugin: Locales found: ${this.locales.join(', ')}`);
194
- // }
195
-
196
- loadAllI18nData() {
197
- console.log('I18nDiffPlugin: Loading all i18n data...');
198
- const files = fs.readdirSync(this.i18nDataPath);
199
- files.forEach(file => {
200
- const locale = path.basename(file, path.extname(file));
201
- const localeFilePath = path.join(this.i18nDataPath, file);
202
- const content = fs.readFileSync(localeFilePath, 'utf-8'); // Regular expression to match 'var i18n = {...};'
203
-
204
- const regex = /var\s+i18n\s*=\s*(\{[\s\S]*\});?/;
205
- const match = content.match(regex);
206
- if (match && match[1]) {
207
- const jsonString = match[1];
208
- try {
209
- const i18nData = eval('(' + jsonString + ')'); // Use eval carefully
210
-
211
- this.allI18nObject[locale] = i18nData;
212
- this.locales.push(locale);
213
- } catch (err) {
214
- console.error(`I18nDiffPlugin: Failed to parse i18n data in ${file}:`, err);
215
- }
216
- } else {
217
- console.warn(`I18nDiffPlugin: Could not extract 'i18n' variable from ${file}`);
218
- }
219
- });
220
- console.log(`I18nDiffPlugin: Locales found: ${this.locales.join(', ')}`);
221
- }
222
- generateI18nChunks(compilation, diffKeys) {
223
- console.log('I18nDiffPlugin: Generating i18n chunks for new or moved keys...');
224
- const chunkName = 'i18n-diff-chunk'; // For each locale, generate the i18n chunk
225
-
226
- this.locales.forEach(locale => {
227
- const i18nData = this.getI18nObjectByLocale(diffKeys, locale);
228
- const moduleSource = this.getTemplateString(i18nData);
229
- const filename = path.join(this.i18nAssetsOutputPath, locale, `${chunkName}.js`); // Ensure the path exists
230
-
231
- const outputPath = path.dirname(filename);
232
- if (!fs.existsSync(outputPath)) {
233
- fs.mkdirSync(outputPath, {
234
- recursive: true
235
- });
236
- } // Emit the chunk
237
-
238
- compilation.assets[filename] = new RawSource(moduleSource);
239
- });
240
- }
241
- getI18nObjectByLocale(i18nKeys, locale) {
242
- const data = {};
243
- i18nKeys.forEach(key => {
244
- if (this.allI18nObject[locale][key]) {
245
- data[key] = this.allI18nObject[locale][key];
246
- } else {
247
- console.warn(`I18nDiffPlugin: Key "${key}" not found in locale "${locale}" data.`);
248
- }
249
- });
250
- return data;
251
- }
252
- getTemplateString(i18nObject) {
253
- // const convertedI18nObject = convertUnicode(
254
- // JSON.stringify(i18nObject, null, 0)
255
- // );
256
- const jsonString = JSON.stringify(i18nObject); //console.log('i18nObject:', i18nObject);
257
-
258
- console.log('jsonString:', jsonString);
259
- return `${this.jsonpFunc}(${jsonString});`;
260
- }
261
- }
262
- module.exports = I18nDiffPlugin;
@@ -1,166 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- var _webpack = require("webpack");
8
- var _path = _interopRequireDefault(require("path"));
9
- function _interopRequireDefault(obj) {
10
- return obj && obj.__esModule ? obj : {
11
- default: obj
12
- };
13
- }
14
-
15
- // import { Template } from 'webpack';
16
- // const pluginName = 'I18nDownloadLogic';
17
- // export default class I18nDownloadLogic {
18
- // constructor({ localeVarName = 'document.documentElement.lang', publicPath = '' }) {
19
- // this.options = {
20
- // localeVarName,
21
- // publicPath: publicPath.endsWith('/') ? publicPath : publicPath + '/'
22
- // };
23
- // }
24
- // apply(compiler) {
25
- // compiler.hooks.thisCompilation.tap(pluginName, compilation => {
26
- // const { mainTemplate } = compilation;
27
- // mainTemplate.hooks.requireEnsure.tap(pluginName, (source, chunk, hash) => {
28
- // return Template.asString([
29
- // source.replace(
30
- // 'var promise = new Promise(function(resolve, reject) {',
31
- // 'var originalPromise = new Promise(function(resolve, reject) {'
32
- // ),
33
- // '',
34
- // '// I18n chunk loading logic',
35
- // '(function(chunkId, promises) {',
36
- // Template.indent([
37
- // `var locale = ${this.options.localeVarName};`,
38
- // 'if (!__webpack_require__.i18n) {',
39
- // Template.indent([
40
- // '__webpack_require__.i18n = {',
41
- // ' loaded: {},',
42
- // ' manifest: null,',
43
- // ' manifestLoading: null,',
44
- // ' loadManifest: function() {',
45
- // ' var self = this;',
46
- // ' if (this.manifest) return Promise.resolve(this.manifest);',
47
- // ' if (this.manifestLoading) return this.manifestLoading;',
48
- // '',
49
- // ' console.log("[I18N] Fetching manifest...");',
50
- // ' this.manifestLoading = fetch(__webpack_require__.p + "i18n-manifest.json")',
51
- // ' .then(function(res) {',
52
- // ' if (!res.ok) throw new Error("Failed to load manifest: " + res.status);',
53
- // ' return res.json();',
54
- // ' })',
55
- // ' .then(function(data) {',
56
- // ' console.log("[I18N] Manifest loaded:", data);',
57
- // ' self.manifest = data;',
58
- // ' self.manifestLoading = null;',
59
- // ' return data;',
60
- // ' })',
61
- // ' .catch(function(error) {',
62
- // ' console.error("[I18N] Manifest load failed:", error);',
63
- // ' self.manifestLoading = null;',
64
- // ' throw error;',
65
- // ' });',
66
- // '',
67
- // ' return this.manifestLoading;',
68
- // ' },',
69
- // ' getChunkI18nFile: function(chunkId, locale) {',
70
- // ' try {',
71
- // ' if (!this.manifest || !this.manifest.locales) return null;',
72
- // ' var localeData = this.manifest.locales[locale];',
73
- // ' return localeData && localeData[chunkId];',
74
- // ' } catch (e) {',
75
- // ' console.error("[I18N] Error getting chunk file:", e);',
76
- // ' return null;',
77
- // ' }',
78
- // ' },',
79
- // ' loadChunkI18n: function(chunkId, locale) {',
80
- // ' var self = this;',
81
- // ' var key = chunkId + "_" + locale;',
82
- // '',
83
- // ' if (this.loaded[key]) {',
84
- // ' return Promise.resolve();',
85
- // ' }',
86
- // '',
87
- // ' return new Promise(function(resolve, reject) {',
88
- // ' var i18nFile = self.getChunkI18nFile(chunkId, locale);',
89
- // ' if (!i18nFile) {',
90
- // ' // Not an error - this chunk might not have i18n data',
91
- // ' console.log("[I18N] No i18n file for chunk:", chunkId);',
92
- // ' resolve();',
93
- // ' return;',
94
- // ' }',
95
- // '',
96
- // ' var script = document.createElement("script");',
97
- // ' script.charset = "utf-8";',
98
- // ' script.setAttribute("data-chunk-id", chunkId);',
99
- // '',
100
- // ' script.onload = function() {',
101
- // ' self.loaded[key] = true;',
102
- // ' resolve();',
103
- // ' };',
104
- // '',
105
- // ' script.onerror = function(error) {',
106
- // ' console.error("[I18N] Failed to load chunk i18n:", chunkId, error);',
107
- // ' // Don\'t reject - we don\'t want to block chunk loading',
108
- // ' resolve();',
109
- // ' };',
110
- // '',
111
- // ' script.src = __webpack_require__.p + i18nFile;',
112
- // ' document.head.appendChild(script);',
113
- // ' });',
114
- // ' }',
115
- // '};'
116
- // ]),
117
- // '}',
118
- // '',
119
- // '// Load i18n data for this chunk if needed',
120
- // 'if (promises && Array.isArray(promises)) {',
121
- // ' promises.push(',
122
- // ' __webpack_require__.i18n.loadManifest()',
123
- // ' .then(function() {',
124
- // ' return __webpack_require__.i18n.loadChunkI18n(chunkId, locale);',
125
- // ' })',
126
- // ' .catch(function(error) {',
127
- // ' console.warn("[I18N] Failed to load i18n for chunk:", chunkId, error);',
128
- // ' })',
129
- // ' );',
130
- // '}'
131
- // ]),
132
- // '})(__webpack_require__.u ? chunkId : (typeof chunkId === "number" ? "" + chunkId : chunkId), promises);'
133
- // ]);
134
- // });
135
- // });
136
- // }
137
- // }
138
- const pluginName = 'I18nDownloadLogic';
139
- class I18nDownloadLogic {
140
- constructor({
141
- filenameTemplate = 'i18n-chunk/[locale]/[name].[chunkhash].i18n.js',
142
- publicPath = '',
143
- localeVarName = 'document.documentElement.lang',
144
- locales = []
145
- }) {
146
- this.locales = locales;
147
- this.publicPath = publicPath;
148
- this.options = {
149
- filenameTemplate,
150
- localeVarName
151
- };
152
- }
153
- apply(compiler) {
154
- compiler.hooks.thisCompilation.tap(pluginName, compilation => {
155
- const {
156
- mainTemplate
157
- } = compilation;
158
- mainTemplate.hooks.requireEnsure.tap(pluginName, (source, chunk, hash) => {
159
- return _webpack.Template.asString([source, '', '// I18n chunk loading logic', '(function() {', _webpack.Template.indent([
160
- // Initialize loading state tracking
161
- 'if (!__webpack_require__.i18n) {', _webpack.Template.indent(['__webpack_require__.i18n = {', ' // Track loaded chunks by locale', ' loaded: {},', '', ' // Current and fallback manifests', ' manifest: null,', ' fallbackManifest: null,', '', ' // Load manifest with fallback support', ' loadManifest: function() {', ' var self = this;', ' if (this.manifest) return Promise.resolve(this.manifest);', '', ' return fetch(__webpack_require__.p + "i18n-manifest.json")', ' .then(function(res) {', ' if (!res.ok) throw new Error("No manifest");', ' return res.json();', ' })', ' .then(function(data) {', ' self.manifest = data;', ' return data;', ' })', ' .catch(function(error) {', ' return fetch(__webpack_require__.p + "i18n-manifest.main.json")', ' .then(function(res) { return res.json(); })', ' .then(function(data) {', ' self.fallbackManifest = data;', ' return self.manifest || data;', ' });', ' });', ' },', '', ' // Find which chunk contains a key', ' findChunkForKey: function(key) {', ' // Check current manifest first', ' if (this.manifest && this.manifest.chunks) {', ' for (var chunk in this.manifest.chunks) {', ' if (this.manifest.chunks[chunk].includes(key)) {', ' return chunk;', ' }', ' }', ' }', '', ' // Check key movement history', ' if (this.manifest && this.manifest.keyMovements && this.manifest.keyMovements[key]) {', ' return this.manifest.keyMovements[key].newChunk;', ' }', '', ' // Check fallback manifest', ' if (this.fallbackManifest && this.fallbackManifest.chunks) {', ' for (var chunk in this.fallbackManifest.chunks) {', ' if (this.fallbackManifest.chunks[chunk].includes(key)) {', ' return chunk;', ' }', ' }', ' }', '', ' return null;', ' },', '', ' // Get all keys for a chunk including moved keys', ' loadChunkKeys: function(chunkId) {', ' var keys = [];', ' if (this.manifest && this.manifest.chunks[chunkId]) {', ' keys = keys.concat(this.manifest.chunks[chunkId]);', ' }', '', ' // Add keys that were moved to this chunk', ' if (this.manifest && this.manifest.keyMovements) {', ' Object.entries(this.manifest.keyMovements)', ' .forEach(function([key, movement]) {', ' if (movement.newChunk === chunkId) {', ' keys.push(key);', ' }', ' });', ' }', '', ' return keys;', ' },', '', ' // Load a chunk for a specific locale', ' loadLocaleChunk: function(chunkId, locale) {', ' var self = this;', ' var loadedKey = chunkId + "_" + locale;', '', ' if (self.loaded[loadedKey]) {', ' return Promise.resolve();', ' }', '', ' return this.loadManifest().then(function(manifest) {', ' var chunkPath = manifest.locales[locale][chunkId];', ' if (!chunkPath) {', ' console.warn("No i18n chunk found for", {chunkId: chunkId, locale: locale});', ' return Promise.resolve();', ' }', '', ' return new Promise(function(resolve, reject) {', ' var script = document.createElement("script");', ' script.charset = "utf-8";', ' script.timeout = 120;', ' script.src = __webpack_require__.p + chunkPath;', '', ' var timeout = setTimeout(function() {', ' onScriptError({ type: "timeout", target: script });', ' }, 120000);', '', ' function onScriptComplete() {', ' script.onerror = script.onload = null;', ' clearTimeout(timeout);', ' self.loaded[loadedKey] = true;', ' resolve();', ' }', '', ' function onScriptError(event) {', ' script.onerror = script.onload = null;', ' clearTimeout(timeout);', ' var errorType = event && event.type;', ' var realSrc = event && event.target && event.target.src;', ' var error = new Error("Loading i18n chunk " + chunkId + " failed.\\n(" + errorType + ": " + realSrc + ")");', ' error.type = errorType;', ' error.request = realSrc;', ' reject(error);', ' }', '', ' script.onerror = onScriptError;', ' script.onload = onScriptComplete;', '', ' document.head.appendChild(script);', ' });', ' });', ' }', '};']), '}', '', '// Load i18n for the current chunk', 'var locale = ' + this.options.localeVarName + ';', 'if (locale && chunkId) {', _webpack.Template.indent(['promises.push(__webpack_require__.i18n.loadLocaleChunk(chunkId, locale));']), '}']), '})();']);
162
- });
163
- });
164
- }
165
- }
166
- exports.default = I18nDownloadLogic;