@plaudit/webpack-extensions 2.62.0 → 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.
@@ -7,71 +7,27 @@ exports.PlainEntrypointsStyleBlockJSONPlugin = void 0;
7
7
  const node_crypto_1 = __importDefault(require("node:crypto"));
8
8
  const node_fs_1 = __importDefault(require("node:fs"));
9
9
  const node_path_1 = __importDefault(require("node:path"));
10
+ const AbstractMultiPhaseLibraryPlugin_1 = require("./AbstractMultiPhaseLibraryPlugin");
11
+ const UnifiedLoaderGenerator_1 = require("./UnifiedLoaderGenerator");
10
12
  const shared_1 = require("../shared");
11
13
  const php_writer_1 = require("../utils/php-writer");
12
14
  const pseduo_semaphore_1 = require("../utils/pseduo-semaphore");
13
- const UnifiedLoaderGenerator_1 = require("./UnifiedLoaderGenerator");
14
15
  const webpack_1 = require("webpack");
15
- class PlainEntrypointsStyleBlockJSONPlugin {
16
+ const promises_1 = __importDefault(require("node:fs/promises"));
17
+ class PlainEntrypointsStyleBlockJSONPlugin extends AbstractMultiPhaseLibraryPlugin_1.AbstractMultiPhaseLibraryPlugin {
16
18
  config;
17
19
  blocksDest;
18
20
  webpackRemoveEmptyScriptsPlugin;
19
21
  static semaphore = new pseduo_semaphore_1.PseudoSemaphore({ collatableWorkableBlockInfo: {}, blocksDest: "", emittingWpmlXml: false }, "Block JSON v3");
20
- static phaseTwoAttached = {};
21
- id;
22
- libraryType;
23
22
  constructor(config, blocksDest, webpackRemoveEmptyScriptsPlugin) {
23
+ super(`block-json-${blocksDest}`, [PlainEntrypointsStyleBlockJSONPlugin.semaphore, UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore]);
24
24
  this.config = config;
25
25
  this.blocksDest = blocksDest;
26
26
  this.webpackRemoveEmptyScriptsPlugin = webpackRemoveEmptyScriptsPlugin;
27
- this.id = Math.random().toString();
28
- this.libraryType = `block-json-${this.blocksDest}`;
29
- PlainEntrypointsStyleBlockJSONPlugin.semaphore.register(this.id);
30
- UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.register(this.id);
31
27
  }
32
28
  apply(compiler) {
33
- webpack_1.library.EnableLibraryPlugin.setEnabled(compiler, this.libraryType);
29
+ super.apply(compiler);
34
30
  compiler.hooks.compilation.tap(this.constructor.name, compilation => {
35
- PlainEntrypointsStyleBlockJSONPlugin.phaseTwoAttached[this.blocksDest] = false;
36
- PlainEntrypointsStyleBlockJSONPlugin.semaphore.reset(this.id);
37
- UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.reset(this.id);
38
- compilation.hooks.beforeChunkIds.tap(this.constructor.name, () => {
39
- if (!PlainEntrypointsStyleBlockJSONPlugin.phaseTwoAttached[this.blocksDest]) {
40
- PlainEntrypointsStyleBlockJSONPlugin.phaseTwoAttached[this.blocksDest] = true;
41
- compilation.hooks.processAssets.tapPromise({ name: `${this.constructor.name}_CompileLoader`, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_REPORT }, async () => {
42
- const allSemaphoreData = (await PlainEntrypointsStyleBlockJSONPlugin.semaphore.wait())
43
- .reduce((acc, cur) => {
44
- (acc[cur.blocksDest] ?? (acc[cur.blocksDest] = [])).push(cur);
45
- return acc;
46
- }, {});
47
- const semaphoreData = allSemaphoreData[this.blocksDest];
48
- if (semaphoreData === undefined) {
49
- compilation.errors.push(new Error(`Semaphore data missing for ${this.blocksDest}`));
50
- return;
51
- }
52
- const workableBlockInfo = semaphoreData.map(sd => sd.collatableWorkableBlockInfo)
53
- .reduce((acc, cur) => {
54
- for (const [k, v] of Object.entries(cur)) {
55
- if (acc[k]) {
56
- acc[k].workableBlockEntrypointsInfo.push(...v.workableBlockEntrypointsInfo);
57
- if (!acc[k].sourcePath && v.sourcePath) {
58
- acc[k].sourcePath = v.sourcePath;
59
- }
60
- }
61
- else {
62
- acc[k] = { ...v, workableBlockEntrypointsInfo: [...v.workableBlockEntrypointsInfo] };
63
- }
64
- acc[k].workableBlockEntrypointsInfo.sort((a, b) => {
65
- return a.handle.localeCompare(b.handle) || a.entrypointField.localeCompare(b.entrypointField);
66
- });
67
- }
68
- return acc;
69
- }, {});
70
- const blockData = this.transformBlocks(compilation, workableBlockInfo, semaphoreData.some(sd => sd.emittingWpmlXml));
71
- this.emitBlockLoaderFile(compilation, blockData);
72
- });
73
- }
74
- });
75
31
  compilation.hooks.processAssets.tapPromise({ name: this.constructor.name, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_ANALYSE, additionalAssets: true }, async (assets) => {
76
32
  if (!("assets.json" in assets)) {
77
33
  return;
@@ -126,10 +82,15 @@ class PlainEntrypointsStyleBlockJSONPlugin {
126
82
  //TODO: Can we guarantee that entrypoint.name is always non-null?
127
83
  const epBlockJson = entrypoint.name + ".json";
128
84
  if (!applicableBlockJsonFiles[epBlockJson]) {
129
- applicableBlockJsonFiles[epBlockJson] = { sourcePath: srcPath, workableBlockEntrypointsInfo: [] };
85
+ const blockJsonText = PlainEntrypointsStyleBlockJSONPlugin.extractAssetSource(compilation, epBlockJson)
86
+ ?? await promises_1.default.readFile(srcPath, 'utf-8');
87
+ if (!blockJsonText) {
88
+ compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`Unable to extract the source for ${epBlockJson}`, srcPath));
89
+ continue;
90
+ }
91
+ applicableBlockJsonFiles[epBlockJson] = { sourcePath: srcPath, workableBlockEntrypointsInfo: [], blockJsonText };
130
92
  }
131
93
  blockJsonOriginToOutputMapping[srcPath] = epBlockJson;
132
- compilation.emitAsset(epBlockJson, asset);
133
94
  }
134
95
  }
135
96
  for (const { entrypoint, entrypointChunk, entrypointLibrary, srcPath } of relevantEntrypoints) {
@@ -198,8 +159,8 @@ class PlainEntrypointsStyleBlockJSONPlugin {
198
159
  delete blockData['__metadata'];
199
160
  new php_writer_1.PHPWriter()
200
161
  .action("init", writer => {
201
- writer.call("\\Plaudit\\Common\\ACF\\BlockManager::autoloadSubfoldersV3", [php_writer_1.Expr.__DIR__, new php_writer_1.Expr((0, shared_1.makeEmittableConfigPHP)(blockData, false, "\t")),
202
- php_writer_1.Expr.__FILE__, new php_writer_1.Expr((0, shared_1.makeEmittableConfigPHP)(metadata, false, "\t")), null]);
162
+ writer.call("\\Plaudit\\Common\\ACF\\BlockManager::autoloadSubfoldersV3", [php_writer_1.Constants.__DIR__, new php_writer_1.EnclosedLiteral((0, shared_1.makeEmittableConfigPHP)(blockData, false, "\t")),
163
+ php_writer_1.Constants.__FILE__, new php_writer_1.EnclosedLiteral((0, shared_1.makeEmittableConfigPHP)(metadata, false, "\t")), null]);
203
164
  }, { accountForAlreadyDoing: true })
204
165
  .emitAsset(compilation, node_path_1.default.join(this.blocksDest, "blockdir-loader.php"));
205
166
  }
@@ -212,18 +173,17 @@ class PlainEntrypointsStyleBlockJSONPlugin {
212
173
  .flatMap(bi => bi.workableBlockEntrypointsInfo)
213
174
  .sort((a, b) => a.handle.localeCompare(b.handle) || a.entrypointField.localeCompare(b.entrypointField));
214
175
  const blockData = {};
215
- for (const [blockJsonAssetName, { sourcePath: blockJsonSourcePath, workableBlockEntrypointsInfo }] of Object.entries(collatedWorkableBlockInfo)) {
176
+ for (const [blockJsonAssetName, { sourcePath: blockJsonSourcePath, workableBlockEntrypointsInfo, blockJsonText }] of Object.entries(collatedWorkableBlockInfo)) {
216
177
  if (!blockJsonSourcePath) {
217
178
  compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`${blockJsonAssetName} does not have a source path`, blockJsonAssetName));
218
179
  continue;
219
180
  }
220
- const sourceDir = node_path_1.default.dirname(blockJsonSourcePath);
221
- const outputDir = node_path_1.default.join(compilation.compiler.outputPath, node_path_1.default.dirname(blockJsonAssetName));
222
- const blockJsonText = PlainEntrypointsStyleBlockJSONPlugin.extractAssetSource(compilation, blockJsonAssetName);
223
181
  if (!blockJsonText) {
224
- compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`Unable to extract the source for ${blockJsonAssetName}`, node_path_1.default.join(sourceDir, 'block.json')));
182
+ compilation.errors.push((0, shared_1.newWebpackErrorForFile)(`${blockJsonAssetName} does not have recorded text`, blockJsonAssetName));
225
183
  continue;
226
184
  }
185
+ const sourceDir = node_path_1.default.dirname(blockJsonSourcePath);
186
+ const outputDir = node_path_1.default.join(compilation.compiler.outputPath, node_path_1.default.dirname(blockJsonAssetName));
227
187
  const blockJson = JSON.parse(blockJsonText);
228
188
  const pathsNeedRemapping = !this.config.standaloneBlocks && blockJson["plaudit"] !== "simple";
229
189
  PlainEntrypointsStyleBlockJSONPlugin.remapReferencedPHPFilesOnKey(blockJson, "setup", pathsNeedRemapping, sourceDir, outputDir, compilation, true);
@@ -436,5 +396,39 @@ class PlainEntrypointsStyleBlockJSONPlugin {
436
396
  }
437
397
  }
438
398
  }
399
+ attachSecondPhase(compilation) {
400
+ compilation.hooks.processAssets.tapPromise({ name: `${this.constructor.name}_CompileLoader`, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_REPORT }, async () => {
401
+ const allSemaphoreData = (await PlainEntrypointsStyleBlockJSONPlugin.semaphore.wait())
402
+ .reduce((acc, cur) => {
403
+ (acc[cur.blocksDest] ?? (acc[cur.blocksDest] = [])).push(cur);
404
+ return acc;
405
+ }, {});
406
+ const semaphoreData = allSemaphoreData[this.blocksDest];
407
+ if (semaphoreData === undefined) {
408
+ compilation.errors.push(new Error(`Semaphore data missing for ${this.blocksDest}`));
409
+ return;
410
+ }
411
+ const workableBlockInfo = semaphoreData.map(sd => sd.collatableWorkableBlockInfo)
412
+ .reduce((acc, cur) => {
413
+ for (const [k, v] of Object.entries(cur)) {
414
+ if (acc[k]) {
415
+ acc[k].workableBlockEntrypointsInfo.push(...v.workableBlockEntrypointsInfo);
416
+ if (!acc[k].sourcePath && v.sourcePath) {
417
+ acc[k].sourcePath = v.sourcePath;
418
+ }
419
+ }
420
+ else {
421
+ acc[k] = { ...v, workableBlockEntrypointsInfo: [...v.workableBlockEntrypointsInfo] };
422
+ }
423
+ acc[k].workableBlockEntrypointsInfo.sort((a, b) => {
424
+ return a.handle.localeCompare(b.handle) || a.entrypointField.localeCompare(b.entrypointField);
425
+ });
426
+ }
427
+ return acc;
428
+ }, {});
429
+ const blockData = this.transformBlocks(compilation, workableBlockInfo, semaphoreData.some(sd => sd.emittingWpmlXml));
430
+ this.emitBlockLoaderFile(compilation, blockData);
431
+ });
432
+ }
439
433
  }
440
434
  exports.PlainEntrypointsStyleBlockJSONPlugin = PlainEntrypointsStyleBlockJSONPlugin;
@@ -1,12 +1,12 @@
1
1
  import type { VerifiedPlauditWordpressWebpackConfig } from "../utils/common-config-helpers";
2
- import { type Compiler, type WebpackPluginInstance } from "webpack";
3
- export declare class SpecialAssetHandlingPlugin implements WebpackPluginInstance {
2
+ import { Compilation, type Compiler } from "webpack";
3
+ import { AbstractMultiPhaseLibraryPlugin } from "./AbstractMultiPhaseLibraryPlugin";
4
+ export declare class SpecialAssetHandlingPlugin extends AbstractMultiPhaseLibraryPlugin {
4
5
  private readonly config;
5
6
  private static readonly semaphore;
6
- private static hasAttachedAssetCollatorForCurrentBatch;
7
7
  private static validPathname?;
8
- private readonly id;
9
8
  constructor(config: VerifiedPlauditWordpressWebpackConfig);
10
9
  apply(compiler: Compiler): void;
11
10
  private collateAssets;
11
+ protected attachSecondPhase(compilation: Compilation): void;
12
12
  }
@@ -10,32 +10,21 @@ const php_writer_1 = require("../utils/php-writer");
10
10
  const pseduo_semaphore_1 = require("../utils/pseduo-semaphore");
11
11
  const UnifiedLoaderGenerator_1 = require("./UnifiedLoaderGenerator");
12
12
  const webpack_1 = require("webpack");
13
- class SpecialAssetHandlingPlugin {
13
+ const AbstractMultiPhaseLibraryPlugin_1 = require("./AbstractMultiPhaseLibraryPlugin");
14
+ class SpecialAssetHandlingPlugin extends AbstractMultiPhaseLibraryPlugin_1.AbstractMultiPhaseLibraryPlugin {
14
15
  config;
15
16
  static semaphore = new pseduo_semaphore_1.PseudoSemaphore({}, "Special");
16
- static hasAttachedAssetCollatorForCurrentBatch = false;
17
17
  static validPathname = undefined;
18
- id;
19
18
  constructor(config) {
19
+ super("special-assets", [SpecialAssetHandlingPlugin.semaphore, UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore]);
20
20
  this.config = config;
21
- this.id = Math.random().toString();
22
21
  }
23
22
  apply(compiler) {
24
23
  if (!this.config.useWebpackResourceFiltering) {
25
24
  return;
26
25
  }
27
- SpecialAssetHandlingPlugin.semaphore.register(this.id);
28
- UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.register(this.id);
26
+ super.apply(compiler);
29
27
  compiler.hooks.compilation.tap(this.constructor.name, compilation => {
30
- SpecialAssetHandlingPlugin.hasAttachedAssetCollatorForCurrentBatch = false;
31
- SpecialAssetHandlingPlugin.semaphore.reset(this.id);
32
- UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.reset(this.id);
33
- compilation.hooks.beforeChunkIds.tap(this.constructor.name, () => {
34
- if (!SpecialAssetHandlingPlugin.hasAttachedAssetCollatorForCurrentBatch) {
35
- SpecialAssetHandlingPlugin.hasAttachedAssetCollatorForCurrentBatch = true;
36
- compilation.hooks.processAssets.tapPromise({ name: `${this.constructor.name}_CompileLoader`, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_REPORT }, () => this.collateAssets(compilation));
37
- }
38
- });
39
28
  compilation.hooks.processAssets.tapPromise({ name: this.constructor.name, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_ANALYSE }, async (assets) => {
40
29
  try {
41
30
  const specialAssetData = {};
@@ -71,6 +60,7 @@ class SpecialAssetHandlingPlugin {
71
60
  }
72
61
  catch (e) {
73
62
  SpecialAssetHandlingPlugin.semaphore.reject(this.id);
63
+ UnifiedLoaderGenerator_1.UnifiedLoaderGenerator.semaphore.reject(this.id);
74
64
  throw e;
75
65
  }
76
66
  });
@@ -94,7 +84,8 @@ class SpecialAssetHandlingPlugin {
94
84
  (0, shared_1.emitResolveBaseUriFunction)(writer);
95
85
  }
96
86
  writer.action("wp_head", writer => {
97
- writer.call("plaudit_webpack_extensions__resolve_base_uri", [php_writer_1.Expr.__DIR__], { assignTo: "$base_uri" }).closePHP();
87
+ const baseUriVar = new php_writer_1.Var("base_uri");
88
+ writer.call("plaudit_webpack_extensions__resolve_base_uri", [php_writer_1.Constants.__DIR__], { assignTo: baseUriVar }).closePHP();
98
89
  for (let [filename, { preload, fetchpriority, crossorigin }] of preloadedAssets) {
99
90
  if (!preload) {
100
91
  continue;
@@ -133,11 +124,14 @@ class SpecialAssetHandlingPlugin {
133
124
  attributes.push(["crossorigin", crossorigin]);
134
125
  }
135
126
  const dynamicAttrs = attributes.map(([k, v]) => v ? `${k}="${v}"` : k).join(" ");
136
- writer.append(`<link rel="preload" href="<?= esc_url($base_uri.'${filename}') ?>" ${dynamicAttrs}>`);
127
+ writer.append(`<link rel="preload" href="<?= ${php_writer_1.Expr.call("esc_url", [php_writer_1.Op.join(baseUriVar, filename)])} ?>" ${dynamicAttrs}>`);
137
128
  }
138
129
  writer.openPHP();
139
130
  });
140
131
  writer.emitAsset(compilation, outputFile);
141
132
  }
133
+ attachSecondPhase(compilation) {
134
+ compilation.hooks.processAssets.tapPromise({ name: this.constructor.name, stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_REPORT }, () => this.collateAssets(compilation));
135
+ }
142
136
  }
143
137
  exports.SpecialAssetHandlingPlugin = SpecialAssetHandlingPlugin;
package/build/shared.d.ts CHANGED
@@ -93,21 +93,6 @@ export declare function makeEmittableConfigPHP(data: any, asFullFile: boolean, p
93
93
  export type EntrypointFields = ["viewScriptModule", "scriptModule"] | ["editorStyle", "viewStyle", "style", "editorScript", "viewScript", "script"];
94
94
  export declare const entrypointFields: ReadonlyArray<EntrypointFields[number]>;
95
95
  export declare function convertEntrypointFieldForAssetType(entrypointField: EntrypointFields[number], assetType: 'script' | 'style'): EntrypointFields[number];
96
- export type Sync<V> = {
97
- sync: Promise<V>;
98
- resolve(v: V): void;
99
- reject(): void;
100
- done: boolean;
101
- };
102
- type Readiness<V> = {
103
- nonModule: Sync<V>;
104
- module: Sync<V>;
105
- };
106
- export declare class SyncsManager<V> {
107
- private readonly readinessMapping;
108
- get(name: string): Readiness<V>;
109
- private makeSync;
110
- }
111
96
  export declare function leadingSlashIt(pathOrSomething: string): string;
112
97
  export declare const scriptExtension: RegExp;
113
98
  export declare const scriptWithoutModuleExtension: RegExp;
package/build/shared.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.styleExtension = exports.scriptWithModuleExtension = exports.scriptWithoutModuleExtension = exports.scriptExtension = exports.SyncsManager = exports.entrypointFields = exports.standardLocationNames = void 0;
6
+ exports.styleExtension = exports.scriptWithModuleExtension = exports.scriptWithoutModuleExtension = exports.scriptExtension = exports.entrypointFields = exports.standardLocationNames = void 0;
7
7
  exports.isRawAssetData = isRawAssetData;
8
8
  exports.determineCurrentSourceType = determineCurrentSourceType;
9
9
  exports.packBlockEntrypointInfoForSmuggling = packBlockEntrypointInfoForSmuggling;
@@ -87,26 +87,6 @@ function convertEntrypointFieldForAssetType(entrypointField, assetType) {
87
87
  const searchRep = assetType === 'script' ? ['tyle', 'cript'] : ['cript', 'tyle'];
88
88
  return entrypointField.replace(...searchRep);
89
89
  }
90
- class SyncsManager {
91
- readinessMapping = new Map();
92
- get(name) {
93
- const res = this.readinessMapping.get(name);
94
- if (res) {
95
- return res;
96
- }
97
- this.readinessMapping.set(name, { nonModule: this.makeSync(), module: this.makeSync() });
98
- return this.readinessMapping.get(name);
99
- }
100
- makeSync() {
101
- const res = { done: false };
102
- res.sync = new Promise((resolve, reject) => {
103
- res.resolve = (v) => resolve(v);
104
- res.reject = () => reject();
105
- });
106
- return res;
107
- }
108
- }
109
- exports.SyncsManager = SyncsManager;
110
90
  function leadingSlashIt(pathOrSomething) {
111
91
  return pathOrSomething.startsWith('/') ? pathOrSomething : ('/' + pathOrSomething);
112
92
  }
@@ -154,19 +134,23 @@ function newWebpackErrorForFile(error, file) {
154
134
  * The primary benefit of emitting a function instead of baking its contents into each function that uses it is that it allows us to avoid recomputing the base uri multiple times
155
135
  */
156
136
  function emitResolveBaseUriFunction(writer) {
157
- writer.function("plaudit_webpack_extensions__resolve_base_uri", ["$dir"], writer => {
137
+ const dir = new php_writer_1.Var("dir");
138
+ const baseUris = new php_writer_1.Var("base_uris");
139
+ const assignmentTarget = new php_writer_1.ArrayAccess(baseUris, dir);
140
+ const path = new php_writer_1.Var("path");
141
+ writer.function("plaudit_webpack_extensions__resolve_base_uri", [dir], writer => {
158
142
  writer
159
- .static("$base_uris", { initializer: [] })
160
- .if("isset($base_uris[$dir])")
161
- .return(new php_writer_1.Expr("$base_uris[$dir]"))
162
- .elseIf("str_starts_with($dir, ABSPATH)")
163
- .append("$path = ltrim(substr($dir, strlen(ABSPATH)), '/');")
164
- .elseIf("str_starts_with($dir, '/workspace/website')")
165
- .append("$path = ltrim(substr($dir, 18), '/');")
143
+ .static(baseUris, { initializer: [] })
144
+ .if(php_writer_1.Expr.isset(assignmentTarget))
145
+ .return(assignmentTarget)
146
+ .elseIf(php_writer_1.Expr.call("str_starts_with", [dir, php_writer_1.Constants.ABSPATH]))
147
+ .assign(path, php_writer_1.Expr.call("ltrim", [php_writer_1.Expr.call("substr", [dir, php_writer_1.Expr.call("strlen", [php_writer_1.Constants.ABSPATH])]), "/"]))
148
+ .elseIf(php_writer_1.Expr.call("str_starts_with", [dir, "/workspace/website"]))
149
+ .assign(path, php_writer_1.Expr.call("ltrim", [php_writer_1.Expr.call("substr", [dir, 18]), "/"]))
166
150
  .else()
167
151
  .call("error_log", ["UNABLE TO FIGURE OUT WHAT THE RELATIVE PATH TO THE BUILT FILES DIRECTORY SHOULD BE"])
168
- .append("$path = '';")
152
+ .assign(path, "")
169
153
  .endIf()
170
- .call("trailingslashit", [new php_writer_1.Expr("home_url($path)")], { return: true, assignTo: "$base_uris[$dir]" });
154
+ .call("trailingslashit", [php_writer_1.Expr.call("home_url", [path])], { return: true, assignTo: assignmentTarget });
171
155
  }, { returnType: "string", includeExistenceCheck: true });
172
156
  }
@@ -1,23 +1,125 @@
1
1
  import { AssetInfo, Compilation } from "webpack";
2
- export declare class Expr {
3
- private readonly value;
4
- private readonly raw;
2
+ export declare abstract class Expr {
5
3
  static readonly jsonToPHPConverter: (obj: unknown, parentIndent?: string) => string;
6
4
  static readonly convertJsonToPHP: (obj: unknown) => string;
7
- static readonly __FILE__: Expr;
8
- static readonly __DIR__: Expr;
9
- constructor(value: string, raw?: boolean);
5
+ protected constructor();
6
+ abstract toString(): string;
7
+ typeName(): string;
8
+ static isset(...checks: (Var | ArrayAccess | ObjectAccess)[]): Call;
9
+ static call(name: string, args: ConstructorParameters<typeof Call>[1]): Call;
10
+ }
11
+ export interface EnclosableExpression extends Expr {
12
+ toEnclosedForm(): string;
13
+ not(): Not;
14
+ }
15
+ export interface PotentiallyWriteableExpression extends EnclosableExpression {
16
+ readonly potentiallyWritable: true;
17
+ }
18
+ export declare function isEnclosableExpression(a: unknown): a is EnclosableExpression;
19
+ export declare function isPotentiallyWriteableExpression(a: unknown): a is PotentiallyWriteableExpression;
20
+ export declare abstract class AbstractEnclosableExpression extends Expr implements EnclosableExpression {
21
+ abstract toEnclosedForm(): string;
22
+ not(): Not;
23
+ }
24
+ export declare abstract class ParenthesesEnclosableExpression extends AbstractEnclosableExpression {
25
+ toEnclosedForm(): string;
26
+ }
27
+ export declare abstract class EnclosedExpression extends AbstractEnclosableExpression {
28
+ toEnclosedForm(): string;
29
+ }
30
+ export declare class Literal extends Expr {
31
+ readonly expression: string;
32
+ constructor(expression: string);
33
+ toString(): string;
34
+ static make(expression: string, enclosed: true): EnclosedLiteral;
35
+ static make(expression: string, enclosureOpen: string, encloserClose: string): EnclosableLiteral;
36
+ static make(expression: string, enclosed?: false | undefined): Literal;
37
+ static name(expression: string): EnclosedLiteral;
38
+ }
39
+ export declare class EnclosedLiteral extends Literal implements EnclosableExpression {
40
+ constructor(expression: string);
41
+ toEnclosedForm(): string;
42
+ not(): Not;
43
+ }
44
+ export declare class EnclosableLiteral extends Literal implements EnclosableExpression {
45
+ private readonly enclosureOpen;
46
+ private readonly enclosureClose;
47
+ constructor(expression: string, enclosureOpen: string, enclosureClose: string);
48
+ toEnclosedForm(): string;
49
+ not(): Not;
50
+ }
51
+ export declare class Var extends EnclosedExpression implements PotentiallyWriteableExpression {
52
+ readonly name: string;
53
+ readonly potentiallyWritable = true;
54
+ constructor(name: string);
55
+ toString(): string;
56
+ }
57
+ export declare class Op extends ParenthesesEnclosableExpression {
58
+ readonly operator: string;
59
+ readonly args: readonly unknown[];
60
+ constructor(operator: string, ...args: unknown[]);
61
+ toString(): string;
62
+ static binary(left: unknown, operator: string, right: unknown): Op;
63
+ static join(...args: unknown[]): Op;
64
+ }
65
+ export declare class Not extends ParenthesesEnclosableExpression {
66
+ readonly expression: EnclosableExpression;
67
+ constructor(expression: EnclosableExpression);
68
+ toString(): string;
69
+ }
70
+ type AtLeastOneArray<T> = [T, ...T[]];
71
+ type ReadonlyAtLeastOneArray<T> = readonly [T, ...T[]];
72
+ export type Accessor = Expr | string | number;
73
+ export type AccessorOrAccessorArray = Accessor | AtLeastOneArray<Accessor>;
74
+ export declare abstract class Access extends EnclosedExpression implements PotentiallyWriteableExpression {
75
+ readonly target: EnclosableExpression;
76
+ readonly potentiallyWritable = true;
77
+ readonly accesses: ReadonlyAtLeastOneArray<Accessor>;
78
+ constructor(target: EnclosableExpression, accesses: AccessorOrAccessorArray);
79
+ abstract endsWithCall(): boolean;
80
+ abstract endsWithPotentiallyWritableExpression(): boolean;
81
+ }
82
+ export declare class ArrayAccess extends Access {
10
83
  toString(): string;
84
+ endsWithCall(): boolean;
85
+ endsWithPotentiallyWritableExpression(): boolean;
86
+ }
87
+ export declare class ObjectAccess extends Access {
88
+ static readonly validObjectKey: RegExp;
89
+ toString(): string;
90
+ endsWithCall(): boolean;
91
+ endsWithPotentiallyWritableExpression(): boolean;
92
+ }
93
+ export declare class Call extends EnclosedExpression implements PotentiallyWriteableExpression {
94
+ readonly callee: string | EnclosableExpression;
95
+ readonly args: readonly unknown[];
96
+ readonly potentiallyWritable = true;
97
+ constructor(callee: string | EnclosableExpression, args: readonly unknown[]);
98
+ toString(): string;
99
+ }
100
+ type Assignable = EnclosedExpression & PotentiallyWriteableExpression;
101
+ export declare class Assignment extends ParenthesesEnclosableExpression {
102
+ readonly value: unknown;
103
+ readonly push: boolean;
104
+ readonly assignees: ReadonlyAtLeastOneArray<Assignable>;
105
+ constructor(assignees: Assignable, value: unknown, push: true);
106
+ constructor(assignees: Assignable | AtLeastOneArray<Assignable>, value: unknown, push?: false | undefined);
107
+ toString(): string;
108
+ }
109
+ export declare abstract class Constants {
110
+ static readonly __FILE__: EnclosedLiteral;
111
+ static readonly __DIR__: EnclosedLiteral;
112
+ static readonly ABSPATH: EnclosedLiteral;
11
113
  }
12
114
  export type ActionOrFilterArgs = {
13
115
  priority?: number | Expr;
14
116
  functionArgParameters?: string[];
15
- useVars?: string[];
117
+ useVars?: Var[];
16
118
  accountForAlreadyDoing?: boolean | Parameters<PHPWriter['call']>[1];
17
119
  };
18
120
  export type FunctionCreationArgs = {
19
121
  includeExistenceCheck?: boolean;
20
- useVars?: string[];
122
+ useVars?: Var[];
21
123
  returnType?: string;
22
124
  assignToName?: boolean;
23
125
  scopeActionDescription?: string;
@@ -39,31 +141,33 @@ export declare class PHPWriter {
39
141
  outdent(): this;
40
142
  setIndentation(level: number): this;
41
143
  append(...lines: (string | Expr)[]): this;
42
- assign(variable: string | string[], expression: unknown | Expr, opts?: {
144
+ assign(assignee: ConstructorParameters<typeof Assignment>[0] | string, expression: unknown, opts?: {
43
145
  chain?: boolean;
44
146
  return?: boolean;
45
147
  }): this;
46
148
  return(expression: unknown | Expr): this;
47
- static(variable: string, opts?: {
48
- initializer?: unknown | Expr;
149
+ static(variable: Var | string, opts?: {
150
+ initializer?: unknown | Literal;
49
151
  withTest?: boolean | 'chainable';
50
152
  }): this;
51
153
  linebreak(): this;
52
- call(func: string, args: unknown[], opts?: {
154
+ call(func: string | EnclosableExpression, args: unknown[], opts?: {
53
155
  chain?: boolean;
54
- assignTo?: string | string[];
156
+ assignTo?: ConstructorParameters<typeof Assignment>[0];
55
157
  return?: boolean;
56
158
  }): this;
57
159
  action(name: string | Expr, contents: (writer: PHPWriter) => void, args?: ActionOrFilterArgs): this;
58
160
  filter(name: string | Expr, contents: (writer: PHPWriter) => void, args?: ActionOrFilterArgs): this;
59
161
  actionOrFilter(type: 'action' | 'filter', name: string | Expr, contents: (writer: PHPWriter) => void, args: ActionOrFilterArgs): this;
60
- if(condition: string): this;
61
- elseIf(condition: string): this;
162
+ if(condition: Expr): this;
163
+ elseIf(condition: Expr): this;
62
164
  else(): this;
63
165
  endIf(): this;
64
- function(name: true, parameters: string[], body: (writer: PHPWriter) => void, args?: FunctionCreationArgs): string;
65
- function(name: string | false, parameters: string[], body: (writer: PHPWriter) => void, args?: FunctionCreationArgs): this;
66
- generateFunctionName(asVariable?: boolean): string;
166
+ function(name: true, parameters: (string | Var)[], body: (writer: PHPWriter) => void, args?: FunctionCreationArgs): Var;
167
+ function(name: string | Var | false, parameters: (string | Var)[], body: (writer: PHPWriter) => void, args?: FunctionCreationArgs): this;
168
+ generateFunctionName(asVariable: true): Var;
169
+ generateFunctionName(asVariable?: false | undefined): string;
170
+ generateFunctionName(asVariable?: boolean): string | Var;
67
171
  closePHP(): this;
68
172
  openPHP(): this;
69
173
  namespace(namespace: string): this;
@@ -91,4 +195,11 @@ export declare class PHPWriter {
91
195
  includeNamespaceAndUse?: boolean;
92
196
  }): string;
93
197
  emitAsset(compilation: Compilation, file: string, assetInfo?: AssetInfo): void;
198
+ /**
199
+ * @param expr Unlike most other methods on this class, this is treated as literal *regardless of the argument's type*
200
+ * @param opts
201
+ * @private
202
+ */
203
+ private appendWithPossibleReturnAndChain;
94
204
  }
205
+ export {};