@plaudit/webpack-extensions 2.9.2 → 2.11.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.
@@ -18,12 +18,12 @@ class AdditionalDependencyInjectorPlugin {
18
18
  }, compilationAssets => {
19
19
  const assetSources = new Map();
20
20
  for (const entrypoint of compilation.entrypoints.values()) {
21
- const typeScriptOrigins = entrypoint.origins.filter(origin => /\.m?tsx?$/.test(origin.request));
22
- if (typeScriptOrigins.length > 0) {
21
+ const req = entrypoint.origins.filter(origin => /\.m?tsx?$/.test(origin.request))[0]?.request;
22
+ if (req) {
23
23
  for (const chunk of entrypoint.chunks) {
24
24
  for (const file of chunk.files) {
25
25
  if (file.endsWith('.asset.php')) {
26
- assetSources.set(file, typeScriptOrigins[0].request);
26
+ assetSources.set(file, req);
27
27
  }
28
28
  }
29
29
  }
@@ -37,7 +37,7 @@ class AdditionalDependencyInjectorPlugin {
37
37
  }
38
38
  const additionalDependencies = [...this.entrypointAdditionalDependencies];
39
39
  const firstLine = node_fs_1.default.readFileSync(assetSource, 'utf8').trim().split(/\r?\n/)[0];
40
- if (firstLine.startsWith("//ADDITIONAL_DEPENDENCIES:")) {
40
+ if (firstLine?.startsWith("//ADDITIONAL_DEPENDENCIES:")) {
41
41
  additionalDependencies.push(...firstLine.substring(26).trim().split(',').map(dep => dep.trim()));
42
42
  }
43
43
  if (additionalDependencies.length > 0) {
@@ -0,0 +1,6 @@
1
+ import { type Compiler, type WebpackPluginInstance } from "webpack";
2
+ export default class ExtensionsConfigFileGeneratorPlugin implements WebpackPluginInstance {
3
+ private readonly extensionsPath;
4
+ constructor(extensionsPath: string);
5
+ apply(compiler: Compiler): void;
6
+ }
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const promises_1 = __importDefault(require("node:fs/promises"));
7
+ const node_path_1 = __importDefault(require("node:path"));
8
+ const webpack_1 = require("webpack");
9
+ class ExtensionsConfigFileGeneratorPlugin {
10
+ extensionsPath;
11
+ constructor(extensionsPath) {
12
+ this.extensionsPath = extensionsPath;
13
+ }
14
+ apply(compiler) {
15
+ compiler.hooks.make.tapPromise('ExtensionsConfigFileGeneratorPlugin', async (compilation) => {
16
+ if (!compilation.contextDependencies.has(this.extensionsPath)) {
17
+ compilation.contextDependencies.add(this.extensionsPath);
18
+ }
19
+ const emissionPromises = [];
20
+ for (const setupFilePath of await promises_1.default.readdir(this.extensionsPath)) {
21
+ if (setupFilePath.endsWith("-setup.php")) {
22
+ const setupFileSourcePath = node_path_1.default.join(this.extensionsPath, setupFilePath);
23
+ compilation.fileDependencies.add(setupFileSourcePath);
24
+ emissionPromises.push(promises_1.default.readFile(setupFileSourcePath)
25
+ .then(contents => compilation.emitAsset(setupFilePath, new webpack_1.sources.RawSource(contents), { size: Buffer.byteLength(contents) })));
26
+ }
27
+ }
28
+ await Promise.all(emissionPromises);
29
+ });
30
+ compiler.hooks.thisCompilation.tap("ExtensionsConfigFileGeneratorPlugin", compilation => {
31
+ compilation.hooks.processAssets.tap({
32
+ name: "ExtensionsConfigFileGeneratorPlugin_ProcessAssets",
33
+ stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_ANALYSE
34
+ }, compilationAssets => {
35
+ const stats = compilation.getStats().toJson({
36
+ hash: true,
37
+ publicPath: true,
38
+ assets: true,
39
+ chunks: true,
40
+ modules: true,
41
+ source: true,
42
+ errorDetails: false,
43
+ timings: false
44
+ });
45
+ if (!stats.assets) {
46
+ throw new Error("Stats did not include assets despite them being requested");
47
+ }
48
+ if (!stats.modules) {
49
+ throw new Error("Stats did not include modules despite them being requested");
50
+ }
51
+ const mapping = {};
52
+ for (const asset of stats.assets) {
53
+ if ((asset.chunks?.length ?? -1) > 1 || !asset.size) {
54
+ continue;
55
+ }
56
+ let match;
57
+ if ((match = /^(.+?)-setup.php$/i.exec(asset.name)) && match[1]) {
58
+ if (!mapping[match[1]]) {
59
+ mapping[match[1]] = { resources: {} };
60
+ }
61
+ mapping[match[1]].setup = `file:./${asset.name}`;
62
+ }
63
+ else if ((match = /^(.+?)-(editor-style|style|view-script|editor-script|script)\.(?:css|m?js)$/i.exec(asset.name)) && match[1] && match[2]) {
64
+ if (!mapping[match[1]]) {
65
+ mapping[match[1]] = { resources: {} };
66
+ }
67
+ let key;
68
+ if (match[2] === "editor-script") {
69
+ key = "editorScript";
70
+ }
71
+ else if (match[2] === "view-script") {
72
+ key = "viewScript";
73
+ }
74
+ else if (match[2] === "editor-style") {
75
+ key = "editorStyle";
76
+ }
77
+ else {
78
+ key = match[2];
79
+ }
80
+ (mapping[match[1]].resources[key] ?? (mapping[match[1]].resources[key] = [])).push([`plaudit_block-extension_${match[1]}-${match[2]}`, asset.name]);
81
+ }
82
+ }
83
+ let contents = `a:${Object.keys(mapping).length}:{`;
84
+ for (const [blockSlug, { setup, resources }] of Object.entries(mapping)) {
85
+ contents += `s:${blockSlug.length}:"${blockSlug}";`;
86
+ contents += `a:${setup ? 2 : 1}:{`; // Open the mapping for the current block as a whole
87
+ // Open the mapping for the current block's resource files
88
+ contents += `i:0;a:${Object.entries(resources).length}:{`;
89
+ for (const [mapping, handlerFiles] of Object.entries(resources)) {
90
+ contents += `s:${mapping.length}:"${mapping}";`;
91
+ contents += `a:${handlerFiles.length}:{`;
92
+ let count = 0;
93
+ for (const handlerFile of handlerFiles) {
94
+ contents += `i:${count++};a:2:{i:0;s:${handlerFile[0].length}:"${handlerFile[0]}";i:1;s:${handlerFile[1].length}:"${handlerFile[1]}";}`;
95
+ }
96
+ contents += "}";
97
+ }
98
+ contents += "}"; // Close the mapping for the current block's resource files
99
+ if (setup) {
100
+ contents += `i:1;s:${setup.length}:"${setup}";`;
101
+ }
102
+ contents += "}"; // Close the mapping for the current block as a whole
103
+ }
104
+ contents += "}";
105
+ compilation.emitAsset("mapping.config", new webpack_1.sources.RawSource(contents.trim()));
106
+ });
107
+ });
108
+ }
109
+ }
110
+ exports.default = ExtensionsConfigFileGeneratorPlugin;
@@ -16,7 +16,7 @@ const nanoConfig = {
16
16
  'cssnano-preset-default',
17
17
  {
18
18
  safe: true,
19
- autoprefixer: false,
19
+ autoprefixer: false, // Unsafe
20
20
  calc: false,
21
21
  colormin: true,
22
22
  convertValues: false,
@@ -29,10 +29,10 @@ const nanoConfig = {
29
29
  discardDuplicates: true,
30
30
  discardEmpty: true,
31
31
  discardOverridden: true,
32
- discardUnused: false,
33
- mergeIdents: false,
32
+ discardUnused: false, // Unsafe
33
+ mergeIdents: false, // Unsafe
34
34
  mergeLonghand: true,
35
- mergeRules: false,
35
+ mergeRules: false, // Off for speed
36
36
  minifyFontValues: true,
37
37
  minifyGradients: true,
38
38
  minifyParams: true,
@@ -47,12 +47,12 @@ const nanoConfig = {
47
47
  normalizeUrl: true,
48
48
  normalizeWhitespace: true,
49
49
  orderedValues: true,
50
- reduceIdents: false,
50
+ reduceIdents: false, // Unsafe
51
51
  reduceInitial: true,
52
52
  reduceTransforms: true,
53
- svgo: false,
53
+ svgo: false, // Off for speed
54
54
  uniqueSelectors: true,
55
- zindex: false,
55
+ zindex: false, // Unsafe
56
56
  filterPlugins: false // I don't know where this one came from. It is not listed in the documentation.
57
57
  }
58
58
  ]
@@ -60,25 +60,25 @@ const nanoConfig = {
60
60
  function postcssConfigBuilder(verbose, variables) {
61
61
  return {
62
62
  plugins: [
63
- require("postcss-import")(),
64
- require("@plaudit/postcss-silent-extend")({ warnOfUnused: verbose }),
65
- require("postcss-mixins")(),
66
- require("@plaudit/postcss-variables")({ variables }),
67
- require("postcss-quantity-queries")(),
68
- require("postcss-short-position")(),
69
- require("postcss-short-size")(),
70
- require("postcss-short-spacing")(),
71
- require("postcss-fallback")(),
72
- require("postcss-property-lookup")({ logLevel: "warn" }),
73
- require("@plaudit/postcss-strip-units")(),
74
- require("postcss-media-minmax")(),
75
- require("postcss-inline-svg")(),
76
- require("postcss-nested")(),
63
+ require("postcss-import")(), // Once
64
+ require("@plaudit/postcss-silent-extend")({ warnOfUnused: verbose }), // Once (marks), OnceExit (apply)
65
+ require("postcss-mixins")(), // There is a PostCSS 8 version, but we're forced to use the old one because the new one uses AtRule, which is too late in the process
66
+ require("@plaudit/postcss-variables")({ variables }), // Once
67
+ require("postcss-quantity-queries")(), // Legacy
68
+ require("postcss-short-position")(), // Legacy
69
+ require("postcss-short-size")(), // Legacy
70
+ require("postcss-short-spacing")(), // Legacy
71
+ require("postcss-fallback")(), // Legacy
72
+ require("postcss-property-lookup")({ logLevel: "warn" }), // Rule
73
+ require("@plaudit/postcss-strip-units")(), // AtRule, Declaration
74
+ require("postcss-media-minmax")(), // AtRule
75
+ require("postcss-inline-svg")(), // AtRule
76
+ require("postcss-nested")(), // Rule
77
77
  require("postcss-url")(),
78
- require("postcss-calc")(calcOptions),
79
- require("@plaudit/postcss-color-function")(),
80
- require("autoprefixer")(autoprefixerOptions),
81
- require("postcss-reporter")({ clearReportedMessages: true }),
78
+ require("postcss-calc")(calcOptions), // OnceExit
79
+ require("@plaudit/postcss-color-function")(), // OnceExit
80
+ require("autoprefixer")(autoprefixerOptions), // OnceExit
81
+ require("postcss-reporter")({ clearReportedMessages: true }), // OnceExit
82
82
  (0, cssnano_1.default)(nanoConfig)
83
83
  ]
84
84
  };
@@ -3,6 +3,7 @@ interface AdvancedOutputConfig {
3
3
  destination: string;
4
4
  withLegacyBlocksIn?: string | undefined;
5
5
  additionalDependencies?: string[];
6
+ directoryLayout?: 'blocks' | 'extensions';
6
7
  }
7
8
  interface PlauditWordpressWebpackConfig {
8
9
  standaloneBlocks?: boolean;
@@ -6,12 +6,13 @@ const node_fs_1 = __importDefault(require("node:fs"));
6
6
  const node_path_1 = __importDefault(require("node:path"));
7
7
  const AdditionalDependencyInjectorPlugin_1 = __importDefault(require("./wordpress-scripts-wrapper/AdditionalDependencyInjectorPlugin"));
8
8
  const BlockJSONStyleRemappingPlugin_1 = __importDefault(require("./wordpress-scripts-wrapper/BlockJSONStyleRemappingPlugin"));
9
+ const ExtensionsConfigFileGeneratorPlugin_1 = __importDefault(require("./wordpress-scripts-wrapper/ExtensionsConfigFileGeneratorPlugin"));
10
+ const VariablesJSMonitorPlugin_1 = __importDefault(require("./wordpress-scripts-wrapper/VariablesJSMonitorPlugin"));
9
11
  const static_configs_1 = require("./wordpress-scripts-wrapper/static-configs");
10
12
  const browser_sync_webpack_plugin_1 = __importDefault(require("browser-sync-webpack-plugin"));
11
13
  const copy_webpack_plugin_1 = __importDefault(require("copy-webpack-plugin"));
12
14
  const fork_ts_checker_webpack_plugin_1 = __importDefault(require("fork-ts-checker-webpack-plugin"));
13
15
  const webpack_remove_empty_scripts_1 = __importDefault(require("webpack-remove-empty-scripts"));
14
- const VariablesJSMonitorPlugin_1 = __importDefault(require("./wordpress-scripts-wrapper/VariablesJSMonitorPlugin"));
15
16
  function joinPossiblyAbsolutePaths(...paths) {
16
17
  return paths.reduce((res, p) => !res || node_path_1.default.isAbsolute(p) ? p : node_path_1.default.join(res, p), '') || '.';
17
18
  }
@@ -229,10 +230,13 @@ module.exports = function (config, webpackConfig = require("@wordpress/scripts/c
229
230
  if (variablesFilePath) {
230
231
  plugins.push(new VariablesJSMonitorPlugin_1.default(variablesFilePath));
231
232
  }
232
- if (copyFiles) {
233
+ if (copyFiles && (typeof dest === 'string' || dest.directoryLayout !== 'extensions')) {
233
234
  plugins.push(new BlockJSONStyleRemappingPlugin_1.default(standaloneBlocks));
234
235
  }
235
236
  plugins.push(new AdditionalDependencyInjectorPlugin_1.default(typeof dest !== 'string' && dest.additionalDependencies ? dest.additionalDependencies : []));
237
+ if (srcIsDirectory && (typeof dest !== 'string' && dest.directoryLayout === 'extensions')) {
238
+ plugins.push(new ExtensionsConfigFileGeneratorPlugin_1.default(srcRoot));
239
+ }
236
240
  if (first) {
237
241
  first = false;
238
242
  if (process.argv.includes('--browser-sync') || process.env['BROWSER_SYNC'] === 'true') {
@@ -246,53 +250,64 @@ module.exports = function (config, webpackConfig = require("@wordpress/scripts/c
246
250
  }
247
251
  let entry;
248
252
  if (srcIsDirectory) {
249
- entry = () => {
250
- const rawEntrypoints = node_fs_1.default.readdirSync(srcRoot, 'utf8')
251
- .map(dir => joinPossiblyAbsolutePaths(srcRoot, dir))
252
- .filter(dir => node_fs_1.default.statSync(dir).isDirectory())
253
- .flatMap(dir => {
254
- const res = [];
255
- try {
256
- const blockJSON = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(dir, 'block.json'), 'utf8'));
257
- for (const key of ["editorStyle", "style", "editorScript", "viewScript", "script"]) {
258
- if (key in blockJSON) {
259
- res.push(...mapToRealEntrypoints(blockJSON[key], dir, ep => ep.startsWith("file:") ? ep.substring(5) : ep));
260
- }
261
- }
262
- return res;
263
- }
264
- catch (e) {
253
+ if (typeof dest !== 'string' && dest.directoryLayout === 'extensions') {
254
+ entry = () => {
255
+ const rawEntrypoints = node_fs_1.default.readdirSync(srcRoot, 'utf8')
256
+ .map(file => joinPossiblyAbsolutePaths(srcRoot, file))
257
+ .filter(file => (scriptExtension.test(file) || styleExtension.test(file)) && node_fs_1.default.statSync(file).isFile())
258
+ .map((file) => [node_path_1.default.basename(file, node_path_1.default.extname(file)), file]);
259
+ return Object.fromEntries(rawEntrypoints);
260
+ };
261
+ }
262
+ else {
263
+ entry = () => {
264
+ const rawEntrypoints = node_fs_1.default.readdirSync(srcRoot, 'utf8')
265
+ .map(dir => joinPossiblyAbsolutePaths(srcRoot, dir))
266
+ .filter(dir => node_fs_1.default.statSync(dir).isDirectory())
267
+ .flatMap(dir => {
268
+ const res = [];
265
269
  try {
266
- const packageJSON = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(dir, 'package.json'), 'utf8'));
267
- res.push(...mapToRealEntrypoints(packageJSON['main'], dir));
268
- res.push(...mapToRealEntrypoints(packageJSON['style'], dir));
270
+ const blockJSON = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(dir, 'block.json'), 'utf8'));
271
+ for (const key of ["editorStyle", "style", "editorScript", "viewScript", "script"]) {
272
+ if (key in blockJSON) {
273
+ res.push(...mapToRealEntrypoints(blockJSON[key], dir, ep => ep.startsWith("file:") ? ep.substring(5) : ep));
274
+ }
275
+ }
276
+ return res;
269
277
  }
270
278
  catch (e) {
271
279
  try {
272
- res.push(...parseEntrypointsJSON(dir));
280
+ const packageJSON = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(dir, 'package.json'), 'utf8'));
281
+ res.push(...mapToRealEntrypoints(packageJSON['main'], dir));
282
+ res.push(...mapToRealEntrypoints(packageJSON['style'], dir));
273
283
  }
274
284
  catch (e) {
275
- // This just means that the directory doesn't contain any declared entrypoints.
285
+ try {
286
+ res.push(...parseEntrypointsJSON(dir));
287
+ }
288
+ catch (e) {
289
+ // This just means that the directory doesn't contain any declared entrypoints.
290
+ }
276
291
  }
277
292
  }
278
- }
279
- return res;
280
- });
281
- const perAssetPathGroupedEntrypoints = groupEntrypointsByAssetFile(rawEntrypoints, e => e[0]);
282
- const currentEntry = {};
283
- for (const groupedEntrypoints of perAssetPathGroupedEntrypoints.values()) {
284
- if (groupedEntrypoints.length === 1) {
285
- currentEntry[groupedEntrypoints[0][0]] = groupedEntrypoints[0][1];
286
- }
287
- else {
288
- const typeCounts = {};
289
- for (const entrypoint of groupedEntrypoints) {
290
- addPotentiallyDuplicatedEntrypointName(currentEntry, entrypoint, typeCounts);
293
+ return res;
294
+ });
295
+ const perAssetPathGroupedEntrypoints = groupEntrypointsByAssetFile(rawEntrypoints, e => e[0]);
296
+ const currentEntry = {};
297
+ for (const groupedEntrypoints of perAssetPathGroupedEntrypoints.values()) {
298
+ if (groupedEntrypoints.length === 1 && groupedEntrypoints[0] !== undefined) {
299
+ currentEntry[groupedEntrypoints[0][0]] = groupedEntrypoints[0][1];
300
+ }
301
+ else {
302
+ const typeCounts = {};
303
+ for (const entrypoint of groupedEntrypoints) {
304
+ addPotentiallyDuplicatedEntrypointName(currentEntry, entrypoint, typeCounts);
305
+ }
291
306
  }
292
307
  }
293
- }
294
- return currentEntry;
295
- };
308
+ return currentEntry;
309
+ };
310
+ }
296
311
  }
297
312
  else {
298
313
  const baseDest = node_path_1.default.basename(destPath);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plaudit/webpack-extensions",
3
- "version": "2.9.2",
3
+ "version": "2.11.0",
4
4
  "scripts": {
5
5
  "prepublishOnly": "rm -rf build && mkdir build && tsc",
6
6
  "build": "tsc",
@@ -19,31 +19,31 @@
19
19
  },
20
20
  "devDependencies": {
21
21
  "@types/browser-sync-webpack-plugin": "^2.2.3",
22
- "@types/node": "^20.8.2",
23
- "@types/tapable": "^2.2.5",
24
- "@types/webpack": "^5.28.3",
25
- "@types/webpack-sources": "^3.2.1",
26
- "postcss-load-config": "^4.0.1",
27
- "postcss-loader": "^7.3.3",
28
- "ts-node": "^10.9.1",
29
- "typescript": "^5.2.2"
22
+ "@types/node": "^20.10.6",
23
+ "@types/tapable": "^2.2.7",
24
+ "@types/webpack": "^5.28.5",
25
+ "@types/webpack-sources": "^3.2.3",
26
+ "postcss-load-config": "^4.0.2",
27
+ "postcss-loader": "^7.3.4",
28
+ "ts-node": "^10.9.2",
29
+ "typescript": "^5.3.3"
30
30
  },
31
31
  "dependencies": {
32
32
  "@plaudit/postcss-color-function": "^5.0.0",
33
33
  "@plaudit/postcss-silent-extend": "^3.0.0",
34
34
  "@plaudit/postcss-strip-units": "^3.0.0",
35
35
  "@plaudit/postcss-variables": "^1.0.0",
36
- "@wordpress/scripts": "^26.13.0",
36
+ "@wordpress/scripts": "^26.19.0",
37
37
  "autoprefixer": "^10.4.16",
38
38
  "browser-sync": "^2.29.3",
39
39
  "browser-sync-webpack-plugin": "^2.3.0",
40
40
  "clean-webpack-plugin": "^4.0.0",
41
41
  "copy-webpack-plugin": "^11.0.0",
42
- "cssnano": "^6.0.1",
42
+ "cssnano": "^6.0.3",
43
43
  "eslint": "^8.50.0",
44
44
  "eslint-plugin-jsdoc": "^46.8.2",
45
45
  "fork-ts-checker-webpack-plugin": "^8.0.0",
46
- "postcss": "^8.4.30",
46
+ "postcss": "^8.4.33",
47
47
  "postcss-calc": "^9.0.1",
48
48
  "postcss-discard-comments": "^6.0.0",
49
49
  "postcss-fallback": "^0.1.0",