@plaudit/webpack-extensions 2.1.3 → 2.2.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.
@@ -1,4 +1,6 @@
1
1
  import type { Compiler, WebpackPluginInstance } from "webpack";
2
2
  export default class BlockJSONStyleRemappingPlugin implements WebpackPluginInstance {
3
3
  apply(compiler: Compiler): void;
4
+ findCommonAncestor(...paths: string[]): string[];
5
+ findRelativeRouteBetween(path1: string, path2: string): string;
4
6
  }
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ const node_fs_1 = __importDefault(require("node:fs"));
6
7
  const node_path_1 = __importDefault(require("node:path"));
7
8
  const webpack_sources_1 = require("webpack-sources");
8
9
  class BlockJSONStyleRemappingPlugin {
@@ -69,11 +70,76 @@ class BlockJSONStyleRemappingPlugin {
69
70
  }
70
71
  }
71
72
  }
73
+ if (json["plaudit"] !== "simple") {
74
+ const sourceDir = node_path_1.default.join(compiler.context, dirname);
75
+ const outputDir = node_path_1.default.join(compiler.outputPath, node_path_1.default.dirname(name));
76
+ const stripFilePrefix = (file) => file.startsWith("file:./") ? file.substring(7) : file;
77
+ let setupFiles = (json["plaudit"]?.["setup"]
78
+ ? (typeof json["plaudit"]["setup"] === 'string' ? [json["plaudit"]["setup"]] : json["plaudit"]["setup"])
79
+ : ["setup.php"])
80
+ .map(p => node_path_1.default.normalize(node_path_1.default.join(sourceDir, stripFilePrefix(p))))
81
+ .filter(p => node_fs_1.default.existsSync(p))
82
+ .map(p => `file:./${this.findRelativeRouteBetween(outputDir, p)}`);
83
+ if (setupFiles.length === 0) {
84
+ if (json["plaudit"]?.["setup"] !== undefined) {
85
+ delete json["plaudit"]["setup"];
86
+ }
87
+ }
88
+ else {
89
+ if (typeof json["plaudit"] !== 'object') {
90
+ json["plaudit"] = {};
91
+ }
92
+ json["plaudit"]["setup"] = setupFiles.length === 1 ? setupFiles[0] : setupFiles;
93
+ }
94
+ if (json["render"] && (json["acf"] || json["plaudit"])) {
95
+ json["render_template"] = json["render"];
96
+ delete json["render"];
97
+ }
98
+ if (json["acf"]) {
99
+ if (json["acf"]["renderTemplate"]) {
100
+ json["render_template"] = json["acf"]["renderTemplate"];
101
+ delete json["acf"]["renderTemplate"];
102
+ }
103
+ else if (json["acf"]["render_template"]) {
104
+ json["render_template"] = json["acf"]["render_template"];
105
+ delete json["acf"]["render_template"];
106
+ }
107
+ }
108
+ let renderTemplate = (json["render_template"]
109
+ ? (typeof json["render_template"] === 'string' ? [json["render_template"]] : json["render_template"])
110
+ : ["template.php", "template.twig"])
111
+ .map(p => node_path_1.default.normalize(node_path_1.default.join(sourceDir, stripFilePrefix(p))))
112
+ .filter(p => node_fs_1.default.existsSync(p))
113
+ .map(p => `file:./${this.findRelativeRouteBetween(outputDir, p)}`);
114
+ if (renderTemplate.length !== 0) {
115
+ json["render_template"] = renderTemplate[0];
116
+ }
117
+ else if (json["render_template"] !== undefined) {
118
+ delete json["render_template"];
119
+ }
120
+ }
72
121
  compilation.updateAsset(name, new webpack_sources_1.RawSource(JSON.stringify(json, undefined, " ")));
73
122
  }
74
123
  }
75
124
  });
76
125
  });
77
126
  }
127
+ findCommonAncestor(...paths) {
128
+ return paths.map(p => node_path_1.default.normalize(p).split(node_path_1.default.sep)).reduce((prior, current) => {
129
+ for (let i = 0, limit = Math.min(prior.length, current.length); i < limit; i++) {
130
+ if (prior[i] !== current[i]) {
131
+ return prior.slice(0, i);
132
+ }
133
+ }
134
+ return current.length < prior.length ? current : prior;
135
+ });
136
+ }
137
+ findRelativeRouteBetween(path1, path2) {
138
+ const commonAncestor = this.findCommonAncestor(path1, path2);
139
+ const route = Array(path1.split(node_path_1.default.sep).length - commonAncestor.length).fill("..");
140
+ `..${node_path_1.default.sep}`.repeat(path1.split(node_path_1.default.sep).length - commonAncestor.length);
141
+ route.push(node_path_1.default.relative(commonAncestor.join(node_path_1.default.sep), path2));
142
+ return route.join(node_path_1.default.sep);
143
+ }
78
144
  }
79
145
  exports.default = BlockJSONStyleRemappingPlugin;
@@ -14,29 +14,76 @@ const webpack_remove_empty_scripts_1 = __importDefault(require("webpack-remove-e
14
14
  function joinPossiblyAbsolutePaths(...paths) {
15
15
  return paths.reduce((res, p) => !res || node_path_1.default.isAbsolute(p) ? p : node_path_1.default.join(res, p), '') || '.';
16
16
  }
17
- function addEntryPointWithMapper(entrypoints, entrypoint, dir, mapper = (entrypoint) => entrypoint) {
18
- for (const ep of Array.isArray(entrypoint) ? entrypoint : [entrypoint]) {
19
- const mapped = joinPossiblyAbsolutePaths(dir, mapper(ep));
20
- if (node_fs_1.default.existsSync(mapped)) {
21
- const parsedEntrypoint = node_path_1.default.parse(mapped);
22
- entrypoints[joinPossiblyAbsolutePaths(node_path_1.default.basename(parsedEntrypoint.dir), parsedEntrypoint.name)] = { import: mapped };
23
- }
24
- }
17
+ function mapToRealEntrypoints(entrypoint, dir, mapper = (entrypoint) => entrypoint) {
18
+ return (Array.isArray(entrypoint) ? entrypoint : [entrypoint])
19
+ .map(ep => joinPossiblyAbsolutePaths(dir, mapper(ep)))
20
+ .filter(ep => node_fs_1.default.existsSync(ep))
21
+ .map(ep => {
22
+ const parsedEntrypoint = node_path_1.default.parse(ep);
23
+ return [joinPossiblyAbsolutePaths(node_path_1.default.basename(parsedEntrypoint.dir), parsedEntrypoint.name), { import: ep }];
24
+ });
25
25
  }
26
26
  function isTruthy(value) {
27
27
  return !!value;
28
28
  }
29
- module.exports = function (config, webpackConfig = require("@wordpress/scripts/config/webpack.config")) {
29
+ function groupEntrypointsByAssetFile(entrypoints, entrypointNameExtractor) {
30
30
  const seenPaths = new Map();
31
- for (const bundleName of (Array.isArray(config.src) ? config.src : Object.values(config.src))) {
32
- const key = bundleName.substring(0, bundleName.length - node_path_1.default.extname(bundleName).length);
31
+ for (const entrypoint of entrypoints) {
32
+ const entrypointName = entrypointNameExtractor(entrypoint);
33
+ const key = entrypointName.substring(0, entrypointName.length - node_path_1.default.extname(entrypointName).length);
33
34
  let seen = seenPaths.get(key);
34
35
  if (seen === undefined) {
35
36
  seenPaths.set(key, seen = []);
36
37
  }
37
- seen.push(bundleName);
38
- node_path_1.default.basename(bundleName, node_path_1.default.extname(bundleName));
38
+ seen.push(entrypoint);
39
+ }
40
+ return seenPaths;
41
+ }
42
+ const scriptExtension = /\.[jt]sx?$/;
43
+ const styleExtension = /\.(p?c|sa)ss$/;
44
+ function scriptOrStyleTest(entryPath) {
45
+ return scriptExtension.test(entryPath) ? "script" : (styleExtension.test(entryPath) ? "style" : "");
46
+ }
47
+ function determineEntrypointType(entrypoint) {
48
+ let res = scriptOrStyleTest(entrypoint[0]);
49
+ if (res) {
50
+ return res;
51
+ }
52
+ if (typeof entrypoint[1] === 'string') {
53
+ return scriptOrStyleTest(entrypoint[1]);
54
+ }
55
+ else if (Array.isArray(entrypoint[1])) {
56
+ return entrypoint[1].reduce((prior, ep) => prior || scriptOrStyleTest(ep), "");
57
+ }
58
+ else if (typeof entrypoint[1].import === 'string') {
59
+ return scriptOrStyleTest(entrypoint[1].import);
60
+ }
61
+ else {
62
+ return entrypoint[1].import.reduce((prior, ep) => prior || scriptOrStyleTest(ep), "");
39
63
  }
64
+ }
65
+ function injectTypeAndCountToEntrypointName(entrypointName, type, typeCounts) {
66
+ const entrypointBasename = entrypointName.substring(0, entrypointName.length - node_path_1.default.extname(entrypointName).length);
67
+ const parts = [];
68
+ if (type) {
69
+ parts.push(type);
70
+ }
71
+ if (typeCounts[type] ?? (typeCounts[type] = 0)) {
72
+ parts.push(typeCounts[type].toString());
73
+ }
74
+ typeCounts[type] += 1;
75
+ return `${entrypointBasename}_${parts.join('-')}${node_path_1.default.extname(entrypointName)}`;
76
+ }
77
+ function addPotentiallyDuplicatedEntrypointName(entry, entrypoint, typeCounts) {
78
+ const type = determineEntrypointType(entrypoint);
79
+ let potentialKey = injectTypeAndCountToEntrypointName(entrypoint[0], type, typeCounts);
80
+ while (entry[potentialKey]) {
81
+ potentialKey = injectTypeAndCountToEntrypointName(entrypoint[0], type, typeCounts);
82
+ }
83
+ entry[potentialKey] = entrypoint[1];
84
+ }
85
+ module.exports = function (config, webpackConfig = require("@wordpress/scripts/config/webpack.config")) {
86
+ const seenPaths = groupEntrypointsByAssetFile(Array.isArray(config.src) ? config.src : Object.values(config.src), bn => bn);
40
87
  let projectPrefix = undefined;
41
88
  let duplicatedPaths = "";
42
89
  for (const sameNamePaths of seenPaths.values()) {
@@ -59,7 +106,7 @@ module.exports = function (config, webpackConfig = require("@wordpress/scripts/c
59
106
  console.error(`Encountered multiple paths that produce the same effective bundle name:${duplicatedPaths}`);
60
107
  process.exit(1);
61
108
  }
62
- const { variables = ["variables.js", "preprocess/variables.js"].map(p => node_path_1.default.join(process.cwd(), p)).filter(p => node_fs_1.default.existsSync(p)).map(p => require(p))[0] ?? {}, verbose = process.argv.includes('--verbose') || process.env['VERBOSE'] === 'true' } = config;
109
+ const { variables = ["variables.js", "src/site/variables.js"].map(p => node_path_1.default.join(process.cwd(), p)).filter(p => node_fs_1.default.existsSync(p)).map(p => require(p))[0] ?? {}, verbose = process.argv.includes('--verbose') || process.env['VERBOSE'] === 'true' } = config;
63
110
  const cssLoader = require.resolve('css-loader');
64
111
  if (cssLoader && webpackConfig.module?.rules) {
65
112
  for (const rule of webpackConfig.module.rules) {
@@ -138,37 +185,39 @@ module.exports = function (config, webpackConfig = require("@wordpress/scripts/c
138
185
  }
139
186
  let entry;
140
187
  if (srcIsDirectory) {
141
- entry = node_fs_1.default.readdirSync(srcRoot, 'utf8')
188
+ const rawEntrypoints = node_fs_1.default.readdirSync(srcRoot, 'utf8')
142
189
  .map(dir => joinPossiblyAbsolutePaths(srcRoot, dir))
143
190
  .filter(dir => node_fs_1.default.statSync(dir).isDirectory())
144
- .reduce((entrypoints, dir) => {
191
+ .flatMap(dir => {
192
+ const res = [];
145
193
  try {
146
194
  const blockJSON = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(dir, 'block.json'), 'utf8'));
147
195
  for (const key of ["editorStyle", "style", "editorScript", "viewScript", "script"]) {
148
196
  if (key in blockJSON) {
149
- addEntryPointWithMapper(entrypoints, blockJSON[key], dir, ep => ep.startsWith("file:") ? ep.substring(5) : ep);
197
+ res.push(...mapToRealEntrypoints(blockJSON[key], dir, ep => ep.startsWith("file:") ? ep.substring(5) : ep));
150
198
  }
151
199
  }
200
+ return res;
152
201
  }
153
202
  catch (e) {
154
203
  try {
155
204
  const packageJSON = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(dir, 'package.json'), 'utf8'));
156
- addEntryPointWithMapper(entrypoints, packageJSON['main'], dir);
157
- addEntryPointWithMapper(entrypoints, packageJSON['style'], dir);
205
+ res.push(...mapToRealEntrypoints(packageJSON['main'], dir));
206
+ res.push(...mapToRealEntrypoints(packageJSON['style'], dir));
158
207
  }
159
208
  catch (e) {
160
209
  try {
161
210
  const entrypointsJSON = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(dir, 'entrypoints.json'), 'utf8'));
162
211
  if (Array.isArray(entrypointsJSON)) {
163
- addEntryPointWithMapper(entrypoints, entrypointsJSON, dir);
212
+ res.push(...mapToRealEntrypoints(entrypointsJSON, dir));
164
213
  }
165
214
  else {
166
215
  for (const [name, config] of Object.entries(entrypointsJSON)) {
167
216
  if (typeof config === 'string') {
168
- entrypoints[name] = joinPossiblyAbsolutePaths(dir, config);
217
+ res.push([name, joinPossiblyAbsolutePaths(dir, config)]);
169
218
  }
170
219
  else if (Array.isArray(config)) {
171
- entrypoints[name] = config.map(c => joinPossiblyAbsolutePaths(dir, c));
220
+ res.push([name, config.map(c => joinPossiblyAbsolutePaths(dir, c))]);
172
221
  }
173
222
  else {
174
223
  if (typeof config.import === 'string') {
@@ -177,7 +226,7 @@ module.exports = function (config, webpackConfig = require("@wordpress/scripts/c
177
226
  else {
178
227
  config.import = config.import.map(c => joinPossiblyAbsolutePaths(dir, c));
179
228
  }
180
- entrypoints[name] = config;
229
+ res.push([name, config]);
181
230
  }
182
231
  }
183
232
  }
@@ -187,8 +236,21 @@ module.exports = function (config, webpackConfig = require("@wordpress/scripts/c
187
236
  }
188
237
  }
189
238
  }
190
- return entrypoints;
191
- }, {});
239
+ return res;
240
+ });
241
+ const perAssetPathGroupedEntrypoints = groupEntrypointsByAssetFile(rawEntrypoints, e => e[0]);
242
+ entry = {};
243
+ for (const groupedEntrypoints of perAssetPathGroupedEntrypoints.values()) {
244
+ if (groupedEntrypoints.length === 1) {
245
+ entry[groupedEntrypoints[0][0]] = groupedEntrypoints[0][1];
246
+ }
247
+ else {
248
+ const typeCounts = {};
249
+ for (const entrypoint of groupedEntrypoints) {
250
+ addPotentiallyDuplicatedEntrypointName(entry, entrypoint, typeCounts);
251
+ }
252
+ }
253
+ }
192
254
  }
193
255
  else {
194
256
  const baseDest = node_path_1.default.basename(dest);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plaudit/webpack-extensions",
3
- "version": "2.1.3",
3
+ "version": "2.2.0",
4
4
  "scripts": {
5
5
  "prepublishOnly": "rm -rf build && mkdir build && tsc",
6
6
  "build": "tsc",