@flatjs/evolve 2.1.0-next.12 → 2.1.0-next.14

Sign up to get free protection for your applications and to get access to all the features.
Files changed (151) hide show
  1. package/dist/compiler/create-global-compiler.d.ts +2 -0
  2. package/dist/compiler/create-global-compiler.js +1 -0
  3. package/dist/constants.js +1 -36
  4. package/dist/create-webpack/create-externals.js +1 -6
  5. package/dist/create-webpack/create-optimization.js +1 -43
  6. package/dist/create-webpack/create-output.js +1 -35
  7. package/dist/create-webpack/create-performance.js +1 -7
  8. package/dist/create-webpack/create-plugins.js +1 -78
  9. package/dist/create-webpack/create-resolve.js +1 -37
  10. package/dist/create-webpack/create-rule-sets.js +1 -20
  11. package/dist/create-webpack/load-watch-options.d.ts +12 -0
  12. package/dist/create-webpack/load-watch-options.js +1 -0
  13. package/dist/create-webpack/load-webpack-config.js +1 -57
  14. package/dist/create-webpack/resolve-public-path.js +1 -15
  15. package/dist/create-webpack/rule-sets/constants.js +1 -3
  16. package/dist/create-webpack/rule-sets/rule-assets.js +1 -52
  17. package/dist/create-webpack/rule-sets/rule-css.js +1 -111
  18. package/dist/create-webpack/rule-sets/rule-less.js +1 -44
  19. package/dist/create-webpack/rule-sets/rule-scripts.d.ts +2 -0
  20. package/dist/create-webpack/rule-sets/rule-scripts.js +1 -34
  21. package/dist/create-webpack/rule-sets/rule-svg-icon.js +1 -25
  22. package/dist/create-webpack/rule-sets/rule-utils.js +1 -10
  23. package/dist/create-webpack/types.d.ts +1 -1
  24. package/dist/create-webpack/types.js +1 -1
  25. package/dist/default-options.js +1 -83
  26. package/dist/define-config/define-config.d.ts +2 -2
  27. package/dist/define-config/define-config.js +1 -4
  28. package/dist/define-config/index.js +1 -1
  29. package/dist/dev-server/add-compiler-to-dev-server.js +1 -58
  30. package/dist/dev-server/create-app-page-route.js +1 -13
  31. package/dist/dev-server/create-dev-server-compiler-task.js +1 -55
  32. package/dist/dev-server/create-dev-server-entries.js +1 -25
  33. package/dist/dev-server/create-dev-server.js +1 -24
  34. package/dist/dev-server/index.d.ts +3 -3
  35. package/dist/dev-server/index.js +1 -6
  36. package/dist/dev-server/middlewares/create-page-middleware.js +1 -33
  37. package/dist/dev-server/middlewares/create-public-assets-middleware.js +1 -25
  38. package/dist/dev-server/middlewares/get-all-sorted-modules.js +1 -24
  39. package/dist/dev-server/middlewares/get-bundle-asset.js +1 -7
  40. package/dist/dev-server/middlewares/get-dev-server-host-uri.js +1 -5
  41. package/dist/dev-server/middlewares/get-hmr-runtime-chunks.js +1 -14
  42. package/dist/dev-server/middlewares/get-normalized-entry-name.js +1 -14
  43. package/dist/dev-server/middlewares/get-page-main-html.js +1 -49
  44. package/dist/dev-server/middlewares/get-page-module-html.js +1 -123
  45. package/dist/dev-server/middlewares/get-project-virtual-path.js +1 -3
  46. package/dist/dev-server/middlewares/get-runtime-manifest.js +1 -25
  47. package/dist/dev-server/middlewares/index.js +1 -2
  48. package/dist/dev-server/middlewares/types.js +1 -1
  49. package/dist/errors/evolve-build-error.js +1 -10
  50. package/dist/helpers/allow-px2rem-for-module.js +1 -6
  51. package/dist/helpers/assert-group-entry-item.js +1 -19
  52. package/dist/helpers/assert-single-compiler.js +1 -45
  53. package/dist/helpers/chunk-entry-map.js +1 -21
  54. package/dist/helpers/delete-object-keys.js +1 -20
  55. package/dist/helpers/enable-bundle-hashname-for-module.js +1 -6
  56. package/dist/helpers/filter-actived-entries.js +1 -42
  57. package/dist/helpers/flat-entry-map.js +1 -11
  58. package/dist/helpers/get-bundle-file-name.js +1 -23
  59. package/dist/helpers/get-git-root.js +1 -4
  60. package/dist/helpers/get-html-plugin-config.js +1 -47
  61. package/dist/helpers/get-max-process-tasks.js +1 -7
  62. package/dist/helpers/get-pacakge-dir.js +1 -13
  63. package/dist/helpers/get-runtime-cdn-base.d.ts +1 -1
  64. package/dist/helpers/get-runtime-cdn-base.js +1 -21
  65. package/dist/helpers/index.d.ts +11 -11
  66. package/dist/helpers/index.js +1 -27
  67. package/dist/helpers/is-deep-equal.js +1 -67
  68. package/dist/helpers/json-serializer.js +1 -52
  69. package/dist/helpers/merge-babel-options.js +1 -45
  70. package/dist/helpers/normalize-check-entry-options.js +1 -28
  71. package/dist/helpers/normalize-entry-map.js +1 -59
  72. package/dist/helpers/normalize-group-name.js +1 -16
  73. package/dist/helpers/normalize-page-proxy.js +1 -9
  74. package/dist/helpers/normalize-resolve-alias.js +1 -7
  75. package/dist/helpers/normalize-template-inject-tokens.js +1 -22
  76. package/dist/helpers/open-page.js +1 -15
  77. package/dist/helpers/print-log.js +1 -49
  78. package/dist/helpers/refresh-evolve-mock-options.js +1 -34
  79. package/dist/helpers/resolve-entry-map-input-files.js +1 -20
  80. package/dist/helpers/script-injects.d.ts +1 -1
  81. package/dist/helpers/script-injects.js +1 -39
  82. package/dist/helpers/should-enable-react-fast-refresh.js +1 -14
  83. package/dist/helpers/split-to-entry-group.d.ts +1 -1
  84. package/dist/helpers/split-to-entry-group.js +1 -139
  85. package/dist/helpers/verify-group-entry-options.js +1 -21
  86. package/dist/index.d.ts +1 -1
  87. package/dist/index.js +1 -5
  88. package/dist/load-config/index.js +1 -1
  89. package/dist/load-config/load-evolve-config.js +1 -41
  90. package/dist/load-config/types.js +1 -1
  91. package/dist/loaders/loader-icon.cjs +2 -1
  92. package/dist/main/create-thread-worker.js +1 -51
  93. package/dist/main/env-verify.js +1 -21
  94. package/dist/main/get-worker-path.js +1 -5
  95. package/dist/main/index.d.ts +1 -1
  96. package/dist/main/index.js +1 -4
  97. package/dist/main/prepare-build.js +1 -39
  98. package/dist/main/prepare-serve.js +1 -69
  99. package/dist/main/prepare-static.js +1 -30
  100. package/dist/main/start-build-dynamic.js +1 -171
  101. package/dist/main/start-build-worker.js +1 -44
  102. package/dist/main/start-build.js +1 -69
  103. package/dist/main/start-group-entry-build.d.ts +1 -1
  104. package/dist/main/start-group-entry-build.js +1 -32
  105. package/dist/main/start-serve.js +1 -34
  106. package/dist/main/start-static.js +1 -19
  107. package/dist/minimizer/create-minimizers.js +1 -25
  108. package/dist/minimizer/default-options.js +1 -14
  109. package/dist/minimizer/image-minimizer.js +1 -65
  110. package/dist/minimizer/index.js +1 -1
  111. package/dist/minimizer/terser-minimizer.js +3 -15
  112. package/dist/minimizer/types.js +1 -1
  113. package/dist/plugins/circular-dependency/circular-dependency-plugin.js +1 -119
  114. package/dist/plugins/circular-dependency/index.js +1 -15
  115. package/dist/plugins/clean-webpack/clean-webpack-plugin.js +1 -173
  116. package/dist/plugins/clean-webpack/index.js +1 -22
  117. package/dist/plugins/define-variable/define-variable-plugin.js +1 -28
  118. package/dist/plugins/define-variable/index.js +1 -1
  119. package/dist/plugins/html-inject-scripts/plugin-html-inject-script.js +1 -27
  120. package/dist/plugins/module-federation/external-template-remotes.js +1 -92
  121. package/dist/plugins/module-federation/index.js +1 -1
  122. package/dist/plugins/module-federation/module-federation.js +1 -100
  123. package/dist/plugins/multi-html/index.js +1 -16
  124. package/dist/plugins/multi-html/multi-html-cdn-plugin.js +1 -83
  125. package/dist/plugins/multi-html/multi-html-plugin.js +1 -65
  126. package/dist/plugins/ts-checker/ts-checker-guard-plugin.d.ts +13 -0
  127. package/dist/plugins/ts-checker/ts-checker-guard-plugin.js +1 -0
  128. package/dist/plugins/ts-checker/ts-checker-plugin.d.ts +1 -2
  129. package/dist/plugins/ts-checker/ts-checker-plugin.js +1 -24
  130. package/dist/types/index.d.ts +2 -1
  131. package/dist/types/index.js +1 -8
  132. package/dist/types/types-ci.js +1 -1
  133. package/dist/types/types-dev-server.d.ts +5 -6
  134. package/dist/types/types-dev-server.js +1 -1
  135. package/dist/types/types-entry-map.js +1 -1
  136. package/dist/types/types-federation.js +1 -1
  137. package/dist/types/types-global-compiler-options.d.ts +7 -0
  138. package/dist/types/types-global-compiler-options.js +1 -0
  139. package/dist/types/types-loader-options.d.ts +2 -7
  140. package/dist/types/types-loader-options.js +1 -1
  141. package/dist/types/types-modular-import.js +1 -1
  142. package/dist/types/types-multi-html.js +1 -1
  143. package/dist/types/types-options.d.ts +6 -1
  144. package/dist/types/types-options.js +1 -1
  145. package/dist/types/types-plugin-options.js +1 -1
  146. package/dist/types/types-threads-options.js +1 -1
  147. package/dist/types/types-webpack.d.ts +1 -1
  148. package/dist/types/types-webpack.js +1 -1
  149. package/package.json +30 -32
  150. package/dist/plugins/ts-checker/index.d.ts +0 -1
  151. package/dist/plugins/ts-checker/index.js +0 -1
@@ -1,119 +1 @@
1
- import { relative } from 'node:path';
2
- import { mergeOptions } from '@flatjs/common';
3
- import Graph from 'tarjan-graph';
4
- import webpack from 'webpack';
5
- const BASE_ERROR = 'Circular dependency detected:\r\n';
6
- const PLUGIN_TITLE = `CircularDependencyPlugin`;
7
- export class CircularDependencyPlugin {
8
- constructor(options = {}) {
9
- this.options = mergeOptions({
10
- exclude: /node_modules/,
11
- include: /.*/,
12
- failOnError: false,
13
- allowAsyncCycles: false,
14
- projectCwd: process.cwd(),
15
- }, options);
16
- }
17
- apply(compiler) {
18
- const cwd = this.options.projectCwd;
19
- // eslint-disable-next-line sonarjs/cognitive-complexity
20
- compiler.hooks.compilation.tap(PLUGIN_TITLE, (compilation) => {
21
- // eslint-disable-next-line sonarjs/cognitive-complexity
22
- compilation.hooks.optimizeModules.tap(PLUGIN_TITLE, (modules) => {
23
- if (this.options.onStart) {
24
- this.options.onStart({ compilation });
25
- }
26
- const dependencyGraph = new (Graph.default || Graph)();
27
- for (const module of modules) {
28
- // Iterate over the current modules dependencies
29
- const dependedModuleIds = [];
30
- for (const dependency of module.dependencies) {
31
- if (dependency.constructor &&
32
- dependency.constructor.name === 'CommonJsSelfReferenceDependency') {
33
- continue;
34
- }
35
- let depModule = null;
36
- if (compilation.moduleGraph) {
37
- // handle getting a module for webpack 5
38
- depModule = compilation.moduleGraph.getModule(dependency);
39
- }
40
- else {
41
- // handle getting a module for webpack 4
42
- depModule = dependency.module;
43
- }
44
- if (!depModule) {
45
- continue;
46
- }
47
- // ignore dependencies that don't have an associated resource
48
- if (!(depModule instanceof webpack.NormalModule) ||
49
- !depModule.resource) {
50
- continue;
51
- }
52
- // optionally ignore dependencies that are resolved asynchronously
53
- if (this.options.allowAsyncCycles && dependency.weak) {
54
- continue;
55
- }
56
- // the dependency was resolved to the current module due to how webpack internals
57
- // setup dependencies like CommonJsSelfReferenceDependency and ModuleDecoratorDependency
58
- if (module === depModule) {
59
- continue;
60
- }
61
- dependedModuleIds.push(depModule.identifier());
62
- }
63
- dependencyGraph.add(module.identifier(), dependedModuleIds);
64
- }
65
- const cycles = dependencyGraph.getCycles();
66
- this.isCyclic(cycles, compilation, cwd);
67
- if (this.options.onEnd) {
68
- this.options.onEnd({ compilation });
69
- }
70
- });
71
- });
72
- }
73
- isCyclic(cycles, compilation, cwd) {
74
- cycles.forEach((vertices) => {
75
- // Convert the array of vertices into an array of module paths
76
- const cyclicAbsolutePaths = vertices
77
- .slice()
78
- .reverse()
79
- .map((vertex) => {
80
- const module = compilation.findModule(vertex.name);
81
- if (!(module instanceof webpack.NormalModule)) {
82
- return null;
83
- }
84
- return module.resource || null;
85
- });
86
- if (cyclicAbsolutePaths.every((resource) => !resource ||
87
- this.options.exclude.test(resource) ||
88
- !this.options.include.test(resource))) {
89
- // If all modules in the cycle are excluded by the config, don't report an error
90
- return;
91
- }
92
- const cyclicPaths = cyclicAbsolutePaths.map((resource) => relative(cwd, resource));
93
- // allow consumers to override all behavior with onDetected
94
- if (this.options.onDetected) {
95
- try {
96
- this.options.onDetected({
97
- paths: cyclicPaths.concat([cyclicPaths[0]]),
98
- compilation: compilation,
99
- });
100
- }
101
- catch (err) {
102
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
103
- compilation.errors.push(err);
104
- }
105
- return;
106
- }
107
- // mark warnings or errors on webpack compilation
108
- const error = new Error(BASE_ERROR.concat(cyclicPaths.concat([cyclicPaths[0]]).join(' -> ')));
109
- if (this.options.failOnError) {
110
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
111
- compilation.errors.push(error);
112
- }
113
- else {
114
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
115
- compilation.warnings.push(error);
116
- }
117
- });
118
- }
119
- }
1
+ import{relative}from"node:path";import Graph from"tarjan-graph";import webpack from"webpack";import{mergeOptions}from"@flatjs/common";const BASE_ERROR="Circular dependency detected:\r\n",PLUGIN_TITLE="CircularDependencyPlugin";export class CircularDependencyPlugin{constructor(o={}){this.options=mergeOptions({exclude:/node_modules/,include:/.*/,failOnError:!1,allowAsyncCycles:!1,projectCwd:process.cwd()},o)}apply(o){const e=this.options.projectCwd;o.hooks.compilation.tap(PLUGIN_TITLE,(o=>{o.hooks.optimizeModules.tap(PLUGIN_TITLE,(t=>{this.options.onStart&&this.options.onStart({compilation:o});const n=new(Graph.default||Graph);for(const e of t){const t=[];for(const n of e.dependencies){if(n.constructor&&"CommonJsSelfReferenceDependency"===n.constructor.name)continue;let r=null;r=o.moduleGraph?o.moduleGraph.getModule(n):n.module,r&&(r instanceof webpack.NormalModule&&r.resource&&(this.options.allowAsyncCycles&&n.weak||e!==r&&t.push(r.identifier())))}n.add(e.identifier(),t)}const r=n.getCycles();this.isCyclic(r,o,e),this.options.onEnd&&this.options.onEnd({compilation:o})}))}))}isCyclic(o,e,t){o.forEach((o=>{const n=o.slice().reverse().map((o=>{const t=e.findModule(o.name);return t instanceof webpack.NormalModule&&t.resource||null}));if(n.every((o=>!o||this.options.exclude.test(o)||!this.options.include.test(o))))return;const r=n.map((o=>relative(t,o)));if(this.options.onDetected){try{this.options.onDetected({paths:r.concat([r[0]]),compilation:e})}catch(o){e.errors.push(o)}return}const s=new Error(BASE_ERROR.concat(r.concat([r[0]]).join(" -> ")));this.options.failOnError?e.errors.push(s):e.warnings.push(s)}))}}
@@ -1,15 +1 @@
1
- import { CircularDependencyPlugin } from './circular-dependency-plugin.js';
2
- /**
3
- * Detect modules with circular dependencies when bundling with webpack for `development` mode.
4
- * @returns
5
- */
6
- export const createCircularDependencyPlugin = (serveMode, evolveOptions) => {
7
- if (!serveMode) {
8
- return [];
9
- }
10
- return [
11
- new CircularDependencyPlugin({
12
- projectCwd: evolveOptions.projectCwd,
13
- }),
14
- ];
15
- };
1
+ import{CircularDependencyPlugin}from"./circular-dependency-plugin.js";export const createCircularDependencyPlugin=(e,n)=>e?[new CircularDependencyPlugin({projectCwd:n.projectCwd})]:[];
@@ -1,173 +1 @@
1
- import { rmSync } from 'node:fs';
2
- import { relative } from 'node:path';
3
- import { fileWalkSync } from '@armit/file-utility';
4
- import { logger } from '@flatjs/common';
5
- import { moduleName } from '../../constants.js';
6
- export class CleanWebpackPlugin {
7
- constructor(options = {}) {
8
- this.verbose = options.verbose === true || false;
9
- this.projectCwd = options.projectCwd || process.cwd();
10
- this.cleanStaleWebpackAssets =
11
- options.cleanStaleWebpackAssets === true ||
12
- options.cleanStaleWebpackAssets === false
13
- ? options.cleanStaleWebpackAssets
14
- : true;
15
- this.protectWebpackAssets =
16
- options.protectWebpackAssets === true ||
17
- options.protectWebpackAssets === false
18
- ? options.protectWebpackAssets
19
- : true;
20
- this.cleanAfterEveryBuildPatterns = Array.isArray(options.cleanAfterEveryBuildPatterns)
21
- ? options.cleanAfterEveryBuildPatterns
22
- : [];
23
- this.cleanOnceBeforeBuildPatterns = Array.isArray(options.cleanOnceBeforeBuildPatterns)
24
- ? options.cleanOnceBeforeBuildPatterns
25
- : ['**/*'];
26
- /**
27
- * Store webpack build assets
28
- */
29
- this.currentAssets = [];
30
- /**
31
- * Only used with cleanOnceBeforeBuildPatterns
32
- */
33
- this.initialClean = false;
34
- this.outputPath = '';
35
- this.apply = this.apply.bind(this);
36
- this.handleInitial = this.handleInitial.bind(this);
37
- this.handleDone = this.handleDone.bind(this);
38
- this.removeFiles = this.removeFiles.bind(this);
39
- }
40
- apply(compiler) {
41
- if (!compiler.options.output || !compiler.options.output.path) {
42
- logger.warn('clean-webpack-plugin: options.output.path not defined. Plugin disabled...', moduleName);
43
- return;
44
- }
45
- this.outputPath = compiler.options.output.path;
46
- /**
47
- * webpack 4+ comes with a new plugin system.
48
- *
49
- * Check for hooks in-order to support old plugin system
50
- */
51
- const hooks = compiler.hooks;
52
- if (this.cleanOnceBeforeBuildPatterns.length !== 0) {
53
- hooks.emit.tap('clean-webpack-plugin', (compilation) => {
54
- this.handleInitial(compilation);
55
- });
56
- }
57
- hooks.done.tap('clean-webpack-plugin', (stats) => {
58
- this.handleDone(stats);
59
- });
60
- }
61
- /**
62
- * Initially remove files from output directory prior to build.
63
- *
64
- * Only happens once.
65
- *
66
- * Warning: It is recommended to initially clean your build directory outside of webpack to minimize unexpected behavior.
67
- */
68
- handleInitial(compilation) {
69
- if (this.initialClean) {
70
- return;
71
- }
72
- /**
73
- * Do not remove files if there are compilation errors
74
- *
75
- * Handle logging inside this.handleDone
76
- */
77
- const stats = compilation.getStats();
78
- if (stats.hasErrors()) {
79
- return;
80
- }
81
- this.initialClean = true;
82
- this.removeFiles(this.cleanOnceBeforeBuildPatterns);
83
- }
84
- handleDone(stats) {
85
- /**
86
- * Do nothing if there is a webpack error
87
- */
88
- if (stats.hasErrors()) {
89
- if (this.verbose) {
90
- logger.warn('clean-webpack-plugin: pausing due to webpack errors', moduleName);
91
- }
92
- return;
93
- }
94
- /**
95
- * Fetch Webpack's output asset files
96
- */
97
- const assets = stats.toJson({
98
- assets: true,
99
- }).assets || [];
100
- const assetList = assets.map((asset) => {
101
- return asset.name;
102
- });
103
- /**
104
- * Get all files that were in the previous build but not the current
105
- *
106
- * (relies on del's cwd: outputPath option)
107
- */
108
- const staleFiles = this.currentAssets.filter((previousAsset) => {
109
- return assetList.includes(previousAsset) === false;
110
- });
111
- /**
112
- * Save assets for next compilation
113
- */
114
- this.currentAssets = assetList.sort();
115
- const removePatterns = [];
116
- /**
117
- * Remove unused webpack assets
118
- */
119
- if (this.cleanStaleWebpackAssets === true && staleFiles.length !== 0) {
120
- removePatterns.push(...staleFiles);
121
- }
122
- /**
123
- * Remove cleanAfterEveryBuildPatterns
124
- */
125
- if (this.cleanAfterEveryBuildPatterns.length !== 0) {
126
- removePatterns.push(...this.cleanAfterEveryBuildPatterns);
127
- }
128
- if (removePatterns.length !== 0) {
129
- this.removeFiles(removePatterns);
130
- }
131
- }
132
- removeFiles(patterns) {
133
- try {
134
- const deleted = fileWalkSync(patterns, {
135
- absolute: true,
136
- unique: true,
137
- // Change context to build directory
138
- cwd: this.outputPath,
139
- dot: true,
140
- ignore: this.protectWebpackAssets ? this.currentAssets : [],
141
- });
142
- for (const filepath of deleted) {
143
- rmSync(filepath, {
144
- force: true,
145
- recursive: true,
146
- });
147
- }
148
- /**
149
- * Log if verbose is enabled
150
- */
151
- if (this.verbose) {
152
- deleted.forEach((file) => {
153
- const filename = relative(this.projectCwd, file);
154
- const message = 'removed';
155
- /**
156
- * Use console.warn over .log
157
- * https://github.com/webpack/webpack/issues/1904
158
- * https://github.com/johnagan/clean-webpack-plugin/issues/11
159
- */
160
- logger.debug(`clean-webpack-plugin: ${message} ${filename}`, moduleName);
161
- });
162
- }
163
- }
164
- catch (error) {
165
- const needsForce = /Cannot delete files\/folders outside the current working directory\./.test(error.message);
166
- if (needsForce) {
167
- const message = 'clean-webpack-plugin: Cannot delete files/folders outside the current working directory. Can be overridden with the `dangerouslyAllowCleanPatternsOutsideProject` option.';
168
- throw new Error(message);
169
- }
170
- throw error;
171
- }
172
- }
173
- }
1
+ import{rmSync}from"node:fs";import{relative}from"node:path";import{fileWalkSync}from"@armit/file-utility";import{logger}from"@flatjs/common";import{moduleName}from"../../constants.js";export class CleanWebpackPlugin{constructor(e={}){this.verbose=!0===e.verbose||!1,this.projectCwd=e.projectCwd||process.cwd(),this.cleanStaleWebpackAssets=!0!==e.cleanStaleWebpackAssets&&!1!==e.cleanStaleWebpackAssets||e.cleanStaleWebpackAssets,this.protectWebpackAssets=!0!==e.protectWebpackAssets&&!1!==e.protectWebpackAssets||e.protectWebpackAssets,this.cleanAfterEveryBuildPatterns=Array.isArray(e.cleanAfterEveryBuildPatterns)?e.cleanAfterEveryBuildPatterns:[],this.cleanOnceBeforeBuildPatterns=Array.isArray(e.cleanOnceBeforeBuildPatterns)?e.cleanOnceBeforeBuildPatterns:["**/*"],this.currentAssets=[],this.initialClean=!1,this.outputPath="",this.apply=this.apply.bind(this),this.handleInitial=this.handleInitial.bind(this),this.handleDone=this.handleDone.bind(this),this.removeFiles=this.removeFiles.bind(this)}apply(e){if(!e.options.output||!e.options.output.path)return void logger.warn("clean-webpack-plugin: options.output.path not defined. Plugin disabled...",moduleName);this.outputPath=e.options.output.path;const t=e.hooks;0!==this.cleanOnceBeforeBuildPatterns.length&&t.emit.tap("clean-webpack-plugin",(e=>{this.handleInitial(e)})),t.done.tap("clean-webpack-plugin",(e=>{this.handleDone(e)}))}handleInitial(e){if(this.initialClean)return;e.getStats().hasErrors()||(this.initialClean=!0,this.removeFiles(this.cleanOnceBeforeBuildPatterns))}handleDone(e){if(e.hasErrors())return void(this.verbose&&logger.warn("clean-webpack-plugin: pausing due to webpack errors",moduleName));const t=(e.toJson({assets:!0}).assets||[]).map((e=>e.name)),s=this.currentAssets.filter((e=>!1===t.includes(e)));this.currentAssets=t.sort();const i=[];!0===this.cleanStaleWebpackAssets&&0!==s.length&&i.push(...s),0!==this.cleanAfterEveryBuildPatterns.length&&i.push(...this.cleanAfterEveryBuildPatterns),0!==i.length&&this.removeFiles(i)}removeFiles(e){try{const t=fileWalkSync(e,{absolute:!0,unique:!0,cwd:this.outputPath,dot:!0,ignore:this.protectWebpackAssets?this.currentAssets:[]});for(const e of t)rmSync(e,{force:!0,recursive:!0});this.verbose&&t.forEach((e=>{const t=relative(this.projectCwd,e);logger.debug(`clean-webpack-plugin: removed ${t}`,moduleName)}))}catch(e){if(/Cannot delete files\/folders outside the current working directory\./.test(e.message)){throw new Error("clean-webpack-plugin: Cannot delete files/folders outside the current working directory. Can be overridden with the `dangerouslyAllowCleanPatternsOutsideProject` option.")}throw e}}}
@@ -1,22 +1 @@
1
- import { join } from 'node:path';
2
- import { ensureSlash } from '@flatjs/common';
3
- import { CleanWebpackPlugin } from './clean-webpack-plugin.js';
4
- /**
5
- * Cleaning up the /dist folder for `production` build
6
- * @param singleEntryItem
7
- * @returns
8
- */
9
- export const createCleanWebpackPlugin = (serveMode, entryMapItemList, evolveOptions) => {
10
- if (serveMode) {
11
- return [];
12
- }
13
- return [
14
- new CleanWebpackPlugin({
15
- verbose: true,
16
- projectCwd: evolveOptions.projectCwd,
17
- cleanOnceBeforeBuildPatterns: entryMapItemList.map((entryMapItem) => {
18
- return `${join(ensureSlash(entryMapItem[0], true), '**/*')}`;
19
- }),
20
- }),
21
- ];
22
- };
1
+ import{join}from"node:path";import{ensureSlash}from"@flatjs/common";import{CleanWebpackPlugin}from"./clean-webpack-plugin.js";export const createCleanWebpackPlugin=(e,n,o)=>e?[]:[new CleanWebpackPlugin({verbose:!0,projectCwd:o.projectCwd,cleanOnceBeforeBuildPatterns:n.map((e=>`${join(ensureSlash(e[0],!0),"**/*")}`))})];
@@ -1,28 +1 @@
1
- /* eslint-disable @typescript-eslint/naming-convention */
2
- import { getLastCommitHash, gitBranchName } from '@armit/git';
3
- import webpack from 'webpack';
4
- /**
5
- * The DefinePlugin replaces variables in your code with other values or expressions at compile time.
6
- * ```ts
7
- * `__SENTRY_DEBUG__`
8
- * `process.env.FLAT_BUILD_DATE`
9
- * `process.env.FLAT_COMMIT_HASH`
10
- * `process.env.FLAT_BRANCH_NAME`
11
- * `process.env.FLAT_RELEASE_VERSION`
12
- * ```
13
- * @returns
14
- */
15
- export const createBuiltinDefineVariables = async (serveMode, evolveOptions) => {
16
- const commitHash = await getLastCommitHash();
17
- const branchName = await gitBranchName();
18
- return [
19
- new webpack.DefinePlugin({
20
- __SENTRY_DEBUG__: serveMode,
21
- 'process.env.FLAT_BUILD_DATE': JSON.stringify(new Date().toISOString()),
22
- 'process.env.FLAT_COMMIT_HASH': JSON.stringify(commitHash),
23
- 'process.env.FLAT_BRANCH_NAME': JSON.stringify(branchName),
24
- 'process.env.FLAT_RELEASE_VERSION': JSON.stringify(evolveOptions.ci?.releaseVersion || commitHash),
25
- ...evolveOptions.pluginOptions.definePlugin,
26
- }),
27
- ];
28
- };
1
+ import webpack from"webpack";import{getLastCommitHash,gitBranchName}from"@armit/git";export const createBuiltinDefineVariables=async(e,i)=>{const t=await getLastCommitHash(),n=await gitBranchName();return[new webpack.DefinePlugin({__SENTRY_DEBUG__:e,"process.env.FLAT_BUILD_DATE":JSON.stringify((new Date).toISOString()),"process.env.FLAT_COMMIT_HASH":JSON.stringify(t),"process.env.FLAT_BRANCH_NAME":JSON.stringify(n),"process.env.FLAT_RELEASE_VERSION":JSON.stringify(i.ci?.releaseVersion||t),...i.pluginOptions.definePlugin})]};
@@ -1 +1 @@
1
- export * from './define-variable-plugin.js';
1
+ export*from"./define-variable-plugin.js";
@@ -1,27 +1 @@
1
- import htmlWebpackPlugin from 'html-webpack-plugin';
2
- const PLUGIN_PREFIX = `HtmlInjectScriptPlugin`;
3
- export class HtmlInjectScriptPlugin {
4
- constructor(scripts) {
5
- this.scripts = scripts || [];
6
- }
7
- processScripts() {
8
- return this.scripts.filter(Boolean).map((asset) => {
9
- return {
10
- tagName: 'script',
11
- innerHTML: asset,
12
- voidTag: false,
13
- attributes: {},
14
- meta: { plugin: 'html-inject-script-webpack-plugin' },
15
- };
16
- });
17
- }
18
- apply(compiler) {
19
- compiler.hooks.compilation.tap(`${PLUGIN_PREFIX}_compilation`, (compilation) => {
20
- const hooks = htmlWebpackPlugin.getHooks(compilation);
21
- hooks.alterAssetTags.tap(`${PLUGIN_PREFIX}_alterAssetTags`, (data) => {
22
- data.assetTags.scripts.unshift(...this.processScripts());
23
- return data;
24
- });
25
- });
26
- }
27
- }
1
+ import htmlWebpackPlugin from"html-webpack-plugin";const PLUGIN_PREFIX="HtmlInjectScriptPlugin";export class HtmlInjectScriptPlugin{constructor(t){this.scripts=t||[]}processScripts(){return this.scripts.filter(Boolean).map((t=>({tagName:"script",innerHTML:t,voidTag:!1,attributes:{},meta:{plugin:"html-inject-script-webpack-plugin"}})))}apply(t){t.hooks.compilation.tap(`${PLUGIN_PREFIX}_compilation`,(t=>{htmlWebpackPlugin.getHooks(t).alterAssetTags.tap(`${PLUGIN_PREFIX}_alterAssetTags`,(t=>(t.assetTags.scripts.unshift(...this.processScripts()),t)))}))}}
@@ -1,92 +1 @@
1
- import webpackSources from 'webpack-sources';
2
- const PLUGIN_NAME = 'ExternalTemplateRemotesPlugin';
3
- const isExternalModule = (module) => {
4
- return module.constructor.name === 'ExternalModule';
5
- };
6
- /**
7
- * @param {string} urlAndGlobal the script request
8
- * @returns {string[]} script url and its global variable
9
- */
10
- function extractUrlAndGlobal(urlAndGlobal) {
11
- const index = urlAndGlobal.indexOf('@');
12
- if (index <= 0 || index === urlAndGlobal.length - 1) {
13
- throw new Error(`Invalid request "${urlAndGlobal}"`);
14
- }
15
- return [urlAndGlobal.substring(index + 1), urlAndGlobal.substring(0, index)];
16
- }
17
- export class ExternalTemplateRemotesPlugin {
18
- apply(compiler) {
19
- compiler.hooks.make.tap(PLUGIN_NAME, (compilation) => {
20
- const scriptExternalModules = [];
21
- compilation.hooks.buildModule.tap(PLUGIN_NAME, (module) => {
22
- if (isExternalModule(module) && module.externalType === 'script') {
23
- scriptExternalModules.push(module);
24
- }
25
- });
26
- compilation.hooks.afterCodeGeneration.tap(PLUGIN_NAME, () => {
27
- scriptExternalModules.forEach((module) => {
28
- const urlTemplate = extractUrlAndGlobal(module.request)[0];
29
- const urlExpression = toExpression(urlTemplate);
30
- const sourceMap = compilation.codeGenerationResults.get(module, undefined).sources;
31
- const rawSource = sourceMap.get('javascript');
32
- if (rawSource) {
33
- const source = new webpackSources.RawSource(rawSource
34
- .source()
35
- .toString()
36
- .replace(`"${urlTemplate}"`, urlExpression));
37
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
38
- sourceMap.set('javascript', source);
39
- }
40
- });
41
- });
42
- });
43
- }
44
- }
45
- /**
46
- * app2@localhost/remoteEntry.js --> "\"app2@localhost/remoteEntry.js\""
47
- * app2@[window.app2Url]/remoteEntry.js --> "\"app2@\" + window.app2Url + \"/remoteEntry.js\""
48
- * @param templateUrl
49
- * @returns
50
- */
51
- // eslint-disable-next-line sonarjs/cognitive-complexity
52
- function toExpression(templateUrl) {
53
- const result = [];
54
- const current = [];
55
- let isExpression = false;
56
- let invalid = false;
57
- for (const c of templateUrl) {
58
- if (c === '[') {
59
- if (isExpression) {
60
- invalid = true;
61
- break;
62
- }
63
- isExpression = true;
64
- if (current.length) {
65
- result.push(`"${current.join('')}"`);
66
- current.length = 0;
67
- }
68
- }
69
- else if (c === ']') {
70
- if (!isExpression) {
71
- invalid = true;
72
- break;
73
- }
74
- isExpression = false;
75
- if (current.length) {
76
- result.push(`${current.join('')}`);
77
- current.length = 0;
78
- }
79
- current.length = 0;
80
- }
81
- else {
82
- current.push(c);
83
- }
84
- }
85
- if (isExpression || invalid) {
86
- throw new Error(`Invalid template URL "${templateUrl}"`);
87
- }
88
- if (current.length) {
89
- result.push(`"${current.join('')}"`);
90
- }
91
- return result.join(' + ');
92
- }
1
+ import webpackSources from"webpack-sources";const PLUGIN_NAME="ExternalTemplateRemotesPlugin",isExternalModule=e=>"ExternalModule"===e.constructor.name;function extractUrlAndGlobal(e){const t=e.indexOf("@");if(t<=0||t===e.length-1)throw new Error(`Invalid request "${e}"`);return[e.substring(t+1),e.substring(0,t)]}export class ExternalTemplateRemotesPlugin{apply(e){e.hooks.make.tap(PLUGIN_NAME,(e=>{const t=[];e.hooks.buildModule.tap(PLUGIN_NAME,(e=>{isExternalModule(e)&&"script"===e.externalType&&t.push(e)})),e.hooks.afterCodeGeneration.tap(PLUGIN_NAME,(()=>{t.forEach((t=>{const o=extractUrlAndGlobal(t.request)[0],n=toExpression(o),r=e.codeGenerationResults.get(t,void 0).sources,s=r.get("javascript");if(s){const e=new webpackSources.RawSource(s.source().toString().replace(`"${o}"`,n));r.set("javascript",e)}}))}))}))}}function toExpression(e){const t=[],o=[];let n=!1,r=!1;for(const s of e)if("["===s){if(n){r=!0;break}n=!0,o.length&&(t.push(`"${o.join("")}"`),o.length=0)}else if("]"===s){if(!n){r=!0;break}n=!1,o.length&&(t.push(`${o.join("")}`),o.length=0),o.length=0}else o.push(s);if(n||r)throw new Error(`Invalid template URL "${e}"`);return o.length&&t.push(`"${o.join("")}"`),t.join(" + ")}
@@ -1 +1 @@
1
- export * from './module-federation.js';
1
+ export*from"./module-federation.js";
@@ -1,100 +1 @@
1
- import { join } from 'node:path';
2
- import { ensureSlash } from '@flatjs/common';
3
- import webpack from 'webpack';
4
- import { normalizeEvolveEntryName } from '../../helpers/normalize-entry-map.js';
5
- import { injectFederationScripts } from '../../helpers/script-injects.js';
6
- import { HtmlInjectScriptPlugin } from '../html-inject-scripts/plugin-html-inject-script.js';
7
- import { ExternalTemplateRemotesPlugin } from './external-template-remotes.js';
8
- /**
9
- * `${projectVirtualPath}/mine` --> evolve_demo_mine
10
- * @param entryPath `${projectVirtualPath}/mine`
11
- */
12
- const normalizeWidgetName = (entryPath = '') => {
13
- return entryPath.replace(/[/-]/g, '_').toLowerCase();
14
- };
15
- const remoteFileName = (entryName) => {
16
- return join(entryName, `micro-remote-module.js`);
17
- };
18
- export const createModuleFederationPlugin = (serveMode, entryMapItemList, evolveOptions) => {
19
- const projectVirtualPath = evolveOptions.projectVirtualPath;
20
- const multiCdnConfig = evolveOptions.multiHtmlCdn;
21
- const multiHtmlCdnResolver = evolveOptions.multiHtmlCdnEnvResolver;
22
- const plugins = [];
23
- for (const entryMapItem of entryMapItemList) {
24
- const [entryName, entryConfig] = entryMapItem;
25
- const moduleFederation = entryConfig.options?.moduleFederation;
26
- if (moduleFederation) {
27
- const { remotes, exposes, ...restFederationOptions } = moduleFederation;
28
- // e.g. `flatjs/evolve/mine` => `flatjs/evolve/home/micro-remote-module.js`
29
- const entryRemoteFileName = remoteFileName(entryName);
30
- // e.g. `flatjs/evolve/mine` => `flatjs_evolve_mine`
31
- const containerName = normalizeWidgetName(entryName);
32
- const patchExposes = exposes
33
- ? Array.isArray(exposes)
34
- ? exposes
35
- : [exposes]
36
- : [];
37
- const myExposes = patchExposes.map((s) => {
38
- const exposeItem = {};
39
- for (const [key, config] of Object.entries(s)) {
40
- exposeItem[key] = {
41
- ...config,
42
- name: join(entryName, config.name.replace(/^\//, '')),
43
- };
44
- }
45
- return exposeItem;
46
- });
47
- const myRemotes = (remotes || []).map(({ name, endpoint }) => {
48
- // e.g. `flatjs/evolve/home`
49
- const normalizedEntryName = normalizeEvolveEntryName(name, projectVirtualPath);
50
- // e.g. `flatjs_evolve_home`
51
- const remoteWidgetName = normalizeWidgetName(normalizedEntryName);
52
- // e.g. `flatjs/evolve/home/micro-remote-module.js`
53
- const refRemoteEntryFileName = remoteFileName(normalizedEntryName);
54
- // construct endpoint for remote widget name.
55
- const endpointPath = endpoint
56
- ? ensureSlash(endpoint(name, normalizedEntryName), false)
57
- : `[window.evolveFetchMicroWidgets()]`;
58
- return {
59
- [remoteWidgetName]: `${remoteWidgetName}@${endpointPath}/${refRemoteEntryFileName}`,
60
- };
61
- });
62
- plugins.push(
63
- // https://webpack.js.org/plugins/module-federation-plugin/
64
- new webpack.container.ModuleFederationPlugin({
65
- /**
66
- * Options for library.
67
- * library: { type: 'var', name: containerName },
68
- * other module federation configurations
69
- */
70
- ...restFederationOptions,
71
- /**
72
- * The name of the container
73
- * `${projectName}-${moduleName}` e.g. `flatjs_evolve_home`
74
- */
75
- name: containerName,
76
- /**
77
- * The filename of the container as relative path inside the `output.path` directory.
78
- * `${entryName}/micro-remote-module.js`, e.g. `flatjs/evolve/home/micro-remote-module.js`
79
- */
80
- filename: entryRemoteFileName,
81
- /**
82
- * Container locations and request scopes from which modules should be resolved and loaded at runtime.
83
- * When provided, property name is used as request scope, otherwise request scope is automatically inferred from container location.
84
- */
85
- remotes: myRemotes,
86
- /**
87
- * Modules that should be exposed by this container.
88
- * When provided, property name is used as public name, otherwise public name is automatically inferred from request.
89
- */
90
- exposes: myExposes,
91
- }), new ExternalTemplateRemotesPlugin());
92
- if (!serveMode) {
93
- plugins.unshift(new HtmlInjectScriptPlugin([
94
- injectFederationScripts(multiCdnConfig, multiHtmlCdnResolver),
95
- ]));
96
- }
97
- }
98
- }
99
- return plugins;
100
- };
1
+ import{join}from"node:path";import webpack from"webpack";import{ensureSlash}from"@flatjs/common";import{normalizeEvolveEntryName}from"../../helpers/normalize-entry-map.js";import{injectFederationScripts}from"../../helpers/script-injects.js";import{HtmlInjectScriptPlugin}from"../html-inject-scripts/plugin-html-inject-script.js";import{ExternalTemplateRemotesPlugin}from"./external-template-remotes.js";const normalizeWidgetName=(e="")=>e.replace(/[/-]/g,"_").toLowerCase(),remoteFileName=e=>join(e,"micro-remote-module.js");export const createModuleFederationPlugin=(e,t,o)=>{const r=o.projectVirtualPath,n=o.multiHtmlCdn,i=o.multiHtmlCdnEnvResolver,m=[];for(const o of t){const[t,a]=o,l=a.options?.moduleFederation;if(l){const{remotes:o,exposes:a,...s}=l,c=remoteFileName(t),p=normalizeWidgetName(t),u=(a?Array.isArray(a)?a:[a]:[]).map((e=>{const o={};for(const[r,n]of Object.entries(e))o[r]={...n,name:join(t,n.name.replace(/^\//,""))};return o})),d=(o||[]).map((({name:e,endpoint:t})=>{const o=normalizeEvolveEntryName(e,r),n=normalizeWidgetName(o),i=remoteFileName(o),m=t?ensureSlash(t(e,o),!1):"[window.evolveFetchMicroWidgets()]";return{[n]:`${n}@${m}/${i}`}}));m.push(new webpack.container.ModuleFederationPlugin({...s,name:p,filename:c,remotes:d,exposes:u}),new ExternalTemplateRemotesPlugin),e||m.unshift(new HtmlInjectScriptPlugin([injectFederationScripts(n,i)]))}}return m};
@@ -1,16 +1 @@
1
- import { FlatEvolveMultiCdnPlugin } from './multi-html-cdn-plugin.js';
2
- import { createMultiHtmlWebpackPlugin } from './multi-html-plugin.js';
3
- export const createHtmlPlugins = (serveMode, entryMapItemList, evolveOptions) => {
4
- const plugins = [];
5
- // Only for `production`, or `library` compiler mode do not need to attach `html-webpack-plugin`
6
- const firstEntryMapItem = entryMapItemList[0];
7
- if (serveMode || firstEntryMapItem[1]?.options?.output?.library) {
8
- return plugins;
9
- }
10
- // Attach `html-webpack-plugin` first
11
- const allEnv = Object.keys(evolveOptions.multiHtmlCdn);
12
- plugins.push(...createMultiHtmlWebpackPlugin(serveMode, evolveOptions, entryMapItemList, allEnv));
13
- // Attach `@flatjs/evolve-plugin-multi-html-cdn`
14
- plugins.push(new FlatEvolveMultiCdnPlugin(evolveOptions));
15
- return plugins;
16
- };
1
+ import{FlatEvolveMultiCdnPlugin}from"./multi-html-cdn-plugin.js";import{createMultiHtmlWebpackPlugin}from"./multi-html-plugin.js";export const createHtmlPlugins=(t,l,u)=>{const i=[],n=l[0];if(t||n[1]?.options?.output?.library)return i;const e=Object.keys(u.multiHtmlCdn);return i.push(...createMultiHtmlWebpackPlugin(t,u,l,e)),i.push(new FlatEvolveMultiCdnPlugin(u)),i};