@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,144 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.UnifiedLoaderGenerator = void 0;
37
- const node_path_1 = __importStar(require("node:path"));
38
- const php_writer_1 = require("@plaudit/php-writer");
39
- const expressions_1 = require("@plaudit/php-writer/expressions");
40
- const AbstractBiPhasicGroupPlugin_1 = require("./AbstractBiPhasicGroupPlugin");
41
- const shared_1 = require("../shared");
42
- const pseudo_semaphore_1 = require("../utils/pseudo-semaphore");
43
- const webpack_1 = require("webpack");
44
- const promises_1 = require("node:fs/promises");
45
- class UnifiedLoaderGenerator extends AbstractBiPhasicGroupPlugin_1.AbstractBiPhasicGroupPlugin {
46
- config;
47
- static semaphore = new pseudo_semaphore_1.PseudoSemaphore("Unified");
48
- constructor(config) {
49
- super("unified-loader", []);
50
- this.config = config;
51
- }
52
- attachStandardPhase(compilation) {
53
- compilation.hooks.afterProcessAssets.tap(this.constructor.name, () => {
54
- compilation.deleteAsset("assets.json");
55
- });
56
- }
57
- attachUniquePhase(compilation) {
58
- this.tapRequiringAssetsJson(compilation, { stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_REPORT }, async () => {
59
- const groupedLoaderInfo = Object.values((await UnifiedLoaderGenerator.semaphore.wait())
60
- .reduce((acc, cur) => {
61
- const accValue = acc[cur.group];
62
- if (accValue === undefined) {
63
- acc[cur.group] = { ...cur, priority: cur.priority ?? 0, staticallyLoadedEntrypoints: cur.staticallyLoadedEntrypoints?.length ? [...cur.staticallyLoadedEntrypoints] : [] };
64
- return acc;
65
- }
66
- if (cur.priority && accValue.priority < cur.priority) {
67
- accValue.priority = cur.priority;
68
- accValue.action = cur.action;
69
- accValue.requiresBaseURI = cur.requiresBaseURI;
70
- }
71
- else if (cur.requiresBaseURI && !accValue.requiresBaseURI) {
72
- accValue.requiresBaseURI = cur.requiresBaseURI;
73
- }
74
- if (cur.staticallyLoadedEntrypoints?.length) {
75
- accValue.staticallyLoadedEntrypoints.push(...cur.staticallyLoadedEntrypoints);
76
- }
77
- return acc;
78
- }, {}))
79
- .sort((a, b) => {
80
- const ap = a.priority ?? 0, bp = b.priority ?? 0;
81
- return ap === bp ? a.group.localeCompare(b.group) : bp - ap;
82
- });
83
- const staticallyLoadedEntrypoints = new Set(groupedLoaderInfo.flatMap(lig => lig.staticallyLoadedEntrypoints));
84
- for (const [file, assetData] of Object.entries((0, shared_1.getAssetsJson)(compilation))) {
85
- if (staticallyLoadedEntrypoints.has(file) || staticallyLoadedEntrypoints.has(file.replace(/\.css$/, '.js')) || staticallyLoadedEntrypoints.has(file.replace(/\.js$/, '.css'))) {
86
- continue;
87
- }
88
- const parsedPath = node_path_1.default.parse(file);
89
- const contents = `<?php return ${(0, php_writer_1.json2php)(assetData)};\n`;
90
- const assetName = node_path_1.default.join(parsedPath.dir, parsedPath.name) + ".asset.php";
91
- compilation[assetName in compilation.assets ? 'updateAsset' : 'emitAsset'](assetName, new webpack_1.sources.RawSource(contents), { size: Buffer.byteLength(contents) });
92
- }
93
- if (this.config.useUnifiedLoader) {
94
- compilation.hooks.afterProcessAssets.tap(this.constructor.name, () => {
95
- let phpFile;
96
- if (compilation.outputOptions.path?.endsWith("-dev")) {
97
- compilation['.gitignore' in compilation.assets ? 'updateAsset' : 'emitAsset']('.gitignore', new webpack_1.sources.RawSource('**'), { size: 2 });
98
- this.ensureDistExists(compilation.outputOptions.path);
99
- phpFile = new php_writer_1.PHPFile();
100
- }
101
- else {
102
- phpFile = this.withDistDevLoader();
103
- }
104
- if (groupedLoaderInfo.some(wc => wc.requiresBaseURI)) {
105
- (0, shared_1.emitResolveBaseUriFunction)(phpFile);
106
- }
107
- for (const { action } of groupedLoaderInfo) {
108
- action(phpFile);
109
- }
110
- (0, shared_1.emitPHPWriterAsAsset)(phpFile, compilation, "unified-loader.php");
111
- });
112
- }
113
- });
114
- }
115
- withDistDevLoader() {
116
- if (this.config.omitDistDev) {
117
- return new php_writer_1.PHPFile();
118
- }
119
- const devLoaderPath = expressions_1.Op.concat(expressions_1.Constants.__DIR__, '-dev/unified-loader.php');
120
- const res = new php_writer_1.PHPFile();
121
- res.getWriter("")
122
- .if(expressions_1.Op.binary(expressions_1.Op.binary(expressions_1.Expr.call('wp_get_environment_type', []), ' === ', 'development'), ' && ', expressions_1.Expr.call('file_exists', [devLoaderPath])))
123
- .require(devLoaderPath, { once: true })
124
- .append("return;")
125
- .endIf();
126
- return res;
127
- }
128
- async ensureDistExists(outputPath) {
129
- if (outputPath.endsWith("-dev")) {
130
- outputPath = outputPath.substring(0, outputPath.length - 4);
131
- }
132
- try {
133
- const contents = await (0, promises_1.readFile)((0, node_path_1.join)(outputPath, "unified-loader.php"), 'utf-8');
134
- if (!contents.includes("-dev/unified-loader.php")) {
135
- await (0, promises_1.writeFile)((0, node_path_1.join)(outputPath, "unified-loader.php"), this.withDistDevLoader().toString() + contents.substring(5), 'utf-8');
136
- }
137
- }
138
- catch {
139
- await (0, promises_1.mkdir)(outputPath, { recursive: true });
140
- await (0, promises_1.writeFile)((0, node_path_1.join)(outputPath, "unified-loader.php"), this.withDistDevLoader().toString(), 'utf-8');
141
- }
142
- }
143
- }
144
- exports.UnifiedLoaderGenerator = UnifiedLoaderGenerator;
@@ -1,7 +0,0 @@
1
- import type { VerifiedPlauditWordpressWebpackConfig } from "../shared";
2
- import type { Compiler, WebpackPluginInstance } from "webpack";
3
- export declare class VariablesJSMonitorPlugin implements WebpackPluginInstance {
4
- private readonly config;
5
- constructor(config: VerifiedPlauditWordpressWebpackConfig);
6
- apply(compiler: Compiler): void;
7
- }
@@ -1,20 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.VariablesJSMonitorPlugin = void 0;
4
- class VariablesJSMonitorPlugin {
5
- config;
6
- constructor(config) {
7
- this.config = config;
8
- }
9
- apply(compiler) {
10
- const variablesFilePath = this.config.variablesFilePath;
11
- if (variablesFilePath) {
12
- compiler.hooks.make.tap(this.constructor.name, compilation => {
13
- if (!compilation.fileDependencies.has(variablesFilePath)) {
14
- compilation.fileDependencies.add(variablesFilePath);
15
- }
16
- });
17
- }
18
- }
19
- }
20
- exports.VariablesJSMonitorPlugin = VariablesJSMonitorPlugin;
@@ -1,17 +0,0 @@
1
- import { AbstractBiPhasicGroupAndEntryPlugin } from "./AbstractBiPhasicGroupAndEntryPlugin";
2
- import { type Compiler, type WebpackPluginInstance } from "webpack";
3
- export declare class WPMLConfigBuilderPlugin implements WebpackPluginInstance {
4
- private readonly destDir;
5
- private readonly referencePlugin;
6
- private static jsdomInstance?;
7
- private static domParser?;
8
- private static xmlSerializer?;
9
- private readonly parsedDocumentsCache;
10
- constructor(destDir: string, referencePlugin: AbstractBiPhasicGroupAndEntryPlugin<any>);
11
- apply(compiler: Compiler): void;
12
- private static getJSDOMInstance;
13
- private static getDOMParser;
14
- private static getXMLSerializer;
15
- private static prettyPrintXML;
16
- private loadWPMLConfigXML;
17
- }
@@ -1,472 +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.WPMLConfigBuilderPlugin = void 0;
7
- const promises_1 = __importDefault(require("node:fs/promises"));
8
- const node_path_1 = __importDefault(require("node:path"));
9
- const shared_1 = require("../shared");
10
- const jsdom_1 = require("jsdom");
11
- const webpack_1 = require("webpack");
12
- const xml_formatter_1 = __importDefault(require("xml-formatter"));
13
- class WPMLConfigBuilderPlugin {
14
- destDir;
15
- referencePlugin;
16
- static jsdomInstance;
17
- static domParser;
18
- static xmlSerializer;
19
- parsedDocumentsCache = new Map();
20
- constructor(destDir, referencePlugin) {
21
- this.destDir = destDir;
22
- this.referencePlugin = referencePlugin;
23
- }
24
- apply(compiler) {
25
- compiler.hooks.compilation.tap(this.constructor.name, compilation => {
26
- compilation.hooks.processAssets.tapPromise({ name: `${this.constructor.name}__processXML`, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL }, async (assets) => {
27
- const entrypoint = compilation.entrypoints.get("wpml-config.xml");
28
- if (!entrypoint) {
29
- return;
30
- }
31
- const blockJsonFiles = this.referencePlugin.getRelevantEntrypoints(compilation)
32
- .map(ep => ep.srcPath)
33
- .filter(srcPath => srcPath.endsWith("block.json"));
34
- const files = Promise.all([
35
- Promise.all(entrypoint.origins.map(origin => origin.request).filter(request => request.endsWith("wpml-config.xml"))
36
- .map(async (request) => this.loadWPMLConfigXML(request, compilation))),
37
- Promise.all(blockJsonFiles.map(async (request) => JSON.parse(await promises_1.default.readFile(request, 'utf8'))))
38
- ]);
39
- const wpmlEmitPath = node_path_1.default.join(this.destDir, "wpml-config.xml");
40
- for (const name of Object.keys(assets)) {
41
- if (name.startsWith("wpml-config.xml") || name.startsWith(wpmlEmitPath)) {
42
- compilation.deleteAsset(name);
43
- }
44
- }
45
- const [wpmlConfigs, blockJsons] = await files;
46
- if (!wpmlConfigs.length && !blockJsons.length) {
47
- return;
48
- }
49
- const mergedConfig = {
50
- customFields: {}, customTermFields: {}, customTypes: {}, gutenbergBlocks: {}, shortcodeList: new Set(), shortcodes: {}, taxonomies: {}
51
- };
52
- const nonMergeableCategories = ['customFields', 'customTermFields', 'customTypes', 'shortcodes', 'taxonomies'];
53
- for (const [wpmlConfig, file] of wpmlConfigs) {
54
- for (const category of nonMergeableCategories) {
55
- for (const [key, value] of Object.entries(wpmlConfig[category])) {
56
- if (key in mergedConfig[category]) {
57
- compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`Already encountered a definition for the ${category} entry named, "${key}"`, file));
58
- }
59
- else {
60
- mergedConfig[category][key] = value;
61
- }
62
- }
63
- }
64
- for (const shortcode of wpmlConfig.shortcodeList) {
65
- mergedConfig.shortcodeList.add(shortcode);
66
- }
67
- for (const [type, block] of Object.entries(wpmlConfig.gutenbergBlocks)) {
68
- const existing = mergedConfig.gutenbergBlocks[type];
69
- try {
70
- mergedConfig.gutenbergBlocks[type] = existing ? mergeWPMLGutenbergBlocks(existing, block) : block;
71
- }
72
- catch (e) {
73
- if (typeof e === 'string') {
74
- compilation.errors.push((0, shared_1.newWebpackErrorForFile)(e, file));
75
- }
76
- else {
77
- compilation.errors.push(e);
78
- }
79
- }
80
- }
81
- }
82
- for (const blockJson of blockJsons) {
83
- const type = blockJson["name"]?.toString();
84
- if (typeof type !== 'string') {
85
- continue;
86
- }
87
- const blockConfig = { type, translate: blockJson['supports']?.['translation'] ?? true ? '1' : '0', keys: [], xPaths: [] };
88
- if (blockJson['plaudit']?.['properties']) {
89
- const snps = blockJson['plaudit']['properties'];
90
- if (Array.isArray(snps)) {
91
- for (const snp of snps) {
92
- convertSNPToKeys(snp, blockConfig.keys);
93
- }
94
- }
95
- else {
96
- convertSNPToKeys(snps, blockConfig.keys);
97
- }
98
- }
99
- if (typeof blockJson['attributes'] === 'object') {
100
- for (const [name, { translatable }] of Object.entries(blockJson['attributes'])) {
101
- if (translatable) {
102
- blockConfig.keys.push({ name, keys: [] });
103
- }
104
- }
105
- }
106
- const existing = mergedConfig.gutenbergBlocks[blockConfig.type];
107
- if (blockConfig.keys.length || blockConfig.xPaths.length) {
108
- mergedConfig.gutenbergBlocks[blockConfig.type] = existing ? mergeWPMLGutenbergBlocks(existing, blockConfig) : blockConfig;
109
- }
110
- else if (!existing) {
111
- mergedConfig.gutenbergBlocks[blockConfig.type] = blockConfig;
112
- }
113
- }
114
- const config = WPMLConfigBuilderPlugin.getDOMParser().parseFromString("<wpml-config></wpml-config>", "application/xml");
115
- appendNamedElementsListToConfig("custom-fields", mergedConfig.customFields, config);
116
- appendNamedElementsListToConfig("custom-term-fields", mergedConfig.customTermFields, config);
117
- appendNamedElementsListToConfig("custom-types", mergedConfig.customTypes, config);
118
- const gutenbergBlocks = Object.values(mergedConfig.gutenbergBlocks);
119
- if (gutenbergBlocks.length) {
120
- const gutenbergBlocksElement = config.createElement("gutenberg-blocks");
121
- gutenbergBlocksElement.append(...gutenbergBlocks
122
- .sort((a, b) => a.type.localeCompare(b.type))
123
- .map(gutenbergBlock => {
124
- const gutenbergBlockElement = config.createElement("gutenberg-block");
125
- gutenbergBlockElement.setAttribute("type", gutenbergBlock.type);
126
- if (gutenbergBlock.label) {
127
- gutenbergBlockElement.setAttribute("label", gutenbergBlock.label);
128
- }
129
- gutenbergBlockElement.setAttribute("translate", gutenbergBlock.translate);
130
- writeGenericSettingsKeys(gutenbergBlock.keys, gutenbergBlockElement, config);
131
- gutenbergBlockElement.append(...gutenbergBlock.xPaths
132
- .sort((a, b) => a.path.localeCompare(b.path))
133
- .map(xPath => {
134
- const xPathElement = config.createElement("xpath");
135
- writeCommonGenericSettingsItemProps(xPathElement, xPath);
136
- xPathElement.append(xPath.path);
137
- return xPathElement;
138
- }));
139
- return gutenbergBlockElement;
140
- }));
141
- config.documentElement.append(gutenbergBlocksElement);
142
- }
143
- if (mergedConfig.shortcodeList.size) {
144
- const node = config.createElement("shortcode-list");
145
- node.append([...mergedConfig.shortcodeList].sort().join(","));
146
- config.documentElement.appendChild(node);
147
- }
148
- appendNamedElementsListToConfig("shortcodes", mergedConfig.shortcodes, config);
149
- appendNamedElementsListToConfig("taxonomies", mergedConfig.taxonomies, config);
150
- compilation[wpmlEmitPath in compilation.assets ? 'updateAsset' : 'emitAsset'](wpmlEmitPath, new webpack_1.sources.RawSource(WPMLConfigBuilderPlugin.prettyPrintXML(config)));
151
- });
152
- });
153
- }
154
- static getJSDOMInstance() {
155
- return WPMLConfigBuilderPlugin.jsdomInstance ?? (WPMLConfigBuilderPlugin.jsdomInstance = new jsdom_1.JSDOM("", { contentType: "text/html" }));
156
- }
157
- static getDOMParser() {
158
- return WPMLConfigBuilderPlugin.domParser ?? (WPMLConfigBuilderPlugin.domParser = new (WPMLConfigBuilderPlugin.getJSDOMInstance().window.DOMParser)());
159
- }
160
- static getXMLSerializer() {
161
- return WPMLConfigBuilderPlugin.xmlSerializer ?? (WPMLConfigBuilderPlugin.xmlSerializer = new (WPMLConfigBuilderPlugin.getJSDOMInstance().window.XMLSerializer)());
162
- }
163
- static prettyPrintXML(document) {
164
- return (0, xml_formatter_1.default)(WPMLConfigBuilderPlugin.getXMLSerializer().serializeToString(document), {
165
- indentation: '\t',
166
- collapseContent: true,
167
- lineSeparator: '\n',
168
- whiteSpaceAtEndOfSelfclosingTag: true,
169
- forceSelfClosingEmptyTag: true,
170
- strictMode: true,
171
- filter(node) {
172
- return node.type === 'Element' || node.type === 'Text';
173
- }
174
- });
175
- }
176
- async loadWPMLConfigXML(file, compilation) {
177
- const contents = await promises_1.default.readFile(file, 'utf8');
178
- const existing = this.parsedDocumentsCache.get(file);
179
- if (existing?.raw === contents) {
180
- return [existing, file];
181
- }
182
- const wpmlConfig = WPMLConfigBuilderPlugin.getDOMParser().parseFromString(contents.replaceAll(/\s+xmlns=['"][^'"]+['"]/sig, ""), "application/xml");
183
- const res = { raw: contents, customFields: {}, customTermFields: {}, customTypes: {}, gutenbergBlocks: {}, shortcodeList: new Set(), shortcodes: {}, taxonomies: {} };
184
- for (const element of wpmlConfig.documentElement.children) {
185
- switch (element.nodeName) {
186
- case "custom-fields":
187
- importStandardTranslateActionMap(element, file, "custom-field", res.customFields, compilation);
188
- break;
189
- case "custom-term-fields":
190
- importStandardTranslateActionMap(element, file, "custom-term-field", res.customTermFields, compilation);
191
- break;
192
- case "custom-types":
193
- importStandardTranslateOptionMap(element, file, "custom-type", res.customTypes, compilation);
194
- break;
195
- case "gutenberg-blocks":
196
- for (const child of element.children) {
197
- try {
198
- const block = convertGutenbergBlockToJSRepresentation(child);
199
- const existing = res.gutenbergBlocks[block.type];
200
- if (existing) {
201
- res.gutenbergBlocks[block.type] = mergeWPMLGutenbergBlocks(existing, block);
202
- }
203
- else {
204
- res.gutenbergBlocks[block.type] = block;
205
- }
206
- }
207
- catch (e) {
208
- if (typeof e === 'string') {
209
- compilation.errors.push((0, shared_1.newWebpackErrorForFile)(e, file));
210
- }
211
- else {
212
- compilation.errors.push(e);
213
- }
214
- }
215
- }
216
- break;
217
- case "shortcode-list":
218
- if (element.textContent) {
219
- for (const shortcode of element.textContent.split(",")) {
220
- res.shortcodeList.add(shortcode.trim());
221
- }
222
- }
223
- break;
224
- case "shortcodes":
225
- for (const child of element.children) {
226
- const tag = child.getElementsByTagName("tag")[0];
227
- const shortcodeName = tag?.textContent?.trim();
228
- if (!shortcodeName) {
229
- compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`A shortcode entry in a wpml-config.xml file is missing its tag name.`, file));
230
- continue;
231
- }
232
- const existing = res.shortcodes[shortcodeName];
233
- if (existing) {
234
- compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`Already encountered a definition for the shortcode entry named, "${shortcodeName}"`, file));
235
- }
236
- else {
237
- res.shortcodes[shortcodeName] = child;
238
- }
239
- }
240
- break;
241
- case "taxonomies":
242
- importStandardTranslateOptionMap(element, file, "taxonomy", res.taxonomies, compilation);
243
- break;
244
- default:
245
- compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`Unsupported element type in a wpml-config.xml file: ${element.nodeName}`, file));
246
- break;
247
- }
248
- }
249
- this.parsedDocumentsCache.set(file, res);
250
- return [res, file];
251
- }
252
- }
253
- exports.WPMLConfigBuilderPlugin = WPMLConfigBuilderPlugin;
254
- function importStandardTranslateOptionMap(element, file, type, actionMap, compilation) {
255
- for (const child of element.children) {
256
- const field = child.textContent;
257
- if (!field) {
258
- compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`Encountered an empty ${type} entry in a wpml-config.xml file.`, file));
259
- continue;
260
- }
261
- const translate = child.getAttribute("translate");
262
- if (!translate) {
263
- compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`The ${type} entry for ${field} is missing the translate attribute.`, file));
264
- continue;
265
- }
266
- const existing = actionMap[field];
267
- if (existing) {
268
- compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`Already encountered a definition for the ${type} entry named, "${field}"`, file));
269
- }
270
- else {
271
- actionMap[field] = child;
272
- }
273
- }
274
- }
275
- function importStandardTranslateActionMap(element, file, type, actionMap, compilation) {
276
- for (const child of element.children) {
277
- const field = child.textContent?.trim();
278
- if (!field) {
279
- compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`Encountered a empty ${type} entry without a name in a wpml-config.xml file.`, file));
280
- continue;
281
- }
282
- const action = child.getAttribute("action");
283
- if (!action) {
284
- compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`The ${type} entry for ${field} is missing an action.`, file));
285
- continue;
286
- }
287
- const existing = actionMap[field];
288
- if (existing) {
289
- compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`Already encountered a definition for the ${type} entry named, "${field}"`, file));
290
- }
291
- else {
292
- actionMap[field] = child;
293
- }
294
- }
295
- }
296
- function convertSNPToKeys(prop, keys) {
297
- if (Array.isArray(prop)) {
298
- for (const p of prop) {
299
- convertSNPToKeys(p, keys);
300
- }
301
- }
302
- else if ('properties' in prop) {
303
- for (const item of prop.properties) {
304
- convertSNPToKeys(item, keys);
305
- }
306
- }
307
- else if ('items' in prop) {
308
- for (const item of prop.items) {
309
- convertSNPToKeys(item, keys);
310
- }
311
- }
312
- else {
313
- if (prop.translatable) {
314
- keys.push({ name: prop.name, keys: [] });
315
- }
316
- else if ('fields' in prop) {
317
- if (prop.fields) {
318
- const nestedKeys = [];
319
- convertSNPToKeys(prop.fields, nestedKeys);
320
- if (nestedKeys.length) {
321
- keys.push({ name: prop.name, keys: nestedKeys });
322
- }
323
- }
324
- }
325
- else if ('itemType' in prop && Array.isArray(prop.itemType)) {
326
- const nestedKeys = [];
327
- convertSNPToKeys(prop.itemType, nestedKeys);
328
- if (nestedKeys.length) {
329
- keys.push({ name: prop.name, keys: nestedKeys });
330
- }
331
- }
332
- }
333
- }
334
- function convertGutenbergBlockToJSRepresentation(element) {
335
- const type = element.getAttribute("type");
336
- if (!type) {
337
- throw `A gutenberg-block entry in a wpml-config.xml file is missing its type attribute.`;
338
- }
339
- const translate = element.getAttribute("translate");
340
- if (!translate) {
341
- throw `The gutenberg-block entry for ${type} is missing its translate attribute.`;
342
- }
343
- if (translate !== '0' && translate !== '1') {
344
- throw `The gutenberg-block entry for ${type} has an invalid translate attribute. Expected 0 or 1, but got, "${translate}"`;
345
- }
346
- const keys = [];
347
- const xPaths = [];
348
- for (const child of element.children) {
349
- if (child.nodeName === 'key') {
350
- keys.push(convertGenericSettingsKeyToJSRepresentation(child, `a gutenberg-block entry for ${type}`));
351
- }
352
- else if (child.nodeName === 'xpath') {
353
- xPaths.push(convertGenericSettingsXPathToJSRepresentation(child, `a gutenberg-block entry for ${type}`));
354
- }
355
- else {
356
- throw `The gutenberg-block entry for ${type} has an unsupported child node ("${child.nodeName}")`;
357
- }
358
- }
359
- return { type, label: element.getAttribute("label"), translate, keys, xPaths };
360
- }
361
- function convertGenericSettingsKeyToJSRepresentation(element, containerName) {
362
- const name = element.getAttribute("name");
363
- if (!name) {
364
- throw `Encountered a key without a name in ${containerName}.`;
365
- }
366
- let encoding = element.getAttribute("encoding");
367
- if (encoding && encoding !== 'json') {
368
- throw `Encountered an invalid encoding on a key named, "${name}" in ${containerName}. It must be either blank or JSON`;
369
- }
370
- else {
371
- encoding = null;
372
- }
373
- let searchMethod = element.getAttribute("searchMethod");
374
- if (searchMethod && searchMethod !== 'wildcards' && searchMethod !== 'regex') {
375
- throw `Encountered an invalid search-method on a key named, "${name}" in ${containerName}. It must be either blank or JSON`;
376
- }
377
- else {
378
- searchMethod = null;
379
- }
380
- return {
381
- name,
382
- label: element.getAttribute("label"),
383
- type: element.getAttribute("type"),
384
- subType: element.getAttribute("sub-type"),
385
- encoding,
386
- searchMethod,
387
- keys: [...element.children].map(child => convertGenericSettingsKeyToJSRepresentation(child, containerName))
388
- };
389
- }
390
- function convertGenericSettingsXPathToJSRepresentation(element, containerName) {
391
- if (!element.textContent) {
392
- throw `Encountered an empty XPath in ${containerName}.`;
393
- }
394
- return {
395
- path: element.textContent,
396
- label: element.getAttribute("label"),
397
- type: element.getAttribute("type"),
398
- subType: element.getAttribute("sub-type")
399
- };
400
- }
401
- function mergeWPMLGutenbergBlocks(existing, novel) {
402
- if (novel.type && existing.type !== novel.type) {
403
- throw `Cannot merge WPML Gutenberg Blocks of differing types`;
404
- }
405
- if (novel.translate && existing.translate !== novel.translate) {
406
- throw `Cannot merge WPML Gutenberg Blocks (${existing.type} and ${novel.type ?? existing.type}) with differing translate values`;
407
- }
408
- return {
409
- type: existing.type,
410
- translate: existing.translate,
411
- label: novel.label ?? existing.label,
412
- keys: novel.keys?.length ? (existing.keys.length ? mergeGenericSettingsKeyLists(existing.keys, novel.keys) : novel.keys) : existing.keys,
413
- xPaths: novel.xPaths?.length ? (existing.xPaths.length ? [...existing.xPaths, ...novel.xPaths] : novel.xPaths) : existing.xPaths
414
- };
415
- }
416
- function mergeGenericSettingsKeyLists(existingKeys, novelKeys) {
417
- const keys = {};
418
- for (const key of existingKeys) {
419
- const existing = keys[key.name];
420
- keys[key.name] = existing ? mergeGenericSettingsKeys(existing, key) : key;
421
- }
422
- for (const key of novelKeys) {
423
- const existing = keys[key.name];
424
- keys[key.name] = existing ? mergeGenericSettingsKeys(existing, key) : key;
425
- }
426
- return Object.values(keys);
427
- }
428
- function mergeGenericSettingsKeys(existing, novel) {
429
- if (existing.encoding && novel.encoding && existing.encoding !== novel.encoding) {
430
- throw `Cannot merge WPMLGenericSettingsKeys with differing encoding values (${existing.encoding} and ${novel.encoding}) on ${novel.name}.`;
431
- }
432
- if (existing.searchMethod && novel.searchMethod && existing.searchMethod !== novel.searchMethod) {
433
- throw `Cannot merge WPMLGenericSettingsKeys with differing search-method values (${existing.searchMethod} and ${novel.searchMethod}) on ${novel.name}.`;
434
- }
435
- return { ...existing, ...novel, keys: mergeGenericSettingsKeyLists(existing.keys, novel.keys) };
436
- }
437
- function writeGenericSettingsKeys(keys, parent, document) {
438
- parent.append(...keys.sort((a, b) => a.name.localeCompare(b.name)).map(key => {
439
- const element = document.createElement("key");
440
- element.setAttribute("name", key.name);
441
- writeCommonGenericSettingsItemProps(element, key);
442
- if (key.encoding) {
443
- element.setAttribute("encoding", key.encoding);
444
- }
445
- if (key.searchMethod) {
446
- element.setAttribute("search-method", key.searchMethod);
447
- }
448
- writeGenericSettingsKeys(key.keys, element, document);
449
- return element;
450
- }));
451
- }
452
- function appendNamedElementsListToConfig(containerName, elements, config) {
453
- const allElements = Object.entries(elements);
454
- if (allElements.length) {
455
- const containerElement = config.createElement(containerName);
456
- config.documentElement.append(containerElement);
457
- containerElement.append(...allElements
458
- .sort(([fieldNameA], [fieldNameB]) => fieldNameA.localeCompare(fieldNameB))
459
- .map(([_, element]) => element));
460
- }
461
- }
462
- function writeCommonGenericSettingsItemProps(element, item) {
463
- if (item.label) {
464
- element.setAttribute("label", item.label);
465
- }
466
- if (item.type) {
467
- element.setAttribute("type", item.type);
468
- }
469
- if (item.subType) {
470
- element.setAttribute("sub-type", item.subType);
471
- }
472
- }
@@ -1,4 +0,0 @@
1
- import type { Externals } from "../shared";
2
- import { EnhancedDependencyExtractionWebpackPlugin } from "../wordpress-ports/dependency-extraction-webpack-plugin";
3
- import type { Configuration } from "webpack";
4
- export declare function makeDependencyExtractionPlugin(externals: Externals | undefined, assumeGlobalizedPlauditLibraries: boolean, externalizing: Required<Configuration>['output']['library']): EnhancedDependencyExtractionWebpackPlugin;