@plaudit/webpack-extensions 2.61.2 → 2.62.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.
@@ -1,40 +0,0 @@
1
- import { Compilation, type Compiler, type WebpackPluginInstance } from "webpack";
2
- export declare class BlockJSONManagingPlugin implements WebpackPluginInstance {
3
- private readonly standaloneBlocks;
4
- private readonly processingModules;
5
- private readonly blocksDest;
6
- static readonly mappableModuleKeys: readonly ["viewScriptModule", "scriptModule"];
7
- static readonly mappableNonModuleKeys: readonly ["editorScript", "script", "viewScript", "editorStyle", "style", "viewStyle"];
8
- private static readonly mappableKeys;
9
- private static readonly blockJsonToEntrypointsMap;
10
- private static readonly blockJsonRawDependenciesMap;
11
- private static readonly blockJSONAssetSourceDirs;
12
- private static readonly blockJsonAssetKeyMapping;
13
- private static readonly syncsManager;
14
- readonly additionalMetadata: Map<string, any>;
15
- private readonly id;
16
- constructor(standaloneBlocks: boolean, processingModules: boolean | undefined, blocksDest: string);
17
- static recordRawDependency(entrypoint: string, dependency: string): void;
18
- static recordBlockJSONAssetSourceDir(entrypoint: string, source: string): void;
19
- apply(compiler: Compiler): void;
20
- static resolveDestinationBySourceExtension(srcPath: string, entrypoint: Compilation['asyncEntrypoints'][number]): string | undefined;
21
- static findCommonAncestor(...paths: string[]): string[];
22
- static findRelativeRouteBetween(path1: string, path2: string): string;
23
- private static remapReferencedPHPFilesOnKey;
24
- private static hashThingForAsset;
25
- private static stripFilePrefix;
26
- private static buildFakeCompilationAssets;
27
- private static incorporateRemappedAsset;
28
- private static remapReferencedAssetFile;
29
- private static getReferencedFileSlot;
30
- private static addAssetToBlockJsonKey;
31
- private registerAssetProcessor;
32
- private static populateEntrypointsMap;
33
- private registerBlockJsonProcessor;
34
- private static normalizeRenderTemplate;
35
- private getAssetDetails;
36
- private static getAssetDataAccountingForCSS;
37
- private static findFirstChunkFileWithExtension;
38
- private static getChunkFilesByRuntimeName;
39
- private stripBlocksDest;
40
- }
@@ -1,594 +0,0 @@
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
- exports.BlockJSONManagingPlugin = void 0;
7
- const node_crypto_1 = __importDefault(require("node:crypto"));
8
- const node_fs_1 = __importDefault(require("node:fs"));
9
- const node_path_1 = __importDefault(require("node:path"));
10
- const shared_1 = require("../shared");
11
- const webpack_1 = require("webpack");
12
- const UnifiedLoaderGenerator_1 = require("./UnifiedLoaderGenerator");
13
- const php_writer_1 = require("../utils/php-writer");
14
- class BlockJSONManagingPlugin {
15
- standaloneBlocks;
16
- processingModules;
17
- blocksDest;
18
- static mappableModuleKeys = ["viewScriptModule", "scriptModule"];
19
- static mappableNonModuleKeys = ["editorScript", "script", "viewScript", "editorStyle", "style", "viewStyle"];
20
- static mappableKeys = [...BlockJSONManagingPlugin.mappableNonModuleKeys, ...BlockJSONManagingPlugin.mappableModuleKeys];
21
- static blockJsonToEntrypointsMap = new Map();
22
- static blockJsonRawDependenciesMap = new Map();
23
- static blockJSONAssetSourceDirs = new Map();
24
- static blockJsonAssetKeyMapping = new Map();
25
- static syncsManager = new shared_1.SyncsManager();
26
- additionalMetadata = new Map();
27
- id;
28
- constructor(standaloneBlocks, processingModules, blocksDest) {
29
- this.standaloneBlocks = standaloneBlocks;
30
- this.processingModules = processingModules;
31
- this.blocksDest = blocksDest;
32
- this.id = Math.random().toString();
33
- if (!this.processingModules) {
34
- UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.register(this.id);
35
- }
36
- }
37
- static recordRawDependency(entrypoint, dependency) {
38
- let deps = BlockJSONManagingPlugin.blockJsonRawDependenciesMap.get(entrypoint);
39
- if (deps === undefined) {
40
- BlockJSONManagingPlugin.blockJsonRawDependenciesMap.set(entrypoint, deps = new Set());
41
- }
42
- deps.add(dependency);
43
- }
44
- static recordBlockJSONAssetSourceDir(entrypoint, source) {
45
- BlockJSONManagingPlugin.blockJSONAssetSourceDirs.set(entrypoint, source);
46
- }
47
- apply(compiler) {
48
- compiler.hooks.compilation.tap(this.constructor.name, compilation => {
49
- this.additionalMetadata.clear();
50
- this.registerAssetProcessor(compilation);
51
- if (!this.processingModules) {
52
- UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.reset(this.id);
53
- this.registerBlockJsonProcessor(compilation);
54
- }
55
- });
56
- }
57
- static resolveDestinationBySourceExtension(srcPath, entrypoint) {
58
- const extensionMatch = /(m?)[jt]sx?$/i.exec(node_path_1.default.extname(srcPath));
59
- if (extensionMatch === null) {
60
- return entrypoint.getFiles().find(file => file.endsWith(".css"));
61
- }
62
- else if (extensionMatch[1]) {
63
- return entrypoint.getFiles().find(file => file.endsWith(".mjs")) ?? entrypoint.getFiles().find(file => file.endsWith(".js"));
64
- }
65
- else {
66
- return entrypoint.getFiles().find(file => file.endsWith(".js"));
67
- }
68
- }
69
- static findCommonAncestor(...paths) {
70
- return paths.map(p => node_path_1.default.normalize(p).split(node_path_1.default.sep)).reduce((prior, current) => {
71
- for (let i = 0, limit = Math.min(prior.length, current.length); i < limit; i++) {
72
- if (prior[i] !== current[i]) {
73
- return prior.slice(0, i);
74
- }
75
- }
76
- return current.length < prior.length ? current : prior;
77
- });
78
- }
79
- static findRelativeRouteBetween(path1, path2) {
80
- const commonAncestor = BlockJSONManagingPlugin.findCommonAncestor(path1, path2);
81
- const route = Array(path1.split(node_path_1.default.sep).length - commonAncestor.length).fill("..");
82
- route.push(node_path_1.default.relative(commonAncestor.join(node_path_1.default.sep), path2));
83
- return route.join(node_path_1.default.sep);
84
- }
85
- static remapReferencedPHPFilesOnKey(json, key, pathsNeedRemapping, sourceDir, outputDir, compilation, inPlaudit) {
86
- const rawValue = (inPlaudit ? json["plaudit"] : json)?.[key];
87
- let rawFiles;
88
- let deleteOnEmpty = true;
89
- if (typeof rawValue === 'string') {
90
- rawFiles = [rawValue];
91
- }
92
- else if (Array.isArray(rawValue) && rawValue.length > 0) {
93
- const fileReferences = rawValue.filter((value) => typeof value === 'string' && value.startsWith("file:./"));
94
- if (fileReferences.length === rawValue.length) {
95
- rawFiles = fileReferences;
96
- }
97
- else {
98
- if (fileReferences.length !== 0) {
99
- const error = new webpack_1.WebpackError(`Encountered a block with a mixture of file-reference and non-file-reference elements in the "${inPlaudit ? 'plaudit.' : ''}${key}" property`);
100
- error.file = node_path_1.default.join(sourceDir, 'block.json');
101
- compilation.warnings.push(error);
102
- rawFiles = fileReferences;
103
- }
104
- else {
105
- rawFiles = [`${key}.php`]; // We want to emit an error if both an appropriately-named file AND an incompatible value exist, so we still need to do the check
106
- }
107
- deleteOnEmpty = false;
108
- }
109
- }
110
- else {
111
- if (rawValue && (!Array.isArray(rawValue) || rawValue.length === 0)) {
112
- deleteOnEmpty = false;
113
- }
114
- rawFiles = [`${key}.php`];
115
- }
116
- const mappedFiles = pathsNeedRemapping
117
- ? rawFiles
118
- .map(p => node_path_1.default.normalize(node_path_1.default.join(sourceDir, BlockJSONManagingPlugin.stripFilePrefix(p))))
119
- .filter(p => node_fs_1.default.existsSync(p))
120
- .map(p => `file:./${BlockJSONManagingPlugin.findRelativeRouteBetween(outputDir, p)}`)
121
- : rawFiles
122
- .filter(p => node_fs_1.default.existsSync(node_path_1.default.normalize(node_path_1.default.join(sourceDir, BlockJSONManagingPlugin.stripFilePrefix(p)))));
123
- if (mappedFiles.length === 0) {
124
- if (deleteOnEmpty && rawValue !== undefined) {
125
- delete (inPlaudit ? json["plaudit"] : json)[key];
126
- }
127
- }
128
- else {
129
- if (inPlaudit && typeof json["plaudit"] !== 'object') {
130
- if (json["plaudit"] === "native") {
131
- json["plaudit"] = { type: "native" };
132
- }
133
- else {
134
- json["plaudit"] = {};
135
- }
136
- }
137
- (inPlaudit ? json["plaudit"] : json)[key] = mappedFiles.length === 1 ? mappedFiles[0] : mappedFiles;
138
- }
139
- }
140
- static hashThingForAsset(thing) {
141
- return node_crypto_1.default.createHash('md5').update(thing).digest("hex").substring(0, 20).toLowerCase();
142
- }
143
- static stripFilePrefix(file) {
144
- return file.startsWith("file:./") ? file.substring(7) : file;
145
- }
146
- static buildFakeCompilationAssets(compilation) {
147
- const res = {};
148
- for (const filePath of compilation.fileDependencies.values()) {
149
- if (filePath.endsWith("/block.json")) {
150
- const directory = node_path_1.default.dirname(node_path_1.default.normalize(filePath));
151
- res[node_path_1.default.join(node_path_1.default.basename(directory), "block.json")] = filePath;
152
- }
153
- }
154
- return res;
155
- }
156
- static incorporateRemappedAsset(cacheableMappedKeys, mappableKey, remappedValue, additionalValues) {
157
- if (additionalValues.length > 0) {
158
- const referencedFilesSlot = BlockJSONManagingPlugin.getReferencedFileSlot(mappableKey);
159
- if (!cacheableMappedKeys.referencedFiles[referencedFilesSlot]) {
160
- cacheableMappedKeys.referencedFiles[referencedFilesSlot] = [...additionalValues];
161
- }
162
- else {
163
- cacheableMappedKeys.referencedFiles[referencedFilesSlot].push(...additionalValues);
164
- }
165
- }
166
- if (Array.isArray(cacheableMappedKeys.directMappings[mappableKey])) {
167
- cacheableMappedKeys.directMappings[mappableKey].push(remappedValue[0]);
168
- }
169
- else if (typeof cacheableMappedKeys.directMappings[mappableKey] === 'string') {
170
- cacheableMappedKeys.directMappings[mappableKey] = [cacheableMappedKeys.directMappings[mappableKey], remappedValue[0]];
171
- }
172
- else {
173
- cacheableMappedKeys.directMappings[mappableKey] = remappedValue[0];
174
- }
175
- cacheableMappedKeys.compositeHash += "~" + remappedValue[1];
176
- }
177
- static remapReferencedAssetFile(value, name) {
178
- if (value.startsWith("file:")) {
179
- const sourceDir = BlockJSONManagingPlugin.blockJSONAssetSourceDirs.get(name) ?? node_path_1.default.dirname(name);
180
- const inputPath = node_path_1.default.normalize(node_path_1.default.join(sourceDir, value.substring(5)));
181
- const outputAndDerivedFiles = BlockJSONManagingPlugin.blockJsonToEntrypointsMap.get(name)?.get(inputPath);
182
- if (outputAndDerivedFiles !== undefined) {
183
- const { entryMeta, derivedFiles } = outputAndDerivedFiles;
184
- const prefix = value.startsWith("./", 5) ? "./" : "";
185
- const relativePath = node_path_1.default.relative(node_path_1.default.dirname(name), entryMeta.path);
186
- const res = [`file:${prefix}${relativePath}`, entryMeta.hash];
187
- if (shared_1.styleExtension.test(entryMeta.path)) {
188
- return [res,
189
- derivedFiles.filter(derivedFile => !shared_1.scriptExtension.test(derivedFile))
190
- .map(derivedFile => `file:./${node_path_1.default.relative(node_path_1.default.dirname(name), derivedFile)}`)
191
- ];
192
- }
193
- else {
194
- return [res, derivedFiles.map(derivedFile => `file:./${node_path_1.default.relative(node_path_1.default.dirname(name), derivedFile)}`)];
195
- }
196
- }
197
- }
198
- return [[value, ""], []];
199
- }
200
- static getReferencedFileSlot(mappableKey) {
201
- if (mappableKey.startsWith("editor")) {
202
- return "editor";
203
- }
204
- else if (mappableKey.startsWith("view")) {
205
- return "view";
206
- }
207
- else {
208
- return "both";
209
- }
210
- }
211
- static addAssetToBlockJsonKey(json, mappableKey, asset) {
212
- if (json[mappableKey] === undefined) {
213
- if (Array.isArray(asset)) {
214
- json[mappableKey] = [...asset];
215
- }
216
- else {
217
- json[mappableKey] = asset;
218
- }
219
- }
220
- else if (typeof json[mappableKey] === 'string') {
221
- if (Array.isArray(asset)) {
222
- json[mappableKey] = [json[mappableKey], ...asset];
223
- }
224
- else {
225
- json[mappableKey] = [json[mappableKey], asset];
226
- }
227
- }
228
- else {
229
- if (Array.isArray(asset)) {
230
- json[mappableKey].push(...asset);
231
- }
232
- else {
233
- json[mappableKey].push(asset);
234
- }
235
- }
236
- }
237
- registerAssetProcessor(compilation) {
238
- const tapName = { name: `${this.constructor.name}_ProcessBlockJSONFiles`, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_DERIVED };
239
- compilation.hooks.processAssets.tapPromise(tapName, async (compilationAssets) => {
240
- const testableCompilationAssets = this.processingModules ? BlockJSONManagingPlugin.buildFakeCompilationAssets(compilation) : compilationAssets;
241
- const currentBlockJSONAssets = BlockJSONManagingPlugin.blockJSONAssetSourceDirs.entries()
242
- .filter(([name]) => name in testableCompilationAssets)
243
- .toArray();
244
- BlockJSONManagingPlugin.populateEntrypointsMap(currentBlockJSONAssets, compilation);
245
- await Promise.all(currentBlockJSONAssets.map(async ([name]) => {
246
- const assetContents = this.processingModules ? node_fs_1.default.readFileSync(testableCompilationAssets[name], 'utf8') : compilation.assets[name]?.buffer().toString();
247
- if (!assetContents) {
248
- return;
249
- }
250
- const json = JSON.parse(assetContents);
251
- const currentAssetKeyMappings = { directMappings: {}, referencedFiles: {}, compositeHash: "" };
252
- for (const mappableKey of BlockJSONManagingPlugin[this.processingModules ? 'mappableModuleKeys' : 'mappableNonModuleKeys']) {
253
- if (mappableKey in json) {
254
- const unmappedValue = json[mappableKey];
255
- if (Array.isArray(unmappedValue)) {
256
- for (const uv of unmappedValue) {
257
- BlockJSONManagingPlugin.incorporateRemappedAsset(currentAssetKeyMappings, mappableKey, ...BlockJSONManagingPlugin.remapReferencedAssetFile(uv, name));
258
- }
259
- }
260
- else if (typeof unmappedValue === 'string') {
261
- BlockJSONManagingPlugin.incorporateRemappedAsset(currentAssetKeyMappings, mappableKey, ...BlockJSONManagingPlugin.remapReferencedAssetFile(unmappedValue, name));
262
- }
263
- }
264
- }
265
- const syncs = BlockJSONManagingPlugin.syncsManager.get(name);
266
- let assetKeyMappings = BlockJSONManagingPlugin.blockJsonAssetKeyMapping.get(name);
267
- if (!assetKeyMappings) {
268
- BlockJSONManagingPlugin.blockJsonAssetKeyMapping.set(name, assetKeyMappings = {});
269
- }
270
- assetKeyMappings[this.processingModules ? 'module' : 'nonModule'] = currentAssetKeyMappings;
271
- if (this.processingModules) {
272
- syncs.module.resolve();
273
- if (!BlockJSONManagingPlugin.mappableNonModuleKeys.some(key => key in json)) {
274
- syncs.nonModule.resolve();
275
- }
276
- await syncs.nonModule.sync;
277
- }
278
- else {
279
- syncs.nonModule.resolve();
280
- if (!BlockJSONManagingPlugin.mappableModuleKeys.some(key => key in json)) {
281
- syncs.module.resolve();
282
- }
283
- await syncs.module.sync;
284
- }
285
- }));
286
- });
287
- }
288
- static populateEntrypointsMap(currentBlockJSONAssets, compilation) {
289
- for (const [name] of currentBlockJSONAssets) {
290
- const dependencies = BlockJSONManagingPlugin.blockJsonRawDependenciesMap.get(name);
291
- if (dependencies) {
292
- for (const dependency of dependencies) {
293
- const entrypoint = compilation.entrypoints.get(dependency);
294
- if (!entrypoint) {
295
- continue;
296
- }
297
- const srcPath = entrypoint.origins.map(origin => origin.request)[0];
298
- if (!srcPath) {
299
- continue;
300
- }
301
- const destPath = BlockJSONManagingPlugin.resolveDestinationBySourceExtension(srcPath, entrypoint);
302
- if (!destPath) {
303
- continue;
304
- }
305
- const entrypointChunk = entrypoint.getEntrypointChunk();
306
- const derivedFiles = entrypointChunk.name
307
- ? BlockJSONManagingPlugin.getChunkFilesByRuntimeName(entrypointChunk.name, compilation).filter(file => file !== destPath)
308
- : [...entrypointChunk.files].filter(file => !file.endsWith(".asset.php") && file !== destPath);
309
- const entryMeta = { hash: entrypointChunk.hash ?? destPath, path: destPath };
310
- const currentEntrypoints = BlockJSONManagingPlugin.blockJsonToEntrypointsMap.get(name);
311
- if (currentEntrypoints) {
312
- currentEntrypoints.set(srcPath, { entryMeta, derivedFiles });
313
- }
314
- else {
315
- BlockJSONManagingPlugin.blockJsonToEntrypointsMap.set(name, new Map([[srcPath, { entryMeta, derivedFiles }]]));
316
- }
317
- }
318
- }
319
- }
320
- }
321
- registerBlockJsonProcessor(compilation) {
322
- const blockDirConfigData = {};
323
- compilation.hooks.processAssets.tap({ name: `${this.constructor.name}_UnifiedLoaderGeneratorIntegration`, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_DERIVED }, () => {
324
- UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.resolve(this.id, {
325
- group: `block-json-${this.blocksDest}`,
326
- requiresBaseURI: false,
327
- action: writer => {
328
- writer
329
- .use("Plaudit\\Common\\ACF\\BlockManager")
330
- .action("init", writer => {
331
- writer.call("BlockManager::autoloadSubfolders", [new php_writer_1.Expr(`__DIR__.${php_writer_1.Expr.convertJsonToPHP("/" + this.blocksDest)}`)]);
332
- }, { accountForAlreadyDoing: true });
333
- }
334
- });
335
- });
336
- compilation.hooks.afterProcessAssets.tap(`${this.constructor.name}_GenerateMetadata`, compilationAssets => {
337
- const currentBlockJSONAssets = BlockJSONManagingPlugin.blockJSONAssetSourceDirs.entries()
338
- .filter(([name]) => name in compilationAssets)
339
- .toArray();
340
- for (const [name, sourceDir] of currentBlockJSONAssets) {
341
- const assetKeyMappings = BlockJSONManagingPlugin.blockJsonAssetKeyMapping.get(name);
342
- let compositeHash = "";
343
- const condensedBlockJsonAssetKeyMappings = {};
344
- for (const subType of ['nonModule', 'module']) {
345
- const mappings = assetKeyMappings[subType];
346
- if (mappings) {
347
- compositeHash += mappings.compositeHash;
348
- for (const mappableKey of BlockJSONManagingPlugin.mappableKeys) {
349
- if (mappings.directMappings[mappableKey]) {
350
- BlockJSONManagingPlugin.addAssetToBlockJsonKey(condensedBlockJsonAssetKeyMappings, mappableKey, mappings.directMappings[mappableKey]);
351
- }
352
- }
353
- for (const [referenceLocation, prefix] of [["editor", "editorS"], ["both", "s"], ["view", "viewS"]]) {
354
- if (mappings.referencedFiles[referenceLocation]) {
355
- for (const referencedFile of mappings.referencedFiles[referenceLocation]) {
356
- if (referencedFile.endsWith(".css")) {
357
- BlockJSONManagingPlugin.addAssetToBlockJsonKey(condensedBlockJsonAssetKeyMappings, `${prefix}tyle`, referencedFile);
358
- }
359
- else if (referencedFile.endsWith(".js")) {
360
- BlockJSONManagingPlugin.addAssetToBlockJsonKey(condensedBlockJsonAssetKeyMappings, `${prefix}cript`, referencedFile);
361
- }
362
- else if (referencedFile.endsWith(".mjs")) {
363
- BlockJSONManagingPlugin.addAssetToBlockJsonKey(condensedBlockJsonAssetKeyMappings, `${prefix}criptModule`, referencedFile);
364
- }
365
- }
366
- }
367
- }
368
- }
369
- }
370
- const assetContents = compilation.assets[name]?.buffer().toString();
371
- if (!assetContents) {
372
- continue;
373
- }
374
- const json = JSON.parse(assetContents);
375
- for (const mappableKey of BlockJSONManagingPlugin.mappableKeys) {
376
- if (mappableKey in condensedBlockJsonAssetKeyMappings) {
377
- json[mappableKey] = condensedBlockJsonAssetKeyMappings[mappableKey];
378
- }
379
- else {
380
- delete json[mappableKey];
381
- }
382
- }
383
- if (json["version"]) {
384
- json["version"] = `${json["version"]}-${BlockJSONManagingPlugin.hashThingForAsset(compositeHash)}`;
385
- }
386
- else {
387
- json["version"] = BlockJSONManagingPlugin.hashThingForAsset(compositeHash);
388
- }
389
- const outputDir = node_path_1.default.join(compilation.compiler.outputPath, node_path_1.default.dirname(name));
390
- const pathsNeedRemapping = !this.standaloneBlocks && json["plaudit"] !== "simple";
391
- BlockJSONManagingPlugin.remapReferencedPHPFilesOnKey(json, "setup", pathsNeedRemapping, sourceDir, outputDir, compilation, true);
392
- BlockJSONManagingPlugin.remapReferencedPHPFilesOnKey(json, "variations", pathsNeedRemapping, sourceDir, outputDir, compilation, false);
393
- BlockJSONManagingPlugin.normalizeRenderTemplate(json, pathsNeedRemapping, sourceDir, outputDir, compilation);
394
- compilation[name in compilation.assets ? 'updateAsset' : 'emitAsset'](name, new webpack_1.sources.RawSource(JSON.stringify(json, undefined, " ")));
395
- blockDirConfigData[node_path_1.default.dirname(name)] = json;
396
- }
397
- let sortedBlockDirConfigData;
398
- const blockDirConfigs = Object.entries(blockDirConfigData).sort(([a], [b]) => a.localeCompare(b));
399
- const rawAssetDataSource = compilation.assets["assets.json"]?.source();
400
- if (typeof rawAssetDataSource === 'string') {
401
- const derivedFilesMap = new Map();
402
- for (const epMap of BlockJSONManagingPlugin.blockJsonToEntrypointsMap.values()) { // For each block.json file's entry point map
403
- for (const epMapValue of epMap.values()) { // For each recorded entry point
404
- const progenitorFile = epMapValue.entryMeta.path;
405
- for (const derivedFile of epMapValue.derivedFiles) { // For each derived (non-auxiliary) file generated by that entry point
406
- derivedFilesMap.set(derivedFile, progenitorFile); // Record a mapping from each derived file to its progenitor
407
- }
408
- }
409
- }
410
- const rawAssetData = JSON.parse(rawAssetDataSource);
411
- for (const chunk of compilation.chunks) {
412
- if (compilation.chunkGraph.getChunkModulesIterableBySourceType(chunk, 'css/mini-extract')) {
413
- const output = BlockJSONManagingPlugin.findFirstChunkFileWithExtension(chunk, ".css");
414
- if (output) {
415
- rawAssetData[output] = { dependencies: [], version: chunk.contentHash['css/mini-extract'] ?? chunk.hash ?? "" };
416
- }
417
- }
418
- }
419
- const scriptHandles = {};
420
- const styleHandles = {};
421
- const usedHandles = { css: {}, js: {} };
422
- for (const [blockFolder, config] of blockDirConfigs) {
423
- for (const mappableKey of BlockJSONManagingPlugin.mappableKeys) {
424
- const cfg = config[mappableKey];
425
- if (cfg) {
426
- if (Array.isArray(cfg)) {
427
- for (let i = 0; i < cfg.length; i++) {
428
- const assetDetails = this
429
- .getAssetDetails(blockFolder, config["name"], cfg[i], rawAssetData, derivedFilesMap, mappableKey, usedHandles);
430
- if (assetDetails) {
431
- (assetDetails.isCss ? styleHandles : scriptHandles)[assetDetails.handle] = assetDetails.handleData;
432
- cfg[i] = assetDetails.handle;
433
- }
434
- }
435
- }
436
- else {
437
- const assetDetails = this
438
- .getAssetDetails(blockFolder, config["name"], cfg, rawAssetData, derivedFilesMap, mappableKey, usedHandles);
439
- if (assetDetails) {
440
- (assetDetails.isCss ? styleHandles : scriptHandles)[assetDetails.handle] = assetDetails.handleData;
441
- config[mappableKey] = assetDetails.handle;
442
- }
443
- }
444
- }
445
- }
446
- }
447
- sortedBlockDirConfigData = Object.fromEntries([
448
- ["__metadata", { version: 3, ...Object.fromEntries(this.additionalMetadata.entries()), scriptHandles, styleHandles }],
449
- ...blockDirConfigs.map(entry => [this.stripBlocksDest(entry[0]), Object.fromEntries(Object.entries(entry[1]).filter(e => e[0] !== '$schema'))])
450
- ]);
451
- compilation.deleteAsset("assets.json");
452
- }
453
- else {
454
- sortedBlockDirConfigData = Object.fromEntries([
455
- ["__metadata", { version: 1, ...Object.fromEntries(this.additionalMetadata.entries()) }],
456
- ...blockDirConfigs.map(entry => [this.stripBlocksDest(entry[0]), Object.fromEntries(Object.entries(entry[1]).filter(e => e[0] !== '$schema'))])
457
- ]);
458
- }
459
- compilation.emitAsset(node_path_1.default.join(this.blocksDest, "blockdir.config.php"), new webpack_1.sources.RawSource((0, shared_1.makeEmittableConfigPHP)(sortedBlockDirConfigData)));
460
- });
461
- }
462
- static normalizeRenderTemplate(json, pathsNeedRemapping, sourceDir, outputDir, compilation) {
463
- if (json["acf"]) {
464
- if (json["acf"]["renderTemplate"]) {
465
- json["render_template"] = json["acf"]["renderTemplate"];
466
- delete json["acf"]["renderTemplate"];
467
- }
468
- else if (json["acf"]["render_template"]) {
469
- json["render_template"] = json["acf"]["render_template"];
470
- delete json["acf"]["render_template"];
471
- }
472
- }
473
- const blockName = json["name"]?.toString() || "non-existent/block-name";
474
- let rawRenderTemplate = json["render"] ?? json["render_template"];
475
- rawRenderTemplate = (rawRenderTemplate
476
- ? (typeof rawRenderTemplate === 'string' ? [rawRenderTemplate] : rawRenderTemplate)
477
- : [`${blockName.substring(blockName.indexOf('/') + 1)}.php`, "template.php", "template.twig"]);
478
- const renderTemplate = pathsNeedRemapping
479
- ? rawRenderTemplate
480
- .map(p => node_path_1.default.normalize(node_path_1.default.join(sourceDir, BlockJSONManagingPlugin.stripFilePrefix(p))))
481
- .filter(p => node_fs_1.default.existsSync(p))
482
- .map(p => `file:./${BlockJSONManagingPlugin.findRelativeRouteBetween(outputDir, p)}`)
483
- : rawRenderTemplate
484
- .filter(p => node_fs_1.default.existsSync(node_path_1.default.normalize(node_path_1.default.join(sourceDir, BlockJSONManagingPlugin.stripFilePrefix(p)))));
485
- if (renderTemplate.length === 0) {
486
- delete json["render_template"];
487
- delete json["render"];
488
- }
489
- else {
490
- let validTemplateLocation, invalidTemplateLocation;
491
- if (json["acf"] || (json["plaudit"] && (json["plaudit"] !== "native" && (typeof json["plaudit"] !== 'object' || json["plaudit"]?.["type"] !== "native")))) {
492
- // ACF-like blocks need to have the template stored in render_template.
493
- // Because we can statically detect ACF-like blocks, we can make the move here instead of at run-time.
494
- validTemplateLocation = "render_template";
495
- invalidTemplateLocation = "render";
496
- }
497
- else {
498
- validTemplateLocation = "render";
499
- invalidTemplateLocation = "render_template";
500
- }
501
- delete json[invalidTemplateLocation];
502
- if (renderTemplate.length > 1) {
503
- const error = new webpack_1.WebpackError("Encountered a block with multiple possible render files");
504
- error.file = node_path_1.default.join(sourceDir, 'block.json');
505
- compilation.warnings.push(error);
506
- json[validTemplateLocation] = renderTemplate.find(p => p.endsWith(".php")) ?? renderTemplate[0];
507
- }
508
- else {
509
- json[validTemplateLocation] = renderTemplate[0];
510
- }
511
- }
512
- }
513
- getAssetDetails(blockFolder, blockName, asset, rawAssetData, derivedFilesMap, mappableKey, usedHandles) {
514
- if (!asset.startsWith("file:./")) {
515
- return undefined;
516
- }
517
- const src = `${blockFolder}/${asset.substring(7)}`;
518
- const isCss = src.endsWith(".css");
519
- let assetData;
520
- if (rawAssetData[src]) {
521
- assetData = rawAssetData[src];
522
- }
523
- else {
524
- const progenitorSrc = derivedFilesMap.get(src);
525
- if (progenitorSrc) {
526
- const tempAssetData = BlockJSONManagingPlugin.getAssetDataAccountingForCSS(progenitorSrc, rawAssetData);
527
- if (tempAssetData) {
528
- assetData = progenitorSrc.endsWith(".css") === isCss
529
- ? tempAssetData
530
- : { ...tempAssetData, dependencies: [] }; // derived files cannot inherit dependencies from their progenitors if they are of a different type
531
- }
532
- else {
533
- assetData = undefined;
534
- }
535
- assetData = tempAssetData ? { ...tempAssetData, dependencies: [] } : undefined;
536
- }
537
- else {
538
- assetData = BlockJSONManagingPlugin.getAssetDataAccountingForCSS(src, rawAssetData);
539
- }
540
- }
541
- if (!assetData) {
542
- return undefined;
543
- }
544
- let handle = this.stripBlocksDest(src.substring(0, src.length - (isCss ? 4 : 3)));
545
- if (blockName && handle.startsWith(blockName.substring(blockName.indexOf("/") + 1) + "/")) {
546
- handle = blockName + handle.substring(handle.indexOf("/"));
547
- }
548
- if (usedHandles[isCss ? 'css' : 'js'][handle] !== undefined) {
549
- handle += "-" + (++usedHandles[isCss ? 'css' : 'js'][handle]);
550
- }
551
- else {
552
- usedHandles[isCss ? 'css' : 'js'][handle] = 0;
553
- }
554
- const rest = isCss || mappableKey.startsWith("editor")
555
- ? [assetData.dependencies, assetData.version]
556
- : [assetData.dependencies, assetData.version, { strategy: 'defer' }];
557
- return { isCss, handle, handleData: { src: this.stripBlocksDest(src), rest } };
558
- }
559
- static getAssetDataAccountingForCSS(src, rawAssetData) {
560
- if (rawAssetData[src]) {
561
- return rawAssetData[src];
562
- }
563
- if (src.endsWith(".css")) {
564
- return rawAssetData[src.substring(0, src.length - 3) + "js"] // A simple style dependency that isn't named "style"
565
- ?? rawAssetData[src.substring(0, src.length - 3).replace("style-style", "style") + "js"]; // A simple style dependency that IS named style
566
- }
567
- return undefined;
568
- }
569
- static findFirstChunkFileWithExtension(chunk, extension) {
570
- for (const file of chunk.files) {
571
- if (file.endsWith(extension)) {
572
- return file;
573
- }
574
- }
575
- return undefined;
576
- }
577
- static getChunkFilesByRuntimeName(runtimeName, compilation) {
578
- const files = new Set();
579
- for (const chunk of compilation.chunks) {
580
- if (typeof chunk.runtime === 'string' ? chunk.runtime === runtimeName : chunk.runtime?.has(runtimeName)) {
581
- for (const file of chunk.files) {
582
- if (!file.endsWith(".asset.php")) {
583
- files.add(file);
584
- }
585
- }
586
- }
587
- }
588
- return [...files];
589
- }
590
- stripBlocksDest(item) {
591
- return this.blocksDest && item.startsWith(this.blocksDest + "/") ? item.substring(this.blocksDest.length + 1 /* we also need to drop the "/" */) : item;
592
- }
593
- }
594
- exports.BlockJSONManagingPlugin = BlockJSONManagingPlugin;