@plaudit/webpack-extensions 3.21.2 → 4.0.0-rc.1

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 (61) hide show
  1. package/CHANGELOG.md +9 -1
  2. package/USER-GUIDE.md +2 -1
  3. package/package.json +27 -49
  4. package/dist/plugins/AbstractBiPhasicGroupAndEntryPlugin.d.ts +0 -25
  5. package/dist/plugins/AbstractBiPhasicGroupAndEntryPlugin.js +0 -86
  6. package/dist/plugins/AbstractBiPhasicGroupPlugin.d.ts +0 -31
  7. package/dist/plugins/AbstractBiPhasicGroupPlugin.js +0 -91
  8. package/dist/plugins/AdditionalDependencyInjectorPlugin.d.ts +0 -11
  9. package/dist/plugins/AdditionalDependencyInjectorPlugin.js +0 -58
  10. package/dist/plugins/EnhancedBlockJSONPlugin.d.ts +0 -47
  11. package/dist/plugins/EnhancedBlockJSONPlugin.js +0 -657
  12. package/dist/plugins/EnhancedDynamicEntryPlugin.d.ts +0 -8
  13. package/dist/plugins/EnhancedDynamicEntryPlugin.js +0 -14
  14. package/dist/plugins/ExtensionsConfigFileGeneratorPlugin.d.ts +0 -20
  15. package/dist/plugins/ExtensionsConfigFileGeneratorPlugin.js +0 -191
  16. package/dist/plugins/ExtensionsConfigFileGeneratorPluginV1.d.ts +0 -9
  17. package/dist/plugins/ExtensionsConfigFileGeneratorPluginV1.js +0 -45
  18. package/dist/plugins/MiniCSSExtractPluginErrorCleaner.d.ts +0 -4
  19. package/dist/plugins/MiniCSSExtractPluginErrorCleaner.js +0 -15
  20. package/dist/plugins/MixableBiPhasicGroupAndEntryPlugin.d.ts +0 -6
  21. package/dist/plugins/MixableBiPhasicGroupAndEntryPlugin.js +0 -13
  22. package/dist/plugins/MixableBiPhasicGroupPlugin.d.ts +0 -6
  23. package/dist/plugins/MixableBiPhasicGroupPlugin.js +0 -13
  24. package/dist/plugins/PackageConfigSanityChecker.d.ts +0 -4
  25. package/dist/plugins/PackageConfigSanityChecker.js +0 -30
  26. package/dist/plugins/PlainEntrypointsConfigFileGeneratorPlugin.d.ts +0 -26
  27. package/dist/plugins/PlainEntrypointsConfigFileGeneratorPlugin.js +0 -392
  28. package/dist/plugins/SpecialAssetHandlingPlugin.d.ts +0 -12
  29. package/dist/plugins/SpecialAssetHandlingPlugin.js +0 -134
  30. package/dist/plugins/UnifiedLoaderGenerator.d.ts +0 -21
  31. package/dist/plugins/UnifiedLoaderGenerator.js +0 -144
  32. package/dist/plugins/VariablesJSMonitorPlugin.d.ts +0 -7
  33. package/dist/plugins/VariablesJSMonitorPlugin.js +0 -20
  34. package/dist/plugins/WPMLConfigBuilder.d.ts +0 -17
  35. package/dist/plugins/WPMLConfigBuilder.js +0 -472
  36. package/dist/plugins/dependency-extraction-webpack-plugin-config-builder.d.ts +0 -4
  37. package/dist/plugins/dependency-extraction-webpack-plugin-config-builder.js +0 -147
  38. package/dist/plugins/index.d.ts +0 -8
  39. package/dist/plugins/index.js +0 -24
  40. package/dist/plugins/static-configs.d.ts +0 -3
  41. package/dist/plugins/static-configs.js +0 -44
  42. package/dist/shared.d.ts +0 -311
  43. package/dist/shared.js +0 -536
  44. package/dist/utils/common-config-helpers.d.ts +0 -28
  45. package/dist/utils/common-config-helpers.js +0 -489
  46. package/dist/utils/css-writer.d.ts +0 -4
  47. package/dist/utils/css-writer.js +0 -46
  48. package/dist/utils/entrypoint-resolution-logic.d.ts +0 -13
  49. package/dist/utils/entrypoint-resolution-logic.js +0 -82
  50. package/dist/utils/location-encoding-filename-parser.d.ts +0 -30
  51. package/dist/utils/location-encoding-filename-parser.js +0 -120
  52. package/dist/utils/path-query-and-related-helpers.d.ts +0 -64
  53. package/dist/utils/path-query-and-related-helpers.js +0 -269
  54. package/dist/utils/pseudo-semaphore.d.ts +0 -14
  55. package/dist/utils/pseudo-semaphore.js +0 -79
  56. package/dist/wordpress-ports/dependency-extraction-webpack-plugin/index.d.ts +0 -72
  57. package/dist/wordpress-ports/dependency-extraction-webpack-plugin/index.js +0 -518
  58. package/dist/wordpress-ports/dependency-extraction-webpack-plugin/util.d.ts +0 -56
  59. package/dist/wordpress-ports/dependency-extraction-webpack-plugin/util.js +0 -155
  60. package/dist/wordpress-scripts-wrapper.d.ts +0 -4
  61. package/dist/wordpress-scripts-wrapper.js +0 -698
@@ -1,698 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- const node_fs_1 = require("node:fs");
6
- const promises_1 = require("node:fs/promises");
7
- const node_path_1 = require("node:path");
8
- const shared_1 = require("./shared");
9
- const entrypoint_resolution_logic_1 = require("./utils/entrypoint-resolution-logic");
10
- const common_config_helpers_1 = require("./utils/common-config-helpers");
11
- const path_query_and_related_helpers_1 = require("./utils/path-query-and-related-helpers");
12
- const AdditionalDependencyInjectorPlugin_1 = require("./plugins/AdditionalDependencyInjectorPlugin");
13
- const dependency_extraction_webpack_plugin_config_builder_1 = require("./plugins/dependency-extraction-webpack-plugin-config-builder");
14
- const EnhancedDynamicEntryPlugin_1 = require("./plugins/EnhancedDynamicEntryPlugin");
15
- const ExtensionsConfigFileGeneratorPlugin_1 = require("./plugins/ExtensionsConfigFileGeneratorPlugin");
16
- const ExtensionsConfigFileGeneratorPluginV1_1 = require("./plugins/ExtensionsConfigFileGeneratorPluginV1");
17
- const MiniCSSExtractPluginErrorCleaner_1 = require("./plugins/MiniCSSExtractPluginErrorCleaner");
18
- const PackageConfigSanityChecker_1 = require("./plugins/PackageConfigSanityChecker");
19
- const PlainEntrypointsConfigFileGeneratorPlugin_1 = require("./plugins/PlainEntrypointsConfigFileGeneratorPlugin");
20
- const EnhancedBlockJSONPlugin_1 = require("./plugins/EnhancedBlockJSONPlugin");
21
- const SpecialAssetHandlingPlugin_1 = require("./plugins/SpecialAssetHandlingPlugin");
22
- const VariablesJSMonitorPlugin_1 = require("./plugins/VariablesJSMonitorPlugin");
23
- const WPMLConfigBuilder_1 = require("./plugins/WPMLConfigBuilder");
24
- const static_configs_1 = require("./plugins/static-configs");
25
- const UnifiedLoaderGenerator_1 = require("./plugins/UnifiedLoaderGenerator");
26
- const copy_webpack_plugin_1 = __importDefault(require("copy-webpack-plugin"));
27
- const fork_ts_checker_webpack_plugin_1 = __importDefault(require("fork-ts-checker-webpack-plugin"));
28
- const webpack_remove_empty_scripts_1 = __importDefault(require("webpack-remove-empty-scripts"));
29
- const location_encoding_filename_parser_1 = require("./utils/location-encoding-filename-parser");
30
- function testForDuplicatedEntryPaths(sources) {
31
- const seenPaths = (0, common_config_helpers_1.groupEntrypointsByAssetFile)(Array.isArray(sources)
32
- ? sources.map(s => typeof s === 'string' ? s : s[1].destination)
33
- : Object.values(sources).map(bn => typeof bn === 'string' ? bn : bn.destination), bn => bn);
34
- let projectPrefix = undefined;
35
- let duplicatedPaths = "";
36
- for (const sameNamePaths of seenPaths.values()) {
37
- if (sameNamePaths.length > 1) {
38
- if (projectPrefix === undefined) {
39
- for (let p = process.cwd(); p.length > 1; p = (0, node_path_1.dirname)(p)) {
40
- if ((0, node_fs_1.existsSync)((0, node_path_1.join)(p, "docker-compose.yml"))) {
41
- projectPrefix = new RegExp(`^${p}`);
42
- break;
43
- }
44
- }
45
- if (projectPrefix === undefined) {
46
- projectPrefix = /^/;
47
- }
48
- }
49
- duplicatedPaths += `\n* ${(0, node_path_1.dirname)(sameNamePaths[0]).replace(projectPrefix, '')}/[${sameNamePaths.map(p => (0, node_path_1.basename)(p)).join(', ')}]`;
50
- }
51
- }
52
- if (duplicatedPaths.length !== 0) {
53
- console.error(`Encountered multiple paths that produce the same effective bundle name:${duplicatedPaths}`);
54
- process.exit(1);
55
- }
56
- }
57
- function replaceDefaultURLProcessing(useWebpackResourceFiltering) {
58
- return (rules) => {
59
- const cssLoader = require.resolve('css-loader');
60
- if (cssLoader) {
61
- return rules.map(rule => {
62
- if (rule && typeof rule === 'object' && "use" in rule && Array.isArray(rule.use)) {
63
- return {
64
- ...rule,
65
- use: rule.use.map(useElement => {
66
- if (useElement && typeof useElement === 'object' && useElement.loader === cssLoader && typeof useElement.options === 'object') {
67
- return {
68
- ...useElement,
69
- options: {
70
- ...useElement.options,
71
- url: {
72
- filter(url) {
73
- return (useWebpackResourceFiltering || !url.startsWith("/"))
74
- && !!url.match(/\.(woff2?|eot|ttf|otf|png|jpe?g|svg|webp|avif|gif|bmp)[^.]*?(\?.*)?/i);
75
- }
76
- }
77
- }
78
- };
79
- }
80
- return useElement;
81
- })
82
- };
83
- }
84
- return rule;
85
- });
86
- }
87
- return rules;
88
- };
89
- }
90
- function injectPostcssConfigOverrides(rules, config, variables, postcssFunctionsConfig) {
91
- const postcssConfig = (0, static_configs_1.postcssConfigBuilder)(name => variables(name) ?? (name === 'ENV' ? '' : undefined), postcssFunctionsConfig);
92
- return rules.map(rule => {
93
- if (rule && typeof rule === 'object') {
94
- if (Array.isArray(rule.use)) {
95
- for (const useItem of rule.use) {
96
- if (useItem && typeof useItem === 'object' && typeof useItem.options === 'object') {
97
- if (useItem.options["sourceMap"] === false) {
98
- useItem.options["sourceMap"] = true;
99
- }
100
- if (useItem.loader?.includes('postcss-loader')) {
101
- if (useItem.options["postcssOptions"]) {
102
- useItem.options["postcssOptions"] = { ...useItem.options["postcssOptions"], ...postcssConfig, sourceMap: true, config: false };
103
- }
104
- else {
105
- useItem.options["postcssOptions"] = { ...postcssConfig, sourceMap: true, config: false };
106
- }
107
- }
108
- }
109
- }
110
- if (rule.test instanceof RegExp) {
111
- if (rule.test.test("index.ts") || rule.test.test("index.mts")) { // Then this is the JavaScript and TypeScript rule
112
- rule.test = /\.m?[jt]sx?$/; // This hacks in support for mjs and mts files
113
- }
114
- if (config.onlyRunPostCSSOnPCSS && rule.test.test("test.css") && !rule.test.test("test.pcss")) {
115
- // We remove PostCSS processing from the .css file handling pipeline
116
- rule.use = rule.use.filter(useItem => !useItem || typeof useItem !== 'object' || !useItem.loader?.includes('postcss-loader'));
117
- }
118
- }
119
- }
120
- if (rule.type === "asset/inline" && rule.test instanceof RegExp && rule.issuer instanceof RegExp && rule.test.test("test.svg") && rule.issuer.test("test.pcss")) {
121
- const { type: originalType, ...commonRuleParams } = rule;
122
- return {
123
- ...commonRuleParams,
124
- oneOf: [
125
- { type: originalType, resourceQuery: /string|inline/i },
126
- { type: "asset/resource", generator: { filename: "images/[name].[hash:8][ext]" } }
127
- ]
128
- };
129
- }
130
- }
131
- return rule;
132
- });
133
- }
134
- function injectSupportForInliningSVGsAsStrings(rules) {
135
- const svgRLoader = require.resolve('@svgr/webpack');
136
- return rules.map(rule => {
137
- if (rule && typeof rule === 'object' && "use" in rule && Array.isArray(rule.use) && (rule.use.includes('@svgr/webpack') || rule.use.includes(svgRLoader))) {
138
- const { test, issuer, ...reactSpecific } = rule;
139
- return { test, issuer, oneOf: [
140
- { type: 'asset/source', resourceQuery: /string/ }, // *.svg?string
141
- reactSpecific
142
- ] };
143
- }
144
- return rule;
145
- });
146
- }
147
- function buildVerifiedConfig(config) {
148
- config = (0, shared_1.applyStandards)(config);
149
- const { standaloneBlocks = false, stats = 'errors-warnings', variables: rawVariables, verbose = process.argv.includes('--verbose') || process.env['VERBOSE'] === 'true', postcss = {}, externals, assumeGlobalizedPlauditLibraries = true, useWebpackResourceFiltering = true, plainEntrypointsVersion = 1, srcDir = "", useUnifiedLoader = false, includePostInitFallback = false, omitDistDev = false, onlyRunPostCSSOnPCSS = false, useBlockSupportsAsThemeJsonDefaults = true, } = config;
150
- let outputDir = config.outputDir ?? "";
151
- if ((0, shared_1.shouldWriteDistDev)({ outputDir, useUnifiedLoader, omitDistDev })) {
152
- outputDir += "-dev";
153
- }
154
- let srcPrefixes;
155
- const trailingSlashedSrcDir = srcDir && !srcDir.endsWith("/") ? srcDir + "/" : srcDir;
156
- if (config.srcPrefixes === undefined) {
157
- srcPrefixes = srcDir ? [trailingSlashedSrcDir] : ["src/"];
158
- }
159
- else {
160
- srcPrefixes = (srcDir && !config.srcPrefixes.includes(trailingSlashedSrcDir) ? [...config.srcPrefixes, trailingSlashedSrcDir] : config.srcPrefixes);
161
- }
162
- let targetHandlePrefix = config.targetHandlePrefix ?? config.plainEntrypointsHandlePrefix ?? "";
163
- if (plainEntrypointsVersion > 1) {
164
- if (!targetHandlePrefix) {
165
- targetHandlePrefix = deriveDefaultHandlePrefixFromComposerJsonOrThemeName(shared_1.kebabCase) ?? "";
166
- if (!targetHandlePrefix) {
167
- throw new Error("Plain Entrypoints V2 and higher require either 'targetHandlePrefix' to be set or an adjacent composer.json or style.css file to be present");
168
- }
169
- }
170
- if (!outputDir) {
171
- throw new Error("Plain Entrypoints V2 and higher require 'outputDir' to be set");
172
- }
173
- }
174
- // Only the lazyLoader emitters read this, so an absence of package metadata is not worth failing a build
175
- // over: php-writer treats an empty namespace as "emit no namespace", which is what we did before 3.10.0
176
- const targetNamespace = config.targetNamespace || deriveDefaultHandlePrefixFromComposerJsonOrThemeName(shared_1.camelCaseForPHPLabels, true) || "";
177
- const { staticEntrypoints, dynamicEntrypoints } = (0, entrypoint_resolution_logic_1.resolveAllConfigLevelEntrypoints)(config);
178
- const rawSources = [...staticEntrypoints, ...dynamicEntrypoints];
179
- let variablesFilePath = undefined;
180
- const currentVariables = rawVariables ?? {};
181
- if (!rawVariables) {
182
- variablesFilePath = ["variables.js", "src/site/variables.js"].map(p => (0, node_path_1.join)(process.cwd(), p)).filter(p => (0, node_fs_1.existsSync)(p))[0];
183
- }
184
- let extensionsVersion = config.extensionsVersion ?? 1;
185
- if (extensionsVersion === 2) {
186
- extensionsVersion = 3; // Version 3 is a backwards-compatible upgrade of version 2, so we can automatically upgrade everything
187
- }
188
- const cfg = {
189
- currentVariables, postcss, standaloneBlocks, stats, variablesFilePath, verbose, externals, assumeGlobalizedPlauditLibraries,
190
- useWebpackResourceFiltering, outputDir, extensionsVersion, plainEntrypointsVersion, srcDir, srcPrefixes, targetHandlePrefix,
191
- useUnifiedLoader, includePostInitFallback, omitDistDev, onlyRunPostCSSOnPCSS, targetNamespace, useBlockSupportsAsThemeJsonDefaults
192
- };
193
- // Destination -> source map
194
- const allocatedDestinations = {};
195
- const partiallyVerifiedSources = rawSources.map(([src, config]) => {
196
- const { destination, additionalDependencies = [], assumeGlobalizedPlauditLibraries = cfg.assumeGlobalizedPlauditLibraries, bundleAnalyzer = false, directoryLayout, externalize, withLegacyBlocksIn = false, lazyLoader, pathQueryParameters: rawPathQueryParameters, enqueuingFlags: rawEnqueuingFlags, locations: rawSourceLocations, } = config;
197
- // This guards against a crash later on down the line due to trying to run a spread on a boolean
198
- if (externalize && typeof externalize !== 'string' && typeof externalize !== 'object') {
199
- throw new TypeError(`externalize must be a string, an array or an object, but "${src}" set externalize to a ${typeof externalize}`);
200
- }
201
- const { flags: queryEnqueuingFlags, remainder: pathQueryParameters, handle: pathQueryHandle } = (0, path_query_and_related_helpers_1.unpackEnqueuingControlFlagsFromPathQueryParameters)(rawPathQueryParameters, src, 'path query parameters');
202
- const enqueuingFlags = (0, path_query_and_related_helpers_1.mergeTwoEnqueuingControlFlagSets)(src, rawEnqueuingFlags, queryEnqueuingFlags);
203
- const normalizedParts = { additionalDependencies, assumeGlobalizedPlauditLibraries, bundleAnalyzer, directoryLayout, externalize, withLegacyBlocksIn, lazyLoader };
204
- let locations;
205
- if (pathQueryHandle === undefined) {
206
- locations = typeof rawSourceLocations === 'string' || typeof rawSourceLocations === 'function' || (rawSourceLocations !== undefined && 'niceName' in rawSourceLocations)
207
- ? { handle: rawSourceLocations } : rawSourceLocations ?? {};
208
- }
209
- else {
210
- const rawSourceHandle = typeof rawSourceLocations === 'string' || typeof rawSourceLocations === 'function' || (rawSourceLocations !== undefined && 'niceName' in rawSourceLocations)
211
- ? rawSourceLocations : rawSourceLocations?.handle;
212
- if (rawSourceHandle === undefined) {
213
- locations = { handle: pathQueryHandle };
214
- }
215
- else if (typeof rawSourceHandle === 'string') {
216
- if (rawSourceHandle !== pathQueryHandle) {
217
- throw new ReferenceError(`Encountered mismatched handles "${rawSourceHandle}" and "${pathQueryHandle}" when preparing "${src}"`);
218
- }
219
- locations = { handle: pathQueryHandle };
220
- }
221
- else {
222
- throw new ReferenceError(`Encountered a function handle and a path query handle when preparing "${src}"`);
223
- }
224
- // This is just a means of merging the new handle into the rawSourceLocations config without mutating the base config
225
- if (rawSourceLocations !== undefined && typeof rawSourceLocations !== 'function' && typeof rawSourceLocations !== 'string') {
226
- locations = { ...rawSourceLocations, ...locations };
227
- }
228
- }
229
- if (typeof locations.registerScriptArgs === 'string' && !['lazy', 'eager', 'inline'].includes(locations.registerScriptArgs)) {
230
- throw new ReferenceError("The only supported string values for registerScriptArgs are 'lazy', 'eager', and 'inline'");
231
- }
232
- if (destination !== undefined) {
233
- const effectiveDestination = toEffectiveWebpackDestination(destination);
234
- allocatedDestinations[effectiveDestination] = src; // We need to pre-populate the allocatedDestinations map with statically declared destinations
235
- return [src, { ...normalizedParts, locations, destination, effectiveDestination, staticallyDeclaredDestination: true, pathQueryParameters, enqueuingFlags }];
236
- }
237
- else {
238
- const naiveDestination = deriveNaiveDestinationFromUnverifiedSourceEntry(src, destination, srcPrefixes);
239
- const effectiveDestination = toEffectiveWebpackDestination(naiveDestination);
240
- return [src, { ...normalizedParts, locations, destination: naiveDestination, effectiveDestination, staticallyDeclaredDestination: false, pathQueryParameters, enqueuingFlags }];
241
- }
242
- });
243
- const dynamicEffectiveDestinationsWithExpectedNaiveDuplicates = partiallyVerifiedSources
244
- .filter(entry => !entry[1].staticallyDeclaredDestination)
245
- .map(entry => entry[1].effectiveDestination)
246
- .reduce((a, dest) => {
247
- a[dest] = (a[dest] !== undefined); // If it's undefined, then this is the first instance, otherwise, it's not the first instance and, therefore, is expected to be a duplicate
248
- return a;
249
- }, {});
250
- const sources = partiallyVerifiedSources
251
- .map(entry => finalizeEntryDestination(entry, dynamicEffectiveDestinationsWithExpectedNaiveDuplicates, allocatedDestinations));
252
- testForDuplicatedEntryPaths(sources);
253
- return cfg.outputDir ? { cfg, sources } : withDerivedOutputDir(cfg, sources);
254
- }
255
- function toEffectiveWebpackDestination(destination) {
256
- const pathParts = (0, node_path_1.parse)(destination);
257
- return (0, node_path_1.join)(pathParts.dir, pathParts.name);
258
- }
259
- function deriveNaiveDestinationFromUnverifiedSourceEntry(src, destination, srcPrefixes) {
260
- if (destination !== undefined) {
261
- return destination;
262
- }
263
- const commaIndex = src.indexOf(',');
264
- const primarySource = stripSrcPrefix(commaIndex > -1 ? src.substring(0, commaIndex).trim() : src, srcPrefixes);
265
- const scriptParts = shared_1.scriptExtension.exec(primarySource);
266
- if (scriptParts !== null) {
267
- return `${scriptParts.groups['filename']}.js`; // filename is always defined here
268
- }
269
- const styleParts = shared_1.styleExtension.exec(primarySource);
270
- if (styleParts !== null) {
271
- return `${styleParts.groups['filename']}.css`; // filename is always defined here
272
- }
273
- return primarySource;
274
- }
275
- function stripSrcPrefix(src, srcPrefixes) {
276
- const prefix = srcPrefixes.find(sp => src.startsWith(sp));
277
- if (!prefix) {
278
- return src;
279
- }
280
- return src[prefix.length] === '/' ? src.substring(prefix.length + 1) : src.substring(prefix.length);
281
- }
282
- function finalizeEntryDestination(entry, dynamicEffectiveDestinationsWithExpectedNaiveDuplicates, allocatedDestinations) {
283
- if (entry[1].staticallyDeclaredDestination) {
284
- return entry;
285
- }
286
- const extension = (0, node_path_1.extname)(entry[1].destination);
287
- const filename = dynamicEffectiveDestinationsWithExpectedNaiveDuplicates[entry[1].effectiveDestination]
288
- ? entry[1].effectiveDestination + (extension === '.css' ? "_style" : "_script")
289
- : entry[1].effectiveDestination;
290
- let count = 0, derivedDestination = filename + extension;
291
- while (derivedDestination in allocatedDestinations && allocatedDestinations[derivedDestination] !== entry[0]) {
292
- derivedDestination = `${filename}_${++count}${extension}`; // We don't want to add deduplication indexes unless absolutely necessary
293
- }
294
- entry[1].additionalDependencies?.sort();
295
- allocatedDestinations[derivedDestination] = entry[0];
296
- return [entry[0], { ...entry[1], destination: derivedDestination }];
297
- }
298
- /**
299
- * TODO: WTF is the bot on about here?
300
- * Derives a prefix from whichever piece of package metadata sits next to the config. Returns undefined
301
- * when there is nothing to derive from at all — a caller that cannot proceed without one says so itself,
302
- * because the ones that can (see `targetNamespace`) would otherwise fail builds that never needed it. A
303
- * file that *is* present but unusable still throws, since that is a misconfiguration rather than an absence.
304
- */
305
- function deriveDefaultHandlePrefixFromComposerJsonOrThemeName(stringTransformer, keepPlauditSep = false) {
306
- let composerJson;
307
- try {
308
- composerJson = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(process.cwd(), "composer.json"), 'utf-8'));
309
- }
310
- catch {
311
- // Then composer.json doesn't exist
312
- return deriveDefaultHandlePrefixFromThemeName(stringTransformer);
313
- }
314
- if (typeof composerJson !== 'object' || typeof composerJson.name !== 'string' || !composerJson.name) {
315
- throw new ReferenceError("targetHandlePrefix was not set and the adjacent composer.json file does not have a valid name in it");
316
- }
317
- return stringTransformer(keepPlauditSep ? composerJson.name.replace(/plaudit\/plaudit-/, 'plaudit/') : composerJson.name.replace(/plaudit\/plaudit/, 'plaudit'));
318
- }
319
- function deriveDefaultHandlePrefixFromThemeName(stringTransformer) {
320
- const styleFilePath = (0, node_path_1.join)(process.cwd(), "style.css");
321
- if (!(0, node_fs_1.existsSync)(styleFilePath)) {
322
- // Then there is no package metadata to derive anything from
323
- return undefined;
324
- }
325
- const styleFileContents = (0, node_fs_1.readFileSync)(styleFilePath, 'utf-8');
326
- const themeName = /^\W*Theme\s*Name:\s*(.+)$/im.exec(styleFileContents)?.[1]?.trim();
327
- if (!themeName) {
328
- throw new ReferenceError("targetHandlePrefix was not set and the adjacent style.css file does not have a valid name in it");
329
- }
330
- return stringTransformer(themeName);
331
- }
332
- function withDerivedOutputDir(cfg, sources) {
333
- const destinations = sources.map(([_, { destination }]) => destination.split(/[\/\\]/g));
334
- if (destinations.length < 2) {
335
- return { cfg, sources };
336
- }
337
- const commonParent = destinations[0][0];
338
- for (const destination of destinations) {
339
- if (destination[0] !== commonParent) {
340
- return { cfg, sources };
341
- }
342
- }
343
- return {
344
- cfg: { ...cfg, outputDir: commonParent },
345
- sources: sources.map(([src, dest]) => {
346
- return [src, { ...dest, destination: dest.destination.substring(commonParent.length + 1) }];
347
- })
348
- };
349
- }
350
- let forkTsCheckerInstalled = false;
351
- function isTypeScriptSourceFile(file) {
352
- return /\.[cm]?tsx?$/i.test(file.split('?')[0] ?? '');
353
- }
354
- const prefixes = ['c', 'm', ''];
355
- const suffixes = ['x', ''];
356
- const tsExtensions = prefixes.map(prefix => prefix + "ts").flatMap(name => suffixes.map(suffix => name + suffix));
357
- function handleDisablingTSCheckerIfNecessary(srcRoot, scriptExtension, plugins) {
358
- if (process.env["NO_TS_CHECKER"] === "true" || forkTsCheckerInstalled) {
359
- return;
360
- }
361
- const include = [];
362
- for (const sr of (Array.isArray(srcRoot) ? srcRoot : [srcRoot])) {
363
- if ((0, node_path_1.extname)(sr).length === 0) {
364
- include.push(...tsExtensions.map(tsExt => (0, node_path_1.join)(sr, "**", `*.${tsExt}`)));
365
- }
366
- else if ((0, shared_1.scriptOrStyleTest)(sr, scriptExtension) === "script") {
367
- include.push(sr);
368
- }
369
- }
370
- if (include.length === 0) {
371
- return;
372
- }
373
- forkTsCheckerInstalled = true;
374
- let logTsStatus = true;
375
- plugins.push({
376
- apply(compiler) {
377
- compiler.hooks.watchRun.tap('PlauditForkTsCheckerCssQuiet', watchingCompiler => {
378
- const changed = [
379
- ...(watchingCompiler.modifiedFiles ?? []),
380
- ...(watchingCompiler.removedFiles ?? [])
381
- ];
382
- logTsStatus = changed.length === 0 || changed.some(isTypeScriptSourceFile);
383
- });
384
- }
385
- });
386
- plugins.push(new fork_ts_checker_webpack_plugin_1.default({
387
- async: true,
388
- logger: {
389
- log(message) {
390
- if (!logTsStatus) {
391
- return;
392
- }
393
- console.log(message);
394
- },
395
- error(message) {
396
- console.error(message);
397
- }
398
- },
399
- typescript: {
400
- diagnosticOptions: {
401
- semantic: true,
402
- syntactic: true,
403
- },
404
- configOverwrite: {
405
- include,
406
- compilerOptions: {
407
- skipLibCheck: true
408
- }
409
- }
410
- },
411
- issue: {
412
- exclude(issue) {
413
- return issue.code === 'TS18003';
414
- }
415
- }
416
- }));
417
- }
418
- function buildCommonPluginConfig(webpackConfig, config, bundleAnalyzer, assumeGlobalizedPlauditLibraries, externalize) {
419
- const plugins = webpackConfig.plugins?.filter(v => !!v)
420
- .filter(plugin => plugin.constructor.name !== 'RtlCssPlugin')
421
- .filter(plugin => plugin.constructor.name !== 'CopyPlugin' && plugin.constructor.name !== 'CleanWebpackPlugin')
422
- .map(plugin => {
423
- if (plugin.constructor.name === 'MiniCssExtractPlugin') {
424
- return new plugin.constructor({
425
- filename(pd) {
426
- const name = pd.chunk?.name?.replaceAll(/__[a-zA-Z0-9]+__/g, ""); // This removes the prefix that the cache group adds
427
- return name ? `${name}.css` : "[name].css";
428
- }
429
- });
430
- }
431
- return plugin;
432
- })
433
- ?? [];
434
- plugins.splice(0, 0, new PackageConfigSanityChecker_1.PackageConfigSanityChecker());
435
- if (bundleAnalyzer) {
436
- plugins.splice(0, 0, new (require("webpack-bundle-analyzer").BundleAnalyzerPlugin)({ analyzerMode: 'static', openAnalyzer: bundleAnalyzer !== 'no-auto-open' }));
437
- }
438
- const removeEmptyScriptsPlugin = new webpack_remove_empty_scripts_1.default({
439
- stage: webpack_remove_empty_scripts_1.default.STAGE_AFTER_PROCESS_PLUGINS,
440
- extensions: ['css', 'scss', 'sass', 'less', 'styl', 'pcss'],
441
- ignore: /block\.json/
442
- });
443
- plugins.push(removeEmptyScriptsPlugin, new MiniCSSExtractPluginErrorCleaner_1.MiniCSSExtractPluginErrorCleaner());
444
- if (config.useWebpackResourceFiltering) {
445
- plugins.push(new SpecialAssetHandlingPlugin_1.SpecialAssetHandlingPlugin(config));
446
- }
447
- plugins.push(new VariablesJSMonitorPlugin_1.VariablesJSMonitorPlugin(config));
448
- // We have to use constructor.name here the version desyncs can result in multiple equivalent versions kicking around
449
- const dependencyExtractionPluginIndex = plugins.findIndex(plugin => plugin.constructor.name === 'DependencyExtractionWebpackPlugin');
450
- if (dependencyExtractionPluginIndex === -1) {
451
- console.error((0, shared_1.dedent) `
452
- Unable to find the DependencyExtractionWebpackPlugin.
453
- If this is your first time seeing this error, please run: pnpm up && pnpm dedupe && pnpm up
454
- Once those commands have finished, re-run whichever command had this error. If it still doesn't work, report the issue immediately.
455
- `);
456
- console.error("Once those commands have finished, re-run whichever command had this error. If it still doesn't work, report the issue immediately.");
457
- throw new 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");
458
- }
459
- const builtDependencyExtractionWebpackPlugin = (0, dependency_extraction_webpack_plugin_config_builder_1.makeDependencyExtractionPlugin)(config.externals, assumeGlobalizedPlauditLibraries, externalize);
460
- plugins[dependencyExtractionPluginIndex] = builtDependencyExtractionWebpackPlugin;
461
- try {
462
- const { PlauditDevPlugin } = require("@plaudit/dev-webpack-plugin");
463
- plugins.push(new PlauditDevPlugin(config));
464
- }
465
- catch { }
466
- return {
467
- plugins, removeEmptyScriptsPlugin,
468
- makeAdditionalDependencyInjectorPlugin(referencePlugin) {
469
- return new AdditionalDependencyInjectorPlugin_1.AdditionalDependencyInjectorPlugin(webpackConfig.output?.module, builtDependencyExtractionWebpackPlugin.addExternalizedDep, referencePlugin);
470
- }
471
- };
472
- }
473
- function commonConfigProcessingPrep(config, webpackConfig) {
474
- let scriptExtension; // This is only used in non-block contexts. It might not actually be necessary, but it is good to have
475
- let entrypointFields;
476
- const processingModules = webpackConfig.output?.module ?? false;
477
- if (processingModules) {
478
- scriptExtension = shared_1.scriptWithModuleExtension;
479
- entrypointFields = ["viewScriptModule"];
480
- }
481
- else {
482
- scriptExtension = shared_1.scriptWithoutModuleExtension;
483
- entrypointFields = ["editorStyle", "viewStyle", "style", "editorScript", "viewScript", "script"];
484
- }
485
- let currentVariables = config.currentVariables;
486
- const fixedRules = [
487
- replaceDefaultURLProcessing(config.useWebpackResourceFiltering),
488
- (rules) => {
489
- return injectPostcssConfigOverrides(rules, config, name => currentVariables[name], config.postcss.functions ?? (() => ({})));
490
- },
491
- injectSupportForInliningSVGsAsStrings
492
- ].reduce((r, a) => a(r), webpackConfig.module?.rules ?? []);
493
- fixedRules.push({
494
- test: /wpml-config\.xml$/i,
495
- type: 'asset/resource',
496
- generator: {
497
- filename: '[name][ext]',
498
- emit: false
499
- }
500
- });
501
- return {
502
- entrypointFields, fixedRules, processingModules, scriptExtension,
503
- updateCurrentVariables: (value) => currentVariables = value
504
- };
505
- }
506
- function destToKey(dest) {
507
- const externalize = typeof dest.externalize === 'object' && dest.externalize !== undefined
508
- ? (Array.isArray(dest.externalize) ? dest.externalize.join("_") : (dest.externalize ? Object.entries(dest.externalize).flat().sort().join() : "undefined"))
509
- : dest.externalize?.toString() ?? "undefined";
510
- return [dest.assumeGlobalizedPlauditLibraries, dest.bundleAnalyzer, externalize].join("~");
511
- }
512
- function processIndividualWebpackConfig(config, webpackConfig, sources, canClean, preferNonModuleTsChecker) {
513
- if (webpackConfig.output?.module) {
514
- // This ensures that module files are emitted as module files
515
- webpackConfig = {
516
- ...webpackConfig,
517
- output: {
518
- ...webpackConfig.output,
519
- filename: '[name].mjs',
520
- chunkFilename: '[name].mjs?ver=[chunkhash]',
521
- }
522
- };
523
- }
524
- const commonConfig = commonConfigProcessingPrep(config, webpackConfig);
525
- const { processingModules, scriptExtension } = commonConfig;
526
- const allSrcRoots = sources.map(([src, dest]) => {
527
- const srcRoots = (dest.withLegacyBlocksIn
528
- ? [...src.split(','), ...(0, shared_1.resolveLegacyBlockScriptsInFolder)((0, node_path_1.join)(config.srcDir, dest.withLegacyBlocksIn))]
529
- : src.split(',')).filter(s => s.endsWith(".json") || !s.substring(s.lastIndexOf('/')).includes('.') || processingModules === shared_1.scriptWithModuleExtension.test(s));
530
- 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));
531
- const srcIsDirectory = !Array.isArray(srcRoot) && (0, node_fs_1.lstatSync)(srcRoot, { throwIfNoEntry: false })?.isDirectory();
532
- if (srcIsDirectory === undefined) {
533
- return undefined;
534
- }
535
- return { srcRoots, src, dest, srcRoot, srcIsDirectory };
536
- }).filter(a => a !== undefined);
537
- const groupedSrcRoots = {};
538
- for (const entry of allSrcRoots) {
539
- const key = destToKey(entry.dest);
540
- (groupedSrcRoots[key] ?? (groupedSrcRoots[key] = [])).push(entry);
541
- }
542
- const batches = Object.values(groupedSrcRoots).filter(shared_1.hasAtLeastOneItem);
543
- return batches.map(currentBatch => {
544
- const { bundleAnalyzer, assumeGlobalizedPlauditLibraries, externalize } = currentBatch[0].dest;
545
- const { plugins, removeEmptyScriptsPlugin, makeAdditionalDependencyInjectorPlugin } = buildCommonPluginConfig(webpackConfig, config, bundleAnalyzer, assumeGlobalizedPlauditLibraries, externalize);
546
- if (!processingModules || !preferNonModuleTsChecker) {
547
- handleDisablingTSCheckerIfNecessary(currentBatch.flatMap(a => a.srcRoots), scriptExtension, plugins);
548
- }
549
- const applicableExtensionTest = (name) => {
550
- return commonConfig.scriptExtension.test(name) || (!processingModules && shared_1.styleExtension.test(name));
551
- };
552
- const contextPath = webpackConfig.context ?? process.cwd();
553
- for (const { dest, src, srcIsDirectory, srcRoot } of currentBatch) {
554
- let plugin;
555
- const sourceType = (0, shared_1.determineCurrentSourceType)(dest, srcIsDirectory);
556
- if (sourceType === "blocks" /* SourceType.blocks */) {
557
- if (!srcIsDirectory) {
558
- continue;
559
- }
560
- plugin = new EnhancedBlockJSONPlugin_1.EnhancedBlockJSONPlugin(config, dest, removeEmptyScriptsPlugin, contextPath, (0, common_config_helpers_1.resolveEntryFromDirectory)(commonConfig, srcRoot, dest));
561
- plugins.push(plugin);
562
- if (!processingModules) {
563
- plugins.push(new WPMLConfigBuilder_1.WPMLConfigBuilderPlugin(dest.destination, plugin));
564
- }
565
- }
566
- else if (sourceType === "extensions" /* SourceType.extensions */) {
567
- if (!srcIsDirectory) {
568
- continue;
569
- }
570
- const entry = async () => {
571
- const rawEntrypoints = [];
572
- for await (const dirent of await (0, promises_1.opendir)(srcRoot)) {
573
- if ((0, shared_1.shouldBeSkipped)(dirent.name)) {
574
- continue;
575
- }
576
- if (dirent.isFile()) {
577
- if (applicableExtensionTest(dirent.name)) {
578
- const absoluteSrc = (0, common_config_helpers_1.joinPossiblyAbsolutePaths)(srcRoot, dirent.name);
579
- const extensionId = (0, node_path_1.parse)(dirent.name).name;
580
- rawEntrypoints.push([(0, node_path_1.join)(dest.destination, (0, node_path_1.basename)(absoluteSrc, (0, node_path_1.extname)(absoluteSrc))), {
581
- import: [absoluteSrc],
582
- plauditMetadata: { dest, absoluteSrc, extensionId }
583
- }]);
584
- }
585
- }
586
- else if (dirent.isDirectory()) {
587
- rawEntrypoints.push(...await walkExtensionsTree((0, node_path_1.join)(srcRoot, dirent.name), dest, applicableExtensionTest, [dirent.name]));
588
- }
589
- }
590
- return Object.fromEntries(rawEntrypoints);
591
- };
592
- plugin = config.extensionsVersion > 1
593
- ? new ExtensionsConfigFileGeneratorPlugin_1.ExtensionsConfigFileGeneratorPlugin(config, srcRoot, dest, contextPath, entry)
594
- : new ExtensionsConfigFileGeneratorPluginV1_1.ExtensionsConfigFileGeneratorPluginV1(dest.destination, contextPath, entry);
595
- plugins.push(plugin);
596
- }
597
- else if (sourceType === "plain" /* SourceType.plain */) {
598
- const absoluteSrc = typeof srcRoot === 'string' ? srcRoot : srcRoot[0];
599
- if (!srcIsDirectory && !applicableExtensionTest(absoluteSrc)) {
600
- continue;
601
- }
602
- const baseDest = stripExtension(dest.destination);
603
- if (config.plainEntrypointsVersion > 1) {
604
- const entry = srcIsDirectory // This being true implies that srcRoot is not an array
605
- ? (0, common_config_helpers_1.resolveEntryFromDirectory)(commonConfig, srcRoot, dest)
606
- : () => ({ [baseDest]: { import: Array.isArray(srcRoot) ? srcRoot : [srcRoot], plauditMetadata: { purpose: "plain-entrypoint", dest, absoluteSrc } } });
607
- plugin = new PlainEntrypointsConfigFileGeneratorPlugin_1.PlainEntrypointsConfigFileGeneratorPlugin(config, process.cwd(), config.outputDir, dest, config.useUnifiedLoader, contextPath, entry);
608
- }
609
- else {
610
- if (srcIsDirectory) {
611
- console.error("Using directory mode with legacy plain entrypoint handling is not supported");
612
- continue;
613
- }
614
- plugin = new EnhancedDynamicEntryPlugin_1.EnhancedDynamicEntryPlugin(contextPath, () => ({ [baseDest]: { import: Array.isArray(srcRoot) ? srcRoot : [srcRoot], plauditMetadata: { purpose: "plain-entrypoint", dest, absoluteSrc } } }));
615
- }
616
- plugins.push(plugin);
617
- }
618
- else {
619
- console.error("Unrecognized sourceType");
620
- continue;
621
- }
622
- plugins.push(makeAdditionalDependencyInjectorPlugin(plugin));
623
- const canCopyFiles = srcIsDirectory && src !== dest.destination;
624
- if (canCopyFiles) {
625
- plugins.push(new copy_webpack_plugin_1.default({
626
- patterns: [{
627
- from: config.standaloneBlocks ? '**/*.(php|twig|svg)' : '**/*.(asset\.php|svg)', //TODO: I'm pretty sure that the dots need proper escaping
628
- to: dest.destination,
629
- context: srcRoot /* canCopyFiles can only be true if srcRoot is a string, so this is safe */, noErrorOnMissing: true
630
- }]
631
- }));
632
- }
633
- }
634
- plugins.push(new UnifiedLoaderGenerator_1.UnifiedLoaderGenerator(config));
635
- return (0, common_config_helpers_1.commonMakeWebpackConfig)(config, commonConfig, webpackConfig, externalize, plugins, canClean && batches.length < 2);
636
- }).filter(cfg => cfg !== undefined);
637
- }
638
- async function walkExtensionsTree(srcRoot, dest, applicableExtensionTest, parents) {
639
- const res = [];
640
- for await (const dirent of await (0, promises_1.opendir)(srcRoot)) {
641
- if ((0, shared_1.shouldBeSkipped)(dirent.name)) {
642
- continue;
643
- }
644
- if (dirent.isFile()) {
645
- if (!applicableExtensionTest(dirent.name)) {
646
- continue;
647
- }
648
- const parsedFilename = (0, location_encoding_filename_parser_1.parseLocationEncodingFilename)(dirent.name);
649
- if (parsedFilename === undefined) {
650
- continue;
651
- }
652
- const absoluteSrc = (0, common_config_helpers_1.joinPossiblyAbsolutePaths)(srcRoot, dirent.name);
653
- let destFile;
654
- if (Object.keys(parsedFilename.locations).length === 1) {
655
- if (parsedFilename.locations.clientView) {
656
- destFile = `view-${parsedFilename.type}`;
657
- }
658
- else if (parsedFilename.locations.clientEditor) {
659
- destFile = `editor-${parsedFilename.type}`;
660
- }
661
- else {
662
- destFile = (0, node_path_1.basename)(absoluteSrc, (0, node_path_1.extname)(absoluteSrc));
663
- }
664
- }
665
- else {
666
- destFile = (0, node_path_1.basename)(absoluteSrc, (0, node_path_1.extname)(absoluteSrc));
667
- }
668
- const extensionId = parents.join("-") + "-" + destFile;
669
- res.push([(0, node_path_1.join)(dest.destination, ...parents, destFile), {
670
- import: [absoluteSrc],
671
- plauditMetadata: { dest, absoluteSrc, extensionId }
672
- }]);
673
- }
674
- else if (dirent.isDirectory()) {
675
- res.push(...await walkExtensionsTree((0, node_path_1.join)(srcRoot, dirent.name), dest, applicableExtensionTest, [...parents, dirent.name]));
676
- }
677
- }
678
- return res;
679
- }
680
- function stripExtension(filepath) {
681
- return (0, node_path_1.join)((0, node_path_1.dirname)(filepath), (0, node_path_1.basename)(filepath, (0, node_path_1.extname)(filepath)));
682
- }
683
- module.exports = function (config, webpackConfig = require("@wordpress/scripts/config/webpack.config")) {
684
- const { cfg, sources } = buildVerifiedConfig(config);
685
- if (Array.isArray(webpackConfig) && (0, shared_1.arrayIsLength)(webpackConfig, 1)) {
686
- webpackConfig = webpackConfig[0];
687
- }
688
- if (Array.isArray(webpackConfig)) {
689
- const hasNonModuleCompiler = webpackConfig.some(cfg => !cfg.output?.module);
690
- return webpackConfig.toSorted((a, b) => {
691
- if (a.output?.module) {
692
- return b.output?.module ? 0 : -1;
693
- }
694
- return b.output?.module ? 1 : 0;
695
- }).flatMap(wpCfg => processIndividualWebpackConfig(cfg, wpCfg, sources, false, hasNonModuleCompiler));
696
- }
697
- return processIndividualWebpackConfig(cfg, webpackConfig, sources, true, false);
698
- };