@plaudit/webpack-extensions 2.53.1 → 2.55.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 (43) hide show
  1. package/build/{wordpress-scripts-wrapper → plugins}/AdditionalDependencyInjectorPlugin.js +3 -3
  2. package/build/{wordpress-scripts-wrapper → plugins}/BlockJSONManagingPlugin.d.ts +5 -5
  3. package/build/{wordpress-scripts-wrapper → plugins}/BlockJSONManagingPlugin.js +17 -33
  4. package/build/plugins/ExtensionsConfigFileGeneratorPlugin.d.ts +13 -0
  5. package/build/plugins/ExtensionsConfigFileGeneratorPlugin.js +173 -0
  6. package/build/plugins/PlainEntrypointsConfigFileGeneratorPlugin.d.ts +24 -0
  7. package/build/plugins/PlainEntrypointsConfigFileGeneratorPlugin.js +244 -0
  8. package/build/plugins/SpecialAssetHandlingPlugin.d.ts +12 -0
  9. package/build/plugins/SpecialAssetHandlingPlugin.js +135 -0
  10. package/build/{wordpress-scripts-wrapper → plugins}/VariablesJSMonitorPlugin.js +1 -1
  11. package/build/{wordpress-scripts-wrapper → plugins}/WPMLConfigBuilder.d.ts +3 -2
  12. package/build/{wordpress-scripts-wrapper → plugins}/WPMLConfigBuilder.js +7 -3
  13. package/build/{wordpress-scripts-wrapper → plugins}/dependency-extraction-webpack-plugin-config-builder.d.ts +1 -7
  14. package/build/shared.d.ts +86 -9
  15. package/build/shared.js +70 -0
  16. package/build/utils/common-config-helpers.d.ts +26 -0
  17. package/build/utils/common-config-helpers.js +336 -0
  18. package/build/{wordpress-scripts-wrapper → utils}/php-serializer.d.ts +1 -1
  19. package/build/{wordpress-scripts-wrapper → utils}/php-serializer.js +1 -1
  20. package/build/utils/php-writer.d.ts +54 -0
  21. package/build/utils/php-writer.js +191 -0
  22. package/build/utils/pseduo-semaphore.d.ts +13 -0
  23. package/build/utils/pseduo-semaphore.js +63 -0
  24. package/build/wordpress-scripts-wrapper.d.ts +1 -27
  25. package/build/wordpress-scripts-wrapper.js +233 -441
  26. package/package.json +4 -4
  27. package/build/wordpress-scripts-wrapper/ExtensionsConfigFileGeneratorPlugin.d.ts +0 -6
  28. package/build/wordpress-scripts-wrapper/ExtensionsConfigFileGeneratorPlugin.js +0 -52
  29. package/build/wordpress-scripts-wrapper/SpecialAssetHandlingPlugin.d.ts +0 -7
  30. package/build/wordpress-scripts-wrapper/SpecialAssetHandlingPlugin.js +0 -107
  31. /package/build/{wordpress-scripts-wrapper → plugins}/AdditionalDependencyInjectorPlugin.d.ts +0 -0
  32. /package/build/{wordpress-scripts-wrapper → plugins}/BrowserSyncPlugin.d.ts +0 -0
  33. /package/build/{wordpress-scripts-wrapper → plugins}/BrowserSyncPlugin.js +0 -0
  34. /package/build/{wordpress-scripts-wrapper → plugins}/MiniCSSExtractPluginErrorCleaner.d.ts +0 -0
  35. /package/build/{wordpress-scripts-wrapper → plugins}/MiniCSSExtractPluginErrorCleaner.js +0 -0
  36. /package/build/{wordpress-scripts-wrapper → plugins}/PackageConfigSanityChecker.d.ts +0 -0
  37. /package/build/{wordpress-scripts-wrapper → plugins}/PackageConfigSanityChecker.js +0 -0
  38. /package/build/{wordpress-scripts-wrapper → plugins}/VariablesJSMonitorPlugin.d.ts +0 -0
  39. /package/build/{wordpress-scripts-wrapper → plugins}/dependency-extraction-webpack-plugin-config-builder.js +0 -0
  40. /package/build/{wordpress-scripts-wrapper → plugins}/static-configs.d.ts +0 -0
  41. /package/build/{wordpress-scripts-wrapper → plugins}/static-configs.js +0 -0
  42. /package/build/{wordpress-scripts-wrapper → utils}/json-to-php-but-with-__-injection.d.ts +0 -0
  43. /package/build/{wordpress-scripts-wrapper → utils}/json-to-php-but-with-__-injection.js +0 -0
@@ -5,51 +5,23 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  const node_fs_1 = __importDefault(require("node:fs"));
6
6
  const promises_1 = __importDefault(require("node:fs/promises"));
7
7
  const node_path_1 = __importDefault(require("node:path"));
8
- const AdditionalDependencyInjectorPlugin_1 = require("./wordpress-scripts-wrapper/AdditionalDependencyInjectorPlugin");
9
- const BlockJSONManagingPlugin_1 = require("./wordpress-scripts-wrapper/BlockJSONManagingPlugin");
10
- const BrowserSyncPlugin_1 = require("./wordpress-scripts-wrapper/BrowserSyncPlugin");
11
- const ExtensionsConfigFileGeneratorPlugin_1 = require("./wordpress-scripts-wrapper/ExtensionsConfigFileGeneratorPlugin");
12
- const MiniCSSExtractPluginErrorCleaner_1 = require("./wordpress-scripts-wrapper/MiniCSSExtractPluginErrorCleaner");
13
- const PackageConfigSanityChecker_1 = require("./wordpress-scripts-wrapper/PackageConfigSanityChecker");
14
- const SpecialAssetHandlingPlugin_1 = require("./wordpress-scripts-wrapper/SpecialAssetHandlingPlugin");
15
- const VariablesJSMonitorPlugin_1 = require("./wordpress-scripts-wrapper/VariablesJSMonitorPlugin");
16
- const WPMLConfigBuilder_1 = require("./wordpress-scripts-wrapper/WPMLConfigBuilder");
17
- const static_configs_1 = require("./wordpress-scripts-wrapper/static-configs");
18
- const dependency_extraction_webpack_plugin_config_builder_1 = require("./wordpress-scripts-wrapper/dependency-extraction-webpack-plugin-config-builder");
8
+ const shared_1 = require("./shared");
9
+ const common_config_helpers_1 = require("./utils/common-config-helpers");
10
+ const AdditionalDependencyInjectorPlugin_1 = require("./plugins/AdditionalDependencyInjectorPlugin");
11
+ const BlockJSONManagingPlugin_1 = require("./plugins/BlockJSONManagingPlugin");
12
+ const BrowserSyncPlugin_1 = require("./plugins/BrowserSyncPlugin");
13
+ const ExtensionsConfigFileGeneratorPlugin_1 = require("./plugins/ExtensionsConfigFileGeneratorPlugin");
14
+ const MiniCSSExtractPluginErrorCleaner_1 = require("./plugins/MiniCSSExtractPluginErrorCleaner");
15
+ const PackageConfigSanityChecker_1 = require("./plugins/PackageConfigSanityChecker");
16
+ const PlainEntrypointsConfigFileGeneratorPlugin_1 = require("./plugins/PlainEntrypointsConfigFileGeneratorPlugin");
17
+ const SpecialAssetHandlingPlugin_1 = require("./plugins/SpecialAssetHandlingPlugin");
18
+ const VariablesJSMonitorPlugin_1 = require("./plugins/VariablesJSMonitorPlugin");
19
+ const WPMLConfigBuilder_1 = require("./plugins/WPMLConfigBuilder");
20
+ const static_configs_1 = require("./plugins/static-configs");
21
+ const dependency_extraction_webpack_plugin_config_builder_1 = require("./plugins/dependency-extraction-webpack-plugin-config-builder");
19
22
  const dependency_extraction_webpack_plugin_1 = __importDefault(require("@wordpress/dependency-extraction-webpack-plugin"));
20
- const copy_webpack_plugin_1 = __importDefault(require("copy-webpack-plugin"));
21
23
  const fork_ts_checker_webpack_plugin_1 = __importDefault(require("fork-ts-checker-webpack-plugin"));
22
24
  const webpack_remove_empty_scripts_1 = __importDefault(require("webpack-remove-empty-scripts"));
23
- function joinPossiblyAbsolutePaths(...paths) {
24
- return paths.filter((p) => !!p)
25
- .reduce((res, p) => !res || node_path_1.default.isAbsolute(p) ? p : node_path_1.default.join(res, p), '') || '.';
26
- }
27
- function mapToRealEntrypoints(entrypoint, dir, mapper = (entrypoint) => entrypoint, lazyDependent, associatedQuery) {
28
- return (Array.isArray(entrypoint) ? entrypoint : [entrypoint])
29
- .map(ep => joinPossiblyAbsolutePaths(dir, mapper(ep)))
30
- .filter(ep => node_fs_1.default.statSync(ep, { throwIfNoEntry: false })?.isFile())
31
- .map(ep => {
32
- const parsedEntrypoint = node_path_1.default.parse(ep);
33
- return [joinPossiblyAbsolutePaths(node_path_1.default.basename(parsedEntrypoint.dir), parsedEntrypoint.name), { import: ep, lazyDependent, associatedQuery }];
34
- });
35
- }
36
- let isInThemeCache = undefined;
37
- function isInTheme() {
38
- return isInThemeCache ?? (isInThemeCache = node_fs_1.default.existsSync(node_path_1.default.join(process.cwd(), "theme.json")));
39
- }
40
- function groupEntrypointsByAssetFile(entrypoints, entrypointNameExtractor) {
41
- const seenPaths = new Map();
42
- for (const entrypoint of entrypoints) {
43
- const entrypointName = entrypointNameExtractor(entrypoint);
44
- const key = entrypointName.substring(0, entrypointName.length - node_path_1.default.extname(entrypointName).length);
45
- let seen = seenPaths.get(key);
46
- if (seen === undefined) {
47
- seenPaths.set(key, seen = []);
48
- }
49
- seen.push(entrypoint);
50
- }
51
- return seenPaths;
52
- }
53
25
  function resolveLegacyBlockScriptsInFolder(folder) {
54
26
  const blockScriptEntrypoints = [];
55
27
  for (const blockDir of node_fs_1.default.readdirSync(folder)) {
@@ -64,52 +36,8 @@ function resolveLegacyBlockScriptsInFolder(folder) {
64
36
  }
65
37
  return blockScriptEntrypoints;
66
38
  }
67
- const scriptWithoutModuleExtension = /\.[jt]sx?$/;
68
- const scriptWithModuleExtension = /\.m[jt]sx?$/;
69
- const styleExtension = /\.(p?c|sa)ss$/;
70
- function scriptOrStyleTest(entryPath, scriptExtension) {
71
- return scriptExtension.test(entryPath) ? "script" : (styleExtension.test(entryPath) ? "style" : "");
72
- }
73
- function determineEntrypointType(entrypoint, scriptExtension) {
74
- let res = scriptOrStyleTest(entrypoint[0], scriptExtension);
75
- if (res) {
76
- return res;
77
- }
78
- if (typeof entrypoint[1] === 'string') {
79
- return scriptOrStyleTest(entrypoint[1], scriptExtension);
80
- }
81
- else if (Array.isArray(entrypoint[1])) {
82
- return entrypoint[1].reduce((prior, ep) => prior || scriptOrStyleTest(ep, scriptExtension), "");
83
- }
84
- else if (typeof entrypoint[1].import === 'string') {
85
- return scriptOrStyleTest(entrypoint[1].import, scriptExtension);
86
- }
87
- else {
88
- return entrypoint[1].import.reduce((prior, ep) => prior || scriptOrStyleTest(ep, scriptExtension), "");
89
- }
90
- }
91
- function injectTypeAndCountToEntrypointName(entrypointName, type, typeCounts) {
92
- const entrypointBasename = entrypointName.substring(0, entrypointName.length - node_path_1.default.extname(entrypointName).length);
93
- const parts = [];
94
- if (type) {
95
- parts.push(type);
96
- }
97
- if (typeCounts[type] ?? (typeCounts[type] = 0)) {
98
- parts.push(typeCounts[type].toString());
99
- }
100
- typeCounts[type] += 1;
101
- return `${entrypointBasename}_${parts.join('-')}${node_path_1.default.extname(entrypointName)}`;
102
- }
103
- function addPotentiallyDuplicatedEntrypointName(entry, entrypoint, typeCounts, scriptExtension) {
104
- const type = determineEntrypointType(entrypoint, scriptExtension);
105
- let potentialKey = injectTypeAndCountToEntrypointName(entrypoint[0], type, typeCounts);
106
- while (entry[potentialKey]) {
107
- potentialKey = injectTypeAndCountToEntrypointName(entrypoint[0], type, typeCounts);
108
- }
109
- entry[potentialKey] = entrypoint[1];
110
- }
111
39
  function testForDuplicatedEntryPaths(config) {
112
- const seenPaths = groupEntrypointsByAssetFile(Array.isArray(config.src) ? config.src : Object.values(config.src).map(bn => typeof bn === 'string' ? bn : bn.destination), bn => bn);
40
+ const seenPaths = (0, common_config_helpers_1.groupEntrypointsByAssetFile)(Array.isArray(config.src) ? config.src : Object.values(config.src).map(bn => typeof bn === 'string' ? bn : bn.destination), bn => bn);
113
41
  let projectPrefix = undefined;
114
42
  let duplicatedPaths = "";
115
43
  for (const sameNamePaths of seenPaths.values()) {
@@ -166,7 +94,7 @@ function replaceDefaultURLProcessing(useWebpackResourceFiltering) {
166
94
  return rules;
167
95
  };
168
96
  }
169
- function injectPostcssConfigOverrides(rules, variables, postcssFunctionsConfig, verbose) {
97
+ function injectPostcssConfigOverrides(rules, config, variables, postcssFunctionsConfig, verbose) {
170
98
  const postcssConfig = (0, static_configs_1.postcssConfigBuilder)(verbose, name => variables(name) ?? (name === 'ENV' ? '' : undefined), postcssFunctionsConfig);
171
99
  return recursivelyAddParentDirectoryStepToImagesAndFonts(rules.map(rule => {
172
100
  if (rule && typeof rule === 'object') {
@@ -202,9 +130,12 @@ function injectPostcssConfigOverrides(rules, variables, postcssFunctionsConfig,
202
130
  }
203
131
  }
204
132
  return rule;
205
- }));
133
+ }), config);
206
134
  }
207
- function recursivelyAddParentDirectoryStepToImagesAndFonts(rules) {
135
+ function recursivelyAddParentDirectoryStepToImagesAndFonts(rules, config) {
136
+ if (config.outputDir) {
137
+ return rules;
138
+ }
208
139
  return rules.map(rule => {
209
140
  if (rule && typeof rule === 'object') {
210
141
  if (typeof rule.generator === 'object') {
@@ -215,7 +146,7 @@ function recursivelyAddParentDirectoryStepToImagesAndFonts(rules) {
215
146
  }
216
147
  }
217
148
  if (rule.oneOf) {
218
- rule = { ...rule, oneOf: recursivelyAddParentDirectoryStepToImagesAndFonts(rule.oneOf) };
149
+ rule = { ...rule, oneOf: recursivelyAddParentDirectoryStepToImagesAndFonts(rule.oneOf, config) };
219
150
  }
220
151
  }
221
152
  return rule;
@@ -234,49 +165,156 @@ function injectSupportForInliningSVGsAsStrings(rules) {
234
165
  return rule;
235
166
  });
236
167
  }
237
- function parseEntrypointsJSON(dir) {
238
- const entrypointsJSON = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(dir, 'entrypoints.json'), 'utf8'));
239
- if (Array.isArray(entrypointsJSON)) {
240
- return mapToRealEntrypoints(entrypointsJSON, dir);
168
+ function buildVerifiedConfig(config) {
169
+ testForDuplicatedEntryPaths(config);
170
+ const { standaloneBlocks = false, stats = 'errors-warnings', variables: rawVariables, verbose = process.argv.includes('--verbose') || process.env['VERBOSE'] === 'true', postcss = {}, externals, assumeGlobalizedPlauditLibraries = true, processTranslationConfigs = true, combineAssetMetadata = true, useWebpackResourceFiltering = true, outputDir = "", extensionsVersion = 1, plainEntrypointsHandlePrefix = "", plainEntrypointsVersion = 1, srcDir = "" } = config;
171
+ if (plainEntrypointsVersion > 1) {
172
+ if (!plainEntrypointsHandlePrefix) {
173
+ throw new Error("Plain Entrypoints V2 and higher require 'plainEntrypointsHandlePrefix' to be set");
174
+ }
175
+ if (!outputDir) {
176
+ throw new Error("Plain Entrypoints V2 and higher require 'outputDir' to be set");
177
+ }
241
178
  }
242
- else {
243
- return Object.entries(entrypointsJSON).map(([name, config]) => {
244
- if (typeof config === 'string') {
245
- return [name, joinPossiblyAbsolutePaths(dir, config)];
246
- }
247
- else if (Array.isArray(config)) {
248
- return [name, config.map(c => joinPossiblyAbsolutePaths(dir, c))];
249
- }
250
- else {
251
- if (typeof config.import === 'string') {
252
- config.import = joinPossiblyAbsolutePaths(dir, config.import);
179
+ let variablesFilePath = undefined;
180
+ const currentVariables = rawVariables ?? {};
181
+ if (!rawVariables) {
182
+ variablesFilePath = ["variables.js", "src/site/variables.js"].map(p => node_path_1.default.join(process.cwd(), p)).filter(p => node_fs_1.default.existsSync(p))[0];
183
+ }
184
+ const cfg = {
185
+ currentVariables, postcss, standaloneBlocks, stats, variablesFilePath, verbose, externals, assumeGlobalizedPlauditLibraries, processTranslationConfigs, combineAssetMetadata,
186
+ useWebpackResourceFiltering, outputDir, extensionsVersion, plainEntrypointsVersion, plainEntrypointsHandlePrefix, srcDir
187
+ };
188
+ const sources = (Array.isArray(config.src) ? config.src.map(s => [s, s]) : Object.entries(config.src))
189
+ .map(entry => {
190
+ let dest = typeof entry[1] === 'string' ? { destination: entry[1] } : entry[1];
191
+ if (srcDir) {
192
+ return [node_path_1.default.join(srcDir, entry[0]), dest];
193
+ }
194
+ const relativeSrc = node_path_1.default.isAbsolute(entry[0]) ? node_path_1.default.relative(process.cwd(), entry[0]) : entry[0];
195
+ if (node_path_1.default.isAbsolute(dest.destination)) {
196
+ dest = { ...dest, destination: node_path_1.default.relative(process.cwd(), dest.destination) };
197
+ }
198
+ return [relativeSrc, dest];
199
+ });
200
+ return cfg.outputDir ? { cfg, sources } : withDerivedOutputDir(cfg, sources);
201
+ }
202
+ function withDerivedOutputDir(cfg, sources) {
203
+ const destinations = sources.map(([_, { destination }]) => destination.split(/[\/\\]/g));
204
+ if (destinations.length < 2) {
205
+ return { cfg, sources };
206
+ }
207
+ const commonParent = destinations[0][0];
208
+ for (const destination of destinations) {
209
+ if (destination[0] !== commonParent) {
210
+ return { cfg, sources };
211
+ }
212
+ }
213
+ return {
214
+ cfg: { ...cfg, outputDir: commonParent },
215
+ sources: sources.map(([src, dest]) => {
216
+ return [src, { ...dest, destination: dest.destination.substring(commonParent.length + 1) }];
217
+ })
218
+ };
219
+ }
220
+ function handleDisablingTSCheckerIfNecessary(srcRoot, scriptExtension, plugins) {
221
+ if (process.env["NO_TS_CHECKER"] !== "true") {
222
+ const include = (Array.isArray(srcRoot) ? srcRoot : [srcRoot])
223
+ .filter(sr => node_path_1.default.extname(sr).length === 0 || (0, common_config_helpers_1.scriptOrStyleTest)(sr, scriptExtension) === "script")
224
+ .map(sr => node_path_1.default.extname(sr).length > 0 ? sr : node_path_1.default.join(sr, "**", "*"));
225
+ if (include.length > 0) {
226
+ plugins.push(new fork_ts_checker_webpack_plugin_1.default({
227
+ async: true,
228
+ typescript: {
229
+ diagnosticOptions: {
230
+ semantic: true,
231
+ syntactic: true,
232
+ },
233
+ configOverwrite: {
234
+ include,
235
+ compilerOptions: {
236
+ skipLibCheck: true
237
+ }
238
+ }
239
+ },
240
+ issue: {
241
+ exclude(issue) {
242
+ return issue.code === 'TS18003'; // This hides the "no TypeScript files found" error while still monitoring the directory
243
+ }
253
244
  }
254
- else {
255
- config.import = config.import.map(c => joinPossiblyAbsolutePaths(dir, c));
245
+ }));
246
+ }
247
+ }
248
+ }
249
+ function buildCommonPluginConfig(srcRoot, scriptExtension, webpackConfig, dest, config, sourceType) {
250
+ const { assumeGlobalizedPlauditLibraries, combineAssetMetadata, externals, extensionsVersion, plainEntrypointsVersion, variablesFilePath } = config;
251
+ const processingModules = webpackConfig.output?.module ?? false;
252
+ const plugins = webpackConfig.plugins?.filter(v => !!v)
253
+ .filter(plugin => plugin.constructor.name !== 'RtlCssPlugin')
254
+ .map(plugin => {
255
+ if (plugin.constructor.name === 'MiniCssExtractPlugin') {
256
+ return new plugin.constructor({
257
+ filename(pd) {
258
+ const name = pd.chunk?.name?.replaceAll(/__[a-zA-Z0-9]+__/g, ""); // This removes the prefix that the cache group adds
259
+ return name ? `${name}.css` : "[name].css";
256
260
  }
257
- return [name, config];
258
- }
259
- });
261
+ });
262
+ }
263
+ return plugin;
264
+ })
265
+ ?? [];
266
+ plugins.splice(0, 0, new PackageConfigSanityChecker_1.PackageConfigSanityChecker());
267
+ if (typeof dest !== 'string' && dest.bundleAnalyzer) {
268
+ plugins.splice(0, 0, new (require("webpack-bundle-analyzer").BundleAnalyzerPlugin)({ analyzerMode: 'static' }));
269
+ }
270
+ handleDisablingTSCheckerIfNecessary(srcRoot, scriptExtension, plugins);
271
+ const removeEmptyScriptsPlugin = new webpack_remove_empty_scripts_1.default({
272
+ stage: webpack_remove_empty_scripts_1.default.STAGE_AFTER_PROCESS_PLUGINS,
273
+ extensions: ['css', 'scss', 'sass', 'less', 'styl', 'pcss']
274
+ });
275
+ plugins.push(removeEmptyScriptsPlugin, new MiniCSSExtractPluginErrorCleaner_1.MiniCSSExtractPluginErrorCleaner());
276
+ if (config.useWebpackResourceFiltering) {
277
+ plugins.push(new SpecialAssetHandlingPlugin_1.SpecialAssetHandlingPlugin(config.outputDir));
278
+ }
279
+ if (variablesFilePath) {
280
+ plugins.push(new VariablesJSMonitorPlugin_1.VariablesJSMonitorPlugin(variablesFilePath));
281
+ }
282
+ const pluginIndex = plugins.findIndex(plugin => plugin instanceof dependency_extraction_webpack_plugin_1.default);
283
+ if (pluginIndex === -1) {
284
+ console.error("Cannot apply externals when they have been disabled via CLI flag. This will greatly increase bundle size and will likely cause the build to fail");
260
285
  }
286
+ else {
287
+ const localAssumeGlobalizedPlauditLibraries = (typeof dest !== 'string' ? dest.assumeGlobalizedPlauditLibraries : undefined) ?? assumeGlobalizedPlauditLibraries;
288
+ const wantsGroupedDepData = combineAssetMetadata
289
+ && ((!processingModules && sourceType === "blocks" /* SourceType.blocks */)
290
+ || (extensionsVersion > 1 && sourceType === "extensions" /* SourceType.extensions */)
291
+ || (plainEntrypointsVersion > 1 && sourceType === "plain" /* SourceType.plain */));
292
+ const builtDependencyExtractionWebpackPlugin = (0, dependency_extraction_webpack_plugin_config_builder_1.makeDependencyExtractionPlugin)(externals, localAssumeGlobalizedPlauditLibraries, wantsGroupedDepData, typeof dest !== 'string' ? dest.externalize : undefined);
293
+ plugins[pluginIndex] = builtDependencyExtractionWebpackPlugin.instance;
294
+ plugins.push(new AdditionalDependencyInjectorPlugin_1.AdditionalDependencyInjectorPlugin(typeof dest !== 'string' && dest.additionalDependencies ? dest.additionalDependencies : [], processingModules, builtDependencyExtractionWebpackPlugin.addExternalizedDep));
295
+ }
296
+ if (process.argv.includes('--browser-sync') || process.env['BROWSER_SYNC'] === 'true') {
297
+ plugins.push(new BrowserSyncPlugin_1.BrowserSyncPlugin());
298
+ }
299
+ return { plugins, removeEmptyScriptsPlugin };
261
300
  }
262
- function processIndividualWebpackConfig(config, webpackConfig, sources, sharedCache) {
301
+ function commonConfigProcessingPrep(config, webpackConfig) {
263
302
  let scriptExtension; // This is only used in non-block contexts. It might not actually be necessary, but it is good to have
264
303
  let entrypointFields;
265
- const processingModules = webpackConfig.output?.module ?? false;
304
+ const processingModules = webpackConfig.output?.module;
266
305
  if (processingModules) {
267
- scriptExtension = scriptWithModuleExtension;
306
+ scriptExtension = common_config_helpers_1.scriptWithModuleExtension;
268
307
  entrypointFields = ["viewScriptModule", "scriptModule"];
269
308
  }
270
309
  else {
271
- scriptExtension = scriptWithoutModuleExtension;
310
+ scriptExtension = common_config_helpers_1.scriptWithoutModuleExtension;
272
311
  entrypointFields = ["editorStyle", "viewStyle", "style", "editorScript", "viewScript", "script"];
273
312
  }
274
- const { standaloneBlocks, variablesFilePath, verbose, externals, assumeGlobalizedPlauditLibraries, combineAssetMetadata } = config;
275
313
  let currentVariables = config.currentVariables;
276
314
  const fixedRules = [
277
315
  replaceDefaultURLProcessing(config.useWebpackResourceFiltering),
278
316
  (rules) => {
279
- return injectPostcssConfigOverrides(rules, name => currentVariables[name], config.postcss.functions ?? (() => ({})), verbose);
317
+ return injectPostcssConfigOverrides(rules, config, name => currentVariables[name], config.postcss.functions ?? (() => ({})), config.verbose);
280
318
  },
281
319
  injectSupportForInliningSVGsAsStrings
282
320
  ].reduce((r, a) => a(r), webpackConfig.module?.rules ?? []);
@@ -290,349 +328,103 @@ function processIndividualWebpackConfig(config, webpackConfig, sources, sharedCa
290
328
  }
291
329
  });
292
330
  }
331
+ return {
332
+ entrypointFields, fixedRules, processingModules, scriptExtension,
333
+ updateCurrentVariables: (value) => currentVariables = value
334
+ };
335
+ }
336
+ //TODO: Try using context to avoid needing to cobble dest paths together?
337
+ function processIndividualWebpackConfig(config, webpackConfig, sources) {
338
+ const commonConfig = commonConfigProcessingPrep(config, webpackConfig);
339
+ const { processingModules, scriptExtension } = commonConfig;
293
340
  return sources.map(([src, dest]) => {
294
- const srcRoots = (typeof dest !== 'string' && dest.withLegacyBlocksIn
295
- ? [...src.split(','), ...resolveLegacyBlockScriptsInFolder(dest.withLegacyBlocksIn)]
296
- : src.split(',')).filter(s => s.endsWith(".json") || !s.substring(s.lastIndexOf('/')).includes('.') || processingModules === scriptWithModuleExtension.test(s));
297
- const destPath = typeof dest === 'string' ? dest : dest.destination;
298
- const srcRoot = srcRoots.length === 1 ? joinPossiblyAbsolutePaths(process.cwd(), src) : srcRoots.map(s => joinPossiblyAbsolutePaths(process.cwd(), s));
341
+ const srcRoots = (dest.withLegacyBlocksIn
342
+ ? [...src.split(','), ...resolveLegacyBlockScriptsInFolder(node_path_1.default.join(config.srcDir, dest.withLegacyBlocksIn))]
343
+ : src.split(',')).filter(s => s.endsWith(".json") || !s.substring(s.lastIndexOf('/')).includes('.') || processingModules === common_config_helpers_1.scriptWithModuleExtension.test(s));
344
+ const srcRoot = srcRoots.length < 2 ? (0, common_config_helpers_1.joinPossiblyAbsolutePaths)(process.cwd(), src) : srcRoots.map(s => (0, common_config_helpers_1.joinPossiblyAbsolutePaths)(process.cwd(), s));
299
345
  const srcIsDirectory = !Array.isArray(srcRoot) && node_fs_1.default.lstatSync(srcRoot, { throwIfNoEntry: false })?.isDirectory();
300
346
  if (srcIsDirectory === undefined) {
301
347
  return undefined;
302
348
  }
303
- const copyFiles = srcIsDirectory && src !== dest;
304
- const plugins = webpackConfig.plugins?.filter(v => !!v)
305
- .filter(plugin => plugin.constructor.name !== 'RtlCssPlugin')
306
- .map(plugin => {
307
- if (plugin.constructor.name === 'MiniCssExtractPlugin') {
308
- return new plugin.constructor({
309
- filename(pd) {
310
- const name = pd.chunk?.name?.replaceAll(/__[a-zA-Z0-9]+__/g, ""); // This removes the prefix that the cache group adds
311
- return name ? `${name}.css` : "[name].css";
312
- }
313
- });
314
- }
315
- return plugin;
316
- })
317
- ?? [];
318
- plugins.splice(0, 0, new PackageConfigSanityChecker_1.PackageConfigSanityChecker());
319
- if (typeof dest !== 'string' && dest.bundleAnalyzer) {
320
- plugins.splice(0, 0, new (require("webpack-bundle-analyzer").BundleAnalyzerPlugin)({ analyzerMode: 'static' }));
321
- }
322
- if (process.env["NO_TS_CHECKER"] !== "true") {
323
- const include = (Array.isArray(srcRoot) ? srcRoot : [srcRoot])
324
- .filter(sr => node_path_1.default.extname(sr).length === 0 || scriptOrStyleTest(sr, scriptExtension) === "script")
325
- .map(sr => node_path_1.default.extname(sr).length > 0 ? sr : node_path_1.default.join(sr, "**", "*"));
326
- if (include.length > 0) {
327
- plugins.push(new fork_ts_checker_webpack_plugin_1.default({
328
- async: true,
329
- typescript: {
330
- diagnosticOptions: {
331
- semantic: true,
332
- syntactic: true,
333
- },
334
- configOverwrite: {
335
- include,
336
- compilerOptions: {
337
- skipLibCheck: true
338
- }
339
- }
340
- },
341
- issue: {
342
- exclude(issue) {
343
- return issue.code === 'TS18003'; // This hides the "no TypeScript files found" error while still monitoring the directory
344
- }
345
- }
346
- }));
347
- }
348
- }
349
- plugins.push(new webpack_remove_empty_scripts_1.default({
350
- stage: webpack_remove_empty_scripts_1.default.STAGE_AFTER_PROCESS_PLUGINS,
351
- extensions: ['css', 'scss', 'sass', 'less', 'styl', 'pcss']
352
- }), new MiniCSSExtractPluginErrorCleaner_1.MiniCSSExtractPluginErrorCleaner());
353
- if (config.useWebpackResourceFiltering) {
354
- plugins.push(new SpecialAssetHandlingPlugin_1.SpecialAssetHandlingPlugin(sharedCache));
355
- }
356
- if (variablesFilePath) {
357
- plugins.push(new VariablesJSMonitorPlugin_1.VariablesJSMonitorPlugin(variablesFilePath));
358
- }
359
- const forBlocksDirectory = copyFiles && (typeof dest === 'string' || (dest.directoryLayout !== 'extensions' && dest.directoryLayout !== 'plain'));
360
- if (forBlocksDirectory) {
361
- const blockJSONManagingPlugin = new BlockJSONManagingPlugin_1.BlockJSONManagingPlugin(standaloneBlocks, processingModules);
362
- plugins.push(blockJSONManagingPlugin);
363
- if (config.processTranslationConfigs && srcIsDirectory && !processingModules) {
364
- plugins.push(new WPMLConfigBuilder_1.WPMLConfigBuilderPlugin(blockJSONManagingPlugin));
365
- }
366
- }
367
- const pluginIndex = plugins.findIndex(plugin => plugin instanceof dependency_extraction_webpack_plugin_1.default);
368
- if (pluginIndex === -1) {
369
- console.error("Cannot apply externals when they have been disabled via CLI flag. This will greatly increase bundle size and will likely cause the build to fail");
370
- }
371
- else {
372
- const localAssumeGlobalizedPlauditLibraries = (typeof dest !== 'string' ? dest.assumeGlobalizedPlauditLibraries : undefined) ?? assumeGlobalizedPlauditLibraries;
373
- const builtDependencyExtractionWebpackPlugin = (0, dependency_extraction_webpack_plugin_config_builder_1.makeDependencyExtractionPlugin)(externals, localAssumeGlobalizedPlauditLibraries, combineAssetMetadata && !processingModules && forBlocksDirectory, typeof dest !== 'string' ? dest.externalize : undefined);
374
- plugins[pluginIndex] = builtDependencyExtractionWebpackPlugin.instance;
375
- plugins.push(new AdditionalDependencyInjectorPlugin_1.AdditionalDependencyInjectorPlugin(typeof dest !== 'string' && dest.additionalDependencies ? dest.additionalDependencies : [], processingModules, builtDependencyExtractionWebpackPlugin.addExternalizedDep));
376
- }
377
- if (srcIsDirectory && (typeof dest !== 'string' && dest.directoryLayout === 'extensions')) {
378
- plugins.push(new ExtensionsConfigFileGeneratorPlugin_1.ExtensionsConfigFileGeneratorPlugin(srcRoot));
379
- }
380
- if (process.argv.includes('--browser-sync') || process.env['BROWSER_SYNC'] === 'true') {
381
- plugins.push(new BrowserSyncPlugin_1.BrowserSyncPlugin());
382
- }
383
- let entry;
384
- if (srcIsDirectory) {
385
- if (typeof dest !== 'string' && dest.directoryLayout === 'extensions') {
386
- entry = async () => {
387
- const rawEntrypoints = [];
388
- for await (const dirent of await promises_1.default.opendir(srcRoot)) {
389
- if (dirent.isFile() && !dirent.name.startsWith("~")) {
390
- if (scriptExtension.test(dirent.name) || styleExtension.test(dirent.name)) {
391
- const file = joinPossiblyAbsolutePaths(srcRoot, dirent.name);
392
- rawEntrypoints.push([node_path_1.default.basename(file, node_path_1.default.extname(file)), file]);
393
- }
394
- }
395
- }
396
- return Object.fromEntries(rawEntrypoints);
397
- };
398
- }
399
- else {
400
- entry = async () => {
401
- const loadingEntrypoints = [];
402
- for await (const dirent of await promises_1.default.opendir(srcRoot)) {
403
- if (!dirent.isDirectory()) {
404
- continue;
405
- }
406
- const dir = joinPossiblyAbsolutePaths(srcRoot, dirent.name);
407
- loadingEntrypoints.push(new Promise(async (resolve) => {
408
- const rawEntrypoints = [];
409
- const wpmlFiles = [];
410
- try {
411
- const blockJSON = JSON.parse(await promises_1.default.readFile(node_path_1.default.join(dir, 'block.json'), 'utf8'));
412
- const blockJSONChunkName = node_path_1.default.join(node_path_1.default.basename(dir), "block.json");
413
- for (const key of entrypointFields) {
414
- if (key in blockJSON) {
415
- rawEntrypoints.push(...mapToRealEntrypoints(blockJSON[key], dir, ep => ep.startsWith("file:") ? ep.substring(5) : ep, blockJSONChunkName));
416
- }
417
- }
418
- wpmlFiles.push(node_path_1.default.join(dir, 'block.json'));
419
- BlockJSONManagingPlugin_1.BlockJSONManagingPlugin.recordBlockJSONAssetSourceDir(blockJSONChunkName, dir);
420
- }
421
- catch (e) {
422
- try {
423
- const packageJSON = JSON.parse(await promises_1.default.readFile(node_path_1.default.join(dir, 'package.json'), 'utf8'));
424
- rawEntrypoints.push(...mapToRealEntrypoints(packageJSON['main'], dir));
425
- rawEntrypoints.push(...mapToRealEntrypoints(packageJSON['style'], dir));
426
- }
427
- catch (e) {
428
- try {
429
- rawEntrypoints.push(...parseEntrypointsJSON(dir));
430
- }
431
- catch (e) {
432
- // This just means that the directory doesn't contain any declared entrypoints.
433
- }
434
- }
435
- }
436
- if (!processingModules) {
437
- try {
438
- const wpmlFilePath = node_path_1.default.join(dir, "wpml-config.xml");
439
- await promises_1.default.access(wpmlFilePath);
440
- wpmlFiles.push(wpmlFilePath);
441
- }
442
- catch (e) {
443
- // This just means that the file doesn't exist
444
- }
445
- }
446
- resolve([rawEntrypoints, wpmlFiles]);
447
- }));
448
- }
449
- const allEntrypoints = await Promise.all(loadingEntrypoints);
450
- const perAssetPathGroupedEntrypoints = groupEntrypointsByAssetFile(allEntrypoints.flatMap(e => e[0]), e => e[0]);
451
- const currentEntry = {};
452
- for (const groupedEntrypoints of perAssetPathGroupedEntrypoints.values()) {
453
- if (groupedEntrypoints.length === 1 && groupedEntrypoints[0] !== undefined) {
454
- currentEntry[groupedEntrypoints[0][0]] = groupedEntrypoints[0][1];
455
- }
456
- else {
457
- const typeCounts = {};
458
- for (const entrypoint of groupedEntrypoints) {
459
- addPotentiallyDuplicatedEntrypointName(currentEntry, entrypoint, typeCounts, scriptExtension);
460
- }
461
- }
462
- }
463
- // This is used to allow for block.json dependencies to correctly account for name-deduplication
464
- for (const [key, entry] of Object.entries(currentEntry)) {
465
- if (typeof entry === 'object' && !Array.isArray(entry) && 'lazyDependent' in entry && typeof entry.lazyDependent === 'string') {
466
- BlockJSONManagingPlugin_1.BlockJSONManagingPlugin.recordRawDependency(entry.lazyDependent, key);
467
- }
468
- }
469
- if (!processingModules) {
470
- const wpmlEntrypointFiles = allEntrypoints.flatMap(e => e[1]);
471
- try {
472
- await promises_1.default.access(node_path_1.default.join(srcRoot, "wpml-config.xml"));
473
- currentEntry["wpml-config.xml"] = { import: [node_path_1.default.join(srcRoot, "wpml-config.xml"), ...wpmlEntrypointFiles] };
474
- }
475
- catch (e) {
476
- if (wpmlEntrypointFiles.length) {
477
- currentEntry["wpml-config.xml"] = { import: wpmlEntrypointFiles };
478
- }
479
- }
480
- }
481
- return currentEntry;
482
- };
483
- }
484
- }
485
- else {
486
- const baseDest = node_path_1.default.basename(destPath);
487
- entry = () => ({
488
- [baseDest.includes('.') ? node_path_1.default.basename(baseDest, node_path_1.default.extname(baseDest)) : baseDest]: srcRoot
489
- });
490
- }
491
- const outPath = joinPossiblyAbsolutePaths(process.cwd(), config.outputDir, srcIsDirectory ? destPath : node_path_1.default.dirname(destPath));
492
- let publicPath = webpackConfig.output?.publicPath;
493
- if (isInTheme()) {
494
- let prefix = process.cwd();
495
- while (prefix.length > 5 && node_path_1.default.basename(prefix) !== "wp-content") {
496
- prefix = node_path_1.default.dirname(prefix);
497
- }
498
- if (prefix.length > 5) {
499
- prefix = node_path_1.default.dirname(prefix);
500
- publicPath = `/${node_path_1.default.relative(prefix, outPath)}/`;
501
- }
502
- }
503
- let viableRoots = [...(Array.isArray(webpackConfig.context) ? webpackConfig.context : [webpackConfig.context ?? process.cwd()])];
504
- if (Array.isArray(srcRoot)) {
505
- viableRoots.push(...(srcIsDirectory ? srcRoot : srcRoot.map(s => node_path_1.default.dirname(s))));
506
- }
507
- else {
508
- viableRoots.push(srcIsDirectory ? srcRoot : node_path_1.default.dirname(srcRoot));
509
- }
510
- let wpContentHolderDirectory = process.cwd();
511
- while (wpContentHolderDirectory.length > 5) {
512
- if (node_path_1.default.basename(wpContentHolderDirectory) === 'wp-content') {
513
- wpContentHolderDirectory = node_path_1.default.dirname(wpContentHolderDirectory);
514
- if (wpContentHolderDirectory.length > 5) {
515
- viableRoots.push(wpContentHolderDirectory);
349
+ switch ((0, shared_1.determineCurrentSourceType)(dest, srcIsDirectory)) {
350
+ case "blocks" /* SourceType.blocks */: {
351
+ if (!srcIsDirectory) {
352
+ return undefined;
516
353
  }
517
- break;
518
- }
519
- wpContentHolderDirectory = node_path_1.default.dirname(wpContentHolderDirectory);
520
- }
521
- const distinctViableRoots = new Set();
522
- viableRoots = viableRoots.filter(value => distinctViableRoots.has(value) ? false : distinctViableRoots.add(value) && true);
523
- let outputLibrary;
524
- if (typeof dest === 'object' && dest.externalize) {
525
- if (Array.isArray(dest.externalize) || typeof dest.externalize === 'string') {
526
- outputLibrary = {
527
- name: dest.externalize,
528
- type: "assign"
529
- };
354
+ const { plugins } = buildCommonPluginConfig(srcRoot, scriptExtension, webpackConfig, dest, config, "blocks" /* SourceType.blocks */);
355
+ return makeBlocksWebpackConfig(config, commonConfig, webpackConfig, dest, src, srcRoot, plugins);
530
356
  }
531
- else {
532
- const originalLibrary = webpackConfig.output?.library;
533
- if (originalLibrary && typeof originalLibrary === 'object' && !Array.isArray(originalLibrary)) {
534
- outputLibrary = {
535
- ...originalLibrary,
536
- ...dest.externalize
537
- };
538
- }
539
- else {
540
- outputLibrary = dest.externalize;
357
+ case "extensions" /* SourceType.extensions */: {
358
+ if (!srcIsDirectory) {
359
+ return undefined;
541
360
  }
361
+ const { plugins } = buildCommonPluginConfig(srcRoot, scriptExtension, webpackConfig, dest, config, "extensions" /* SourceType.extensions */);
362
+ return makeExtensionsWebpackConfig(config, commonConfig, webpackConfig, dest, src, srcRoot, plugins);
542
363
  }
543
- }
544
- else {
545
- outputLibrary = webpackConfig.output?.library;
546
- }
547
- return {
548
- ...webpackConfig,
549
- devtool: 'source-map',
550
- mode: "production",
551
- output: {
552
- ...webpackConfig.output,
553
- path: outPath,
554
- chunkFilename: 'webpack-chunks/[id].js',
555
- publicPath: publicPath,
556
- library: outputLibrary
557
- },
558
- optimization: {
559
- ...webpackConfig.optimization,
560
- splitChunks: {
561
- ...(webpackConfig.optimization?.splitChunks || {}),
562
- cacheGroups: {
563
- style: {
564
- // This is a flagrant abuse of cache groups, but it fixes a persistent problem wherein the dependencies and versions of scripts and styles were bleeding into each-other
565
- type: 'css/mini-extract',
566
- chunks: 'all',
567
- enforce: true,
568
- name(_, chunks, cacheGroupKey) {
569
- const chunkName = chunks.find(chunk => chunk.name)?.name;
570
- // We use "__${cacheGroupKey}__" instead of "${cacheGroupKey}-" to make it easier to remove when generating the filename
571
- const filename = `__${cacheGroupKey}__${node_path_1.default.basename(chunkName)}`;
572
- const dirname = node_path_1.default.dirname(chunkName);
573
- return dirname === '.' ? filename : `${dirname}/${filename}`;
574
- }
575
- },
576
- default: false
577
- }
578
- }
579
- },
580
- module: {
581
- ...webpackConfig.module,
582
- rules: fixedRules
583
- },
584
- resolve: {
585
- ...webpackConfig.resolve,
586
- roots: viableRoots,
587
- extensions: ['.mjsx', '.mjs', '.mtsx', '.mts', '.jsx', '.tsx', '.ts', '...']
588
- },
589
- stats: config.stats,
590
- plugins: copyFiles
591
- ? plugins.map(plugin => !processingModules && plugin.constructor.name === 'CopyPlugin'
592
- ? new copy_webpack_plugin_1.default({ patterns: [{ from: standaloneBlocks ? '**/(block.json|*.(php|twig|svg))' : '**/(block.json|*.(asset\.php|svg))',
593
- context: srcRoot, noErrorOnMissing: true }] })
594
- : plugin)
595
- : (srcIsDirectory
596
- ? plugins.filter(plugin => plugin.constructor.name !== 'CopyPlugin' && plugin.constructor.name !== 'CleanWebpackPlugin')
597
- : plugins.filter(plugin => plugin.constructor.name !== 'CopyPlugin')),
598
- entry() {
599
- if (variablesFilePath) {
600
- delete require.cache[require.resolve(variablesFilePath)];
601
- currentVariables = require(variablesFilePath);
364
+ case "plain" /* SourceType.plain */:
365
+ if (config.plainEntrypointsVersion > 1) {
366
+ // plainEntrypoints.push({dest, src, srcRoot});
367
+ // return undefined;
368
+ return makePlainV2WebpackConfig(config, commonConfig, webpackConfig, dest, src, srcRoot, srcIsDirectory);
602
369
  }
603
- return entry();
604
- },
605
- performance: {
606
- ...webpackConfig.performance,
607
- assetFilter(assetFilename) {
608
- // We don't want to warn about the sizes of incompressible assets
609
- return !/\.(map|svg|png|jpe?g|gif)$/i.test(assetFilename);
610
- }
611
- }
612
- };
370
+ const { plugins } = buildCommonPluginConfig(srcRoot, scriptExtension, webpackConfig, dest, config, "plain" /* SourceType.plain */);
371
+ return makePlainV1WebpackConfig(config, commonConfig, webpackConfig, dest, src, srcRoot, plugins, srcIsDirectory);
372
+ }
613
373
  }).filter(cfg => cfg !== undefined);
614
374
  }
615
- module.exports = function (config, webpackConfig = require("@wordpress/scripts/config/webpack.config")) {
616
- testForDuplicatedEntryPaths(config);
617
- const { standaloneBlocks = false, stats = 'errors-warnings', variables: rawVariables, verbose = process.argv.includes('--verbose') || process.env['VERBOSE'] === 'true', postcss = {}, externals, assumeGlobalizedPlauditLibraries = true, processTranslationConfigs = true, combineAssetMetadata = true, useWebpackResourceFiltering = true, outputDir = "" } = config;
618
- let variablesFilePath = undefined;
619
- const currentVariables = rawVariables ?? {};
620
- if (!rawVariables) {
621
- variablesFilePath = ["variables.js", "src/site/variables.js"].map(p => node_path_1.default.join(process.cwd(), p)).filter(p => node_fs_1.default.existsSync(p))[0];
375
+ function makeBlocksWebpackConfig(config, commonConfig, webpackConfig, dest, src, srcRoot, plugins) {
376
+ const { processingModules } = commonConfig;
377
+ const blockJSONManagingPlugin = new BlockJSONManagingPlugin_1.BlockJSONManagingPlugin(config.standaloneBlocks, processingModules, dest.destination);
378
+ plugins.push(blockJSONManagingPlugin);
379
+ if (config.processTranslationConfigs && !processingModules) {
380
+ plugins.push(new WPMLConfigBuilder_1.WPMLConfigBuilderPlugin(blockJSONManagingPlugin, dest.destination));
622
381
  }
623
- const cfg = {
624
- currentVariables, postcss, standaloneBlocks, stats, variablesFilePath, verbose, externals, assumeGlobalizedPlauditLibraries, processTranslationConfigs, combineAssetMetadata,
625
- useWebpackResourceFiltering, outputDir
382
+ return (0, common_config_helpers_1.commonMakeWebpackConfig)(config, commonConfig, webpackConfig, true, dest, src, srcRoot, (0, common_config_helpers_1.resolveEntryFromDirectory)(commonConfig, srcRoot, dest), plugins);
383
+ }
384
+ function makeExtensionsWebpackConfig(config, commonConfig, webpackConfig, dest, src, srcRoot, plugins) {
385
+ plugins.push(new ExtensionsConfigFileGeneratorPlugin_1.ExtensionsConfigFileGeneratorPlugin(srcRoot, config.extensionsVersion, dest.destination));
386
+ const entry = async () => {
387
+ const rawEntrypoints = [];
388
+ for await (const dirent of await promises_1.default.opendir(srcRoot)) {
389
+ if (dirent.isFile() && !dirent.name.startsWith("~")) {
390
+ if (commonConfig.scriptExtension.test(dirent.name) || common_config_helpers_1.styleExtension.test(dirent.name)) {
391
+ const file = (0, common_config_helpers_1.joinPossiblyAbsolutePaths)(srcRoot, dirent.name);
392
+ rawEntrypoints.push([node_path_1.default.join(dest.destination, node_path_1.default.basename(file, node_path_1.default.extname(file))), file]);
393
+ }
394
+ }
395
+ }
396
+ return Object.fromEntries(rawEntrypoints);
626
397
  };
627
- const sources = Array.isArray(config.src) ? config.src.map(s => [s, s]) : Object.entries(config.src);
628
- const sharedCache = {};
398
+ return (0, common_config_helpers_1.commonMakeWebpackConfig)(config, commonConfig, webpackConfig, true, dest, src, srcRoot, entry, plugins);
399
+ }
400
+ function makePlainV1WebpackConfig(config, commonConfig, webpackConfig, dest, src, srcRoot, plugins, srcIsDirectory) {
401
+ const baseDest = stripExtension(dest.destination);
402
+ const entry = srcIsDirectory // This being true implies that srcRoot is not an array
403
+ ? (0, common_config_helpers_1.resolveEntryFromDirectory)(commonConfig, srcRoot, dest)
404
+ : () => ({ [baseDest]: srcRoot });
405
+ return (0, common_config_helpers_1.commonMakeWebpackConfig)(config, commonConfig, webpackConfig, srcIsDirectory, dest, src, srcRoot, entry, plugins);
406
+ }
407
+ function makePlainV2WebpackConfig(config, commonConfig, webpackConfig, dest, src, srcRoot, srcIsDirectory) {
408
+ const { plugins } = buildCommonPluginConfig(srcRoot, commonConfig.scriptExtension, webpackConfig, dest, config, "extensions" /* SourceType.extensions */);
409
+ plugins.push(new PlainEntrypointsConfigFileGeneratorPlugin_1.PlainEntrypointsConfigFileGeneratorPlugin(process.cwd(), config.outputDir, dest.locations ?? {}, config.plainEntrypointsHandlePrefix));
410
+ const baseDest = stripExtension(dest.destination);
411
+ const entry = srcIsDirectory // This being true implies that srcRoot is not an array
412
+ ? (0, common_config_helpers_1.resolveEntryFromDirectory)(commonConfig, srcRoot, dest)
413
+ : () => ({ [baseDest]: srcRoot });
414
+ return (0, common_config_helpers_1.commonMakeWebpackConfig)(config, commonConfig, webpackConfig, srcIsDirectory, dest, src, srcRoot, entry, plugins);
415
+ }
416
+ function stripExtension(filepath) {
417
+ return node_path_1.default.join(node_path_1.default.dirname(filepath), node_path_1.default.basename(filepath, node_path_1.default.extname(filepath)));
418
+ }
419
+ module.exports = function (config, webpackConfig = require("@wordpress/scripts/config/webpack.config")) {
420
+ const { cfg, sources } = buildVerifiedConfig(config);
629
421
  if (Array.isArray(webpackConfig)) {
630
422
  return webpackConfig.toSorted((a, b) => {
631
423
  if (a.output?.module) {
632
424
  return b.output?.module ? 0 : -1;
633
425
  }
634
426
  return b.output?.module ? 1 : 0;
635
- }).flatMap(wpCfg => processIndividualWebpackConfig(cfg, wpCfg, sources, sharedCache));
427
+ }).flatMap(wpCfg => processIndividualWebpackConfig(cfg, wpCfg, sources));
636
428
  }
637
- return processIndividualWebpackConfig(cfg, webpackConfig, sources, sharedCache);
429
+ return processIndividualWebpackConfig(cfg, webpackConfig, sources);
638
430
  };