@plaudit/webpack-extensions 0.0.22 → 1.0.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,6 +1,4 @@
1
1
  import { type Compiler, type WebpackPluginInstance } from "webpack";
2
2
  export default class AdditionalDependencyInjectorPlugin implements WebpackPluginInstance {
3
- private readonly filesWithAdditionalDependencies;
4
- constructor(filesWithAdditionalDependencies?: Map<string, string[]>);
5
3
  apply(compiler: Compiler): void;
6
4
  }
@@ -8,43 +8,35 @@ const node_path_1 = __importDefault(require("node:path"));
8
8
  const webpack_1 = require("webpack");
9
9
  const webpack_sources_1 = require("webpack-sources");
10
10
  class AdditionalDependencyInjectorPlugin {
11
- filesWithAdditionalDependencies;
12
- constructor(filesWithAdditionalDependencies = new Map()) {
13
- this.filesWithAdditionalDependencies = filesWithAdditionalDependencies;
14
- }
15
11
  apply(compiler) {
16
12
  compiler.hooks.thisCompilation.tap("AdditionalDependencyInjectorPlugin", compilation => {
17
13
  compilation.hooks.processAssets.tap({
18
14
  name: "AdditionalDependencyInjectorPlugin_ProcessAssets",
19
15
  stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_ANALYSE
20
16
  }, compilationAssets => {
21
- const srcDir = process.env['WP_SRC_DIRECTORY'] || 'src';
22
- const srcRoot = node_path_1.default.join(process.cwd(), srcDir);
23
- Object.entries(compilationAssets).map(([name, asset]) => {
17
+ for (const [name, asset] of Object.entries(compilationAssets)) {
24
18
  if (name.endsWith(".asset.php") && asset instanceof webpack_sources_1.RawSource) {
25
19
  const extensionlessName = name.substring(0, name.length - 10);
26
20
  const additionalDependencies = [];
27
- const possibleExtensions = ['ts', 'tsx', 'js', 'jsx'];
28
- for (const possibleExtension of possibleExtensions) {
29
- const possibleFile = node_path_1.default.join(srcRoot, `${extensionlessName}.${possibleExtension}`);
30
- if (node_fs_1.default.existsSync(possibleFile)) {
31
- const firstLine = node_fs_1.default.readFileSync(possibleFile, 'utf8').trim().split(/\r?\n/)[0];
32
- if (firstLine.startsWith("//ADDITIONAL_DEPENDENCIES:")) {
33
- additionalDependencies.push(...firstLine.substring(26).trim().split(','));
21
+ dependencyFinder: for (const srcRoot of compilation.contextDependencies) {
22
+ for (const possibleExtension of ['ts', 'tsx', 'js', 'jsx']) {
23
+ const possibleFile = node_path_1.default.join(srcRoot, `${extensionlessName}.${possibleExtension}`);
24
+ if (node_fs_1.default.existsSync(possibleFile)) {
25
+ const firstLine = node_fs_1.default.readFileSync(possibleFile, 'utf8').trim().split(/\r?\n/)[0];
26
+ if (firstLine.startsWith("//ADDITIONAL_DEPENDENCIES:")) {
27
+ additionalDependencies.push(...firstLine.substring(26).trim().split(','));
28
+ }
29
+ break dependencyFinder;
34
30
  }
35
- break;
36
31
  }
37
32
  }
38
- if (this.filesWithAdditionalDependencies.has(extensionlessName)) {
39
- additionalDependencies.push(...this.filesWithAdditionalDependencies.get(extensionlessName));
40
- }
41
33
  const seen = new Set();
42
34
  const additionalDeps = additionalDependencies.filter(dep => !seen.has(dep) && seen.add(dep)).sort().map(v => `'${v}'`).join(', ');
43
35
  if (additionalDeps) {
44
36
  compilation.updateAsset(name, new webpack_sources_1.RawSource(asset.source().replace(/('dependencies'\s+=>\s+(?:array\(|\[))(.*)([)\]], 'version')/g, (match, g1, g2, g3) => `${g1}${g2.length > 0 ? `${g2}, ${additionalDeps}` : additionalDeps}${g3}`)));
45
37
  }
46
38
  }
47
- });
39
+ }
48
40
  });
49
41
  });
50
42
  }
@@ -31,22 +31,31 @@ class BlockJSONStyleRemappingPlugin {
31
31
  }
32
32
  return undefined;
33
33
  }).filter((v) => v !== undefined) ?? []);
34
- const styleKeys = ["editorStyle", "style", "viewStyle"];
34
+ const remapValue = (value, name, dirname) => {
35
+ if (value.startsWith("file:")) {
36
+ const styleInputPath = node_path_1.default.normalize(node_path_1.default.join(compiler.context, dirname, value.substring(5)));
37
+ const styleOutputPath = singleFileInputToOutputName.get(styleInputPath);
38
+ if (styleOutputPath !== undefined) {
39
+ const prefix = value.startsWith("./", 5) ? "./" : "";
40
+ const relativePath = node_path_1.default.relative(node_path_1.default.dirname(name), styleOutputPath);
41
+ return `file:${prefix}${relativePath}`;
42
+ }
43
+ }
44
+ return value;
45
+ };
46
+ const mappableKeys = ["editorStyle", "style", "viewStyle", "viewScript", "script", "editorScript"];
35
47
  Object.entries(compilationAssets).map(([name, asset]) => {
36
48
  if (name.endsWith("block.json") && asset instanceof webpack_sources_1.RawSource) {
37
49
  const dirname = node_path_1.default.dirname(assetSourceFiles.get(name) ?? name);
38
50
  const json = JSON.parse(asset.source());
39
- for (const styleKey of styleKeys) {
40
- if (styleKey in json) {
41
- const style = json[styleKey];
42
- if (typeof style === 'string' && style.startsWith('file:')) {
43
- const styleInputPath = node_path_1.default.normalize(node_path_1.default.join(compiler.context, dirname, style.substring(5)));
44
- const styleOutputPath = singleFileInputToOutputName.get(styleInputPath);
45
- if (styleOutputPath !== undefined) {
46
- const prefix = style.startsWith("./", 5) ? "./" : "";
47
- const relativePath = node_path_1.default.relative(node_path_1.default.dirname(name), styleOutputPath);
48
- json[styleKey] = `file:${prefix}${relativePath}`;
49
- }
51
+ for (const mappableKey of mappableKeys) {
52
+ if (mappableKey in json) {
53
+ const unmappedValue = json[mappableKey];
54
+ if (Array.isArray(unmappedValue)) {
55
+ json[mappableKey] = unmappedValue.map(value => remapValue(value, name, dirname));
56
+ }
57
+ else if (typeof unmappedValue === 'string') {
58
+ json[mappableKey] = remapValue(unmappedValue, name, dirname);
50
59
  }
51
60
  }
52
61
  }
@@ -1,7 +1,7 @@
1
1
  import type { Configuration } from "webpack";
2
2
  export interface PlauditWordpressWebpackConfig {
3
- legacyPostcssPlugins: boolean;
4
- variables: Record<string, any>;
5
- src: string;
3
+ legacyPostcssPlugins?: boolean;
4
+ variables?: Record<string, any>;
5
+ src: Record<string, string>;
6
6
  }
7
- export default function (config?: Partial<PlauditWordpressWebpackConfig>, webpackConfig?: Configuration): Configuration;
7
+ export default function (config: PlauditWordpressWebpackConfig, webpackConfig?: Configuration): Configuration[];
@@ -10,25 +10,18 @@ const BlockJSONStyleRemappingPlugin_1 = __importDefault(require("./BlockJSONStyl
10
10
  const copy_webpack_plugin_1 = __importDefault(require("copy-webpack-plugin"));
11
11
  const fork_ts_checker_webpack_plugin_1 = __importDefault(require("fork-ts-checker-webpack-plugin"));
12
12
  const webpack_remove_empty_scripts_1 = __importDefault(require("webpack-remove-empty-scripts"));
13
- function addEntryPointWithFilter(entrypoints, entrypoint, mapper = (entrypoint) => entrypoint) {
14
- if (Array.isArray(entrypoint)) {
15
- entrypoints.push(...entrypoint.map(mapper));
16
- }
17
- else {
18
- entrypoints.push(mapper(entrypoint));
13
+ function addEntryPointWithMapper(entrypoints, entrypoint, dir, mapper = (entrypoint) => entrypoint) {
14
+ for (const ep of Array.isArray(entrypoint) ? entrypoint : [entrypoint]) {
15
+ const mapped = node_path_1.default.join(dir, mapper(ep));
16
+ if (node_fs_1.default.existsSync(mapped)) {
17
+ const parsedEntrypoint = node_path_1.default.parse(mapped);
18
+ entrypoints[node_path_1.default.join(node_path_1.default.basename(parsedEntrypoint.dir), parsedEntrypoint.name)] = { import: mapped };
19
+ }
19
20
  }
20
21
  }
21
- function default_1(config = {}, webpackConfig = require("@wordpress/scripts/config/webpack.config")) {
22
+ function default_1(config, webpackConfig = require("@wordpress/scripts/config/webpack.config")) {
22
23
  const { legacyPostcssPlugins = false, variables = node_fs_1.default.existsSync("./variables.js") ? require("./variables.js") : {}, // TODO: There must be a better way to handle this...
23
- src = process.env['WP_SRC_DIRECTORY'] || 'src' } = config;
24
- (webpackConfig.plugins ?? (webpackConfig.plugins = [])).push(new fork_ts_checker_webpack_plugin_1.default({
25
- typescript: {
26
- diagnosticOptions: {
27
- semantic: true,
28
- syntactic: true,
29
- },
30
- },
31
- }), new webpack_remove_empty_scripts_1.default({ stage: webpack_remove_empty_scripts_1.default.STAGE_AFTER_PROCESS_PLUGINS }), new BlockJSONStyleRemappingPlugin_1.default(), new AdditionalDependencyInjectorPlugin_1.default(), new copy_webpack_plugin_1.default({ patterns: [{ from: '**/*.(twig|svg)', context: src, noErrorOnMissing: true }] }));
24
+ } = config;
32
25
  // Nano Config
33
26
  // http://cssnano.co/guides/optimisations/ For the value to use click on one and then
34
27
  const nanoConfig = {
@@ -123,46 +116,77 @@ function default_1(config = {}, webpackConfig = require("@wordpress/scripts/conf
123
116
  }
124
117
  }
125
118
  }
126
- const baseEntry = webpackConfig.entry;
127
- webpackConfig.entry = () => {
128
- const srcDir = process.env['WP_SRC_DIRECTORY'] || 'src';
119
+ (webpackConfig.plugins ?? (webpackConfig.plugins = [])).push(new fork_ts_checker_webpack_plugin_1.default({
120
+ typescript: {
121
+ diagnosticOptions: {
122
+ semantic: true,
123
+ syntactic: true,
124
+ },
125
+ },
126
+ }), new webpack_remove_empty_scripts_1.default({ stage: webpack_remove_empty_scripts_1.default.STAGE_AFTER_PROCESS_PLUGINS }), new BlockJSONStyleRemappingPlugin_1.default(), new AdditionalDependencyInjectorPlugin_1.default());
127
+ return Object.entries(config.src).map(([srcDir, dest]) => {
129
128
  const srcRoot = node_path_1.default.join(process.cwd(), srcDir);
130
- const entrypoints = node_fs_1.default.readdirSync(srcRoot, 'utf8')
131
- .map(dir => node_path_1.default.join(srcRoot, dir))
132
- .filter(dir => node_fs_1.default.statSync(dir).isDirectory())
133
- .flatMap(dir => {
134
- const entrypoints = [];
135
- try {
136
- const blockJSON = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(dir, 'block.json'), 'utf8'));
137
- for (const key of ["editorStyle", "style", "editorScript", "viewScript", "script"]) {
138
- if (key in blockJSON) {
139
- addEntryPointWithFilter(entrypoints, blockJSON[key], ep => ep.startsWith("file:") ? ep.substring(5) : ep);
140
- }
141
- }
142
- }
143
- catch (e) {
129
+ return {
130
+ ...webpackConfig,
131
+ output: {
132
+ ...webpackConfig.output,
133
+ path: node_path_1.default.join(process.cwd(), dest)
134
+ },
135
+ plugins: webpackConfig.plugins.map(plugin => plugin.constructor.name === 'CopyPlugin'
136
+ ? new copy_webpack_plugin_1.default({ patterns: [{ from: '**/(block.json|*.(php|twig|svg))', context: srcRoot, noErrorOnMissing: true }] })
137
+ : plugin),
138
+ entry: node_fs_1.default.readdirSync(srcRoot, 'utf8')
139
+ .map(dir => node_path_1.default.join(srcRoot, dir))
140
+ .filter(dir => node_fs_1.default.statSync(dir).isDirectory())
141
+ .reduce((entrypoints, dir) => {
144
142
  try {
145
- const packageJSON = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(dir, 'package.json'), 'utf8'));
146
- addEntryPointWithFilter(entrypoints, packageJSON['main']);
147
- addEntryPointWithFilter(entrypoints, packageJSON['style']);
143
+ const blockJSON = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(dir, 'block.json'), 'utf8'));
144
+ for (const key of ["editorStyle", "style", "editorScript", "viewScript", "script"]) {
145
+ if (key in blockJSON) {
146
+ addEntryPointWithMapper(entrypoints, blockJSON[key], dir, ep => ep.startsWith("file:") ? ep.substring(5) : ep);
147
+ }
148
+ }
148
149
  }
149
150
  catch (e) {
150
- // This just means that the directory doesn't contain any declared entrypoints.
151
+ try {
152
+ const packageJSON = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(dir, 'package.json'), 'utf8'));
153
+ addEntryPointWithMapper(entrypoints, packageJSON['main'], dir);
154
+ addEntryPointWithMapper(entrypoints, packageJSON['style'], dir);
155
+ }
156
+ catch (e) {
157
+ try {
158
+ const entrypointsJSON = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(dir, 'entrypoints.json'), 'utf8'));
159
+ if (Array.isArray(entrypointsJSON)) {
160
+ addEntryPointWithMapper(entrypoints, entrypointsJSON, dir);
161
+ }
162
+ else {
163
+ for (const [name, config] of Object.entries(entrypointsJSON)) {
164
+ if (typeof config === 'string') {
165
+ entrypoints[name] = node_path_1.default.join(dir, config);
166
+ }
167
+ else if (Array.isArray(config)) {
168
+ entrypoints[name] = config.map(c => node_path_1.default.join(dir, c));
169
+ }
170
+ else {
171
+ if (typeof config.import === 'string') {
172
+ config.import = node_path_1.default.join(dir, config.import);
173
+ }
174
+ else {
175
+ config.import = config.import.map(c => node_path_1.default.join(dir, c));
176
+ }
177
+ entrypoints[name] = config;
178
+ }
179
+ }
180
+ }
181
+ }
182
+ catch (e) {
183
+ // This just means that the directory doesn't contain any declared entrypoints.
184
+ }
185
+ }
151
186
  }
152
- }
153
- return entrypoints.length === 0 ? undefined : entrypoints.map(entrypoint => node_path_1.default.join(dir, entrypoint));
154
- })
155
- .filter((entrypoint) => typeof entrypoint === 'string' && node_fs_1.default.existsSync(entrypoint));
156
- const convertEntrypointsToObject = () => entrypoints.reduce((entry, entrypoint) => {
157
- const parsedEntrypoint = node_path_1.default.parse(entrypoint);
158
- return {
159
- ...entry,
160
- [node_path_1.default.join(node_path_1.default.basename(parsedEntrypoint.dir), parsedEntrypoint.name)]: { import: entrypoint }
161
- };
162
- }, {});
163
- const firstPassBaseEntries = typeof baseEntry === 'function' ? baseEntry() : baseEntry;
164
- return firstPassBaseEntries instanceof Promise ? firstPassBaseEntries.then(convertEntrypointsToObject) : convertEntrypointsToObject();
165
- };
166
- return webpackConfig;
187
+ return entrypoints;
188
+ }, {})
189
+ };
190
+ });
167
191
  }
168
192
  exports.default = default_1;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plaudit/webpack-extensions",
3
- "version": "0.0.22",
3
+ "version": "1.0.0",
4
4
  "scripts": {
5
5
  "prepublishOnly": "rm -rf build && mkdir build && tsc",
6
6
  "build": "tsc",
@@ -28,8 +28,8 @@
28
28
  "@wordpress/scripts": "^26.2.0",
29
29
  "autoprefixer": "^10.4.14",
30
30
  "clean-webpack-plugin": "^4.0.0",
31
- "copy-webpack-plugin": "^11.0.0",
32
31
  "cssnano": "^6.0.0",
32
+ "eslint": "^8.38.0",
33
33
  "fork-ts-checker-webpack-plugin": "^8.0.0",
34
34
  "postcss": "^8.4.23",
35
35
  "postcss-calc": "^8.2.4",
@@ -54,6 +54,7 @@
54
54
  "webpack-sources": "^3.2.3"
55
55
  },
56
56
  "peerDependencies": {
57
+ "copy-webpack-plugin": "^11.0.0",
57
58
  "postcss-load-config": "^4.0.1",
58
59
  "postcss-loader": "^7.2.4",
59
60
  "webpack": "^5.80.0",