@plaudit/webpack-extensions 2.89.2 → 3.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 (55) hide show
  1. package/CHANGELOG.md +0 -110
  2. package/USER-GUIDE.md +81 -117
  3. package/{dist → build}/plugins/EnhancedBlockJSONPlugin.d.ts +4 -7
  4. package/{dist → build}/plugins/EnhancedBlockJSONPlugin.js +53 -116
  5. package/{dist → build}/plugins/ExtensionsConfigFileGeneratorPlugin.d.ts +3 -7
  6. package/{dist → build}/plugins/ExtensionsConfigFileGeneratorPlugin.js +10 -74
  7. package/{dist → build}/plugins/ExtensionsConfigFileGeneratorPluginV1.d.ts +1 -1
  8. package/{dist → build}/plugins/ExtensionsConfigFileGeneratorPluginV1.js +0 -4
  9. package/{dist → build}/plugins/PlainEntrypointsConfigFileGeneratorPlugin.js +20 -46
  10. package/{dist → build}/plugins/UnifiedLoaderGenerator.d.ts +2 -1
  11. package/build/plugins/static-configs.d.ts +3 -0
  12. package/build/plugins/static-configs.js +33 -0
  13. package/{dist → build}/shared.d.ts +18 -86
  14. package/{dist → build}/shared.js +11 -124
  15. package/{dist → build}/utils/common-config-helpers.d.ts +1 -1
  16. package/{dist → build}/utils/common-config-helpers.js +49 -126
  17. package/{dist → build}/wordpress-scripts-wrapper.js +36 -70
  18. package/package.json +26 -36
  19. package/dist/plugins/static-configs.d.ts +0 -3
  20. package/dist/plugins/static-configs.js +0 -91
  21. package/dist/utils/entrypoint-resolution-logic.d.ts +0 -10
  22. package/dist/utils/entrypoint-resolution-logic.js +0 -82
  23. package/dist/utils/location-encoding-filename-parser.d.ts +0 -26
  24. package/dist/utils/location-encoding-filename-parser.js +0 -118
  25. package/dist/utils/path-query-and-related-helpers.d.ts +0 -58
  26. package/dist/utils/path-query-and-related-helpers.js +0 -263
  27. /package/{dist → build}/plugins/AbstractBiPhasicGroupAndEntryPlugin.d.ts +0 -0
  28. /package/{dist → build}/plugins/AbstractBiPhasicGroupAndEntryPlugin.js +0 -0
  29. /package/{dist → build}/plugins/AbstractBiPhasicGroupPlugin.d.ts +0 -0
  30. /package/{dist → build}/plugins/AbstractBiPhasicGroupPlugin.js +0 -0
  31. /package/{dist → build}/plugins/AdditionalDependencyInjectorPlugin.d.ts +0 -0
  32. /package/{dist → build}/plugins/AdditionalDependencyInjectorPlugin.js +0 -0
  33. /package/{dist → build}/plugins/BrowserSyncPlugin.d.ts +0 -0
  34. /package/{dist → build}/plugins/BrowserSyncPlugin.js +0 -0
  35. /package/{dist → build}/plugins/EnhancedDynamicEntryPlugin.d.ts +0 -0
  36. /package/{dist → build}/plugins/EnhancedDynamicEntryPlugin.js +0 -0
  37. /package/{dist → build}/plugins/MiniCSSExtractPluginErrorCleaner.d.ts +0 -0
  38. /package/{dist → build}/plugins/MiniCSSExtractPluginErrorCleaner.js +0 -0
  39. /package/{dist → build}/plugins/PackageConfigSanityChecker.d.ts +0 -0
  40. /package/{dist → build}/plugins/PackageConfigSanityChecker.js +0 -0
  41. /package/{dist → build}/plugins/PlainEntrypointsConfigFileGeneratorPlugin.d.ts +0 -0
  42. /package/{dist → build}/plugins/SpecialAssetHandlingPlugin.d.ts +0 -0
  43. /package/{dist → build}/plugins/SpecialAssetHandlingPlugin.js +0 -0
  44. /package/{dist → build}/plugins/UnifiedLoaderGenerator.js +0 -0
  45. /package/{dist → build}/plugins/VariablesJSMonitorPlugin.d.ts +0 -0
  46. /package/{dist → build}/plugins/VariablesJSMonitorPlugin.js +0 -0
  47. /package/{dist → build}/plugins/WPMLConfigBuilder.d.ts +0 -0
  48. /package/{dist → build}/plugins/WPMLConfigBuilder.js +0 -0
  49. /package/{dist → build}/plugins/dependency-extraction-webpack-plugin-config-builder.d.ts +0 -0
  50. /package/{dist → build}/plugins/dependency-extraction-webpack-plugin-config-builder.js +0 -0
  51. /package/{dist → build}/utils/css-writer.d.ts +0 -0
  52. /package/{dist → build}/utils/css-writer.js +0 -0
  53. /package/{dist → build}/utils/pseduo-semaphore.d.ts +0 -0
  54. /package/{dist → build}/utils/pseduo-semaphore.js +0 -0
  55. /package/{dist → build}/wordpress-scripts-wrapper.d.ts +0 -0
@@ -1,91 +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.postcssConfigBuilder = postcssConfigBuilder;
7
- const cssnano_1 = __importDefault(require("cssnano"));
8
- // Options: calc
9
- const calcOptions = { precision: 4, mediaQueries: true, selectors: true };
10
- // Options: autoprefixerOptions
11
- const autoprefixerOptions = { grid: "autoplace" };
12
- // Nano Config
13
- // http://cssnano.co/guides/optimisations/ For the value to use click on one and then
14
- const nanoConfig = {
15
- preset: [
16
- 'cssnano-preset-default',
17
- {
18
- safe: true,
19
- autoprefixer: false, // Unsafe
20
- calc: false,
21
- colormin: true,
22
- convertValues: false,
23
- discardComments: {
24
- remove(comment) {
25
- const commentKeepRegexp = /^!|@cms|@preserve|@cc_on|\bMIT\b|\bMPL\b|\bGPL\b|\bBSD\b|\bISCL\b|\(c\)|\bLicense\b|\bCopyright\b/i;
26
- return !commentKeepRegexp.test(comment);
27
- }
28
- },
29
- discardDuplicates: true,
30
- discardEmpty: true,
31
- discardOverridden: true,
32
- discardUnused: false, // Unsafe
33
- mergeIdents: false, // Unsafe
34
- mergeLonghand: true,
35
- mergeRules: false, // Off for speed
36
- minifyFontValues: true,
37
- minifyGradients: true,
38
- minifyParams: true,
39
- minifySelectors: true,
40
- normalizeCharset: true,
41
- normalizeDisplayValues: true,
42
- normalizePositions: true,
43
- normalizeRepeatStyle: true,
44
- normalizeString: true,
45
- normalizeTimingFunctions: true,
46
- normalizeUnicode: true,
47
- normalizeUrl: true,
48
- normalizeWhitespace: true,
49
- orderedValues: true,
50
- reduceIdents: false, // Unsafe
51
- reduceInitial: true,
52
- reduceTransforms: true,
53
- svgo: false, // Off for speed
54
- uniqueSelectors: true,
55
- zindex: false, // Unsafe
56
- filterPlugins: false // I don't know where this one came from. It is not listed in the documentation.
57
- }
58
- ]
59
- };
60
- function makeDefaultPostCSSFunctions(variables) {
61
- const magnitude = new Intl.NumberFormat("en-US", { maximumFractionDigits: 4 });
62
- return {
63
- pxAsRem(value) {
64
- return value ? `${magnitude.format(parseFloat(value.toString()) / (variables("font_size") || 16))}rem` : "1rem";
65
- }
66
- };
67
- }
68
- function postcssConfigBuilder(verbose, variables, postCSSFunctions) {
69
- return {
70
- plugins: [
71
- require("postcss-import")(), // Once
72
- require("@plaudit/postcss-silent-extend")({ warnOfUnused: verbose }), // Once (marks), OnceExit (apply)
73
- require("postcss-mixins")(), // There is a PostCSS 8 version, but we're forced to use the old one because the new one uses AtRule, which is too late in the process
74
- require("@plaudit/postcss-variables")({ variables }), // Once
75
- require("postcss-functions")({ functions: { ...makeDefaultPostCSSFunctions(variables), ...postCSSFunctions(variables) } }),
76
- require("@plaudit/postcss-legacy-shorthand/position")(), // Legacy
77
- require("@plaudit/postcss-legacy-shorthand/size")(), // Legacy
78
- require("@plaudit/postcss-legacy-shorthand/spacing")(), // Legacy
79
- require("postcss-property-lookup")({ logLevel: "warn" }), // Rule
80
- require("@plaudit/postcss-strip-units")(), // AtRule, Declaration
81
- require("postcss-media-minmax")(), // AtRule
82
- require("postcss-nested")(), // Rule
83
- require("postcss-url")(),
84
- require("postcss-calc")(calcOptions), // OnceExit
85
- require("@plaudit/postcss-color-function")(), // OnceExit
86
- require("autoprefixer")(autoprefixerOptions), // OnceExit
87
- require("postcss-reporter")({ clearReportedMessages: true }), // OnceExit
88
- (0, cssnano_1.default)(nanoConfig)
89
- ]
90
- };
91
- }
@@ -1,10 +0,0 @@
1
- import { type AdvancedOutputConfig, type PlauditWordpressWebpackConfig } from "../shared";
2
- export declare const enum SourceType {
3
- blocks = "blocks",
4
- extensions = "extensions",
5
- plain = "plain"
6
- }
7
- export declare function isSourceType(str: string): str is SourceType;
8
- type Entrypoints = [string, AdvancedOutputConfig][];
9
- export declare function resolveAllConfigLevelEntrypoints(config: PlauditWordpressWebpackConfig, projectRoot?: string): Record<'staticEntrypoints' | 'dynamicEntrypoints', Entrypoints>;
10
- export {};
@@ -1,82 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isSourceType = isSourceType;
4
- exports.resolveAllConfigLevelEntrypoints = resolveAllConfigLevelEntrypoints;
5
- const node_path_1 = require("node:path");
6
- const location_encoding_filename_parser_1 = require("./location-encoding-filename-parser");
7
- const path_query_and_related_helpers_1 = require("./path-query-and-related-helpers");
8
- const shared_1 = require("../shared");
9
- function isSourceType(str) {
10
- return str === "blocks" /* SourceType.blocks */ || str === "extensions" /* SourceType.extensions */ || str === "plain" /* SourceType.plain */;
11
- }
12
- function resolveAllConfigLevelEntrypoints(config, projectRoot = process.cwd()) {
13
- const srcDir = config.srcDir ?? "";
14
- const normalizeSrcAndDestination = ([rawSrc, dest]) => {
15
- let [src, pathQueryParameters] = (0, path_query_and_related_helpers_1.unpackPotentiallyPrefixedFilePath)(rawSrc);
16
- if (srcDir) {
17
- src = (0, node_path_1.join)(srcDir, src);
18
- }
19
- src = (0, node_path_1.isAbsolute)(src) ? (0, node_path_1.relative)(projectRoot, src) : src;
20
- let resultObject;
21
- if (dest.destination !== undefined && (0, node_path_1.isAbsolute)(dest.destination)) {
22
- resultObject = { ...dest, destination: (0, node_path_1.relative)(projectRoot, dest.destination) };
23
- }
24
- else {
25
- resultObject = { ...dest };
26
- }
27
- return [src, pathQueryParameters ? { ...resultObject, pathQueryParameters } : resultObject];
28
- };
29
- if (Array.isArray(config.src)) {
30
- return {
31
- staticEntrypoints: config.src.map(s => normalizeSrcAndDestination([s, { destination: s }])),
32
- dynamicEntrypoints: []
33
- };
34
- }
35
- else {
36
- const configSrc = config.src ?? {};
37
- // We check for files with location-encoding filenames and add the pertinent ones to the sources
38
- const dynamicallyIncludedEntrypoints = [];
39
- if (srcDir) { // This will only work if we have a unified src root
40
- const dynamicallyIncludedEntrypointsRoot = (0, node_path_1.isAbsolute)(srcDir) ? srcDir : (0, node_path_1.join)(projectRoot, srcDir);
41
- for (const dirent of (0, shared_1.synchronousDirIterator)(dynamicallyIncludedEntrypointsRoot)) {
42
- if (dirent.name in configSrc || `./${dirent.name}` in configSrc) {
43
- continue;
44
- }
45
- if (dirent.isDirectory()) {
46
- // If it's a directory that does not have an existing config entry, but does correspond to one of the non-plain SourceTypes, assume that it matches that source type
47
- if (isSourceType(dirent.name) && dirent.name !== "plain" /* SourceType.plain */) {
48
- dynamicallyIncludedEntrypoints.push([dirent.name, { directoryLayout: dirent.name }]);
49
- continue;
50
- }
51
- for (const nestedDirent of (0, shared_1.synchronousDirIterator)((0, node_path_1.join)(dynamicallyIncludedEntrypointsRoot, dirent.name))) {
52
- if (!nestedDirent.isFile()) {
53
- continue;
54
- }
55
- const cfgName = (0, node_path_1.join)(dirent.name, nestedDirent.name);
56
- if (cfgName in configSrc || `./${cfgName}` in configSrc) {
57
- continue;
58
- }
59
- const parsedFilename = (0, location_encoding_filename_parser_1.parseLocationEncodingFilename)(cfgName);
60
- if (parsedFilename === undefined) {
61
- continue;
62
- }
63
- dynamicallyIncludedEntrypoints.push([cfgName, { locations: parsedFilename.locations, enqueuingFlags: parsedFilename.flags }]);
64
- }
65
- }
66
- else if (dirent.isFile()) {
67
- const parsedFilename = (0, location_encoding_filename_parser_1.parseLocationEncodingFilename)(dirent.name);
68
- if (parsedFilename === undefined) {
69
- continue;
70
- }
71
- dynamicallyIncludedEntrypoints.push([dirent.name, { locations: parsedFilename.locations, enqueuingFlags: parsedFilename.flags }]);
72
- }
73
- }
74
- }
75
- return {
76
- staticEntrypoints: Object.entries(configSrc).map(([k, v]) => {
77
- return normalizeSrcAndDestination([k, typeof v === 'boolean' ? {} : (typeof v === 'string' ? { destination: v } : v)]);
78
- }),
79
- dynamicEntrypoints: dynamicallyIncludedEntrypoints.map(normalizeSrcAndDestination)
80
- };
81
- }
82
- }
@@ -1,26 +0,0 @@
1
- import { RealUsageLocations } from "../shared";
2
- import { NormalizedEnqueuingControlFlags } from "./path-query-and-related-helpers";
3
- export type ParsedLocationEncodingFilename = {
4
- type: 'script' | 'style' | 'script-module';
5
- locations: RealUsageLocations & {
6
- register?: boolean | number;
7
- };
8
- flags: NormalizedEnqueuingControlFlags;
9
- niceName?: string;
10
- };
11
- export declare function parseLocationEncodingFilename(filename: string): ParsedLocationEncodingFilename | undefined;
12
- export declare function parseLocationEncodingFilenameForBlock(filename: string, errorBuilder?: (message: string, filename: string) => unknown): Omit<ParsedLocationEncodingFilename, 'locations'> & {
13
- locations: Pick<RealUsageLocations, 'clientEditor' | 'clientView'>;
14
- } | undefined;
15
- /**
16
- * This handles detecting all keys of standardLocationNamesMeta as well as "view", "client-view", "editor", "client-editor", and "block-assets".
17
- * It MUST be kept in sync with standardLocationNamesMeta
18
- * @param segment
19
- */
20
- export declare function extractLocationFromPropertyEncodingFilenameSegment(segment: string): {
21
- readonly locationName: "clientView" | "clientEditor" | "blockAssets" | "admin" | "login" | "customizer" | "analytics" | "register";
22
- readonly priority: number | true;
23
- } | {
24
- readonly locationName: false;
25
- readonly priority?: undefined;
26
- };
@@ -1,118 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseLocationEncodingFilename = parseLocationEncodingFilename;
4
- exports.parseLocationEncodingFilenameForBlock = parseLocationEncodingFilenameForBlock;
5
- exports.extractLocationFromPropertyEncodingFilenameSegment = extractLocationFromPropertyEncodingFilenameSegment;
6
- const node_path_1 = require("node:path");
7
- const shared_1 = require("../shared");
8
- function parseLocationEncodingFilename(filename) {
9
- const { name, ext } = (0, node_path_1.parse)(filename);
10
- if (name.startsWith("~")) {
11
- return undefined;
12
- }
13
- let type = /^\.(?:s[ac]|p?c)ss$/i.test(ext) ? 'style' : /^\.m[jt]sx?/i.test(ext) ? 'script-module' : /^\.[jt]sx?/i.test(ext) ? 'script' : false;
14
- if (type === false) {
15
- return undefined;
16
- }
17
- const locations = {};
18
- const flags = {};
19
- const nameSegments = name.split("."); //Split always returns at least one string
20
- const typeOverrideMatch = /^(?<enqueuePosition>.+)-(?<typeOverride>script|style|script-module)$|^(?<typeOverride>script|style|script-module)$/.exec(nameSegments[0]);
21
- if (typeOverrideMatch) {
22
- nameSegments[0] = typeOverrideMatch.groups?.["enqueuePosition"] ?? "both"; // We override the first segment with the version without the type override
23
- type = typeOverrideMatch.groups?.["typeOverride"];
24
- }
25
- const inlinePattern = /^(?<inline>inline)(?:[-=](?<position>before|after))?$|^strategy[-=](?<inline>inline)(?:-(?<position>before|after))?$/;
26
- const strategyPattern = /^strategy[-=](?<strategy>eager|lazy|defer|async)$|^(?<strategy>lazy|eager)$/;
27
- const fetchpriorityPattern = /^fetchpriority[-=](auto|low|high)$/;
28
- const bothViewAndEditorLocationPattern = /^(?:client-)?(?<both>both)(?:[-=](?<priority>-?\d+))?$/;
29
- let niceName = undefined;
30
- for (const segment of nameSegments) {
31
- const { locationName, priority } = extractLocationFromPropertyEncodingFilenameSegment(segment);
32
- if (locationName) {
33
- locations[locationName] = priority;
34
- continue;
35
- }
36
- const lcSegment = segment.toLowerCase();
37
- const { both, priority: bothPriority } = bothViewAndEditorLocationPattern.exec(lcSegment)?.groups ?? {};
38
- if (both) {
39
- const priority = bothPriority !== undefined ? parseInt(bothPriority) : true;
40
- locations.clientView = priority;
41
- locations.clientEditor = priority;
42
- continue;
43
- }
44
- const { inline, position: inlinePosition } = (inlinePattern.exec(lcSegment)?.groups ?? {});
45
- if (inline) {
46
- flags.inline = true;
47
- flags.position = inlinePosition;
48
- continue;
49
- }
50
- const strategy = strategyPattern.exec(lcSegment)?.groups?.['strategy']?.toLowerCase();
51
- if (strategy) {
52
- flags.strategy = strategy;
53
- continue;
54
- }
55
- const fetchpriority = fetchpriorityPattern.exec(lcSegment)?.[1];
56
- if (fetchpriority !== undefined) {
57
- flags.fetchpriority = fetchpriority;
58
- continue;
59
- }
60
- switch (segment.toLowerCase()) {
61
- // Loading flags
62
- case "in-footer":
63
- case "in_footer":
64
- flags.in_footer = true;
65
- break;
66
- case "in-header":
67
- case "in_header":
68
- flags.in_footer = false;
69
- break;
70
- default:
71
- if (niceName === undefined) {
72
- niceName = segment;
73
- }
74
- break;
75
- }
76
- }
77
- // This means that it wasn't a location-encoding filename
78
- if (Object.values(locations).length === 0) {
79
- return undefined;
80
- }
81
- return { type, locations, flags, niceName };
82
- }
83
- function parseLocationEncodingFilenameForBlock(filename, errorBuilder = shared_1.newWebpackErrorForFile) {
84
- const parsedFilename = parseLocationEncodingFilename(filename);
85
- if (parsedFilename !== undefined) {
86
- if ((0, shared_1.constantKeys)(parsedFilename.locations).some(value => value !== 'clientView' && value !== 'clientEditor')) {
87
- throw errorBuilder(`Block assets cannot be enqueued anywhere other than view, editor, or both. Saw: ${(0, shared_1.constantKeys)(parsedFilename).join(", ")}`, filename);
88
- }
89
- if (Object.values(parsedFilename.locations).some(value => typeof value === 'number')) {
90
- throw errorBuilder(`Block assets cannot be enqueued with a priority`, filename);
91
- }
92
- }
93
- return parsedFilename;
94
- }
95
- const standardLocationNamesAndPriorityPatternInFilenameSegment = /^(?:(?<view>clientView|client-view|view)|(?<editor>clientEditor|client-editor|editor)|(?<blockAssets>blockAssets|block-assets)|(?<locationName>admin|login|customizer|analytics|register))(?:[-=](?<priority>-?\d+))?$/;
96
- /**
97
- * This handles detecting all keys of standardLocationNamesMeta as well as "view", "client-view", "editor", "client-editor", and "block-assets".
98
- * It MUST be kept in sync with standardLocationNamesMeta
99
- * @param segment
100
- */
101
- function extractLocationFromPropertyEncodingFilenameSegment(segment) {
102
- const { view, editor, blockAssets, locationName, priority: rawPriority } = standardLocationNamesAndPriorityPatternInFilenameSegment.exec(segment)
103
- ?.groups ?? {};
104
- const priority = rawPriority !== undefined ? parseInt(rawPriority) : true;
105
- if (view) {
106
- return { locationName: "clientView", priority };
107
- }
108
- if (editor) {
109
- return { locationName: "clientEditor", priority };
110
- }
111
- if (blockAssets) {
112
- return { locationName: "blockAssets", priority };
113
- }
114
- if (locationName) {
115
- return { locationName, priority };
116
- }
117
- return { locationName: false };
118
- }
@@ -1,58 +0,0 @@
1
- import type { Compilation } from "webpack";
2
- import { type InlinedAsset, type PathQueryParameters, type ScriptArgsObject } from "../shared";
3
- export declare function getAssetFileContents(compilation: Compilation, name: string): string;
4
- export declare function unpackPotentiallyPrefixedFilePath(filePath: string): [string, PathQueryParameters | undefined];
5
- /**
6
- * The following substitutions are performed:
7
- * <ul>
8
- * <li>parameters without an assigned value -> a boolean parameter set to true</li>
9
- * <li>true and false -> their boolean equivalents</li>
10
- * <li>numeric values -> their number equivalents</li>
11
- * </ul>
12
- *
13
- * @param pathQuery the part after the "?" in a webpack inclusion path
14
- * @return the query as an object with common string -> JS type conversions already performed
15
- */
16
- export declare function unpackPathQuery(pathQuery: string): PathQueryParameters | undefined;
17
- export type LoadingStrategy = boolean | 'defer' | 'async' | 'eager' | 'lazy' | 'inline';
18
- export declare function isValidLoadingStrategy(strategy: any): strategy is LoadingStrategy | undefined;
19
- export declare function newInvalidLoadingStrategyError(strategy: unknown, file: string): import("webpack").WebpackError;
20
- export type InFooter = boolean;
21
- export declare function isValidInFooter(in_footer: unknown): in_footer is InFooter;
22
- export declare function newInvalidInFooterError(in_footer: unknown, file: string): import("webpack").WebpackError;
23
- export type FetchPriority = 'auto' | 'low' | 'high';
24
- export declare function isValidFetchPriority(fetchpriority: unknown): fetchpriority is FetchPriority;
25
- export declare function newInvalidFetchPriorityError(fetchpriority: unknown, file: string): import("webpack").WebpackError;
26
- export type PositionForInlineStrategy = 'before' | 'after';
27
- export declare function isValidPositionForInlineStrategy(position: unknown): position is PositionForInlineStrategy;
28
- export declare function newInvalidPositionForInlineStrategyError(position: unknown, file: string): import("webpack").WebpackError;
29
- /**
30
- * This function ensures that the passed pathQueryParameters are normalized for the config-loading step, NOT the emission step
31
- */
32
- export type NormalizedEnqueuingControlFlags = {
33
- strategy?: Exclude<LoadingStrategy, 'inline'>;
34
- in_footer?: InFooter;
35
- inline?: boolean;
36
- fetchpriority?: FetchPriority;
37
- position?: 'before' | 'after';
38
- };
39
- export declare function mergeTwoEnqueuingControlFlagSets(file: string, ...argsBlocks: (NormalizedEnqueuingControlFlags | undefined)[]): NormalizedEnqueuingControlFlags | undefined;
40
- export declare function unpackEnqueuingControlFlagsFromPathQueryParameters(pathQueryParameters: PathQueryParameters | undefined, file: string, sourceType: 'registerScriptArgs' | 'path query parameters'): {
41
- flags?: NormalizedEnqueuingControlFlags;
42
- handle?: string;
43
- remainder?: PathQueryParameters;
44
- };
45
- /**
46
- * This function does a few things:
47
- * <ol>
48
- * <li>It converts the strategy, in_footer, and fetchpriority flags into a valid script args object</li>
49
- * <li>If inline is true, it records the contents of the asset and the value of the position flag for later injection and removes the asset from the compilation output</li>
50
- * </ol>
51
- * @param compilation
52
- * @param file
53
- * @param flags
54
- */
55
- export declare function convertEnqueuingControlFlagsToScriptArgsObject(compilation: Compilation, file: string, flags: NormalizedEnqueuingControlFlags | undefined): {
56
- scriptArgsObject?: ScriptArgsObject;
57
- inlinedAsset?: InlinedAsset;
58
- };
@@ -1,263 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getAssetFileContents = getAssetFileContents;
4
- exports.unpackPotentiallyPrefixedFilePath = unpackPotentiallyPrefixedFilePath;
5
- exports.unpackPathQuery = unpackPathQuery;
6
- exports.isValidLoadingStrategy = isValidLoadingStrategy;
7
- exports.newInvalidLoadingStrategyError = newInvalidLoadingStrategyError;
8
- exports.isValidInFooter = isValidInFooter;
9
- exports.newInvalidInFooterError = newInvalidInFooterError;
10
- exports.isValidFetchPriority = isValidFetchPriority;
11
- exports.newInvalidFetchPriorityError = newInvalidFetchPriorityError;
12
- exports.isValidPositionForInlineStrategy = isValidPositionForInlineStrategy;
13
- exports.newInvalidPositionForInlineStrategyError = newInvalidPositionForInlineStrategyError;
14
- exports.mergeTwoEnqueuingControlFlagSets = mergeTwoEnqueuingControlFlagSets;
15
- exports.unpackEnqueuingControlFlagsFromPathQueryParameters = unpackEnqueuingControlFlagsFromPathQueryParameters;
16
- exports.convertEnqueuingControlFlagsToScriptArgsObject = convertEnqueuingControlFlagsToScriptArgsObject;
17
- const node_path_1 = require("node:path");
18
- const shared_1 = require("../shared");
19
- function getAssetFileContents(compilation, name) {
20
- const asset = compilation.getAsset(name);
21
- if (!asset) {
22
- throw new Error(`${name} is unexpectedly missing`);
23
- }
24
- const assetSource = asset.source.source();
25
- return typeof assetSource === 'string' ? assetSource : assetSource?.toString('utf-8');
26
- }
27
- function unpackPotentiallyPrefixedFilePath(filePath) {
28
- if (filePath.startsWith("file:")) {
29
- filePath = filePath.substring(5);
30
- }
31
- const queryStart = filePath.indexOf("?");
32
- if (queryStart === -1) {
33
- return [filePath, undefined];
34
- }
35
- else {
36
- return [filePath.substring(0, queryStart), unpackPathQuery(filePath.substring(queryStart + 1))];
37
- }
38
- }
39
- /**
40
- * The following substitutions are performed:
41
- * <ul>
42
- * <li>parameters without an assigned value -> a boolean parameter set to true</li>
43
- * <li>true and false -> their boolean equivalents</li>
44
- * <li>numeric values -> their number equivalents</li>
45
- * </ul>
46
- *
47
- * @param pathQuery the part after the "?" in a webpack inclusion path
48
- * @return the query as an object with common string -> JS type conversions already performed
49
- */
50
- function unpackPathQuery(pathQuery) {
51
- if (!pathQuery) {
52
- return undefined;
53
- }
54
- return new URLSearchParams(pathQuery.replaceAll(/((?:[&?]|^)\w+)(&|$)/g, "$1=true$2")).entries()
55
- .map(([key, value]) => {
56
- if (value === 'true') {
57
- return [key, true];
58
- }
59
- if (value === 'false') {
60
- return [key, false];
61
- }
62
- if (Number.isFinite(+value)) {
63
- return [key, +value];
64
- }
65
- return [key, value];
66
- })
67
- .reduce((collector, [key, value]) => {
68
- if (collector[key] instanceof Array) {
69
- collector[key].push(value);
70
- }
71
- else if (key in collector) {
72
- collector[key] = [collector[key], value];
73
- }
74
- else {
75
- collector[key] = value;
76
- }
77
- return collector;
78
- }, {});
79
- }
80
- const namedStrategies = ['defer', 'async', 'eager', 'lazy', 'inline'];
81
- function isValidLoadingStrategy(strategy) {
82
- return strategy === undefined || (typeof strategy === 'string' && namedStrategies.includes(strategy));
83
- }
84
- function newInvalidLoadingStrategyError(strategy, file) {
85
- return (0, shared_1.newWebpackErrorForFile)(`The strategy was invalid. Received: ${strategy}, Expected: undefined|boolean|'${namedStrategies.join("'|'")}'`, file);
86
- }
87
- function isValidInFooter(in_footer) {
88
- return typeof in_footer === 'boolean';
89
- }
90
- function newInvalidInFooterError(in_footer, file) {
91
- return (0, shared_1.newWebpackErrorForFile)(`The in_footer value was invalid. Received: ${in_footer}, Expected: undefined|boolean`, file);
92
- }
93
- function isValidFetchPriority(fetchpriority) {
94
- return typeof fetchpriority === 'string' && ["auto", "low", "high"].includes(fetchpriority);
95
- }
96
- function newInvalidFetchPriorityError(fetchpriority, file) {
97
- return (0, shared_1.newWebpackErrorForFile)(`The fetchpriority value was invalid. Received: ${fetchpriority}, Expected: undefined|'auto'|'low'|'high'`, file);
98
- }
99
- function isValidPositionForInlineStrategy(position) {
100
- return typeof position === 'string' && ["before", "after"].includes(position);
101
- }
102
- function newInvalidPositionForInlineStrategyError(position, file) {
103
- return (0, shared_1.newWebpackErrorForFile)(`The position value for the inlined asset was invalid. Received: ${position}, Expected: undefined|'before'|'after'`, file);
104
- }
105
- function mergeTwoEnqueuingControlFlagSets(file, ...argsBlocks) {
106
- const filteredArgsBlocks = argsBlocks.filter(argsBlock => argsBlock !== undefined);
107
- if (filteredArgsBlocks.length === 0) {
108
- return undefined;
109
- }
110
- if ((0, shared_1.arrayIsLength)(filteredArgsBlocks, 1)) {
111
- return filteredArgsBlocks[0];
112
- }
113
- const res = {};
114
- for (const key of ['strategy', 'in_footer', 'fetchpriority', 'inline', 'position']) {
115
- for (const argsBlock of filteredArgsBlocks) {
116
- if (key in argsBlock) {
117
- if (!(key in res)) {
118
- res[key] = argsBlock[key];
119
- }
120
- else if (argsBlock[key] !== res[key]) {
121
- throw (0, shared_1.newWebpackErrorForFile)(`The ${key} values in the control flag sets for the file conflict`, file);
122
- }
123
- }
124
- }
125
- }
126
- return res;
127
- }
128
- function unpackEnqueuingControlFlagsFromPathQueryParameters(pathQueryParameters, file, sourceType) {
129
- if (pathQueryParameters === undefined) {
130
- return {};
131
- }
132
- const { strategy, in_footer: normalizedInFooter, 'in-footer': alternateInFooter, fetchpriority, position, handle, ...remainder } = pathQueryParameters;
133
- let flags;
134
- switch (strategy) {
135
- case 'defer':
136
- case 'async':
137
- flags = { strategy };
138
- break;
139
- case 'eager':
140
- flags = { strategy: 'eager' };
141
- break;
142
- case 'lazy':
143
- flags = { strategy: 'defer', in_footer: true };
144
- break;
145
- case 'inline':
146
- flags = { inline: true };
147
- break;
148
- case true:
149
- case false:
150
- flags = { in_footer: strategy };
151
- break;
152
- case null:
153
- case undefined:
154
- flags = {};
155
- break;
156
- default:
157
- throw newInvalidLoadingStrategyError(strategy, file);
158
- }
159
- if (flags.inline === undefined && pathQueryParameters['inline'] !== undefined) {
160
- flags.inline = !!pathQueryParameters['inline'];
161
- }
162
- const in_footer = normalizedInFooter ?? alternateInFooter;
163
- if (in_footer !== undefined) {
164
- if (!isValidInFooter(in_footer)) {
165
- throw newInvalidInFooterError(in_footer, file);
166
- }
167
- flags.in_footer = in_footer;
168
- }
169
- if (pathQueryParameters['fetchpriority'] !== undefined) {
170
- if (!isValidFetchPriority(pathQueryParameters['fetchpriority'])) {
171
- throw newInvalidFetchPriorityError(pathQueryParameters['fetchpriority'], file);
172
- }
173
- if (flags.fetchpriority !== undefined && flags.fetchpriority !== pathQueryParameters['fetchpriority']) {
174
- throw (0, shared_1.newWebpackErrorForFile)(`The strategy and fetchpriority values in the ${sourceType} for the file conflict. Got ${strategy} and ${pathQueryParameters['fetchpriority']}`, file);
175
- }
176
- flags.fetchpriority = pathQueryParameters['fetchpriority'];
177
- }
178
- if (flags.inline && (pathQueryParameters['position'] === 'before' || pathQueryParameters['position'] === 'after')) {
179
- flags.position = pathQueryParameters['position'];
180
- }
181
- if (handle !== undefined && (typeof handle !== 'string' || handle.length < 5)) {
182
- throw (0, shared_1.newWebpackErrorForFile)(`The handle was invalid. Received: ${handle}. Expected: a string that is at least 5 characters long`, file);
183
- }
184
- return Object.keys(flags).length > 0 ? { flags, handle, remainder } : { handle, remainder };
185
- }
186
- /**
187
- * This function does a few things:
188
- * <ol>
189
- * <li>It converts the strategy, in_footer, and fetchpriority flags into a valid script args object</li>
190
- * <li>If inline is true, it records the contents of the asset and the value of the position flag for later injection and removes the asset from the compilation output</li>
191
- * </ol>
192
- * @param compilation
193
- * @param file
194
- * @param flags
195
- */
196
- function convertEnqueuingControlFlagsToScriptArgsObject(compilation, file, flags) {
197
- if (flags === undefined) {
198
- return {};
199
- }
200
- const { strategy, in_footer, inline, position, fetchpriority } = flags;
201
- const scriptArgsObject = {};
202
- let inlinedAsset = undefined;
203
- switch (strategy) {
204
- case 'async':
205
- case 'defer':
206
- scriptArgsObject.strategy = strategy;
207
- break;
208
- case 'eager':
209
- scriptArgsObject.in_footer = false;
210
- break;
211
- case 'lazy':
212
- scriptArgsObject.strategy = 'defer';
213
- scriptArgsObject.in_footer = true;
214
- break;
215
- case true:
216
- case false:
217
- scriptArgsObject.in_footer = strategy;
218
- break;
219
- case null:
220
- case undefined:
221
- // This is included because are effectively validating the strategy value with this switch statement, and "not defined" is a valid state
222
- break;
223
- default:
224
- throw newInvalidLoadingStrategyError(strategy, file);
225
- }
226
- if (in_footer !== undefined) {
227
- if (!isValidInFooter(in_footer)) {
228
- throw newInvalidInFooterError(in_footer, file);
229
- }
230
- scriptArgsObject.in_footer = in_footer;
231
- }
232
- if (inline) {
233
- inlinedAsset = { contents: getAssetFileContents(compilation, file) };
234
- removeFileAndAssetPHP(compilation, file);
235
- if (position !== undefined) {
236
- if (!isValidPositionForInlineStrategy(position)) {
237
- throw newInvalidPositionForInlineStrategyError(position, file);
238
- }
239
- inlinedAsset.position = position;
240
- }
241
- if (inlinedAsset.position !== 'before' && scriptArgsObject.strategy !== undefined) {
242
- compilation.warnings.push((0, shared_1.newWebpackErrorForFile)("Deferred and async scripts that have inlined JS attached in the 'after' position will cause WordPress to convert all of their dependencies to eager scripts at runtime", file));
243
- }
244
- if (scriptArgsObject.in_footer === undefined) {
245
- scriptArgsObject.in_footer = true;
246
- }
247
- }
248
- if (fetchpriority !== undefined) {
249
- if (!isValidFetchPriority(fetchpriority)) {
250
- throw newInvalidFetchPriorityError(fetchpriority, file);
251
- }
252
- if (inlinedAsset !== undefined) {
253
- compilation.warnings.push((0, shared_1.newWebpackErrorForFile)("Fetchpriority has no effect on inlined assets", file));
254
- }
255
- scriptArgsObject.fetchpriority = fetchpriority;
256
- }
257
- return Object.keys(scriptArgsObject).length > 0 ? { scriptArgsObject, inlinedAsset } : { inlinedAsset };
258
- }
259
- function removeFileAndAssetPHP(compilation, file) {
260
- const pathParts = (0, node_path_1.parse)(file);
261
- compilation.deleteAsset((0, node_path_1.join)(pathParts.dir, pathParts.name) + ".asset.php");
262
- compilation.deleteAsset(file);
263
- }