@powerlines/engine 0.0.2

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 (70) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +303 -0
  3. package/dist/_internal/worker.cjs +4824 -0
  4. package/dist/_internal/worker.d.cts +38 -0
  5. package/dist/_internal/worker.d.cts.map +1 -0
  6. package/dist/_internal/worker.d.mts +38 -0
  7. package/dist/_internal/worker.d.mts.map +1 -0
  8. package/dist/_internal/worker.mjs +4785 -0
  9. package/dist/_internal/worker.mjs.map +1 -0
  10. package/dist/api.cjs +1265 -0
  11. package/dist/api.d.cts +265 -0
  12. package/dist/api.d.cts.map +1 -0
  13. package/dist/api.d.mts +265 -0
  14. package/dist/api.d.mts.map +1 -0
  15. package/dist/api.mjs +1261 -0
  16. package/dist/api.mjs.map +1 -0
  17. package/dist/base-context-BUnL_9z8.mjs +241 -0
  18. package/dist/base-context-BUnL_9z8.mjs.map +1 -0
  19. package/dist/base-context-CFvO2N9I.cjs +248 -0
  20. package/dist/chunk-C0xms8kb.cjs +34 -0
  21. package/dist/context/index.cjs +11 -0
  22. package/dist/context/index.d.cts +658 -0
  23. package/dist/context/index.d.cts.map +1 -0
  24. package/dist/context/index.d.mts +658 -0
  25. package/dist/context/index.d.mts.map +1 -0
  26. package/dist/context/index.mjs +5 -0
  27. package/dist/engine-context-BuD9AGfd.mjs +41 -0
  28. package/dist/engine-context-BuD9AGfd.mjs.map +1 -0
  29. package/dist/engine-context-NO6enYev.cjs +45 -0
  30. package/dist/execution-context-BxANz9k2.cjs +2600 -0
  31. package/dist/execution-context-CNhvjS52.mjs +2556 -0
  32. package/dist/execution-context-CNhvjS52.mjs.map +1 -0
  33. package/dist/fs-D1nIP45P.mjs +226 -0
  34. package/dist/fs-D1nIP45P.mjs.map +1 -0
  35. package/dist/fs-XogSgMqT.cjs +262 -0
  36. package/dist/index.cjs +569 -0
  37. package/dist/index.d.cts +126 -0
  38. package/dist/index.d.cts.map +1 -0
  39. package/dist/index.d.mts +126 -0
  40. package/dist/index.d.mts.map +1 -0
  41. package/dist/index.mjs +568 -0
  42. package/dist/index.mjs.map +1 -0
  43. package/dist/schemas.cjs +9 -0
  44. package/dist/schemas.d.cts +127 -0
  45. package/dist/schemas.d.cts.map +1 -0
  46. package/dist/schemas.d.mts +127 -0
  47. package/dist/schemas.d.mts.map +1 -0
  48. package/dist/schemas.mjs +3 -0
  49. package/dist/storage/index.cjs +9 -0
  50. package/dist/storage/index.d.cts +419 -0
  51. package/dist/storage/index.d.cts.map +1 -0
  52. package/dist/storage/index.d.mts +419 -0
  53. package/dist/storage/index.d.mts.map +1 -0
  54. package/dist/storage/index.mjs +3 -0
  55. package/dist/ts-morph-BaLPVAdB.cjs +114 -0
  56. package/dist/ts-morph-D0CaA37w.mjs +102 -0
  57. package/dist/ts-morph-D0CaA37w.mjs.map +1 -0
  58. package/dist/tsconfig-Cstsoprg.mjs +155 -0
  59. package/dist/tsconfig-Cstsoprg.mjs.map +1 -0
  60. package/dist/tsconfig-DeyWQC2N.cjs +198 -0
  61. package/dist/typescript/index.cjs +13 -0
  62. package/dist/typescript/index.d.cts +106 -0
  63. package/dist/typescript/index.d.cts.map +1 -0
  64. package/dist/typescript/index.d.mts +106 -0
  65. package/dist/typescript/index.d.mts.map +1 -0
  66. package/dist/typescript/index.mjs +4 -0
  67. package/dist/virtual-BNdKVkRw.cjs +548 -0
  68. package/dist/virtual-gIlTc3Lj.mjs +513 -0
  69. package/dist/virtual-gIlTc3Lj.mjs.map +1 -0
  70. package/package.json +183 -0
@@ -0,0 +1,4785 @@
1
+ #!/usr/bin/env -S NODE_OPTIONS=--enable-source-maps node
2
+ import { colorText, createLog, extendLog } from "@powerlines/core/lib/logger";
3
+ import { getFileHeaderWarningText, getTypescriptFileHeader } from "@powerlines/core/lib/utilities/file-header";
4
+ import { format, formatFolder } from "@powerlines/core/lib/utilities/format";
5
+ import { addPluginHook, dedupeHooklist, findInvalidPluginConfig, isDuplicate, isPlugin, isPluginConfig, isPluginConfigObject, isPluginConfigTuple, isPluginHook, isPluginHookField, mergeConfig, replacePathTokens } from "@powerlines/core/plugin-utils";
6
+ import { formatLogMessage } from "@storm-software/config-tools/logger/console";
7
+ import { toArray } from "@stryke/convert/to-array";
8
+ import { copyFiles } from "@stryke/fs/copy-file";
9
+ import { exists, existsSync } from "@stryke/fs/exists";
10
+ import { createDirectory, createDirectorySync, removeDirectory } from "@stryke/fs/helpers";
11
+ import { install } from "@stryke/fs/install";
12
+ import { listFiles, listFilesSync } from "@stryke/fs/list-files";
13
+ import { doesPackageMatch, getPackageListing, isPackageExists, isPackageListed } from "@stryke/fs/package-fns";
14
+ import { getResolutionCombinations, resolve, resolvePackage, resolveSync } from "@stryke/fs/resolve";
15
+ import { getUnique, getUniqueBy } from "@stryke/helpers/get-unique";
16
+ import { omit } from "@stryke/helpers/omit";
17
+ import { appendPath } from "@stryke/path/append";
18
+ import { findFileDotExtensionSafe, findFileExtensionSafe, findFileName, findFilePath, hasFileExtension, relativePath } from "@stryke/path/file-path-fns";
19
+ import { isParentPath } from "@stryke/path/is-parent-path";
20
+ import { joinPaths } from "@stryke/path/join-paths";
21
+ import { replaceExtension, replacePath } from "@stryke/path/replace";
22
+ import { titleCase } from "@stryke/string-format/title-case";
23
+ import { isError } from "@stryke/type-checks/is-error";
24
+ import { isFunction } from "@stryke/type-checks/is-function";
25
+ import { isNumber } from "@stryke/type-checks/is-number";
26
+ import { isObject } from "@stryke/type-checks/is-object";
27
+ import { isPromiseLike } from "@stryke/type-checks/is-promise";
28
+ import { isSet } from "@stryke/type-checks/is-set";
29
+ import { isSetObject } from "@stryke/type-checks/is-set-object";
30
+ import { isSetString } from "@stryke/type-checks/is-set-string";
31
+ import { isString } from "@stryke/type-checks/is-string";
32
+ import chalk from "chalk";
33
+ import defu, { createDefu, defu as defu$1 } from "defu";
34
+ import Handlebars from "handlebars";
35
+ import { CACHE_HASH_LENGTH, DEFAULT_ENVIRONMENT, GLOBAL_ENVIRONMENT, PLUGIN_NON_HOOK_FIELDS, ROOT_HASH_LENGTH } from "@powerlines/core/constants";
36
+ import { readJsonFile, readJsonFileSync } from "@stryke/fs/json";
37
+ import { joinPaths as joinPaths$1 } from "@stryke/path/join";
38
+ import { getUniqueInputs, isTypeDefinition, resolveInputsSync } from "@powerlines/core/lib/entry";
39
+ import { relativeToWorkspaceRoot } from "@stryke/fs/get-workspace-root";
40
+ import { murmurhash } from "@stryke/hash";
41
+ import { hashDirectory } from "@stryke/hash/node";
42
+ import { deepClone } from "@stryke/helpers/deep-clone";
43
+ import { fetchRequest } from "@stryke/http/fetch";
44
+ import { kebabCase } from "@stryke/string-format/kebab-case";
45
+ import { isNull } from "@stryke/type-checks/is-null";
46
+ import { uuid } from "@stryke/unique-id/uuid";
47
+ import { match, tsconfigPathsToRegExp } from "bundle-require";
48
+ import { resolveCompatibilityDates } from "compatx";
49
+ import { create } from "flat-cache";
50
+ import { parse } from "oxc-parser";
51
+ import { Agent, Response, interceptors, setGlobalDispatcher } from "undici";
52
+ import "@stryke/fs/remove-file";
53
+ import { LogLevelLabel } from "@storm-software/config-tools/types";
54
+ import * as $ from "@stryke/capnp";
55
+ import { readFileBuffer, readFileBufferSync, writeFileBuffer } from "@stryke/fs/buffer";
56
+ import { correctPath, stripStars } from "@stryke/path/correct-path";
57
+ import { globToRegex } from "@stryke/path/glob-to-regex";
58
+ import { isAbsolutePath } from "@stryke/path/is-type";
59
+ import { slash } from "@stryke/path/slash";
60
+ import { prettyBytes } from "@stryke/string-format/pretty-bytes";
61
+ import { isRegExp } from "@stryke/type-checks/is-regexp";
62
+ import { Blob as Blob$1 } from "node:buffer";
63
+ import { fileURLToPath } from "node:url";
64
+ import { isDirectory, isFile } from "@stryke/fs/is-file";
65
+ import { readFile, readFileSync } from "@stryke/fs/read-file";
66
+ import { writeFile, writeFileSync } from "@stryke/fs/write-file";
67
+ import { unlinkSync } from "node:fs";
68
+ import { unlink } from "node:fs/promises";
69
+ import { resolve as resolve$1 } from "node:path";
70
+ import ts from "typescript";
71
+ import { loadUserConfigFile } from "@powerlines/core/lib/config";
72
+ import { getEnvPaths } from "@stryke/env/get-env-paths";
73
+ import { StormJSON } from "@stryke/json/storm-json";
74
+ import { formatDistanceToNowStrict } from "date-fns/formatDistanceToNowStrict";
75
+ import { createJiti } from "jiti";
76
+ import { getField } from "@stryke/helpers/get-field";
77
+ import { DiagnosticCategory, InMemoryFileSystemHost, Node, Project } from "ts-morph";
78
+ import { getPackageName, getPackageVersion, hasPackageVersion } from "@stryke/string-format/package";
79
+ import { getObjectDiff } from "@donedeal0/superdiff";
80
+
81
+ //#region src/_internal/helpers/environment.ts
82
+ function createEnvironment(name, userConfig) {
83
+ return defu(userConfig.environments?.[name] ?? {}, {
84
+ name,
85
+ title: userConfig.title || titleCase(userConfig.name),
86
+ ssr: false,
87
+ mainFields: userConfig?.platform === "browser" ? [
88
+ "browser",
89
+ "module",
90
+ "jsnext:main",
91
+ "jsnext"
92
+ ] : [
93
+ "module",
94
+ "jsnext:main",
95
+ "jsnext"
96
+ ],
97
+ extensions: [
98
+ ".mjs",
99
+ ".js",
100
+ ".mts",
101
+ ".ts",
102
+ ".jsx",
103
+ ".tsx",
104
+ ".json"
105
+ ],
106
+ consumer: userConfig?.platform === "browser" ? "client" : "server",
107
+ preview: userConfig?.platform === "browser" ? {
108
+ port: 5173,
109
+ open: true,
110
+ strictPort: false,
111
+ host: "localhost",
112
+ allowedHosts: ["."],
113
+ cors: true,
114
+ headers: {}
115
+ } : void 0
116
+ }, userConfig);
117
+ }
118
+ function createDefaultEnvironment(userConfig) {
119
+ return createEnvironment(DEFAULT_ENVIRONMENT, userConfig);
120
+ }
121
+
122
+ //#endregion
123
+ //#region src/_internal/helpers/meta.ts
124
+ /**
125
+ * Generates a prefixed project root hash object.
126
+ *
127
+ * @remarks
128
+ * This function returns a string where the project root hash is prefixed with the project name plus a hyphen. If the total length of this string combination exceeds 45 characters, it will truncate the hash.
129
+ *
130
+ * @param name - The name of the project.
131
+ * @param rootHash - The hash of the project root.
132
+ * @returns An object containing the name and project root hash.
133
+ */
134
+ function getPrefixedRootHash(name, rootHash) {
135
+ const combined = `${kebabCase(name)}_${rootHash}`;
136
+ return combined.length > ROOT_HASH_LENGTH ? combined.slice(0, ROOT_HASH_LENGTH) : combined;
137
+ }
138
+ /**
139
+ * Writes the meta file for the context.
140
+ *
141
+ * @param context - The context to write the meta file for.
142
+ * @returns A promise that resolves when the meta file has been written.
143
+ */
144
+ async function writeMetaFile(context) {
145
+ const metaFilePath = joinPaths(context.dataPath, "meta.json");
146
+ context.debug(`Writing runtime metadata to ${metaFilePath}`);
147
+ await context.fs.write(metaFilePath, JSON.stringify(context.meta, null, 2));
148
+ }
149
+
150
+ //#endregion
151
+ //#region schemas/fs.ts
152
+ var FileMetadata_KeyValuePair = class extends $.Struct {
153
+ static _capnp = {
154
+ displayName: "KeyValuePair",
155
+ id: "eabb26cf58b2a14c",
156
+ size: new $.ObjectSize(0, 2)
157
+ };
158
+ get key() {
159
+ return $.utils.getText(0, this);
160
+ }
161
+ set key(value) {
162
+ $.utils.setText(0, value, this);
163
+ }
164
+ get value() {
165
+ return $.utils.getText(1, this);
166
+ }
167
+ set value(value) {
168
+ $.utils.setText(1, value, this);
169
+ }
170
+ toString() {
171
+ return "FileMetadata_KeyValuePair_" + super.toString();
172
+ }
173
+ };
174
+ /**
175
+ * The identifier for the file data.
176
+ *
177
+ */
178
+ var FileMetadata = class FileMetadata extends $.Struct {
179
+ static KeyValuePair = FileMetadata_KeyValuePair;
180
+ static _capnp = {
181
+ displayName: "FileMetadata",
182
+ id: "8e2cab5d7e28c7b3",
183
+ size: new $.ObjectSize(8, 3),
184
+ defaultType: "normal"
185
+ };
186
+ static _Properties;
187
+ /**
188
+ * The type of the file.
189
+ *
190
+ */
191
+ get id() {
192
+ return $.utils.getText(0, this);
193
+ }
194
+ set id(value) {
195
+ $.utils.setText(0, value, this);
196
+ }
197
+ /**
198
+ * The timestamp representing the file's creation date.
199
+ *
200
+ */
201
+ get type() {
202
+ return $.utils.getText(1, this, FileMetadata._capnp.defaultType);
203
+ }
204
+ set type(value) {
205
+ $.utils.setText(1, value, this);
206
+ }
207
+ /**
208
+ * Additional metadata associated with the file.
209
+ *
210
+ */
211
+ get timestamp() {
212
+ return $.utils.getUint32(0, this);
213
+ }
214
+ set timestamp(value) {
215
+ $.utils.setUint32(0, value, this);
216
+ }
217
+ _adoptProperties(value) {
218
+ $.utils.adopt(value, $.utils.getPointer(2, this));
219
+ }
220
+ _disownProperties() {
221
+ return $.utils.disown(this.properties);
222
+ }
223
+ get properties() {
224
+ return $.utils.getList(2, FileMetadata._Properties, this);
225
+ }
226
+ _hasProperties() {
227
+ return !$.utils.isNull($.utils.getPointer(2, this));
228
+ }
229
+ _initProperties(length) {
230
+ return $.utils.initList(2, FileMetadata._Properties, length, this);
231
+ }
232
+ set properties(value) {
233
+ $.utils.copyFrom(value, $.utils.getPointer(2, this));
234
+ }
235
+ toString() {
236
+ return "FileMetadata_" + super.toString();
237
+ }
238
+ };
239
+ /**
240
+ * An identifier for the file.
241
+ *
242
+ */
243
+ var FileId = class extends $.Struct {
244
+ static _capnp = {
245
+ displayName: "FileId",
246
+ id: "990d6a471072f997",
247
+ size: new $.ObjectSize(0, 2)
248
+ };
249
+ /**
250
+ * A virtual (or actual) path to the file in the file system.
251
+ *
252
+ */
253
+ get id() {
254
+ return $.utils.getText(0, this);
255
+ }
256
+ set id(value) {
257
+ $.utils.setText(0, value, this);
258
+ }
259
+ get path() {
260
+ return $.utils.getText(1, this);
261
+ }
262
+ set path(value) {
263
+ $.utils.setText(1, value, this);
264
+ }
265
+ toString() {
266
+ return "FileId_" + super.toString();
267
+ }
268
+ };
269
+ /**
270
+ * An identifier for the file.
271
+ *
272
+ */
273
+ var FileStorage = class extends $.Struct {
274
+ static _capnp = {
275
+ displayName: "FileStorage",
276
+ id: "9dca66ac858c9ebe",
277
+ size: new $.ObjectSize(0, 2)
278
+ };
279
+ /**
280
+ * A virtual (or actual) path to the file in the file system.
281
+ *
282
+ */
283
+ get path() {
284
+ return $.utils.getText(0, this);
285
+ }
286
+ set path(value) {
287
+ $.utils.setText(0, value, this);
288
+ }
289
+ get code() {
290
+ return $.utils.getText(1, this);
291
+ }
292
+ set code(value) {
293
+ $.utils.setText(1, value, this);
294
+ }
295
+ toString() {
296
+ return "FileStorage_" + super.toString();
297
+ }
298
+ };
299
+ var FileSystem = class FileSystem extends $.Struct {
300
+ static _capnp = {
301
+ displayName: "FileSystem",
302
+ id: "ae0c23d43e56abcf",
303
+ size: new $.ObjectSize(0, 3)
304
+ };
305
+ static _Ids;
306
+ static _Storage;
307
+ static _Metadata;
308
+ _adoptIds(value) {
309
+ $.utils.adopt(value, $.utils.getPointer(0, this));
310
+ }
311
+ _disownIds() {
312
+ return $.utils.disown(this.ids);
313
+ }
314
+ get ids() {
315
+ return $.utils.getList(0, FileSystem._Ids, this);
316
+ }
317
+ _hasIds() {
318
+ return !$.utils.isNull($.utils.getPointer(0, this));
319
+ }
320
+ _initIds(length) {
321
+ return $.utils.initList(0, FileSystem._Ids, length, this);
322
+ }
323
+ set ids(value) {
324
+ $.utils.copyFrom(value, $.utils.getPointer(0, this));
325
+ }
326
+ _adoptStorage(value) {
327
+ $.utils.adopt(value, $.utils.getPointer(1, this));
328
+ }
329
+ _disownStorage() {
330
+ return $.utils.disown(this.storage);
331
+ }
332
+ get storage() {
333
+ return $.utils.getList(1, FileSystem._Storage, this);
334
+ }
335
+ _hasStorage() {
336
+ return !$.utils.isNull($.utils.getPointer(1, this));
337
+ }
338
+ _initStorage(length) {
339
+ return $.utils.initList(1, FileSystem._Storage, length, this);
340
+ }
341
+ set storage(value) {
342
+ $.utils.copyFrom(value, $.utils.getPointer(1, this));
343
+ }
344
+ _adoptMetadata(value) {
345
+ $.utils.adopt(value, $.utils.getPointer(2, this));
346
+ }
347
+ _disownMetadata() {
348
+ return $.utils.disown(this.metadata);
349
+ }
350
+ get metadata() {
351
+ return $.utils.getList(2, FileSystem._Metadata, this);
352
+ }
353
+ _hasMetadata() {
354
+ return !$.utils.isNull($.utils.getPointer(2, this));
355
+ }
356
+ _initMetadata(length) {
357
+ return $.utils.initList(2, FileSystem._Metadata, length, this);
358
+ }
359
+ set metadata(value) {
360
+ $.utils.copyFrom(value, $.utils.getPointer(2, this));
361
+ }
362
+ toString() {
363
+ return "FileSystem_" + super.toString();
364
+ }
365
+ };
366
+ FileMetadata._Properties = $.CompositeList(FileMetadata_KeyValuePair);
367
+ FileSystem._Ids = $.CompositeList(FileId);
368
+ FileSystem._Storage = $.CompositeList(FileStorage);
369
+ FileSystem._Metadata = $.CompositeList(FileMetadata);
370
+
371
+ //#endregion
372
+ //#region src/storage/base.ts
373
+ /**
374
+ * Abstract base class for storage adapters, providing a template for storage operations.
375
+ */
376
+ var BaseStorageAdapter = class {
377
+ /**
378
+ * Indicates whether the storage adapter has been disposed.
379
+ */
380
+ #isDisposed = false;
381
+ /**
382
+ * Configuration options for the storage adapter.
383
+ */
384
+ options;
385
+ /**
386
+ * The storage preset for the adapter.
387
+ *
388
+ * @remarks
389
+ * This can be used as an alternate way to identify the type of storage being used.
390
+ */
391
+ preset = null;
392
+ /**
393
+ * Constructor for the BaseStorageAdapter.
394
+ *
395
+ * @param context - The Powerlines context.
396
+ * @param options - Configuration options for the storage adapter.
397
+ */
398
+ constructor(context, options = { base: "/" }) {
399
+ this.context = context;
400
+ this.options = options;
401
+ this.options.base = resolve$1(options.base);
402
+ this.options.isReadOnly = !!options.isReadOnly;
403
+ }
404
+ /**
405
+ * Asynchronously checks if a key exists in the storage.
406
+ *
407
+ * @param key - The key to check for existence.
408
+ * @returns A promise that resolves to `true` if the key exists, otherwise `false`.
409
+ */
410
+ async exists(key) {
411
+ return this.existsSync(key);
412
+ }
413
+ /**
414
+ * Asynchronously retrieves the value associated with a given key.
415
+ *
416
+ * @param key - The key whose value is to be retrieved.
417
+ * @returns A promise that resolves to the value associated with the key, or `null` if the key does not exist.
418
+ */
419
+ async get(key) {
420
+ return this.getSync(key);
421
+ }
422
+ /**
423
+ * Asynchronously sets the value for a given key.
424
+ *
425
+ * @param key - The key to set the value for.
426
+ * @param value - The value to set.
427
+ */
428
+ async set(key, value) {
429
+ if (!this.isReadOnly && (!this.existsSync(key) || this.overwrite)) this.setSync(key, value);
430
+ }
431
+ /**
432
+ * Synchronously creates a directory at the specified path.
433
+ *
434
+ * @param _ - The path of the directory to create.
435
+ */
436
+ mkdirSync(_) {}
437
+ /**
438
+ * Creates a directory at the specified path.
439
+ *
440
+ * @param dirPath - The path of the directory to create.
441
+ */
442
+ async mkdir(dirPath) {
443
+ return Promise.resolve(this.mkdirSync(dirPath));
444
+ }
445
+ /**
446
+ * Asynchronously removes a key from the storage.
447
+ *
448
+ * @param key - The key to remove.
449
+ */
450
+ async remove(key) {
451
+ if (!this.isReadOnly && this.overwrite) this.removeSync(key);
452
+ }
453
+ /**
454
+ * Synchronously removes all entries from the storage that match the provided base path.
455
+ *
456
+ * @param base - The base path to clear keys from.
457
+ */
458
+ clearSync(base) {
459
+ if (!this.isReadOnly && this.overwrite) {
460
+ const keys = this.listSync(base || this.options.base);
461
+ if (!keys.length) return;
462
+ keys.map((key) => this.removeSync(base && !key.startsWith(base) ? joinPaths$1(base, key) : key));
463
+ }
464
+ }
465
+ /**
466
+ * Asynchronously removes all entries from the storage that match the provided base path.
467
+ *
468
+ * @param base - The base path to clear keys from.
469
+ * @returns A promise that resolves when the operation is complete.
470
+ */
471
+ async clear(base) {
472
+ if (!this.isReadOnly && this.overwrite) {
473
+ const keys = await this.list(base || this.options.base);
474
+ if (!keys.length) return;
475
+ await Promise.all(keys.map(async (key) => this.remove(base && !key.startsWith(base) ? joinPaths$1(base, key) : key)));
476
+ }
477
+ }
478
+ /**
479
+ * Asynchronously lists all keys under a given base path.
480
+ *
481
+ * @param base - The base path to list keys from.
482
+ * @returns A promise that resolves to an array of keys under the specified base path.
483
+ */
484
+ async list(base) {
485
+ return this.listSync(base);
486
+ }
487
+ /**
488
+ * Synchronously checks if the given key is a directory.
489
+ *
490
+ * @param _ - The key to check.
491
+ * @returns `true` if the key is a directory, otherwise `false`.
492
+ */
493
+ isDirectorySync(_) {
494
+ return false;
495
+ }
496
+ /**
497
+ * Checks if the given key is a directory.
498
+ *
499
+ * @param key - The key to check.
500
+ * @returns A promise that resolves to `true` if the key is a directory, otherwise `false`.
501
+ */
502
+ async isDirectory(key) {
503
+ return Promise.resolve(this.isDirectorySync(key));
504
+ }
505
+ /**
506
+ * Synchronously checks if the given key is a file.
507
+ *
508
+ * @param key - The key to check.
509
+ * @returns `true` if the key is a file, otherwise `false`.
510
+ */
511
+ isFileSync(key) {
512
+ return this.existsSync(key) && !this.isDirectorySync(key);
513
+ }
514
+ /**
515
+ * Checks if the given key is a file.
516
+ *
517
+ * @param key - The key to check.
518
+ * @returns A promise that resolves to `true` if the key is a file, otherwise `false`.
519
+ */
520
+ async isFile(key) {
521
+ return Promise.resolve(this.isFileSync(key));
522
+ }
523
+ /**
524
+ * Disposes of the storage adapter, releasing any held resources.
525
+ *
526
+ * @returns A promise that resolves when the disposal is complete.
527
+ */
528
+ dispose() {
529
+ return Promise.resolve();
530
+ }
531
+ /**
532
+ * Async dispose method to clean up resources.
533
+ *
534
+ * @returns A promise that resolves when disposal is complete.
535
+ */
536
+ async [Symbol.asyncDispose]() {
537
+ return this._dispose();
538
+ }
539
+ /**
540
+ * Determines if the storage adapter is read-only based on the provided options.
541
+ *
542
+ * @returns `true` if the storage adapter is read-only, otherwise `false`.
543
+ */
544
+ get isReadOnly() {
545
+ return !!this.options.isReadOnly;
546
+ }
547
+ /**
548
+ * Determines if the storage adapter should overwrite existing keys based on the provided options and context configuration.
549
+ *
550
+ * @returns `true` if the storage adapter should overwrite existing keys, otherwise `false`.
551
+ */
552
+ get overwrite() {
553
+ return !this.isReadOnly && this.context.config.output.overwrite !== false;
554
+ }
555
+ /**
556
+ * Resolves a given key to its full path within the storage adapter.
557
+ *
558
+ * @param key - The key to resolve.
559
+ * @returns The resolved full path for the key.
560
+ */
561
+ resolve(key) {
562
+ if (!key) return this.options.base;
563
+ if (/\.\.:|\.\.$/.test(key)) throw new Error(`[${this.name}]: Invalid key: ${JSON.stringify(key)} provided to storage adapter.`);
564
+ return appendPath(correctPath(key).replace(/:/g, "/"), this.options.base);
565
+ }
566
+ /**
567
+ * Disposes of the storage adapter, releasing any held resources.
568
+ *
569
+ * @returns A promise that resolves when the disposal is complete.
570
+ */
571
+ async _dispose() {
572
+ if (!this.#isDisposed) {
573
+ await Promise.resolve(this.dispose());
574
+ this.#isDisposed = true;
575
+ }
576
+ }
577
+ };
578
+
579
+ //#endregion
580
+ //#region src/storage/helpers.ts
581
+ /**
582
+ * Checks if an error is a file system error.
583
+ *
584
+ * @param err - The error to check.
585
+ * @returns `true` if the error is a file system error, otherwise `false`.
586
+ */
587
+ function isFileError(err) {
588
+ return isError(err) && "code" in err && err.code;
589
+ }
590
+ /**
591
+ * Ignores file not found errors.
592
+ *
593
+ * @param err - The error to check.
594
+ * @returns `null` if the error is a file not found error, otherwise returns the error.
595
+ */
596
+ function ignoreNotfound(err) {
597
+ return isFileError(err) && (err.code === "ENOENT" || err.code === "EISDIR" ? null : err);
598
+ }
599
+
600
+ //#endregion
601
+ //#region src/storage/file-system.ts
602
+ /**
603
+ * File system storage adapter implementation.
604
+ */
605
+ var FileSystemStorageAdapter = class extends BaseStorageAdapter {
606
+ /**
607
+ * A name identifying the storage adapter type.
608
+ */
609
+ name = "file-system";
610
+ /**
611
+ * The storage preset for the adapter.
612
+ *
613
+ * @remarks
614
+ * This can be used as an alternate way to identify the type of storage being used.
615
+ */
616
+ preset = "fs";
617
+ /**
618
+ * Constructor for the FileSystemStorageAdapter.
619
+ *
620
+ * @param context - The Powerlines context.
621
+ * @param options - Configuration options for the storage adapter.
622
+ */
623
+ constructor(context, options) {
624
+ super(context, options);
625
+ }
626
+ /**
627
+ * Synchronously checks if a key exists in the storage.
628
+ *
629
+ * @param key - The key to check for existence.
630
+ * @returns Returns `true` if the key exists, otherwise `false`.
631
+ */
632
+ existsSync(key) {
633
+ return existsSync(this.resolve(key));
634
+ }
635
+ /**
636
+ * Asynchronously checks if a key exists in the storage.
637
+ *
638
+ * @param key - The key to check for existence.
639
+ * @returns A promise that resolves to `true` if the key exists, otherwise `false`.
640
+ */
641
+ async exists(key) {
642
+ return exists(this.resolve(key));
643
+ }
644
+ /**
645
+ * Synchronously retrieves the value associated with a given key.
646
+ *
647
+ * @param key - The key whose value is to be retrieved.
648
+ * @returns The value associated with the key, or `null` if the key does not exist.
649
+ */
650
+ getSync(key) {
651
+ return readFileSync(this.resolve(key));
652
+ }
653
+ /**
654
+ * Asynchronously retrieves the value associated with a given key.
655
+ *
656
+ * @param key - The key whose value is to be retrieved.
657
+ * @returns A promise that resolves to the value associated with the key, or `null` if the key does not exist.
658
+ */
659
+ async get(key) {
660
+ return readFile(this.resolve(key));
661
+ }
662
+ /**
663
+ * Synchronously sets the value for a given key.
664
+ *
665
+ * @param key - The key to set the value for.
666
+ * @param value - The value to set.
667
+ */
668
+ setSync(key, value) {
669
+ if (!this.isReadOnly) if (this.existsSync(this.resolve(key)) && !this.overwrite) {
670
+ const existingValue = this.getSync(this.resolve(key));
671
+ if (isSetString(existingValue) && existingValue.includes(getFileHeaderWarningText(true, this.context.config.framework))) return writeFileSync(this.resolve(key), existingValue.replace(getFileHeaderWarningText(true, this.context.config.framework), getFileHeaderWarningText(false, this.context.config.framework)));
672
+ } else return writeFileSync(this.resolve(key), value);
673
+ }
674
+ /**
675
+ * Asynchronously sets the value for a given key.
676
+ *
677
+ * @param key - The key to set the value for.
678
+ * @param value - The value to set.
679
+ */
680
+ async set(key, value) {
681
+ if (!this.isReadOnly) if (this.existsSync(this.resolve(key)) && !this.overwrite) {
682
+ const existingValue = await this.get(this.resolve(key));
683
+ if (isSetString(existingValue) && existingValue.includes(getFileHeaderWarningText(true, this.context.config.framework))) return writeFile(this.resolve(key), existingValue.replace(getFileHeaderWarningText(true, this.context.config.framework), getFileHeaderWarningText(false, this.context.config.framework)));
684
+ } else return writeFile(this.resolve(key), value);
685
+ }
686
+ /**
687
+ * Synchronously removes a key from the storage.
688
+ *
689
+ * @param key - The key to remove.
690
+ */
691
+ removeSync(key) {
692
+ if (!this.isReadOnly && this.overwrite) try {
693
+ return unlinkSync(this.resolve(key));
694
+ } catch (err) {
695
+ return ignoreNotfound(err);
696
+ }
697
+ }
698
+ /**
699
+ * Asynchronously removes a key from the storage.
700
+ *
701
+ * @param key - The key to remove.
702
+ */
703
+ async remove(key) {
704
+ if (!this.isReadOnly && this.overwrite) return unlink(this.resolve(key)).catch(ignoreNotfound);
705
+ }
706
+ /**
707
+ * Synchronously creates a directory at the specified path.
708
+ *
709
+ * @param dirPath - The path of the directory to create.
710
+ */
711
+ mkdirSync(dirPath) {
712
+ createDirectorySync(this.resolve(dirPath));
713
+ }
714
+ /**
715
+ * Creates a directory at the specified path.
716
+ *
717
+ * @param dirPath - The path of the directory to create.
718
+ */
719
+ async mkdir(dirPath) {
720
+ await createDirectory(this.resolve(dirPath));
721
+ }
722
+ /**
723
+ * Lists all keys under a given base path synchronously.
724
+ *
725
+ * @param base - The base path to list keys from.
726
+ * @returns An array of keys under the specified base path.
727
+ */
728
+ listSync(base) {
729
+ try {
730
+ return listFilesSync(this.resolve(base), { ignore: this.options.ignore });
731
+ } catch (err) {
732
+ return ignoreNotfound(err) ?? [];
733
+ }
734
+ }
735
+ /**
736
+ * Asynchronously lists all keys under a given base path.
737
+ *
738
+ * @param base - The base path to list keys from.
739
+ * @returns A promise that resolves to an array of keys under the specified base path.
740
+ */
741
+ async list(base) {
742
+ return listFiles(this.resolve(base), { ignore: this.options.ignore }).catch(ignoreNotfound).then((r) => r || []);
743
+ }
744
+ /**
745
+ * Synchronously checks if the given key is a directory.
746
+ *
747
+ * @param key - The key to check.
748
+ * @returns `true` if the key is a directory, otherwise `false`.
749
+ */
750
+ isDirectorySync(key) {
751
+ return isDirectory(this.resolve(key));
752
+ }
753
+ /**
754
+ * Synchronously checks if the given key is a file.
755
+ *
756
+ * @param key - The key to check.
757
+ * @returns `true` if the key is a file, otherwise `false`.
758
+ */
759
+ isFileSync(key) {
760
+ return isFile(this.resolve(key));
761
+ }
762
+ };
763
+
764
+ //#endregion
765
+ //#region src/storage/virtual.ts
766
+ /**
767
+ * Virtual/in-memory storage adapter implementation.
768
+ */
769
+ var VirtualStorageAdapter = class extends BaseStorageAdapter {
770
+ /**
771
+ * A name identifying the storage adapter type.
772
+ */
773
+ name = "virtual";
774
+ /**
775
+ * The storage preset for the adapter.
776
+ *
777
+ * @remarks
778
+ * This can be used as an alternate way to identify the type of storage being used.
779
+ */
780
+ preset = "virtual";
781
+ /**
782
+ * In-memory data storage.
783
+ */
784
+ data = /* @__PURE__ */ new Map();
785
+ /**
786
+ * Constructor for the VirtualStorageAdapter.
787
+ *
788
+ * @param context - The Powerlines context.
789
+ * @param options - Configuration options for the storage adapter.
790
+ */
791
+ constructor(context, options) {
792
+ super(context, options);
793
+ }
794
+ /**
795
+ * Synchronously checks if a key exists in the storage.
796
+ *
797
+ * @param key - The key to check for existence.
798
+ * @returns Returns `true` if the key exists, otherwise `false`.
799
+ */
800
+ existsSync(key) {
801
+ return this.data.has(this.resolve(key));
802
+ }
803
+ /**
804
+ * Synchronously retrieves the value associated with a given key.
805
+ *
806
+ * @param key - The key whose value is to be retrieved.
807
+ * @returns The value associated with the key, or `null` if the key does not exist.
808
+ */
809
+ getSync(key) {
810
+ return this.data.get(this.resolve(key)) ?? null;
811
+ }
812
+ /**
813
+ * Synchronously sets the value for a given key.
814
+ *
815
+ * @param key - The key to set the value for.
816
+ * @param value - The value to set.
817
+ */
818
+ setSync(key, value) {
819
+ if (!this.isReadOnly && (!this.existsSync(key) || this.overwrite)) this.data.set(this.resolve(key), value);
820
+ }
821
+ /**
822
+ * Synchronously removes a key from the storage.
823
+ *
824
+ * @param key - The key to remove.
825
+ */
826
+ removeSync(key) {
827
+ if (!this.isReadOnly && this.overwrite) this.data.delete(this.resolve(key));
828
+ }
829
+ /**
830
+ * Lists all keys under a given base path synchronously.
831
+ *
832
+ * @param base - The base path to list keys from.
833
+ * @returns An array of keys under the specified base path.
834
+ */
835
+ listSync(base) {
836
+ return [...this.data.keys().filter((key) => !base ? true : isParentPath(key, this.resolve(base)))];
837
+ }
838
+ /**
839
+ * Disposes of the storage adapter, releasing any held resources.
840
+ *
841
+ * @returns A promise that resolves when the disposal is complete.
842
+ */
843
+ async dispose() {
844
+ return this.clear();
845
+ }
846
+ /**
847
+ * Determines if the storage adapter should overwrite existing keys based on the provided options and context configuration.
848
+ *
849
+ * @returns `true` if the storage adapter should overwrite existing keys, otherwise `false`.
850
+ */
851
+ get overwrite() {
852
+ return !this.isReadOnly;
853
+ }
854
+ };
855
+
856
+ //#endregion
857
+ //#region src/_internal/helpers/constants.ts
858
+ const DEFAULT_EXTENSIONS = [
859
+ "js",
860
+ "ts",
861
+ "cjs",
862
+ "cts",
863
+ "mjs",
864
+ "mts",
865
+ "tsx",
866
+ "jsx",
867
+ "json",
868
+ "json5",
869
+ "jsonc",
870
+ "md",
871
+ "mdx"
872
+ ];
873
+
874
+ //#endregion
875
+ //#region src/_internal/vfs.ts
876
+ function toFilePath(path) {
877
+ return correctPath(slash(path?.toString() || ".").replace(/^file:\/\//, ""));
878
+ }
879
+ /**
880
+ * Checks if a given file id is valid based on the specified prefix.
881
+ *
882
+ * @param id - The file ID to check.
883
+ * @param prefix - The prefix to use for built-in files. Default is "powerlines".
884
+ * @returns `true` if the file ID is valid, otherwise `false`.
885
+ */
886
+ function isValidId(id, prefix = "powerlines") {
887
+ return id.replace(/^\\0/, "").startsWith(`${prefix.replace(/:$/, "")}`);
888
+ }
889
+ /**
890
+ * Formats a file id by removing the file extension and prepended runtime prefix.
891
+ *
892
+ * @param id - The file ID to format.
893
+ * @param prefix - The prefix to use for built-in files. Default is "powerlines".
894
+ * @returns The formatted file ID.
895
+ */
896
+ function normalizeId(id, prefix = "powerlines") {
897
+ return replaceExtension(toFilePath(id)).replace(/^\\0/, "").replace(/^powerlines:/, "").replace(new RegExp(`^${prefix.replace(/:$/, "")}:`), "");
898
+ }
899
+ /**
900
+ * Normalizes a given path by resolving it against the project root, workspace root, and built-ins path.
901
+ *
902
+ * @param path - The path to normalize.
903
+ * @param builtinsPath - The path to built-in files.
904
+ * @param prefix - The prefix to use for built-in files. Default is "powerlines".
905
+ * @returns The normalized path.
906
+ */
907
+ function normalizePath(path, builtinsPath, prefix = "powerlines") {
908
+ if (!isSetString(path)) {
909
+ if (!isString(path)) throw new Error("Path type must be a string or a file descriptor");
910
+ throw new Error("Path cannot be empty");
911
+ }
912
+ return isAbsolutePath(path) ? path : isValidId(toFilePath(path), prefix) ? normalizeId(toFilePath(path), prefix).replace(new RegExp(`^${prefix.replace(/:$/, "")}:`), builtinsPath) : toFilePath(path);
913
+ }
914
+ /**
915
+ * Normalizes glob patterns by resolving them against the workspace root.
916
+ *
917
+ * @param workspaceRoot - The root directory of the workspace.
918
+ * @param patterns - The glob patterns to normalize.
919
+ * @returns An array of normalized glob patterns.
920
+ */
921
+ function normalizeGlobPatterns(workspaceRoot, patterns) {
922
+ return getUnique(toArray(patterns).map((pattern) => {
923
+ if (isSetObject(pattern) && (isSetString(pattern.input) || isSetString(pattern.glob))) return joinPaths$1(pattern.input || workspaceRoot, pattern.glob || "**/*");
924
+ else if (!isSetString(pattern)) return;
925
+ return pattern;
926
+ }).filter(isSetString));
927
+ }
928
+ /**
929
+ * Represents a virtual file system (VFS) that stores files and their associated metadata in virtual memory.
930
+ *
931
+ * @remarks
932
+ * This class provides methods to manage virtual files, check their existence, retrieve their content, and manipulate the virtual file system. It allows for efficient file management and retrieval without relying on the actual file system.
933
+ */
934
+ var VirtualFileSystem = class VirtualFileSystem {
935
+ /**
936
+ * A map of virtual file IDs to their associated metadata.
937
+ */
938
+ #metadata;
939
+ /**
940
+ * A map of underlying file paths to their virtual file IDs.
941
+ */
942
+ #ids;
943
+ /**
944
+ * A map of virtual file IDs to their underlying file paths.
945
+ */
946
+ #paths;
947
+ /**
948
+ * The unified volume that combines the virtual file system with the real file system.
949
+ *
950
+ * @remarks
951
+ * This volume allows for seamless access to both virtual and real files.
952
+ */
953
+ #storage;
954
+ /**
955
+ * A cache for module resolution results.
956
+ */
957
+ #resolverCache;
958
+ /**
959
+ * Indicator specifying if the virtual file system (VFS) is disposed
960
+ */
961
+ #isDisposed = false;
962
+ /**
963
+ * The context of the virtual file system.
964
+ */
965
+ #context;
966
+ /**
967
+ * The file system's logging function.
968
+ */
969
+ #log;
970
+ /**
971
+ * Normalizes a given module id by resolving it against the built-ins path.
972
+ *
973
+ * @param id - The module id to normalize.
974
+ * @returns The normalized module id.
975
+ */
976
+ #normalizeId(id) {
977
+ let normalized = id;
978
+ if (isParentPath(normalized, this.#context.builtinsPath)) normalized = replacePath(normalized, this.#context.builtinsPath);
979
+ return normalizeId(normalized, this.#context.config.framework);
980
+ }
981
+ /**
982
+ * Normalizes a given path by resolving it against the project root, workspace root, and built-ins path.
983
+ *
984
+ * @param path - The path to normalize.
985
+ * @returns The normalized path.
986
+ */
987
+ #normalizePath(path) {
988
+ if (!isSetString(path)) {
989
+ if (!isString(path)) throw new Error("Path type must be a string or a file descriptor");
990
+ throw new Error("Path cannot be empty");
991
+ }
992
+ return normalizePath(path.includes("{") || path.includes("}") ? replacePathTokens(this.#context, path) : path, this.#context.builtinsPath, this.#context.config.framework);
993
+ }
994
+ /**
995
+ * Gets the storage adapter and relative key for a given key.
996
+ *
997
+ * @remarks
998
+ * The `key` can be either a path or a storage adapter name.
999
+ *
1000
+ * @param key - The key to get the storage adapter for.
1001
+ * @returns The storage adapter and relative key for the given key.
1002
+ */
1003
+ #getStorage(key, preset) {
1004
+ const path = this.resolveSync(this.#normalizePath(key)) || key;
1005
+ for (const base of Object.keys(this.#storage).filter(Boolean).sort().reverse()) if ((path === base || isParentPath(path, base)) && (!preset || this.#storage[base]?.preset?.toLowerCase() === preset.toLowerCase())) return {
1006
+ base,
1007
+ relativeKey: replacePath(path, base),
1008
+ adapter: this.#storage[base]
1009
+ };
1010
+ if (!preset || this.#storage[""]?.preset?.toLowerCase() === preset.toLowerCase()) return {
1011
+ base: "",
1012
+ relativeKey: path,
1013
+ adapter: this.#storage[""]
1014
+ };
1015
+ this.#storage[path] = preset === "virtual" ? new VirtualStorageAdapter(this.#context, { base: path }) : new FileSystemStorageAdapter(this.#context, { base: path });
1016
+ return {
1017
+ base: path,
1018
+ relativeKey: "",
1019
+ adapter: this.#storage[path]
1020
+ };
1021
+ }
1022
+ /**
1023
+ * Gets all storage adapters that match a given base key.
1024
+ *
1025
+ * @param base - The base key to match storage adapters against.
1026
+ * @param includeParent - Whether to include parent storage adapters.
1027
+ * @returns An array of storage adapters that match the given base key.
1028
+ */
1029
+ #getStorages(base = "", includeParent = false) {
1030
+ const baseKey = this.resolveSync(base) || base;
1031
+ return Object.keys(this.#storage).sort().reverse().filter((key) => isParentPath(key, baseKey) || includeParent && isParentPath(baseKey, key) || baseKey.includes("*") && (isParentPath(stripStars(baseKey), key) || globToRegex(replaceExtension(baseKey)).test(key))).map((key) => ({
1032
+ relativeBase: baseKey.length > key.length ? baseKey.slice(key.length) : void 0,
1033
+ base: key,
1034
+ adapter: this.#storage[key]
1035
+ }));
1036
+ }
1037
+ /**
1038
+ * A helper function to resolve modules in the virtual file system (VFS).
1039
+ *
1040
+ * @remarks
1041
+ * This function can be used to resolve modules relative to the project root directory.
1042
+ *
1043
+ * @example
1044
+ * ```ts
1045
+ * const resolved = await context.resolvePath("some-module", "/path/to/importer");
1046
+ * ```
1047
+ *
1048
+ * @param id - The module to resolve.
1049
+ * @param importer - An optional path to the importer module.
1050
+ * @param options - Additional resolution options.
1051
+ * @returns A promise that resolves to the resolved module path.
1052
+ */
1053
+ #innerResolve = async (id, importer, options = {}) => {
1054
+ let path = id;
1055
+ if (path.includes("{") || path.includes("}")) path = replacePathTokens(this.#context, path);
1056
+ if (options.skipAlias !== true) path = this.resolveAlias(path);
1057
+ if (isAbsolutePath(path) && (!options.isFile || !await this.isDirectory(path))) return path;
1058
+ const resolverCacheKey = murmurhash({
1059
+ path: this.#normalizeId(path),
1060
+ importer,
1061
+ options
1062
+ });
1063
+ let result;
1064
+ if (!this.#context.config.skipCache) {
1065
+ result = this.resolverCache.get(resolverCacheKey);
1066
+ if (result) return result;
1067
+ }
1068
+ result = this.paths[this.#normalizeId(path)];
1069
+ if (!isSetString(result)) {
1070
+ const paths = options.paths ?? [];
1071
+ if (importer && !paths.includes(importer)) paths.push(importer);
1072
+ if (!importer) {
1073
+ paths.push(this.#context.config.cwd);
1074
+ paths.push(appendPath(this.#context.config.root, this.#context.config.cwd));
1075
+ paths.push(appendPath(joinPaths$1(this.#context.config.root, "src"), this.#context.config.cwd));
1076
+ }
1077
+ paths.push(...Object.keys(this.#context.tsconfig?.options?.paths ?? {}).filter((tsconfigPath) => path.startsWith(tsconfigPath.replace(/\*$/, ""))).map((tsconfigPath) => this.#context.tsconfig?.options?.paths?.[tsconfigPath]).flat().filter(Boolean).map((tsconfigPath) => appendPath(tsconfigPath, this.#context.config.cwd)));
1078
+ for (const combination of getResolutionCombinations(path, { paths: getUnique(paths) })) {
1079
+ const { relativeKey, adapter } = this.#getStorage(combination);
1080
+ if (await adapter.exists(relativeKey)) {
1081
+ result = combination;
1082
+ break;
1083
+ }
1084
+ }
1085
+ if (!isSetString(result)) try {
1086
+ result = await resolve(path, {
1087
+ ...options,
1088
+ paths
1089
+ });
1090
+ } catch {}
1091
+ }
1092
+ if (isSetString(result)) {
1093
+ if (!this.#context.config.skipCache) this.resolverCache.set(this.#normalizeId(path), result);
1094
+ return result;
1095
+ }
1096
+ };
1097
+ /**
1098
+ * A synchronous helper function to resolve modules using the Jiti resolver
1099
+ *
1100
+ * @remarks
1101
+ * This function can be used to resolve modules relative to the project root directory.
1102
+ *
1103
+ * @example
1104
+ * ```ts
1105
+ * const resolvedPath = context.resolveSync("some-module", "/path/to/importer");
1106
+ * ```
1107
+ *
1108
+ * @param id - The module to resolve.
1109
+ * @param importer - An optional path to the importer module.
1110
+ * @param options - Additional resolution options.
1111
+ * @returns The resolved module path.
1112
+ */
1113
+ #innerResolveSync = (id, importer, options = {}) => {
1114
+ let path = id;
1115
+ if (path.includes("{") || path.includes("}")) path = replacePathTokens(this.#context, path);
1116
+ if (options.skipAlias !== true) path = this.resolveAlias(path);
1117
+ if (isAbsolutePath(path) && (!options.isFile || !this.isDirectorySync(path))) return path;
1118
+ let result;
1119
+ if (!this.#context.config.skipCache) {
1120
+ result = this.resolverCache.get(this.#normalizeId(path));
1121
+ if (isSetString(result)) return result;
1122
+ }
1123
+ result = this.paths[this.#normalizeId(path)];
1124
+ if (!isSetString(result)) {
1125
+ const paths = options.paths ?? [];
1126
+ if (importer && !paths.includes(importer)) paths.push(importer);
1127
+ if (!importer) {
1128
+ paths.push(this.#context.config.cwd);
1129
+ paths.push(appendPath(this.#context.config.root, this.#context.config.cwd));
1130
+ paths.push(appendPath(joinPaths$1(this.#context.config.root, "src"), this.#context.config.cwd));
1131
+ }
1132
+ paths.push(...Object.keys(this.#context.tsconfig?.options?.paths ?? {}).filter((tsconfigPath) => path.startsWith(tsconfigPath.replace(/\*$/, ""))).map((tsconfigPath) => this.#context.tsconfig?.options?.paths?.[tsconfigPath]).flat().filter(Boolean).map((tsconfigPath) => appendPath(tsconfigPath, this.#context.config.cwd)));
1133
+ for (const combination of getResolutionCombinations(path, { paths })) {
1134
+ const { relativeKey, adapter } = this.#getStorage(combination);
1135
+ if (adapter.existsSync(relativeKey)) {
1136
+ result = combination;
1137
+ break;
1138
+ }
1139
+ }
1140
+ if (!isSetString(result)) try {
1141
+ result = resolveSync(path, {
1142
+ ...options,
1143
+ paths
1144
+ });
1145
+ } catch {}
1146
+ }
1147
+ if (isSetString(result)) {
1148
+ if (!this.#context.config.skipCache) this.resolverCache.set(this.#normalizeId(path), result);
1149
+ return result;
1150
+ }
1151
+ };
1152
+ /**
1153
+ * Creates a virtual file system (VFS) that is backed up to a Cap'n Proto message buffer.
1154
+ *
1155
+ * @param context - The context of the virtual file system, typically containing options and logging functions.
1156
+ * @returns A promise that resolves to a new virtual file system instance.
1157
+ */
1158
+ static async create(context) {
1159
+ context.debug("Starting virtual file system (VFS) initialization processes...");
1160
+ let result;
1161
+ if (!context.config.skipCache && existsSync(joinPaths$1(context.dataPath, "fs.bin"))) {
1162
+ const buffer = await readFileBuffer(joinPaths$1(context.dataPath, "fs.bin"));
1163
+ const fs = new $.Message(buffer, false).getRoot(FileSystem);
1164
+ result = new VirtualFileSystem(context, fs);
1165
+ if (fs._hasStorage() && fs.storage.length > 0) await Promise.all(fs.storage.values().map(async (file) => {
1166
+ if (file.path && file.code) {
1167
+ let id;
1168
+ if (fs._hasIds()) id = fs.ids.find((fileId) => fileId.path === file.path);
1169
+ let metadata;
1170
+ if (fs._hasMetadata()) metadata = fs.metadata.find((meta) => meta.id === result.#normalizeId(id?.id ?? file.path));
1171
+ await result.write(file.path, file.code, { meta: {
1172
+ id: result.#normalizeId(id?.id ?? metadata?.id ?? file.path),
1173
+ type: metadata?.type || "normal",
1174
+ properties: metadata?._hasProperties() ? metadata?.properties.values().reduce((ret, kvp) => {
1175
+ ret[kvp.key] = kvp.value;
1176
+ return ret;
1177
+ }, {}) : void 0,
1178
+ timestamp: metadata?.timestamp
1179
+ } });
1180
+ }
1181
+ }));
1182
+ } else result = new VirtualFileSystem(context, new $.Message().initRoot(FileSystem));
1183
+ result.#log(LogLevelLabel.DEBUG, "Successfully completed virtual file system (VFS) initialization.");
1184
+ return result;
1185
+ }
1186
+ /**
1187
+ * Synchronously creates a virtual file system (VFS) that is backed up to a Cap'n Proto message buffer.
1188
+ *
1189
+ * @param context - The context of the virtual file system, typically containing options and logging functions.
1190
+ * @returns A new virtual file system instance.
1191
+ */
1192
+ static createSync(context) {
1193
+ context.debug("Starting virtual file system (VFS) initialization processes...");
1194
+ let result;
1195
+ if (!context.config.skipCache && existsSync(joinPaths$1(context.dataPath, "fs.bin"))) {
1196
+ const buffer = readFileBufferSync(joinPaths$1(context.dataPath, "fs.bin"));
1197
+ const fs = new $.Message(buffer, false).getRoot(FileSystem);
1198
+ result = new VirtualFileSystem(context, fs);
1199
+ if (fs._hasStorage() && fs.storage.length > 0) fs.storage.values().forEach((file) => {
1200
+ if (file.path && file.code) {
1201
+ let id;
1202
+ if (fs._hasIds()) id = fs.ids.find((fileId) => fileId.path === file.path);
1203
+ let metadata;
1204
+ if (fs._hasMetadata()) metadata = fs.metadata.find((meta) => meta.id === result.#normalizeId(id?.id ?? file.path));
1205
+ result.writeSync(file.path, file.code, { meta: {
1206
+ id: result.#normalizeId(id?.id ?? metadata?.id ?? file.path),
1207
+ type: metadata?.type,
1208
+ properties: metadata?._hasProperties() ? metadata?.properties.values().reduce((ret, kvp) => {
1209
+ ret[kvp.key] = kvp.value;
1210
+ return ret;
1211
+ }, {}) : void 0,
1212
+ timestamp: metadata?.timestamp
1213
+ } });
1214
+ }
1215
+ });
1216
+ } else result = new VirtualFileSystem(context, new $.Message().initRoot(FileSystem));
1217
+ result.#log(LogLevelLabel.DEBUG, "Successfully completed virtual file system (VFS) initialization.");
1218
+ return result;
1219
+ }
1220
+ /**
1221
+ * A map of file ids to their metadata.
1222
+ */
1223
+ get metadata() {
1224
+ return new Proxy(this.#metadata, {
1225
+ get: (target, prop) => {
1226
+ return target[this.#normalizeId(prop)];
1227
+ },
1228
+ set: (target, prop, value) => {
1229
+ target[this.#normalizeId(prop)] = value;
1230
+ return true;
1231
+ },
1232
+ deleteProperty: (target, prop) => {
1233
+ delete target[this.#normalizeId(prop)];
1234
+ return true;
1235
+ },
1236
+ has: (target, prop) => {
1237
+ return this.#normalizeId(prop) in target;
1238
+ },
1239
+ ownKeys: (target) => {
1240
+ return getUnique(Reflect.ownKeys(target).map((key) => this.#normalizeId(key)));
1241
+ }
1242
+ });
1243
+ }
1244
+ /**
1245
+ * A map of file paths to their module ids.
1246
+ */
1247
+ get ids() {
1248
+ return new Proxy(this.#ids, {
1249
+ get: (target, prop) => {
1250
+ return target[this.#normalizePath(prop)];
1251
+ },
1252
+ set: (target, prop, value) => {
1253
+ target[this.#normalizePath(prop)] = value;
1254
+ return true;
1255
+ },
1256
+ deleteProperty: (target, prop) => {
1257
+ delete target[this.#normalizePath(prop)];
1258
+ return true;
1259
+ },
1260
+ has: (target, prop) => {
1261
+ return this.#normalizePath(prop) in target;
1262
+ },
1263
+ ownKeys: (target) => {
1264
+ return getUnique(Reflect.ownKeys(target).map((key) => this.#normalizePath(key)));
1265
+ }
1266
+ });
1267
+ }
1268
+ /**
1269
+ * A map of module ids to their file paths.
1270
+ */
1271
+ get paths() {
1272
+ return new Proxy(this.#paths, {
1273
+ get: (target, prop) => {
1274
+ return this.#normalizeId(prop) in target ? target[this.#normalizeId(prop)] : void 0;
1275
+ },
1276
+ set: (target, prop, value) => {
1277
+ target[this.#normalizeId(prop)] = value;
1278
+ return true;
1279
+ },
1280
+ deleteProperty: (target, prop) => {
1281
+ delete target[this.#normalizeId(prop)];
1282
+ return true;
1283
+ },
1284
+ has: (target, prop) => {
1285
+ return this.#normalizeId(prop) in target;
1286
+ },
1287
+ ownKeys: (target) => {
1288
+ return getUnique(Reflect.ownKeys(target).map((key) => this.#normalizeId(key)));
1289
+ }
1290
+ });
1291
+ }
1292
+ /**
1293
+ * Gets the resolver cache.
1294
+ */
1295
+ get resolverCache() {
1296
+ if (!this.#resolverCache) this.#resolverCache = create({
1297
+ cacheId: "module-resolution",
1298
+ cacheDir: this.#context.cachePath,
1299
+ ttl: 2.5 * 60 * 1e3,
1300
+ lruSize: 8e3,
1301
+ persistInterval: 100
1302
+ });
1303
+ return this.#resolverCache;
1304
+ }
1305
+ /**
1306
+ * Creates a new instance of the {@link VirtualFileSystem}.
1307
+ *
1308
+ * @param context - The context of the virtual file system, typically containing options and logging functions.
1309
+ * @param fs - A buffer containing the serialized virtual file system data.
1310
+ */
1311
+ constructor(context, fs) {
1312
+ this.#context = context;
1313
+ this.#storage = { "": new FileSystemStorageAdapter(context) };
1314
+ if (isSetObject(this.#context.config.output.storage)) this.#storage = {
1315
+ ...this.#storage,
1316
+ ...this.#context.config.output.storage
1317
+ };
1318
+ this.#storage.virtual ??= new VirtualStorageAdapter(context, { base: "/_virtual" });
1319
+ this.#storage[this.#context.config.output.path] ??= new FileSystemStorageAdapter(context, { base: this.#context.config.output.path });
1320
+ if (this.#context.config.output.copy && this.#context.config.output.copy.path) this.#storage[this.#context.config.output.copy.path] ??= new FileSystemStorageAdapter(context, { base: this.#context.config.output.copy.path });
1321
+ if (this.#context.config.output.storage !== "fs") {
1322
+ this.#storage[this.#context.artifactsPath] ??= new VirtualStorageAdapter(context, { base: this.#context.artifactsPath });
1323
+ this.#storage[this.#context.builtinsPath] ??= new VirtualStorageAdapter(context, { base: this.#context.builtinsPath });
1324
+ this.#storage[this.#context.entryPath] ??= new VirtualStorageAdapter(context, { base: this.#context.entryPath });
1325
+ }
1326
+ this.#metadata = {};
1327
+ if (fs._hasMetadata()) this.#metadata = fs.metadata.values().reduce((ret, metadata) => {
1328
+ ret[metadata.id] = {
1329
+ id: metadata.id,
1330
+ type: metadata.type,
1331
+ timestamp: metadata.timestamp ?? Date.now(),
1332
+ properties: metadata._hasProperties() ? metadata.properties.values().reduce((ret, item) => {
1333
+ ret[item.key] = item.value;
1334
+ return ret;
1335
+ }, {}) : {}
1336
+ };
1337
+ return ret;
1338
+ }, {});
1339
+ this.#ids = {};
1340
+ this.#paths = {};
1341
+ if (fs._hasIds()) {
1342
+ this.#ids = fs.ids.values().reduce((ret, identifier) => {
1343
+ ret[identifier.path] ??= identifier.id;
1344
+ return ret;
1345
+ }, {});
1346
+ this.#paths = fs.ids.values().reduce((ret, identifier) => {
1347
+ ret[identifier.id] ??= identifier.path;
1348
+ return ret;
1349
+ }, {});
1350
+ }
1351
+ this.#log = extendLog(this.#context.log, "file-system");
1352
+ }
1353
+ /**
1354
+ * Asynchronously checks if a file exists in the virtual file system (VFS).
1355
+ *
1356
+ * @param path - The path to the file.
1357
+ * @returns A promise that resolves to `true` if the file exists, otherwise `false`.
1358
+ */
1359
+ async exists(path) {
1360
+ const { relativeKey, adapter } = this.#getStorage(path);
1361
+ return adapter.exists(relativeKey);
1362
+ }
1363
+ /**
1364
+ * Synchronously checks if a file exists in the virtual file system (VFS).
1365
+ *
1366
+ * @param path - The path to the file.
1367
+ * @returns `true` if the file exists, otherwise `false`.
1368
+ */
1369
+ existsSync(path) {
1370
+ const { relativeKey, adapter } = this.#getStorage(path);
1371
+ return adapter.existsSync(relativeKey);
1372
+ }
1373
+ /**
1374
+ * Checks if a file is virtual in the virtual file system (VFS).
1375
+ *
1376
+ * @param path - The path to the file.
1377
+ * @param importer - An optional path to the importer module.
1378
+ * @param options - Additional resolution options.
1379
+ * @returns `true` if the file is virtual, otherwise `false`.
1380
+ */
1381
+ isVirtual(path, importer, options) {
1382
+ const resolved = this.resolveSync(path, importer, options);
1383
+ if (!isSetString(resolved)) {
1384
+ if (isSet(resolved)) throw new Error(`Resolved path is not a string: ${String(resolved)}`);
1385
+ return false;
1386
+ }
1387
+ return this.#getStorage(resolved)?.adapter?.preset === "virtual" || resolved.startsWith(`${this.#context.config.framework}:`) || path.startsWith(`${this.#context.config.framework}:`);
1388
+ }
1389
+ /**
1390
+ * Checks if a path is a directory in the virtual file system (VFS).
1391
+ *
1392
+ * @param path - The path to check.
1393
+ * @param importer - An optional path to the importer module.
1394
+ * @param options - Additional resolution options.
1395
+ * @returns `true` if the path is a directory, otherwise `false`.
1396
+ */
1397
+ isDirectorySync(path, importer, options) {
1398
+ const resolved = this.resolveSync(path, importer, options);
1399
+ if (!isSetString(resolved)) {
1400
+ if (isSet(resolved)) throw new Error(`Resolved path is not a string: ${String(resolved)}`);
1401
+ return false;
1402
+ }
1403
+ return !!(this.existsSync(resolved) && this.#getStorage(resolved)?.adapter?.isDirectorySync(resolved));
1404
+ }
1405
+ /**
1406
+ * Checks if a path is a directory in the virtual file system (VFS).
1407
+ *
1408
+ * @param path - The path to check.
1409
+ * @param importer - An optional path to the importer module.
1410
+ * @param options - Additional resolution options.
1411
+ * @returns `true` if the path is a directory, otherwise `false`.
1412
+ */
1413
+ async isDirectory(path, importer, options) {
1414
+ const resolved = await this.resolve(path, importer, options);
1415
+ if (!isSetString(resolved)) {
1416
+ if (isSet(resolved)) throw new Error(`Resolved path is not a string: ${String(resolved)}`);
1417
+ return false;
1418
+ }
1419
+ return !!(await this.exists(resolved) && await this.#getStorage(resolved)?.adapter?.isDirectory(resolved));
1420
+ }
1421
+ /**
1422
+ * Checks if a path is a file in the virtual file system (VFS).
1423
+ *
1424
+ * @param path - The path to check.
1425
+ * @param importer - An optional path to the importer module.
1426
+ * @param options - Additional resolution options.
1427
+ * @returns `true` if the path is a file, otherwise `false`.
1428
+ */
1429
+ isFileSync(path, importer, options) {
1430
+ const resolved = this.resolveSync(path, importer, options);
1431
+ if (!isSetString(resolved)) {
1432
+ if (isSet(resolved)) throw new Error(`Resolved path is not a string: ${String(resolved)}`);
1433
+ return false;
1434
+ }
1435
+ return this.#getStorage(resolved)?.adapter?.isFileSync(resolved) ?? false;
1436
+ }
1437
+ /**
1438
+ * Checks if a path is a file in the virtual file system (VFS).
1439
+ *
1440
+ * @param path - The path to check.
1441
+ * @param importer - An optional path to the importer module.
1442
+ * @param options - Additional resolution options.
1443
+ * @returns `true` if the path is a file, otherwise `false`.
1444
+ */
1445
+ async isFile(path, importer, options) {
1446
+ const resolved = await this.resolve(path, importer, options);
1447
+ if (!isSetString(resolved)) {
1448
+ if (isSet(resolved)) throw new Error(`Resolved path is not a string: ${String(resolved)}`);
1449
+ return false;
1450
+ }
1451
+ return await this.#getStorage(resolved)?.adapter?.isFile(resolved) ?? false;
1452
+ }
1453
+ /**
1454
+ * Checks if a file Id must be resolved by the virtual file system (VFS).
1455
+ *
1456
+ * @remarks
1457
+ * Examples of file Ids that would be considered virtual include:
1458
+ * - Ids that start with the framework specific prefix (e.g. `powerlines:`)
1459
+ * - Ids that match a configured alias for virtual modules (returned true from {@link VirtualFileSystemInterface.isVirtual})
1460
+ *
1461
+ * @param path - The path or id of the file.
1462
+ * @param importer - An optional path to the importer module, used for resolving the file path.
1463
+ * @param options - Additional options for resolving the file path.
1464
+ * @returns `true` if the file is virtual, otherwise `false`.
1465
+ */
1466
+ isResolvableId(path, importer, options) {
1467
+ return path.startsWith(`${this.#context.config.framework}:`) || this.isVirtual(path, importer, options) || this.isAlias(path) || this.isTsconfigPath(path);
1468
+ }
1469
+ /**
1470
+ * Lists files in a given path.
1471
+ *
1472
+ * @param path - The path to list files from.
1473
+ * @returns An array of file names in the specified path.
1474
+ */
1475
+ listSync(path) {
1476
+ let resolvedPath = path;
1477
+ if (resolvedPath.includes("*")) {
1478
+ this.#log(LogLevelLabel.WARN, `Invoking "listSync" with a glob pattern is not supported. It is likely you meant to use "globSync". Path: ${path}`);
1479
+ resolvedPath = stripStars(resolvedPath);
1480
+ }
1481
+ return getUnique(this.#getStorages(resolvedPath, true).map((storage) => storage.adapter.listSync(storage.relativeBase ? storage.base ? appendPath(storage.relativeBase, storage.base) : storage.relativeBase : storage.base)).flat().filter(Boolean));
1482
+ }
1483
+ /**
1484
+ * Lists files in a given path.
1485
+ *
1486
+ * @param path - The path to list files from.
1487
+ * @returns An array of file names in the specified path.
1488
+ */
1489
+ async list(path) {
1490
+ let resolvedPath = path;
1491
+ if (resolvedPath.includes("*")) {
1492
+ this.#log(LogLevelLabel.WARN, `Invoking "list" with a glob pattern is not supported. It is likely you meant to use "glob". Path: ${path}`);
1493
+ resolvedPath = stripStars(resolvedPath);
1494
+ }
1495
+ return getUnique((await Promise.all(this.#getStorages(resolvedPath, true).map(async (storage) => storage.adapter.list(storage.relativeBase ? storage.base ? appendPath(storage.relativeBase, storage.base) : storage.relativeBase : storage.base)))).flat().filter(Boolean));
1496
+ }
1497
+ /**
1498
+ * Removes a file in the virtual file system (VFS).
1499
+ *
1500
+ * @param path - The path to create the directory at.
1501
+ */
1502
+ async remove(path) {
1503
+ const normalizedPath = this.#normalizePath(path);
1504
+ this.#log(LogLevelLabel.TRACE, `Removing file: ${normalizedPath}`);
1505
+ const { relativeKey, adapter } = this.#getStorage(normalizedPath);
1506
+ if (hasFileExtension(normalizedPath)) await adapter.remove(relativeKey);
1507
+ else await adapter.clear(relativeKey);
1508
+ const id = this.#ids[normalizedPath];
1509
+ if (id && this.#metadata[id]) {
1510
+ delete this.#metadata[id];
1511
+ delete this.#ids[normalizedPath];
1512
+ delete this.#paths[id];
1513
+ }
1514
+ }
1515
+ /**
1516
+ * Removes a file in the virtual file system (VFS).
1517
+ *
1518
+ * @param path - The path to create the directory at.
1519
+ */
1520
+ removeSync(path) {
1521
+ const normalizedPath = this.#normalizePath(path);
1522
+ this.#log(LogLevelLabel.TRACE, `Removing file: ${normalizedPath}`);
1523
+ const { relativeKey, adapter } = this.#getStorage(normalizedPath);
1524
+ if (hasFileExtension(normalizedPath)) adapter.removeSync(relativeKey);
1525
+ else adapter.clearSync(relativeKey);
1526
+ const id = this.#ids[normalizedPath];
1527
+ if (id && this.#metadata[id]) {
1528
+ delete this.#metadata[id];
1529
+ delete this.#ids[normalizedPath];
1530
+ delete this.#paths[id];
1531
+ }
1532
+ }
1533
+ /**
1534
+ * Glob files in the virtual file system (VFS) based on the provided pattern(s).
1535
+ *
1536
+ * @param patterns - A pattern (or multiple patterns) to use to determine the file paths to return
1537
+ * @returns An array of file paths matching the provided pattern(s)
1538
+ */
1539
+ async glob(patterns) {
1540
+ const results = [];
1541
+ for (const pattern of normalizeGlobPatterns(this.#context.config.cwd, patterns)) {
1542
+ const normalized = this.#normalizePath(pattern);
1543
+ if (!/[*?[\]{}]/.test(normalized) && !normalized.includes("*")) if (this.isDirectorySync(normalized)) results.push(...await this.list(normalized));
1544
+ else {
1545
+ const resolved = await this.resolve(normalized);
1546
+ if (resolved && !results.includes(resolved)) results.push(resolved);
1547
+ }
1548
+ else {
1549
+ const absPattern = isAbsolutePath(normalized) ? normalized : this.#normalizePath(appendPath(normalized, this.#context.config.cwd));
1550
+ await Promise.all((await this.list(stripStars(absPattern))).map(async (file) => {
1551
+ if (globToRegex(absPattern).test(file)) {
1552
+ const resolved = await this.resolve(file);
1553
+ if (resolved && !results.includes(resolved)) results.push(resolved);
1554
+ }
1555
+ }));
1556
+ }
1557
+ }
1558
+ return results;
1559
+ }
1560
+ /**
1561
+ * Synchronously glob files in the virtual file system (VFS) based on the provided pattern(s).
1562
+ *
1563
+ * @param patterns - A pattern (or multiple patterns) to use to determine the file paths to return
1564
+ * @returns An array of file paths matching the provided pattern(s)
1565
+ */
1566
+ globSync(patterns) {
1567
+ const results = [];
1568
+ for (const pattern of normalizeGlobPatterns(this.#context.config.cwd, patterns)) {
1569
+ const normalized = this.#normalizePath(pattern);
1570
+ if (!/[*?[\]{}]/.test(normalized) && !normalized.includes("*")) if (this.isDirectorySync(normalized)) results.push(...this.listSync(normalized));
1571
+ else {
1572
+ const resolved = this.resolveSync(normalized);
1573
+ if (resolved && !results.includes(resolved)) results.push(resolved);
1574
+ }
1575
+ else {
1576
+ const absPattern = isAbsolutePath(normalized) ? normalized : this.#normalizePath(appendPath(normalized, this.#context.config.cwd));
1577
+ const files = this.listSync(stripStars(absPattern));
1578
+ for (const file of files) if (globToRegex(absPattern).test(file)) {
1579
+ const resolved = this.resolveSync(file);
1580
+ if (resolved && !results.includes(resolved)) results.push(resolved);
1581
+ }
1582
+ }
1583
+ }
1584
+ return results;
1585
+ }
1586
+ /**
1587
+ * Copies a file from one path to another in the virtual file system (VFS).
1588
+ *
1589
+ * @param srcPath - The source path to copy
1590
+ * @param destPath - The destination path to copy to
1591
+ */
1592
+ async copy(srcPath, destPath) {
1593
+ const src = srcPath instanceof URL ? fileURLToPath(srcPath) : srcPath;
1594
+ const dest = destPath instanceof URL ? fileURLToPath(destPath) : destPath;
1595
+ if (!isSetString(src) && (!isSetObject(src) || !isSetString(src.input)) || !isSetString(dest)) return;
1596
+ const sourceStr = isString(src) ? src : src.input ? src.input : this.#context.config.cwd;
1597
+ const source = await this.resolve(sourceStr);
1598
+ if (!source) return;
1599
+ if (this.isDirectorySync(source) || isSetString(src) && src.includes("*") || isSetObject(src) && isSetString(src.glob)) await Promise.all((await this.glob(src)).map(async (file) => {
1600
+ return this.copy(file, appendPath(replacePath(file, sourceStr), dest));
1601
+ }));
1602
+ else {
1603
+ const content = await this.read(source);
1604
+ if (content !== void 0) await this.write(this.#normalizePath(dest), content, { skipFormat: true });
1605
+ }
1606
+ }
1607
+ /**
1608
+ * Synchronously copies a file from one path to another in the virtual file system (VFS).
1609
+ *
1610
+ * @param srcPath - The source path to copy
1611
+ * @param destPath - The destination path to copy to
1612
+ */
1613
+ copySync(srcPath, destPath) {
1614
+ const src = srcPath instanceof URL ? fileURLToPath(srcPath) : srcPath;
1615
+ const dest = destPath instanceof URL ? fileURLToPath(destPath) : destPath;
1616
+ if (!isSetString(src) && (!isSetObject(src) || !isSetString(src.input)) || !isSetString(dest)) return;
1617
+ const sourceStr = isString(src) ? src : src.input ? src.input : this.#context.config.cwd;
1618
+ const source = this.resolveSync(sourceStr);
1619
+ if (!source) return;
1620
+ if (this.isDirectorySync(source) || isSetString(src) && src.includes("*") || isSetObject(src) && isSetString(src.glob)) this.globSync(src).map((file) => {
1621
+ return this.copySync(file, appendPath(findFilePath(replacePath(file, sourceStr)), dest));
1622
+ });
1623
+ else {
1624
+ const content = this.readSync(source);
1625
+ if (content !== void 0) this.writeSync(this.#normalizePath(hasFileExtension(dest) ? dest : appendPath(findFileName(source), dest)), content, { skipFormat: true });
1626
+ }
1627
+ }
1628
+ /**
1629
+ * Moves a file (or files) from one path to another in the virtual file system (VFS).
1630
+ *
1631
+ * @param srcPath - The source path to move
1632
+ * @param destPath - The destination path to move to
1633
+ */
1634
+ async move(srcPath, destPath) {
1635
+ if (hasFileExtension(srcPath)) {
1636
+ await this.copy(srcPath, destPath);
1637
+ await this.remove(srcPath);
1638
+ } else await Promise.all((await this.list(srcPath)).map(async (file) => {
1639
+ await this.copy(file, destPath);
1640
+ await this.remove(file);
1641
+ }));
1642
+ }
1643
+ /**
1644
+ * Synchronously moves a file (or files) from one path to another in the virtual file system (VFS).
1645
+ *
1646
+ * @param srcPath - The source path to move
1647
+ * @param destPath - The destination path to move to
1648
+ */
1649
+ moveSync(srcPath, destPath) {
1650
+ if (hasFileExtension(srcPath)) {
1651
+ this.copySync(srcPath, destPath);
1652
+ this.removeSync(srcPath);
1653
+ } else this.listSync(srcPath).forEach((file) => {
1654
+ this.copySync(file, destPath);
1655
+ this.removeSync(file);
1656
+ });
1657
+ }
1658
+ /**
1659
+ * Asynchronously reads a file from the virtual file system (VFS).
1660
+ *
1661
+ * @param path - The path or ID of the file to read.
1662
+ * @returns A promise that resolves to the contents of the file as a string, or undefined if the file does not exist.
1663
+ */
1664
+ async read(path) {
1665
+ const filePath = await this.resolve(path, void 0, { isFile: true });
1666
+ if (!filePath || !this.existsSync(filePath)) return;
1667
+ const { adapter } = this.#getStorage(filePath);
1668
+ this.#log(LogLevelLabel.TRACE, `Reading ${adapter.name} file: ${filePath}`);
1669
+ return await adapter.get(filePath) ?? void 0;
1670
+ }
1671
+ /**
1672
+ * Synchronously reads a file from the virtual file system (VFS).
1673
+ *
1674
+ * @param path - The path or ID of the file to read.
1675
+ * @returns The contents of the file as a string, or undefined if the file does not exist.
1676
+ */
1677
+ readSync(path) {
1678
+ const filePath = this.resolveSync(path, void 0, { isFile: true });
1679
+ if (!filePath || !this.existsSync(filePath)) return;
1680
+ const { adapter } = this.#getStorage(filePath);
1681
+ this.#log(LogLevelLabel.TRACE, `Reading ${adapter.name} file: ${filePath}`);
1682
+ return adapter.getSync(filePath) ?? void 0;
1683
+ }
1684
+ /**
1685
+ * Writes a file to the virtual file system (VFS).
1686
+ *
1687
+ * @param path - The path to the file.
1688
+ * @param data - The contents of the file.
1689
+ * @param options - Optional parameters for writing the file.
1690
+ * @returns A promise that resolves when the file is written.
1691
+ */
1692
+ async write(path, data = "", options = {}) {
1693
+ const meta = options.meta ?? {};
1694
+ const resolvedPath = await this.resolve(this.#normalizePath(path)) || path;
1695
+ const { relativeKey, adapter } = this.#getStorage(resolvedPath, options.storage);
1696
+ this.#log(LogLevelLabel.TRACE, `Writing ${resolvedPath} to ${adapter.name === "virtual" ? "the virtual file system" : adapter.name === "file-system" ? "the local file system" : adapter.name} (size: ${prettyBytes(new Blob$1(toArray(data)).size)})`);
1697
+ let code = data;
1698
+ try {
1699
+ if (!options.skipFormat) code = await format(this.#context, resolvedPath, data);
1700
+ } catch (err) {
1701
+ if (DEFAULT_EXTENSIONS.includes(findFileExtensionSafe(resolvedPath, { fullExtension: true }))) this.#log(LogLevelLabel.WARN, `Failed to format file ${resolvedPath} before writing: ${err.message}`);
1702
+ code = data;
1703
+ }
1704
+ this.#log(LogLevelLabel.TRACE, `Writing ${resolvedPath} to ${adapter.name === "virtual" ? "the virtual file system" : adapter.name === "file-system" ? "the local file system" : adapter.name} (size: ${prettyBytes(new Blob$1(toArray(code)).size)})`);
1705
+ const id = this.#normalizeId(meta.id || resolvedPath);
1706
+ this.metadata[id] = {
1707
+ type: "normal",
1708
+ timestamp: Date.now(),
1709
+ ...this.metadata[id] ?? {},
1710
+ ...meta
1711
+ };
1712
+ this.paths[id] = resolvedPath;
1713
+ this.ids[resolvedPath] = id;
1714
+ return adapter.set(relativeKey, code);
1715
+ }
1716
+ /**
1717
+ * Synchronously writes a file to the virtual file system (VFS).
1718
+ *
1719
+ * @param path - The file to write.
1720
+ * @param data - The contents of the file.
1721
+ * @param options - Optional parameters for writing the file.
1722
+ */
1723
+ writeSync(path, data = "", options = {}) {
1724
+ const meta = options.meta ?? {};
1725
+ const resolvedPath = this.resolveSync(this.#normalizePath(path)) || path;
1726
+ const { relativeKey, adapter } = this.#getStorage(resolvedPath, options.storage);
1727
+ this.#log(LogLevelLabel.TRACE, `Writing ${resolvedPath} file to ${adapter.name === "virtual" ? "the virtual file system" : adapter.name === "file-system" ? "the local file system" : adapter.name} (size: ${prettyBytes(new Blob$1(toArray(data)).size)})`);
1728
+ const id = this.#normalizeId(meta.id || resolvedPath);
1729
+ this.metadata[id] = {
1730
+ type: "normal",
1731
+ timestamp: Date.now(),
1732
+ ...this.metadata[id] ?? {},
1733
+ ...meta
1734
+ };
1735
+ this.paths[id] = resolvedPath;
1736
+ this.ids[resolvedPath] = id;
1737
+ return adapter.setSync(relativeKey, data);
1738
+ }
1739
+ /**
1740
+ * Synchronously creates a directory at the specified path.
1741
+ *
1742
+ * @param dirPath - The path of the directory to create.
1743
+ */
1744
+ mkdirSync(dirPath) {
1745
+ return this.#getStorage(dirPath)?.adapter?.mkdirSync(dirPath);
1746
+ }
1747
+ /**
1748
+ * Creates a directory at the specified path.
1749
+ *
1750
+ * @param path - The path of the directory to create.
1751
+ */
1752
+ async mkdir(path) {
1753
+ return this.#getStorage(path)?.adapter?.mkdir(path);
1754
+ }
1755
+ /**
1756
+ * Retrieves the metadata of a file in the virtual file system (VFS).
1757
+ *
1758
+ * @param pathOrId - The path or ID of the file to retrieve metadata for.
1759
+ * @returns The metadata of the file, or undefined if the file does not exist.
1760
+ */
1761
+ getMetadata(pathOrId) {
1762
+ const resolved = this.resolveSync(pathOrId);
1763
+ if (resolved && this.metadata[resolved]) return this.metadata[resolved];
1764
+ }
1765
+ /**
1766
+ * Resolves a given module ID using the configured aliases.
1767
+ *
1768
+ * @remarks
1769
+ * This function can be used to map module IDs to different paths based on the alias configuration.
1770
+ *
1771
+ * @param id - The module ID to resolve.
1772
+ * @returns The resolved module ID - after applying any configured aliases (this will be the same as the input ID if no aliases match).
1773
+ */
1774
+ resolveAlias(id) {
1775
+ let path = id;
1776
+ if (this.#context.config.resolve.alias) {
1777
+ if (Array.isArray(this.#context.config.resolve.alias) && this.#context.config.resolve.alias.length > 0) {
1778
+ const found = this.#context.config.resolve.alias.filter((alias) => isSetString(alias.find) && (alias.find === path || path.startsWith(`${alias.find}/`)) || isRegExp(alias.find) && alias.find.test(path));
1779
+ if (found.length > 0) {
1780
+ const alias = found.reduce((ret, current) => {
1781
+ return (isSetString(ret.find) ? ret.find.length : isRegExp(ret.find) ? ret.find.source.length : 0) > (isSetString(current.find) ? current.find.length : isRegExp(current.find) ? current.find.source.length : 0) ? ret : current;
1782
+ });
1783
+ if (isSetString(alias.find)) path = path.replace(new RegExp(`^${alias.find}`), alias.replacement);
1784
+ else if (isRegExp(alias.find)) path = path.replace(alias.find, alias.replacement);
1785
+ }
1786
+ } else if (isSetObject(this.#context.config.resolve.alias)) {
1787
+ const found = Object.keys(this.#context.config.resolve.alias).filter((key) => key === path || path.startsWith(`${key}/`));
1788
+ if (found.length > 0) {
1789
+ const alias = found.reduce((ret, current) => {
1790
+ return ret.length > current.length ? ret : current;
1791
+ });
1792
+ path = path.replace(new RegExp(`^${alias}`), this.#context.config.resolve.alias[alias]);
1793
+ }
1794
+ }
1795
+ }
1796
+ return path;
1797
+ }
1798
+ /**
1799
+ * Checks if a given module ID is an alias.
1800
+ *
1801
+ * @remarks
1802
+ * This function can be used to determine if a module ID matches any configured aliases.
1803
+ *
1804
+ * @param id - The module ID to check.
1805
+ * @returns A boolean indicating whether the module ID is an alias.
1806
+ */
1807
+ isAlias(id) {
1808
+ const path = id;
1809
+ if (this.#context.config.resolve.alias) {
1810
+ if (Array.isArray(this.#context.config.resolve.alias) && this.#context.config.resolve.alias.length > 0) return this.#context.config.resolve.alias.filter((alias) => isSetString(alias.find) && (alias.find === path || path.startsWith(`${alias.find}/`)) || isRegExp(alias.find) && alias.find.test(path)).length > 0;
1811
+ else if (isSetObject(this.#context.config.resolve.alias)) return Object.keys(this.#context.config.resolve.alias).filter((key) => key === path || path.startsWith(`${key}/`)).length > 0;
1812
+ }
1813
+ return false;
1814
+ }
1815
+ /**
1816
+ * Checks if a given module ID is a tsconfig path.
1817
+ *
1818
+ * @remarks
1819
+ * This function can be used to determine if a module ID matches any configured tsconfig paths.
1820
+ *
1821
+ * @param id - The module ID to check.
1822
+ * @returns A boolean indicating whether the module ID is a tsconfig path.
1823
+ */
1824
+ isTsconfigPath(id) {
1825
+ return !!(this.#context.tsconfig.options.paths && Object.keys(this.#context.tsconfig.options.paths).length > 0 && match(id, this.#context.resolvePatterns));
1826
+ }
1827
+ /**
1828
+ * A helper function to resolve modules in the virtual file system (VFS).
1829
+ *
1830
+ * @remarks
1831
+ * This function can be used to resolve modules relative to the project root directory.
1832
+ *
1833
+ * @example
1834
+ * ```ts
1835
+ * const resolved = await context.resolvePath("some-module", "/path/to/importer");
1836
+ * ```
1837
+ *
1838
+ * @param id - The module to resolve.
1839
+ * @param importer - An optional path to the importer module.
1840
+ * @param options - Additional resolution options.
1841
+ * @returns A promise that resolves to the resolved module path.
1842
+ */
1843
+ async resolve(id, importer, options = {}) {
1844
+ const origResult = await this.#innerResolve(id, importer, options);
1845
+ if (origResult && options.isFile && await this.isDirectory(origResult)) {
1846
+ const indexResult = await this.resolve(joinPaths$1(origResult, "index"), importer, options);
1847
+ if (indexResult) return indexResult;
1848
+ if (!hasFileExtension(origResult)) for (const ext of DEFAULT_EXTENSIONS) {
1849
+ const extResult = await this.resolve(`${origResult}.${ext}`, importer, options);
1850
+ if (extResult) return extResult;
1851
+ }
1852
+ return;
1853
+ }
1854
+ return origResult;
1855
+ }
1856
+ /**
1857
+ * A synchronous helper function to resolve modules using the Jiti resolver
1858
+ *
1859
+ * @remarks
1860
+ * This function can be used to resolve modules relative to the project root directory.
1861
+ *
1862
+ * @example
1863
+ * ```ts
1864
+ * const resolvedPath = context.resolveSync("some-module", "/path/to/importer");
1865
+ * ```
1866
+ *
1867
+ * @param id - The module to resolve.
1868
+ * @param importer - An optional path to the importer module.
1869
+ * @param options - Additional resolution options.
1870
+ * @returns The resolved module path.
1871
+ */
1872
+ resolveSync(id, importer, options = {}) {
1873
+ const origResult = this.#innerResolveSync(id, importer, options);
1874
+ if (origResult && options.isFile && this.isDirectorySync(origResult)) {
1875
+ const indexResult = this.resolveSync(joinPaths$1(origResult, "index"), importer, options);
1876
+ if (indexResult) return indexResult;
1877
+ if (!hasFileExtension(origResult)) for (const ext of DEFAULT_EXTENSIONS) {
1878
+ const extResult = this.resolveSync(`${origResult}.${ext}`, importer, options);
1879
+ if (extResult) return extResult;
1880
+ }
1881
+ return;
1882
+ }
1883
+ return origResult;
1884
+ }
1885
+ /**
1886
+ * Disposes of the virtual file system (VFS) by saving its state to disk.
1887
+ */
1888
+ async dispose() {
1889
+ if (!this.#isDisposed) {
1890
+ this.#isDisposed = true;
1891
+ this.#log(LogLevelLabel.DEBUG, "Disposing virtual file system...");
1892
+ await this.remove(joinPaths$1(this.#context.dataPath, "fs.bin"));
1893
+ const message = new $.Message();
1894
+ const fs = message.initRoot(FileSystem);
1895
+ const storage = fs._initStorage(Object.keys(this.#paths).length);
1896
+ await Promise.all(Object.values(this.#paths).map(async (path, index) => {
1897
+ const code = await this.read(path);
1898
+ const fd = storage.get(index);
1899
+ fd.path = path;
1900
+ fd.code = code || "";
1901
+ }));
1902
+ const ids = fs._initIds(Object.keys(this.#ids).length);
1903
+ Object.entries(this.#ids).filter(([, id]) => id).forEach(([path, id], index) => {
1904
+ const fileId = ids.get(index);
1905
+ fileId.id = id;
1906
+ fileId.path = path;
1907
+ });
1908
+ const metadata = fs._initMetadata(Object.keys(this.#metadata).length);
1909
+ Object.entries(this.#metadata).filter(([, value]) => value).forEach(([id, value], index) => {
1910
+ const fileMetadata = metadata.get(index);
1911
+ fileMetadata.id = id;
1912
+ fileMetadata.type = value.type;
1913
+ fileMetadata.timestamp = value.timestamp ?? Date.now();
1914
+ if (value.properties) {
1915
+ const props = fileMetadata._initProperties(Object.keys(value.properties).length);
1916
+ Object.entries(value.properties).filter(([, val]) => isSetString(val)).forEach(([key, val], index) => {
1917
+ const prop = props.get(index);
1918
+ prop.key = key;
1919
+ prop.value = val;
1920
+ });
1921
+ }
1922
+ });
1923
+ await writeFileBuffer(joinPaths$1(this.#context.dataPath, "fs.bin"), message.toArrayBuffer());
1924
+ if (!this.#context.config.skipCache) this.resolverCache.save(true);
1925
+ await Promise.all(this.#getStorages().map(async (storage) => storage.adapter.dispose()));
1926
+ this.#log(LogLevelLabel.TRACE, "Virtual file system has been disposed.");
1927
+ }
1928
+ }
1929
+ async [Symbol.asyncDispose]() {
1930
+ return this.dispose();
1931
+ }
1932
+ };
1933
+
1934
+ //#endregion
1935
+ //#region src/typescript/tsconfig.ts
1936
+ /**
1937
+ * Get the path to the tsconfig.json file.
1938
+ *
1939
+ * @param workspaceRoot - The root directory of the workspace.
1940
+ * @param projectRoot - The root directory of the project.
1941
+ * @param tsconfig - The path to the tsconfig.json file.
1942
+ * @returns The absolute path to the tsconfig.json file.
1943
+ * @throws If the tsconfig.json file does not exist.
1944
+ */
1945
+ function getTsconfigFilePath(workspaceRoot, projectRoot, tsconfig) {
1946
+ let tsconfigFilePath;
1947
+ if (tsconfig) tsconfigFilePath = tryTsconfigFilePath(workspaceRoot, projectRoot, tsconfig);
1948
+ else {
1949
+ tsconfigFilePath = tryTsconfigFilePath(workspaceRoot, projectRoot, "tsconfig.app.json");
1950
+ if (!tsconfigFilePath) {
1951
+ tsconfigFilePath = tryTsconfigFilePath(workspaceRoot, projectRoot, "tsconfig.lib.json");
1952
+ if (!tsconfigFilePath) tsconfigFilePath = tryTsconfigFilePath(workspaceRoot, projectRoot, "tsconfig.json");
1953
+ }
1954
+ }
1955
+ if (!tsconfigFilePath) throw new Error(`Cannot find the \`tsconfig.json\` configuration file for the project at ${projectRoot}.`);
1956
+ return tsconfigFilePath;
1957
+ }
1958
+ /**
1959
+ * Get the path to the tsconfig.json file.
1960
+ *
1961
+ * @param workspaceRoot - The root directory of the workspace.
1962
+ * @param projectRoot - The root directory of the project.
1963
+ * @param tsconfig - The path to the tsconfig.json file.
1964
+ * @returns The absolute path to the tsconfig.json file.
1965
+ * @throws If the tsconfig.json file does not exist.
1966
+ */
1967
+ function tryTsconfigFilePath(workspaceRoot, projectRoot, tsconfig) {
1968
+ let tsconfigFilePath = tsconfig;
1969
+ if (!existsSync(tsconfigFilePath)) {
1970
+ tsconfigFilePath = appendPath(tsconfig, projectRoot);
1971
+ if (!existsSync(tsconfigFilePath)) {
1972
+ tsconfigFilePath = appendPath(tsconfig, appendPath(projectRoot, workspaceRoot));
1973
+ if (!existsSync(tsconfigFilePath)) return;
1974
+ }
1975
+ }
1976
+ return tsconfigFilePath;
1977
+ }
1978
+ /**
1979
+ * Check if the TypeScript configuration type matches any of the provided types.
1980
+ *
1981
+ * @param tsconfigType - The type from the TypeScript configuration.
1982
+ * @param types - An array of type names to check against.
1983
+ * @returns True if the TypeScript configuration type matches any of the provided types, false otherwise.
1984
+ */
1985
+ function findMatch(tsconfigType, types, extensions = [
1986
+ ".ts",
1987
+ ".tsx",
1988
+ ".d.ts"
1989
+ ]) {
1990
+ return types.find((type) => tsconfigType?.toString().toLowerCase() === type?.toString().toLowerCase() || tsconfigType?.toString().toLowerCase() === `./${type?.toString().toLowerCase()}` || `./${tsconfigType?.toString().toLowerCase()}` === type?.toString().toLowerCase() || extensions.some((ext) => `${tsconfigType?.toString().toLowerCase()}${ext}` === type?.toString().toLowerCase() || `${tsconfigType?.toString().toLowerCase()}${ext}` === `./${type?.toString().toLowerCase()}` || `${type?.toString().toLowerCase()}${ext}` === `./${tsconfigType?.toString().toLowerCase()}` || tsconfigType?.toString().toLowerCase() === `${type?.toString().toLowerCase()}${ext}` || tsconfigType?.toString().toLowerCase() === `./${type?.toString().toLowerCase()}${ext}` || type?.toString().toLowerCase() === `./${tsconfigType?.toString().toLowerCase()}${ext}`));
1991
+ }
1992
+ /**
1993
+ * Check if the TypeScript configuration type matches any of the provided types.
1994
+ *
1995
+ * @param tsconfigType - The type from the TypeScript configuration.
1996
+ * @param types - An array of type names to check against.
1997
+ * @returns True if the TypeScript configuration type matches any of the provided types, false otherwise.
1998
+ */
1999
+ function findIncludeMatch(tsconfigType, types) {
2000
+ return findMatch(tsconfigType, types, [
2001
+ ".ts",
2002
+ ".tsx",
2003
+ ".d.ts",
2004
+ ".js",
2005
+ ".jsx",
2006
+ ".mjs",
2007
+ ".cjs",
2008
+ ".mts",
2009
+ ".cts",
2010
+ "/*.ts",
2011
+ "/*.tsx",
2012
+ "/*.d.ts",
2013
+ "/*.js",
2014
+ "/*.jsx",
2015
+ "/*.mjs",
2016
+ "/*.cjs",
2017
+ "/*.mts",
2018
+ "/*.cts",
2019
+ "/**/*.ts",
2020
+ "/**/*.tsx",
2021
+ "/**/*.d.ts",
2022
+ "/**/*.js",
2023
+ "/**/*.jsx",
2024
+ "/**/*.mjs",
2025
+ "/**/*.cjs",
2026
+ "/**/*.mts",
2027
+ "/**/*.cts"
2028
+ ]);
2029
+ }
2030
+ /**
2031
+ * Check if the TypeScript configuration type matches any of the provided types.
2032
+ *
2033
+ * @param tsconfigType - The type from the TypeScript configuration.
2034
+ * @param types - An array of type names to check against.
2035
+ * @returns True if the TypeScript configuration type matches any of the provided types, false otherwise.
2036
+ */
2037
+ function isIncludeMatchFound(tsconfigType, types) {
2038
+ return findIncludeMatch(tsconfigType, types) !== void 0;
2039
+ }
2040
+ /**
2041
+ * Get the parsed TypeScript configuration.
2042
+ *
2043
+ * @param workspaceRoot - The root directory of the workspace.
2044
+ * @param projectRoot - The root directory of the project.
2045
+ * @param tsconfig - The path to the tsconfig.json file.
2046
+ * @param tsconfigRaw - The raw tsconfig.json content.
2047
+ * @param originalTsconfigJson - The original tsconfig.json content.
2048
+ * @param host - The TypeScript parse config host.
2049
+ * @returns The resolved TypeScript configuration.
2050
+ */
2051
+ function getParsedTypeScriptConfig(workspaceRoot, projectRoot, tsconfig, tsconfigRaw = {}, originalTsconfigJson, host = ts.sys) {
2052
+ const tsconfigFilePath = getTsconfigFilePath(workspaceRoot, projectRoot, tsconfig);
2053
+ const tsconfigJson = readJsonFileSync(tsconfigFilePath);
2054
+ if (!tsconfigJson) throw new Error(`Cannot find the \`tsconfig.json\` configuration file at ${joinPaths(projectRoot, tsconfig ?? "tsconfig.json")}`);
2055
+ const parsedCommandLine = ts.parseJsonConfigFileContent(defu(tsconfigRaw ?? {}, tsconfigJson), host, appendPath(projectRoot, workspaceRoot));
2056
+ if (parsedCommandLine.errors.length > 0) {
2057
+ const errorMessage = `Cannot parse the TypeScript compiler options. Please investigate the following issues:
2058
+ ${parsedCommandLine.errors.map((error) => `- ${(error.category !== void 0 && error.code ? `[${error.category}-${error.code}]: ` : "") + error.messageText.toString()}`).join("\n")}
2059
+ `;
2060
+ throw new Error(errorMessage);
2061
+ }
2062
+ return {
2063
+ ...parsedCommandLine,
2064
+ originalTsconfigJson: originalTsconfigJson ?? tsconfigJson,
2065
+ tsconfigJson,
2066
+ tsconfigFilePath
2067
+ };
2068
+ }
2069
+
2070
+ //#endregion
2071
+ //#region src/_internal/helpers/resolver.ts
2072
+ /**
2073
+ * Create a Jiti resolver for the given workspace and project root.
2074
+ *
2075
+ * @param options - The options for creating the resolver.
2076
+ * @returns A Jiti instance configured for the specified workspace and project root.
2077
+ */
2078
+ function resolveOptions(options) {
2079
+ return defu(options, {
2080
+ interopDefault: true,
2081
+ fsCache: options.mode !== "development" ? joinPaths(options.cacheDir, "jiti") : false,
2082
+ moduleCache: options.mode !== "development"
2083
+ });
2084
+ }
2085
+ /**
2086
+ * Create a Jiti resolver for the given workspace and project root.
2087
+ *
2088
+ * @param options - The options for creating the resolver.
2089
+ * @returns A Jiti instance configured for the specified workspace and project root.
2090
+ */
2091
+ function createResolver(options) {
2092
+ const baseResolver = createJiti(joinPaths(options.workspaceRoot, options.root), resolveOptions(options));
2093
+ baseResolver.plugin = createJiti(joinPaths(options.workspaceRoot, options.root), resolveOptions(options));
2094
+ return baseResolver;
2095
+ }
2096
+
2097
+ //#endregion
2098
+ //#region src/context/base-context.ts
2099
+ var PowerlinesBaseContext = class PowerlinesBaseContext {
2100
+ #timestamp = Date.now();
2101
+ #logLevel = "info";
2102
+ /**
2103
+ * The path to the Powerlines package
2104
+ */
2105
+ powerlinesPath;
2106
+ /**
2107
+ * The module resolver for the project
2108
+ */
2109
+ resolver;
2110
+ /**
2111
+ * The options provided to the Powerlines process
2112
+ */
2113
+ options;
2114
+ /**
2115
+ * The parsed configuration file for the project
2116
+ */
2117
+ configFile;
2118
+ /**
2119
+ * A timestamp representing when the context was initialized
2120
+ */
2121
+ get timestamp() {
2122
+ return new Date(this.#timestamp);
2123
+ }
2124
+ get logLevel() {
2125
+ return this.#logLevel || "info";
2126
+ }
2127
+ set logLevel(level) {
2128
+ this.#logLevel = level;
2129
+ }
2130
+ /**
2131
+ * The logger function
2132
+ */
2133
+ get log() {
2134
+ const level = this.logLevel || "info";
2135
+ if (!this.logger || this.logger.level !== level) this.logger = {
2136
+ log: this.createLog(),
2137
+ level
2138
+ };
2139
+ return this.logger.log;
2140
+ }
2141
+ /**
2142
+ * The environment paths for the project
2143
+ */
2144
+ get envPaths() {
2145
+ return getEnvPaths({
2146
+ orgId: this.options.organization,
2147
+ appId: this.options.framework || "powerlines",
2148
+ workspaceRoot: this.options.cwd || process.cwd() || "."
2149
+ });
2150
+ }
2151
+ /**
2152
+ * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.
2153
+ *
2154
+ * @remarks
2155
+ * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.
2156
+ *
2157
+ * @returns A promise that resolves to the cloned context.
2158
+ */
2159
+ async clone() {
2160
+ const clone = new PowerlinesBaseContext();
2161
+ await clone.init(this.options);
2162
+ return clone;
2163
+ }
2164
+ /**
2165
+ * A logging function for fatal messages
2166
+ *
2167
+ * @param message - The message to log.
2168
+ */
2169
+ fatal(message) {
2170
+ this.log(LogLevelLabel.FATAL, isString(message) ? message : StormJSON.stringify(message));
2171
+ }
2172
+ /**
2173
+ * A logging function for error messages
2174
+ *
2175
+ * @param message - The message to log.
2176
+ */
2177
+ error(message) {
2178
+ this.log(LogLevelLabel.ERROR, isString(message) ? message : StormJSON.stringify(message));
2179
+ }
2180
+ /**
2181
+ * A logging function for warning messages
2182
+ *
2183
+ * @param message - The message to log.
2184
+ */
2185
+ warn(message) {
2186
+ this.log(LogLevelLabel.WARN, isString(message) ? message : StormJSON.stringify(message));
2187
+ }
2188
+ /**
2189
+ * A logging function for informational messages
2190
+ *
2191
+ * @param message - The message to log.
2192
+ */
2193
+ info(message) {
2194
+ this.log(LogLevelLabel.INFO, isString(message) ? message : StormJSON.stringify(message));
2195
+ }
2196
+ /**
2197
+ * A logging function for debug messages
2198
+ *
2199
+ * @param message - The message to log.
2200
+ */
2201
+ debug(message) {
2202
+ this.log(LogLevelLabel.DEBUG, isString(message) ? message : StormJSON.stringify(message));
2203
+ }
2204
+ /**
2205
+ * A logging function for trace messages
2206
+ *
2207
+ * @param message - The message to log.
2208
+ */
2209
+ trace(message) {
2210
+ this.log(LogLevelLabel.TRACE, isString(message) ? message : StormJSON.stringify(message));
2211
+ }
2212
+ /**
2213
+ * A function to create a timer for measuring the duration of asynchronous operations
2214
+ *
2215
+ * @example
2216
+ * ```ts
2217
+ * const stopTimer = context.timer("Your Async Operation");
2218
+ * await performAsyncOperation();
2219
+ * stopTimer(); // "Your Async Operation completed in 123.45 milliseconds"
2220
+ * ```
2221
+ *
2222
+ * @param name - The name of the timer.
2223
+ * @returns A function that, when called, stops the timer and logs the duration.
2224
+ */
2225
+ timer(name) {
2226
+ const startDate = Date.now();
2227
+ const startDuration = performance.now();
2228
+ return () => {
2229
+ const duration = performance.now() - startDuration;
2230
+ this.log(LogLevelLabel.PERFORMANCE, `${chalk.bold.cyanBright(name)} completed in ${chalk.bold.cyanBright(duration < 1e3 ? `${duration.toFixed(2)} milliseconds` : formatDistanceToNowStrict(startDate))}`);
2231
+ };
2232
+ }
2233
+ /**
2234
+ * Create a new logger instance
2235
+ *
2236
+ * @param name - The name to use for the logger instance
2237
+ * @returns A logger function
2238
+ */
2239
+ createLog(name = null) {
2240
+ return createLog(name, {
2241
+ ...this.options,
2242
+ logLevel: isNull(this.logLevel) ? "silent" : this.logLevel
2243
+ });
2244
+ }
2245
+ /**
2246
+ * Extend the current logger instance with a new name
2247
+ *
2248
+ * @param name - The name to use for the extended logger instance
2249
+ * @returns A logger function
2250
+ */
2251
+ extendLog(name) {
2252
+ return extendLog(this.log, name);
2253
+ }
2254
+ /**
2255
+ * A logger function specific to this context
2256
+ */
2257
+ logger;
2258
+ /**
2259
+ * Initialize the context with the provided configuration options
2260
+ *
2261
+ * @remarks
2262
+ * This method will set up the resolver and load the user configuration file based on the provided options. It is called during the construction of the context and can also be called when cloning the context to ensure that the new context has the same configuration and resolver setup.
2263
+ *
2264
+ * @param options - The configuration options to initialize the context with
2265
+ */
2266
+ async init(options = {}) {
2267
+ if (!this.powerlinesPath) {
2268
+ const powerlinesPath = await resolvePackage("powerlines");
2269
+ if (!powerlinesPath) throw new Error("Could not resolve `powerlines` package location.");
2270
+ this.powerlinesPath = powerlinesPath;
2271
+ }
2272
+ this.options = defu({
2273
+ root: options.root,
2274
+ cwd: options.cwd,
2275
+ mode: options.mode,
2276
+ framework: options.framework,
2277
+ organization: options.organization,
2278
+ configFile: options.configFile
2279
+ }, this.options ?? {}, {
2280
+ cwd: process.cwd() || ".",
2281
+ mode: "production",
2282
+ framework: "powerlines"
2283
+ });
2284
+ this.resolver = createResolver({
2285
+ workspaceRoot: this.options.cwd,
2286
+ root: this.options.root,
2287
+ cacheDir: this.envPaths.cache,
2288
+ mode: this.options.mode,
2289
+ logLevel: this.logLevel
2290
+ });
2291
+ this.configFile = await loadUserConfigFile(this.options, this.resolver);
2292
+ }
2293
+ };
2294
+
2295
+ //#endregion
2296
+ //#region src/context/context.ts
2297
+ setGlobalDispatcher(new Agent({ keepAliveTimeout: 1e4 }).compose(interceptors.retry({
2298
+ maxRetries: 3,
2299
+ minTimeout: 1e3,
2300
+ maxTimeout: 1e4,
2301
+ timeoutFactor: 2,
2302
+ retryAfter: true
2303
+ })));
2304
+ var PowerlinesContext = class PowerlinesContext extends PowerlinesBaseContext {
2305
+ /**
2306
+ * Internal references storage
2307
+ *
2308
+ * @danger
2309
+ * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
2310
+ *
2311
+ * @internal
2312
+ */
2313
+ #internal = {};
2314
+ #checksum = null;
2315
+ #buildId = uuid();
2316
+ #releaseId = uuid();
2317
+ #fs;
2318
+ #tsconfig;
2319
+ #parserCache;
2320
+ #requestCache;
2321
+ #getConfigProps(config = {}) {
2322
+ return mergeConfig({
2323
+ name: config.name,
2324
+ title: config.title,
2325
+ compatibilityDate: resolveCompatibilityDates(config.compatibilityDate, "latest"),
2326
+ description: config.description,
2327
+ projectType: config.projectType,
2328
+ customLogger: config.customLogger,
2329
+ logLevel: config.logLevel,
2330
+ tsconfig: config.tsconfig,
2331
+ tsconfigRaw: config.tsconfigRaw,
2332
+ skipCache: config.skipCache,
2333
+ autoInstall: config.autoInstall,
2334
+ input: isSetString(config.input) ? [config.input] : config.input,
2335
+ plugins: config.plugins,
2336
+ mode: config.mode,
2337
+ resolve: config.resolve,
2338
+ framework: config.framework,
2339
+ ...config,
2340
+ output: {
2341
+ ...config.output ?? {},
2342
+ path: config.output?.path ? appendPath(config.output.path, appendPath(this.config.root, this.config.cwd)) : void 0
2343
+ }
2344
+ }, { output: config.framework ? {
2345
+ artifactsPath: `.${config.framework ?? "powerlines"}`,
2346
+ dts: true,
2347
+ types: joinPaths$1(this.config.root, `${config.framework ?? "powerlines"}.d.ts`)
2348
+ } : {} });
2349
+ }
2350
+ /**
2351
+ * Create a new Storm context from the workspace root and user config.
2352
+ *
2353
+ * @param options - The options for resolving the context.
2354
+ * @returns A promise that resolves to the new context.
2355
+ */
2356
+ static async fromOptions(options) {
2357
+ const context = new PowerlinesContext(options);
2358
+ await context.init(options);
2359
+ const powerlinesPath = await resolvePackage("powerlines");
2360
+ if (!powerlinesPath) throw new Error("Could not resolve `powerlines` package location.");
2361
+ context.powerlinesPath = powerlinesPath;
2362
+ return context;
2363
+ }
2364
+ /**
2365
+ * The options provided to the Powerlines process
2366
+ */
2367
+ options;
2368
+ /**
2369
+ * An object containing the dependencies that should be installed for the project
2370
+ */
2371
+ dependencies = {};
2372
+ /**
2373
+ * An object containing the development dependencies that should be installed for the project
2374
+ */
2375
+ devDependencies = {};
2376
+ /**
2377
+ * The persisted meta information about the current build
2378
+ */
2379
+ persistedMeta = void 0;
2380
+ /**
2381
+ * The parsed `package.json` file for the project
2382
+ */
2383
+ packageJson;
2384
+ /**
2385
+ * The parsed `project.json` file for the project
2386
+ */
2387
+ projectJson = void 0;
2388
+ /**
2389
+ * The resolved tsconfig file paths for the project
2390
+ */
2391
+ resolvePatterns = [];
2392
+ /**
2393
+ * Internal context fields and methods
2394
+ *
2395
+ * @danger
2396
+ * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
2397
+ *
2398
+ * @internal
2399
+ */
2400
+ get $$internal() {
2401
+ return this.#internal;
2402
+ }
2403
+ /**
2404
+ * Internal context fields and methods
2405
+ *
2406
+ * @danger
2407
+ * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
2408
+ *
2409
+ * @internal
2410
+ */
2411
+ set $$internal(value) {
2412
+ this.#internal = value;
2413
+ }
2414
+ /**
2415
+ * The resolved entry type definitions for the project
2416
+ */
2417
+ get entry() {
2418
+ const entry = this.resolvedEntry;
2419
+ return resolveInputsSync(this, entry && entry.length > 0 ? entry : Array.isArray(this.config.input) || isSetObject(this.config.input) && !isTypeDefinition(this.config.input) ? this.config.input : toArray(this.config.input).flat());
2420
+ }
2421
+ /**
2422
+ * The TypeScript configuration parsed from the tsconfig file
2423
+ */
2424
+ get tsconfig() {
2425
+ if (!this.#tsconfig) this.tsconfig = { tsconfigFilePath: this.config.tsconfig };
2426
+ return this.#tsconfig;
2427
+ }
2428
+ /**
2429
+ * Sets the TypeScript configuration parsed from the tsconfig file
2430
+ */
2431
+ set tsconfig(value) {
2432
+ this.#tsconfig = value;
2433
+ this.resolvePatterns = tsconfigPathsToRegExp(value?.options?.paths ?? {});
2434
+ }
2435
+ /**
2436
+ * The virtual file system interface for the project
2437
+ */
2438
+ get fs() {
2439
+ if (!this.#fs) this.#fs = VirtualFileSystem.createSync(this);
2440
+ return this.#fs;
2441
+ }
2442
+ /**
2443
+ * Get the checksum of the project's current state
2444
+ */
2445
+ get checksum() {
2446
+ return this.#checksum;
2447
+ }
2448
+ /**
2449
+ * The meta information about the current build
2450
+ */
2451
+ get meta() {
2452
+ return {
2453
+ buildId: this.#buildId,
2454
+ releaseId: this.#releaseId,
2455
+ checksum: this.#checksum,
2456
+ timestamp: this.timestamp.getTime(),
2457
+ rootHash: murmurhash({
2458
+ workspaceRoot: this.options?.cwd,
2459
+ root: this.config?.root
2460
+ }, { maxLength: ROOT_HASH_LENGTH }),
2461
+ configHash: murmurhash(this.config, { maxLength: CACHE_HASH_LENGTH })
2462
+ };
2463
+ }
2464
+ /**
2465
+ * The resolved configuration options
2466
+ */
2467
+ get config() {
2468
+ return this.resolvedConfig;
2469
+ }
2470
+ /**
2471
+ * Get the path to the artifacts directory for the project
2472
+ */
2473
+ get artifactsPath() {
2474
+ return joinPaths$1(this.config.cwd, this.config.root, this.config.output.artifactsPath);
2475
+ }
2476
+ /**
2477
+ * Get the path to the builtin modules used by the project
2478
+ */
2479
+ get builtinsPath() {
2480
+ return joinPaths$1(this.artifactsPath, "builtins");
2481
+ }
2482
+ /**
2483
+ * Get the path to the entry directory for the project
2484
+ */
2485
+ get entryPath() {
2486
+ return joinPaths$1(this.artifactsPath, "entry");
2487
+ }
2488
+ /**
2489
+ * Get the path to the infrastructure modules used by the project
2490
+ */
2491
+ get infrastructurePath() {
2492
+ return joinPaths$1(this.artifactsPath, "infrastructure");
2493
+ }
2494
+ /**
2495
+ * Get the path to the data directory for the project
2496
+ */
2497
+ get dataPath() {
2498
+ return joinPaths$1(this.envPaths.data, "projects", getPrefixedRootHash(this.config.name, this.meta.rootHash));
2499
+ }
2500
+ /**
2501
+ * Get the path to the cache directory for the project
2502
+ */
2503
+ get cachePath() {
2504
+ return joinPaths$1(this.envPaths.cache, "projects", murmurhash({
2505
+ checksum: this.#checksum,
2506
+ config: this.meta.configHash
2507
+ }, { maxLength: CACHE_HASH_LENGTH }));
2508
+ }
2509
+ /**
2510
+ * Get the path to the generated declaration file for the project
2511
+ */
2512
+ get typesPath() {
2513
+ return this.config.output.types ? appendPath(this.config.output.types, this.config.cwd) : joinPaths$1(this.config.cwd, this.config.root, "powerlines.d.ts");
2514
+ }
2515
+ /**
2516
+ * Get the project root relative to the workspace root
2517
+ */
2518
+ get relativeToWorkspaceRoot() {
2519
+ return relativeToWorkspaceRoot(this.config.root);
2520
+ }
2521
+ /**
2522
+ * The builtin module id that exist in the Powerlines virtual file system
2523
+ */
2524
+ get builtins() {
2525
+ return Object.values(this.fs.metadata).filter((meta) => meta && meta.type === "builtin").map((meta) => meta?.id).filter(Boolean);
2526
+ }
2527
+ /**
2528
+ * The alias mappings for the project used during module resolution
2529
+ *
2530
+ * @remarks
2531
+ * This includes both the built-in module aliases as well as any custom aliases defined in the build configuration.
2532
+ */
2533
+ get alias() {
2534
+ return this.builtins.reduce((ret, id) => {
2535
+ const moduleId = `${this.config?.framework || "powerlines"}:${id.replace(/^.*:/, "")}`;
2536
+ if (!ret[moduleId]) {
2537
+ const path = this.fs.paths[id];
2538
+ if (path) ret[moduleId] = path;
2539
+ }
2540
+ return ret;
2541
+ }, this.config.resolve.alias ? Array.isArray(this.config.resolve.alias) ? this.config.resolve.alias.reduce((ret, alias) => {
2542
+ if (!ret[alias.find.toString()]) ret[alias.find.toString()] = alias.replacement;
2543
+ return ret;
2544
+ }, {}) : this.config.resolve.alias : {});
2545
+ }
2546
+ /**
2547
+ * Gets the parser cache.
2548
+ */
2549
+ get parserCache() {
2550
+ if (!this.#parserCache) this.#parserCache = create({
2551
+ cacheId: "parser",
2552
+ cacheDir: this.cachePath,
2553
+ ttl: 7200 * 1e3,
2554
+ lruSize: 5e3,
2555
+ persistInterval: 250
2556
+ });
2557
+ return this.#parserCache;
2558
+ }
2559
+ /**
2560
+ * Gets the request cache.
2561
+ */
2562
+ get requestCache() {
2563
+ if (!this.#requestCache) this.#requestCache = create({
2564
+ cacheId: "http",
2565
+ cacheDir: this.cachePath,
2566
+ ttl: 360 * 60 * 1e3,
2567
+ lruSize: 5e3,
2568
+ persistInterval: 250
2569
+ });
2570
+ return this.#requestCache;
2571
+ }
2572
+ /**
2573
+ * The entry points that exist in the Powerlines virtual file system
2574
+ */
2575
+ get resolvedEntry() {
2576
+ return Object.entries(this.fs.metadata).filter(([, meta]) => meta && meta.type === "entry").map(([path, meta]) => {
2577
+ const typeDefinition = { file: path };
2578
+ if (meta.properties) {
2579
+ if (isSetString(meta.properties.file)) typeDefinition.file = meta.properties.file;
2580
+ if (isSetString(meta.properties.name)) typeDefinition.name = meta.properties.name;
2581
+ if (isSetString(meta.properties["input.file"]) || isSetString(meta.properties["input.name"])) {
2582
+ typeDefinition.input ??= {};
2583
+ if (isSetString(meta.properties["input.file"])) typeDefinition.input.file = meta.properties["input.file"];
2584
+ if (isSetString(meta.properties["input.name"])) typeDefinition.input.name = meta.properties["input.name"];
2585
+ }
2586
+ if (isSetString(meta.properties.output)) typeDefinition.output = meta.properties.output;
2587
+ }
2588
+ return typeDefinition;
2589
+ }).filter(Boolean);
2590
+ }
2591
+ /**
2592
+ * Creates a new StormContext instance.
2593
+ *
2594
+ * @param options - The options to use for creating the context, including the resolved configuration and workspace settings.
2595
+ */
2596
+ constructor(options) {
2597
+ super();
2598
+ this.options = options;
2599
+ }
2600
+ /**
2601
+ * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.
2602
+ *
2603
+ * @remarks
2604
+ * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.
2605
+ *
2606
+ * @returns A promise that resolves to the cloned context.
2607
+ */
2608
+ async clone() {
2609
+ const clone = await PowerlinesContext.fromOptions(this.config);
2610
+ return this.copyTo(clone);
2611
+ }
2612
+ /**
2613
+ * Create a new logger instance
2614
+ *
2615
+ * @param name - The name to use for the logger instance
2616
+ * @returns A logger function
2617
+ */
2618
+ createLog(name = null) {
2619
+ return createLog(name, {
2620
+ ...this.config,
2621
+ logLevel: isNull(this.logLevel) ? "silent" : this.logLevel
2622
+ });
2623
+ }
2624
+ /**
2625
+ * A function to perform HTTP fetch requests
2626
+ *
2627
+ * @remarks
2628
+ * This function uses a caching layer to avoid duplicate requests during the Powerlines process.
2629
+ *
2630
+ * @example
2631
+ * ```ts
2632
+ * const response = await context.fetch("https://api.example.com/data");
2633
+ * const data = await response.json();
2634
+ * ```
2635
+ *
2636
+ * @see https://github.com/nodejs/undici
2637
+ *
2638
+ * @param input - The URL to fetch.
2639
+ * @param options - The fetch request options.
2640
+ * @returns A promise that resolves to a response returned by the fetch.
2641
+ */
2642
+ async fetch(input, options = {}) {
2643
+ const cacheKey = murmurhash({
2644
+ input: input.toString(),
2645
+ options: JSON.stringify(options)
2646
+ });
2647
+ if (!this.config.skipCache && !options.skipCache) {
2648
+ const cached = this.requestCache.get(cacheKey);
2649
+ if (cached) return new Response(cached.body, {
2650
+ status: cached.status,
2651
+ statusText: cached.statusText,
2652
+ headers: cached.headers
2653
+ });
2654
+ }
2655
+ const response = await fetchRequest(input, {
2656
+ timeout: 12e3,
2657
+ ...options
2658
+ });
2659
+ const result = {
2660
+ body: await response.text(),
2661
+ status: response.status,
2662
+ statusText: response.statusText,
2663
+ headers: Object.fromEntries(response.headers.entries())
2664
+ };
2665
+ if (!this.config.skipCache && !options.skipCache) try {
2666
+ this.requestCache.set(cacheKey, result);
2667
+ } catch {}
2668
+ return new Response(result.body, {
2669
+ status: result.status,
2670
+ statusText: result.statusText,
2671
+ headers: result.headers
2672
+ });
2673
+ }
2674
+ /**
2675
+ * Parse code using [Oxc-Parser](https://github.com/oxc/oxc) into an (ESTree-compatible)[https://github.com/estree/estree] AST object.
2676
+ *
2677
+ * @remarks
2678
+ * This function can be used to parse TypeScript code into an AST for further analysis or transformation.
2679
+ *
2680
+ * @example
2681
+ * ```ts
2682
+ * const ast = context.parse("const x: number = 42;");
2683
+ * ```
2684
+ *
2685
+ * @see https://rollupjs.org/plugin-development/#this-parse
2686
+ * @see https://github.com/oxc/oxc
2687
+ *
2688
+ * @param code - The source code to parse.
2689
+ * @param options - The options to pass to the parser.
2690
+ * @returns An (ESTree-compatible)[https://github.com/estree/estree] AST object.
2691
+ */
2692
+ async parse(code, options = {}) {
2693
+ const cacheKey = murmurhash({
2694
+ code,
2695
+ options
2696
+ });
2697
+ let result;
2698
+ if (!this.config.skipCache) {
2699
+ result = this.parserCache.get(cacheKey);
2700
+ if (result) return result;
2701
+ }
2702
+ result = await parse(`source.${options.lang || "ts"}`, code, {
2703
+ ...options,
2704
+ sourceType: "module",
2705
+ showSemanticErrors: this.config.mode === "development"
2706
+ });
2707
+ if (!this.config.skipCache) this.parserCache.set(cacheKey, result);
2708
+ return result;
2709
+ }
2710
+ /**
2711
+ * A helper function to resolve modules in the Virtual File System
2712
+ *
2713
+ * @remarks
2714
+ * This function can be used to resolve modules relative to the project root directory.
2715
+ *
2716
+ * @example
2717
+ * ```ts
2718
+ * const resolved = await context.resolve("some-module", "/path/to/importer");
2719
+ * ```
2720
+ *
2721
+ * @param id - The module to resolve.
2722
+ * @param importer - An optional path to the importer module.
2723
+ * @param options - Additional resolution options.
2724
+ * @returns A promise that resolves to the resolved module path.
2725
+ */
2726
+ async resolve(id, importer, options = {}) {
2727
+ let moduleId = id;
2728
+ if (this.config.resolve.alias) {
2729
+ if (Array.isArray(this.config.resolve.alias)) {
2730
+ const alias = this.config.resolve.alias.find((a) => match(moduleId, [a.find]));
2731
+ if (alias) moduleId = alias.replacement;
2732
+ } else if (isSetObject(this.config.resolve.alias) && this.config.resolve.alias[id]) moduleId = this.config.resolve.alias[id];
2733
+ }
2734
+ if (this.fs.isResolvableId(moduleId) || importer && this.fs.isResolvableId(importer)) {
2735
+ let resolvedImporter = importer;
2736
+ if (importer && this.fs.isResolvableId(importer)) resolvedImporter = await this.fs.resolve(importer, void 0, defu({
2737
+ conditions: this.config.resolve.conditions,
2738
+ extensions: this.config.resolve.extensions
2739
+ }, options));
2740
+ const result = await this.fs.resolve(moduleId, resolvedImporter, defu({
2741
+ conditions: this.config.resolve.conditions,
2742
+ extensions: this.config.resolve.extensions
2743
+ }, options));
2744
+ if (!result) return;
2745
+ const external = Boolean(!match(moduleId, this.config.resolve.noExternal) && (match(moduleId, this.config.resolve.external) || moduleId.startsWith("node:") || (!this.fs.isVirtual(moduleId, importer, options) || this.fs.isVirtual(moduleId, importer, options) && this.config.projectType !== "application") && this.config.resolve.skipNodeModulesBundle && !/^[A-Z]:[/\\]|^\.{0,2}\/|^\.{1,2}$/.test(moduleId)));
2746
+ return {
2747
+ id: result,
2748
+ external,
2749
+ virtual: !external
2750
+ };
2751
+ }
2752
+ if (this.config.resolve.skipNodeModulesBundle) {
2753
+ if (match(moduleId, this.resolvePatterns) || match(moduleId, this.config.resolve.noExternal)) return;
2754
+ if (match(moduleId, this.config.resolve.external) || moduleId.startsWith("node:")) return {
2755
+ id: moduleId,
2756
+ external: true,
2757
+ virtual: false
2758
+ };
2759
+ if (!/^[A-Z]:[/\\]|^\.{0,2}\/|^\.{1,2}$/.test(moduleId)) return {
2760
+ id: moduleId,
2761
+ external: true,
2762
+ virtual: false
2763
+ };
2764
+ } else {
2765
+ if (match(moduleId, this.config.resolve.noExternal)) return;
2766
+ if (match(moduleId, this.config.resolve.external) || moduleId.startsWith("node:")) return {
2767
+ id: moduleId,
2768
+ external: true,
2769
+ virtual: false
2770
+ };
2771
+ }
2772
+ }
2773
+ /**
2774
+ * A helper function to load modules from the Virtual File System
2775
+ *
2776
+ * @remarks
2777
+ * This function can be used to load modules relative to the project root directory.
2778
+ *
2779
+ * @example
2780
+ * ```ts
2781
+ * const module = await context.load("some-module", "/path/to/importer");
2782
+ * ```
2783
+ *
2784
+ * @param id - The module to load.
2785
+ * @returns A promise that resolves to the loaded module.
2786
+ */
2787
+ async load(id) {
2788
+ const resolvedId = await this.fs.resolve(id);
2789
+ if (!resolvedId) return;
2790
+ const code = await this.fs.read(resolvedId);
2791
+ if (!code) return;
2792
+ return {
2793
+ code,
2794
+ map: null
2795
+ };
2796
+ }
2797
+ /**
2798
+ * Get the builtin virtual files that exist in the Powerlines virtual file system
2799
+ */
2800
+ async getBuiltins() {
2801
+ return Promise.all(Object.entries(this.fs.metadata).filter(([, meta]) => meta && meta.type === "builtin").map(async ([id, meta]) => {
2802
+ const code = await this.fs.read(id);
2803
+ const path = this.fs.paths[id];
2804
+ return {
2805
+ ...meta,
2806
+ path,
2807
+ code
2808
+ };
2809
+ }));
2810
+ }
2811
+ /**
2812
+ * Resolves a file and writes it to the VFS if it does not already exist
2813
+ *
2814
+ * @param code - The source code of the file
2815
+ * @param path - The path to write the file to
2816
+ * @param options - Additional options for writing the file
2817
+ */
2818
+ async emit(code, path, options = {}) {
2819
+ const filePath = options.extension ? findFileExtensionSafe(path) ? options.extension.startsWith(".") ? path.replace(findFileDotExtensionSafe(path), options.extension) : path.replace(findFileExtensionSafe(path), options.extension) : options.extension.startsWith(".") ? `${path}${options.extension}` : `${path}.${options.extension}` : findFileExtensionSafe(path) ? path : `${path}.ts`;
2820
+ if (isFunction(this.emitFile) && options.emitWithBundler) return this.emitFile({
2821
+ needsCodeReference: options.needsCodeReference,
2822
+ originalFileName: options.originalFileName,
2823
+ fileName: filePath,
2824
+ source: code,
2825
+ type: "asset"
2826
+ });
2827
+ return this.fs.write(filePath, code, options);
2828
+ }
2829
+ /**
2830
+ * Synchronously resolves a file and writes it to the VFS if it does not already exist
2831
+ *
2832
+ * @param code - The source code of the file
2833
+ * @param path - The path to write the file to
2834
+ * @param options - Additional options for writing the file
2835
+ */
2836
+ emitSync(code, path, options = {}) {
2837
+ const filePath = options.extension ? findFileExtensionSafe(path) ? options.extension.startsWith(".") ? path.replace(findFileDotExtensionSafe(path), options.extension) : path.replace(findFileExtensionSafe(path), options.extension) : options.extension.startsWith(".") ? `${path}${options.extension}` : `${path}.${options.extension}` : findFileExtensionSafe(path) ? path : `${path}.ts`;
2838
+ if (isFunction(this.emitFile) && options.emitWithBundler) return this.emitFile({
2839
+ needsCodeReference: options.needsCodeReference,
2840
+ originalFileName: options.originalFileName,
2841
+ fileName: filePath,
2842
+ source: code,
2843
+ type: "asset"
2844
+ });
2845
+ return this.fs.writeSync(filePath, code, options);
2846
+ }
2847
+ /**
2848
+ * Resolves a entry virtual file and writes it to the VFS if it does not already exist
2849
+ *
2850
+ * @param code - The source code of the entry file
2851
+ * @param path - A path to write the entry file to
2852
+ * @param options - Optional write file options
2853
+ */
2854
+ async emitEntry(code, path, options = {}) {
2855
+ return this.emit(code, appendPath(path, this.entryPath), defu({ meta: {
2856
+ type: "entry",
2857
+ properties: {
2858
+ file: appendPath(path, this.entryPath),
2859
+ name: options?.name,
2860
+ output: options?.output,
2861
+ "input.file": options?.input?.file,
2862
+ "input.name": options?.input?.name
2863
+ }
2864
+ } }, omit(options, ["name"])));
2865
+ }
2866
+ /**
2867
+ * Synchronously resolves a entry virtual file and writes it to the VFS if it does not already exist
2868
+ *
2869
+ * @param code - The source code of the entry file
2870
+ * @param path - A path to write the entry file to
2871
+ * @param options - Optional write file options
2872
+ */
2873
+ emitEntrySync(code, path, options = {}) {
2874
+ return this.emitSync(code, appendPath(path, this.entryPath), defu({ meta: {
2875
+ type: "entry",
2876
+ properties: {
2877
+ file: appendPath(path, this.entryPath),
2878
+ name: options?.name,
2879
+ output: options?.output,
2880
+ "input.file": options?.input?.file,
2881
+ "input.name": options?.input?.name
2882
+ }
2883
+ } }, omit(options, ["name"])));
2884
+ }
2885
+ /**
2886
+ * Resolves a builtin virtual file and writes it to the VFS if it does not already exist
2887
+ *
2888
+ * @param code - The source code of the builtin file
2889
+ * @param id - The unique identifier of the builtin file
2890
+ * @param options - Optional write file options
2891
+ */
2892
+ async emitBuiltin(code, id, options = {}) {
2893
+ if (!this.builtinsPath) throw new Error(`The builtins path is not set. Cannot emit builtin file with id "${id}".`);
2894
+ if (!isSetString(id)) throw new Error(`The builtin id must be a non-empty string. Received: ${String(id)}`);
2895
+ return this.emit(code, appendPath(id, this.builtinsPath), defu(options, { meta: {
2896
+ type: "builtin",
2897
+ id
2898
+ } }));
2899
+ }
2900
+ /**
2901
+ * Synchronously resolves a builtin virtual file and writes it to the VFS if it does not already exist
2902
+ *
2903
+ * @param code - The source code of the builtin file
2904
+ * @param id - The unique identifier of the builtin file
2905
+ * @param options - Optional write file options
2906
+ */
2907
+ emitBuiltinSync(code, id, options = {}) {
2908
+ if (!this.builtinsPath) throw new Error(`The builtins path is not set. Cannot emit builtin file with id "${id}".`);
2909
+ if (!isSetString(id)) throw new Error(`The builtin id must be a non-empty string. Received: ${String(id)}`);
2910
+ return this.emitSync(code, appendPath(id, this.builtinsPath), defu(options, { meta: {
2911
+ type: "builtin",
2912
+ id
2913
+ } }));
2914
+ }
2915
+ /**
2916
+ * Resolves a builtin virtual file and writes it to the VFS if it does not already exist
2917
+ *
2918
+ * @param code - The source code of the builtin file
2919
+ * @param id - The unique identifier of the builtin file
2920
+ * @param options - Optional write file options
2921
+ */
2922
+ async emitInfrastructure(code, id, options = {}) {
2923
+ if (!this.infrastructurePath) throw new Error(`The infrastructure path is not set. Cannot emit infrastructure file with id "${id}".`);
2924
+ if (!isSetString(id)) throw new Error(`The infrastructure id must be a non-empty string. Received: ${String(id)}`);
2925
+ return this.emit(code, appendPath(id, this.infrastructurePath), defu(options, { meta: {
2926
+ type: "infrastructure",
2927
+ id
2928
+ } }));
2929
+ }
2930
+ /**
2931
+ * Synchronously resolves an infrastructure virtual file and writes it to the VFS if it does not already exist
2932
+ *
2933
+ * @param code - The source code of the infrastructure file
2934
+ * @param id - The unique identifier of the infrastructure file
2935
+ * @param options - Optional write file options
2936
+ */
2937
+ emitInfrastructureSync(code, id, options = {}) {
2938
+ if (!this.infrastructurePath) throw new Error(`The infrastructure path is not set. Cannot emit infrastructure file with id "${id}".`);
2939
+ if (!isSetString(id)) throw new Error(`The infrastructure id must be a non-empty string. Received: ${String(id)}`);
2940
+ return this.emitSync(code, appendPath(id, this.infrastructurePath), defu(options, { meta: {
2941
+ type: "infrastructure",
2942
+ id
2943
+ } }));
2944
+ }
2945
+ /**
2946
+ * Generates a checksum representing the current context state
2947
+ *
2948
+ * @param root - The root directory of the project to generate the checksum for
2949
+ * @returns A promise that resolves to a string representing the checksum
2950
+ */
2951
+ async generateChecksum(root = this.config.root) {
2952
+ this.#checksum = await hashDirectory(root, { ignore: [
2953
+ "node_modules",
2954
+ ".git",
2955
+ ".nx",
2956
+ ".cache",
2957
+ "tmp",
2958
+ "dist"
2959
+ ] });
2960
+ return this.#checksum;
2961
+ }
2962
+ /**
2963
+ * Initialize the context with the provided configuration options
2964
+ *
2965
+ * @param config - The partial configuration options to initialize the context with
2966
+ */
2967
+ async setup(config) {
2968
+ this.resolvedConfig = mergeConfig({
2969
+ inlineConfig: this.config.inlineConfig ?? {},
2970
+ userConfig: this.config.userConfig ?? {},
2971
+ pluginConfig: this.config.pluginConfig ?? {},
2972
+ tsconfig: getTsconfigFilePath(this.config.cwd, this.config.root, config.tsconfig ?? this.config.tsconfig)
2973
+ }, this.options, this.#getConfigProps(config), this.#getConfigProps(this.config), {
2974
+ name: this.projectJson?.name || this.packageJson?.name,
2975
+ version: this.packageJson?.version,
2976
+ description: this.packageJson?.description,
2977
+ output: mergeConfig(this.config.output ?? {}, {
2978
+ path: this.config.root ? appendPath(joinPaths$1(this.config.root, "dist"), this.config.cwd) : void 0,
2979
+ copy: { assets: [
2980
+ { glob: "LICENSE" },
2981
+ {
2982
+ input: this.config.root,
2983
+ glob: "*.md"
2984
+ },
2985
+ {
2986
+ input: this.config.root,
2987
+ glob: "package.json"
2988
+ }
2989
+ ] },
2990
+ artifactsPath: `.${this.config.framework ?? "powerlines"}`,
2991
+ dts: true,
2992
+ types: joinPaths$1(this.config.root, `${this.config.framework ?? "powerlines"}.d.ts`)
2993
+ })
2994
+ }, {
2995
+ projectType: "application",
2996
+ platform: "neutral",
2997
+ logLevel: "info",
2998
+ preview: false,
2999
+ environments: {},
3000
+ resolve: {}
3001
+ });
3002
+ this.logger = {
3003
+ log: this.createLog(this.config.name),
3004
+ level: isNull(this.logLevel) ? "silent" : this.logLevel
3005
+ };
3006
+ if (this.config.output?.format) this.config.output.format = getUnique(toArray(this.config.output?.format));
3007
+ this.config.plugins = (this.config.plugins ?? []).filter(Boolean).reduce((ret, plugin) => {
3008
+ if (isPlugin(plugin) && isDuplicate(plugin, ret.filter((p) => isPlugin(p)))) return ret;
3009
+ ret.push(plugin);
3010
+ return ret;
3011
+ }, []);
3012
+ this.config.input = getUniqueInputs(this.config.input);
3013
+ if (this.config.name?.startsWith("@") && this.config.name.split("/").filter(Boolean).length > 1) this.config.name = this.config.name.split("/").filter(Boolean)[1];
3014
+ this.config.title ??= titleCase(this.config.name);
3015
+ if (this.config.userConfig.resolve?.external) this.config.userConfig.resolve.external = getUnique(this.config.userConfig.resolve.external);
3016
+ if (this.config.userConfig.resolve?.noExternal) this.config.userConfig.resolve.noExternal = getUnique(this.config.userConfig.resolve.noExternal);
3017
+ if (this.config.resolve.external) this.config.resolve.external = getUnique(this.config.resolve.external);
3018
+ if (this.config.resolve.noExternal) this.config.resolve.noExternal = getUnique(this.config.resolve.noExternal);
3019
+ this.config.output.format = getUnique(toArray(this.config.output?.format ?? (this.config.projectType === "library" ? ["cjs", "esm"] : ["esm"])));
3020
+ if (this.config.output.dts !== false && !this.config.output.types) this.config.output.types = `${this.config.root ? `${this.config.root}/` : ""}${this.config.framework ?? "powerlines"}.d.ts`;
3021
+ if (this.config.root && this.config.root !== "." && this.config.root !== "./" && this.config.root !== this.options.cwd) this.config.output.path ??= joinPaths$1(this.config.root, "dist");
3022
+ else this.config.output.path ??= "dist";
3023
+ if (this.config.root && this.config.output.copy !== false) this.config.output.copy = {
3024
+ path: joinPaths$1(this.options.cwd, "dist", replacePath(this.config.root, this.options.cwd)),
3025
+ ...this.config.output.copy || {}
3026
+ };
3027
+ if (this.config.output.copy && this.config.output.copy.path && this.config.output.copy.assets && Array.isArray(this.config.output.copy.assets)) this.config.output.copy.assets = getUniqueBy(this.config.output.copy.assets.map((asset) => {
3028
+ return {
3029
+ glob: isSetObject(asset) ? asset.glob : asset,
3030
+ input: isString(asset) || !asset.input || asset.input === "." || asset.input === "/" || asset.input === "./" ? this.options.cwd : isParentPath(asset.input, this.config.cwd) || asset.input === this.config.cwd ? asset.input : appendPath(asset.input, this.config.cwd),
3031
+ output: isSetObject(asset) && asset.output ? isParentPath(asset.output, this.config.cwd) ? asset.output : appendPath(joinPaths$1(this.config.output.copy.path, replacePath(replacePath(asset.output, replacePath(this.config.output.copy.path, this.config.cwd)), this.config.output.copy.path)), this.config.cwd) : appendPath(this.config.output.copy.path, this.config.cwd),
3032
+ ignore: isSetObject(asset) && asset.ignore ? toArray(asset.ignore) : void 0
3033
+ };
3034
+ }), (a) => `${a.input}-${a.glob}-${a.output}`);
3035
+ this.config.plugins = (this.config.plugins ?? []).filter(Boolean).reduce((ret, plugin) => {
3036
+ if (isPlugin(plugin) && isDuplicate(plugin, ret.filter((p) => isPlugin(p)))) return ret;
3037
+ ret.push(plugin);
3038
+ return ret;
3039
+ }, []);
3040
+ if (this.config.tsconfig) this.config.tsconfig = replacePathTokens(this, this.config.tsconfig);
3041
+ if (this.config.output.types) if (isSetString(this.config.output.types)) this.config.output.types = replacePathTokens(this, this.config.output.types);
3042
+ else this.config.output.types = joinPaths$1(this.config.root, `${this.config.framework ?? "powerlines"}.d.ts`);
3043
+ if (!this.config.userConfig?.logLevel && !this.config.inlineConfig?.logLevel) if (this.config.mode === "development") this.config.logLevel = "debug";
3044
+ else this.config.logLevel = "info";
3045
+ if (!this.config.userConfig?.output?.sourceMap && !this.config.inlineConfig?.output?.sourceMap) if (this.config.mode === "development") this.config.output.sourceMap = true;
3046
+ else this.config.output.sourceMap = false;
3047
+ if (!this.config.userConfig?.output?.minify && !this.config.inlineConfig?.output?.minify) if (this.config.mode === "production") this.config.output.minify = true;
3048
+ else this.config.output.minify = false;
3049
+ if (this.config.output.copy && this.config.output.copy.assets) this.config.output.copy.assets = this.config.output.copy.assets.map((asset) => ({
3050
+ ...asset,
3051
+ glob: replacePathTokens(this, asset.glob),
3052
+ ignore: asset.ignore ? asset.ignore.map((ignore) => replacePathTokens(this, ignore)) : void 0,
3053
+ input: replacePathTokens(this, asset.input),
3054
+ output: replacePathTokens(this, asset.output)
3055
+ }));
3056
+ if (isSetString(this.config.output?.storage) && this.config.output.storage === "virtual" || isSetObject(this.config.output?.storage) && Object.values(this.config.output.storage).every((adapter) => adapter.preset === "virtual")) this.config.output.overwrite = true;
3057
+ this.#fs ??= await VirtualFileSystem.create(this);
3058
+ }
3059
+ /**
3060
+ * The resolved configuration for this context
3061
+ */
3062
+ resolvedConfig = {};
3063
+ /**
3064
+ * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.
3065
+ *
3066
+ * @remarks
3067
+ * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.
3068
+ *
3069
+ * @returns The cloned context.
3070
+ */
3071
+ copyTo(context) {
3072
+ context.dependencies = deepClone(this.dependencies);
3073
+ context.devDependencies = deepClone(this.devDependencies);
3074
+ context.persistedMeta = this.persistedMeta ? deepClone(this.persistedMeta) : void 0;
3075
+ context.packageJson = deepClone(this.packageJson);
3076
+ context.projectJson = this.projectJson ? deepClone(this.projectJson) : void 0;
3077
+ context.tsconfig = deepClone(this.tsconfig);
3078
+ context.$$internal = this.$$internal;
3079
+ return context;
3080
+ }
3081
+ /**
3082
+ * Initialize the context with the provided configuration options
3083
+ *
3084
+ * @remarks
3085
+ * This method will set up the resolver and load the user configuration file based on the provided options. It is called during the construction of the context and can also be called when cloning the context to ensure that the new context has the same configuration and resolver setup.
3086
+ *
3087
+ * @param options - The configuration options to initialize the context with
3088
+ */
3089
+ async init(options = {}) {
3090
+ await super.init(options);
3091
+ this.options.configIndex = options.configIndex ?? this.options.configIndex ?? 0;
3092
+ const projectJsonPath = joinPaths$1(this.options.root, "project.json");
3093
+ if (existsSync(projectJsonPath)) this.projectJson = await readJsonFile(projectJsonPath);
3094
+ const packageJsonPath = joinPaths$1(this.options.root, "package.json");
3095
+ if (existsSync(packageJsonPath)) {
3096
+ this.packageJson = await readJsonFile(packageJsonPath);
3097
+ this.options.organization ??= isSetObject(this.packageJson?.author) ? kebabCase(this.packageJson?.author?.name) : kebabCase(this.packageJson?.author);
3098
+ }
3099
+ this.#checksum = await this.generateChecksum(this.options.root);
3100
+ const userConfig = this.configFile.config ? Array.isArray(this.configFile.config) && this.configFile.config.length > this.options.configIndex ? this.configFile.config[this.options.configIndex] : this.configFile.config : {};
3101
+ this.resolvedConfig = {
3102
+ ...this.options,
3103
+ ...userConfig,
3104
+ userConfig
3105
+ };
3106
+ }
3107
+ };
3108
+
3109
+ //#endregion
3110
+ //#region src/_internal/helpers/hooks.ts
3111
+ const mergeResultObjects = createDefu((obj, key, value) => {
3112
+ if (isString(obj[key]) && isString(value)) {
3113
+ obj[key] = `${obj[key] || ""}\n${value || ""}`.trim();
3114
+ return true;
3115
+ }
3116
+ return false;
3117
+ });
3118
+ /**
3119
+ * Merges the current hook result with the previous results based on their types.
3120
+ *
3121
+ * @param currentResult - The current hook result to merge with the previous results.
3122
+ * @param previousResults - The previous hook results to merge with the current result.
3123
+ * @returns The merged result.
3124
+ */
3125
+ function mergeResults(currentResult, previousResults) {
3126
+ if (!previousResults || previousResults.length === 0) return [currentResult];
3127
+ if (isSetString(currentResult)) previousResults = [`${isSetString(previousResults[0]) ? previousResults[0] || "" : ""}\n${isSetString(previousResults[0]) ? currentResult.replace(previousResults[0], "") : currentResult}`.trim()];
3128
+ else if (isObject(currentResult)) previousResults = [mergeResultObjects(currentResult, previousResults[0] ?? {})];
3129
+ return previousResults;
3130
+ }
3131
+ /**
3132
+ * Merges multiple hook results together, with special handling for string values and object values.
3133
+ *
3134
+ * @param currentResult - The current hook result to merge with the previous results.
3135
+ * @param previousResults - The previous hook results to merge with the current result.
3136
+ * @returns The merged result.
3137
+ */
3138
+ function mergeConfigs(currentResult, previousResults) {
3139
+ if (isString(currentResult)) previousResults = `${isString(previousResults) ? previousResults || "" : ""}\n${currentResult || ""}`.trim();
3140
+ else if (isObject(currentResult)) previousResults = mergeConfig(currentResult, previousResults ?? {});
3141
+ return previousResults;
3142
+ }
3143
+ /**
3144
+ * Calls a hook with the given context, options, and arguments.
3145
+ *
3146
+ * @param context - The context to use when calling the hook.
3147
+ * @param key - The hook to call.
3148
+ * @param options - Options for calling the hook.
3149
+ * @param args - Arguments to pass to the hook.
3150
+ * @returns The return value of the hook.
3151
+ */
3152
+ async function callHook(context, key, options, ...args) {
3153
+ const hooks = context.selectHooks(key, options);
3154
+ if (hooks.length > 0) {
3155
+ context.debug(` 🧩 Calling ${hooks.length} ${chalk.bold.cyanBright(`${key}${options?.order ? ` (${options.order})` : ""}`)} plugin hook${hooks.length > 1 ? "s" : ""}:\n${hooks.map((hook, index) => ` ${index + 1}. ${colorText(hook.plugin.name)}`).join("\n")}`);
3156
+ const invokeHook = async (hook, hookArgs) => {
3157
+ return Reflect.apply(hook.handler, hook.context, hookArgs);
3158
+ };
3159
+ let results = [];
3160
+ if (options?.sequential === false) results = await Promise.all(hooks.map(async (hook) => {
3161
+ if (!isFunction(hook.handler)) throw new Error(`Plugin hook handler for hook "${key}" is not a function.`);
3162
+ return invokeHook(hook, [...args]);
3163
+ }));
3164
+ else for (const hook of hooks) {
3165
+ if (!isFunction(hook.handler)) throw new Error(`Plugin hook handler for hook "${key}" is not a function.`);
3166
+ if (options?.result === "first" || options?.asNextParam === false) {
3167
+ results.push(await Promise.resolve(invokeHook(hook, [...args])));
3168
+ if (options?.result === "first" && isSet(results[results.length - 1])) break;
3169
+ } else {
3170
+ const sequenceArgs = [...args];
3171
+ if (results.length > 0 && sequenceArgs.length > 0) sequenceArgs[0] = isFunction(options.asNextParam) ? await Promise.resolve(options.asNextParam(results[0])) : results[0];
3172
+ const result = await Promise.resolve(invokeHook(hook, [...sequenceArgs]));
3173
+ if (result) if (options.result === "last") results = [result];
3174
+ else if (options.result === "merge" && options.merge) results = [results.length > 0 && results[0] ? await Promise.resolve(options.merge(result, results[0])) : result];
3175
+ else results = mergeResults(result, results);
3176
+ }
3177
+ }
3178
+ const definedResults = results.filter((result) => isSet(result));
3179
+ if (definedResults.length > 0) {
3180
+ let mergedResult = void 0;
3181
+ for (const result of definedResults) mergedResult = defu$1(result, mergedResult ?? {});
3182
+ return mergedResult;
3183
+ }
3184
+ }
3185
+ }
3186
+ function extractHooks(context, hooks, plugin, key, parentKey) {
3187
+ const combinedKey = parentKey ? `${parentKey}:${key}` : key;
3188
+ const pluginField = getField(plugin, combinedKey.replace(/:/g, "."));
3189
+ if (isPluginHookField(combinedKey) && isPluginHook(pluginField)) {
3190
+ const pluginHook = pluginField;
3191
+ if (!isPluginHook(pluginHook)) return hooks;
3192
+ hooks[combinedKey] ??= {
3193
+ preEnforced: [],
3194
+ preOrdered: [],
3195
+ normal: [],
3196
+ postEnforced: [],
3197
+ postOrdered: []
3198
+ };
3199
+ if (plugin.enforce) {
3200
+ const hookListOrder = `${plugin.enforce}Enforced`;
3201
+ hooks[combinedKey][hookListOrder] ??= [];
3202
+ hooks[combinedKey][hookListOrder] = addPluginHook(context, plugin, pluginHook, hooks[combinedKey][hookListOrder]);
3203
+ return hooks;
3204
+ }
3205
+ if (isFunction(pluginHook) || !pluginHook.order) {
3206
+ hooks[combinedKey].normal ??= [];
3207
+ hooks[combinedKey].normal = addPluginHook(context, plugin, pluginHook, hooks[combinedKey].normal);
3208
+ return hooks;
3209
+ }
3210
+ const hookListOrder = `${pluginHook.order}Ordered`;
3211
+ hooks[combinedKey][hookListOrder] ??= [];
3212
+ hooks[combinedKey][hookListOrder] = addPluginHook(context, plugin, pluginHook, hooks[combinedKey][hookListOrder]);
3213
+ return hooks;
3214
+ } else if (isSetObject(pluginField)) return Object.keys(pluginField).map((pluginKey) => extractHooks(context, hooks, plugin, pluginKey, combinedKey)).reduce((ret, current) => {
3215
+ Object.keys(current).forEach((key) => {
3216
+ ret[key] ??= {
3217
+ preEnforced: [],
3218
+ preOrdered: [],
3219
+ normal: [],
3220
+ postEnforced: [],
3221
+ postOrdered: []
3222
+ };
3223
+ [
3224
+ "preEnforced",
3225
+ "preOrdered",
3226
+ "normal",
3227
+ "postEnforced",
3228
+ "postOrdered"
3229
+ ].forEach((order) => {
3230
+ if (current[key]?.[order]) {
3231
+ ret[key][order] ??= [];
3232
+ ret[key][order] = ret[key][order].concat(current[key][order]);
3233
+ }
3234
+ });
3235
+ });
3236
+ return ret;
3237
+ }, hooks);
3238
+ return hooks;
3239
+ }
3240
+
3241
+ //#endregion
3242
+ //#region src/context/plugin-context.ts
3243
+ /**
3244
+ * Create a Proxy-based PluginContext
3245
+ *
3246
+ * @param plugin - The plugin instance
3247
+ * @param environment - The environment context
3248
+ * @returns The proxied plugin context
3249
+ */
3250
+ function createPluginContext(plugin, environment) {
3251
+ const normalizeMessage = (message) => {
3252
+ return isString(message) ? message : message.message;
3253
+ };
3254
+ const log = environment.extendLog(plugin.name.replaceAll(":", " - "));
3255
+ const callHookFn = async (hook, options, ...args) => {
3256
+ return environment.$$internal.api.callHook(hook, {
3257
+ sequential: true,
3258
+ result: "merge",
3259
+ ...options,
3260
+ environment
3261
+ }, ...args);
3262
+ };
3263
+ const meta = {};
3264
+ return new Proxy({}, {
3265
+ get(_, prop) {
3266
+ if (prop === "$$internal") return {
3267
+ ...environment.$$internal,
3268
+ environment,
3269
+ callHook: callHookFn,
3270
+ meta
3271
+ };
3272
+ if (prop === "log" || prop === "logger") return log;
3273
+ if (prop === "fatal") return (message) => {
3274
+ log(LogLevelLabel.FATAL, normalizeMessage(message));
3275
+ };
3276
+ if (prop === "error") return (message) => {
3277
+ log(LogLevelLabel.ERROR, normalizeMessage(message));
3278
+ };
3279
+ if (prop === "warn") return (message) => {
3280
+ log(LogLevelLabel.WARN, normalizeMessage(message));
3281
+ };
3282
+ if (prop === "info") return (message) => {
3283
+ log(LogLevelLabel.INFO, normalizeMessage(message));
3284
+ };
3285
+ if (prop === "debug") return (message) => {
3286
+ log(LogLevelLabel.DEBUG, normalizeMessage(message));
3287
+ };
3288
+ if (prop === "trace") return (message) => {
3289
+ log(LogLevelLabel.TRACE, normalizeMessage(message));
3290
+ };
3291
+ return environment[prop];
3292
+ },
3293
+ set(_, prop, value) {
3294
+ if ([
3295
+ "$$internal",
3296
+ "environment",
3297
+ "config",
3298
+ "log",
3299
+ "logger",
3300
+ "error",
3301
+ "warn",
3302
+ "plugins",
3303
+ "hooks",
3304
+ "addPlugin",
3305
+ "selectHooks"
3306
+ ].includes(prop)) {
3307
+ log(LogLevelLabel.WARN, `Cannot set read-only property "${String(prop)}"`);
3308
+ return false;
3309
+ }
3310
+ environment[prop] = value;
3311
+ return true;
3312
+ }
3313
+ });
3314
+ }
3315
+
3316
+ //#endregion
3317
+ //#region src/context/environment-context.ts
3318
+ var PowerlinesEnvironmentContext = class PowerlinesEnvironmentContext extends PowerlinesContext {
3319
+ /**
3320
+ * The hooks registered by plugins in this environment
3321
+ */
3322
+ #hooks = {};
3323
+ /**
3324
+ * Create a new context from the config.
3325
+ *
3326
+ * @param options - The resolved execution options.
3327
+ * @param config - The user configuration options.
3328
+ * @returns A promise that resolves to the new context.
3329
+ */
3330
+ static async fromConfig(options, config) {
3331
+ const context = new PowerlinesEnvironmentContext(options, config);
3332
+ await context.init(options);
3333
+ await context.setup(config);
3334
+ const powerlinesPath = await resolvePackage("powerlines");
3335
+ if (!powerlinesPath) throw new Error("Could not resolve `powerlines` package location.");
3336
+ context.powerlinesPath = powerlinesPath;
3337
+ return context;
3338
+ }
3339
+ /**
3340
+ * The resolved environment configuration
3341
+ */
3342
+ environment;
3343
+ /**
3344
+ * The list of plugins applied to this environment
3345
+ */
3346
+ plugins = [];
3347
+ /**
3348
+ * Create a new logger instance
3349
+ *
3350
+ * @param name - The name to use for the logger instance
3351
+ * @returns A logger function
3352
+ */
3353
+ createLog(name = null) {
3354
+ return createLog(name, {
3355
+ ...this.config,
3356
+ logLevel: isNull(this.config.logLevel) ? "silent" : this.config.logLevel,
3357
+ environment: this.environment?.name
3358
+ });
3359
+ }
3360
+ /**
3361
+ * The hooks registered by plugins in this environment
3362
+ */
3363
+ get hooks() {
3364
+ return this.#hooks;
3365
+ }
3366
+ /**
3367
+ * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.
3368
+ *
3369
+ * @remarks
3370
+ * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.
3371
+ *
3372
+ * @returns A promise that resolves to the cloned context.
3373
+ */
3374
+ async clone() {
3375
+ const context = await PowerlinesEnvironmentContext.fromConfig(this.options, this.config);
3376
+ return this.copyTo(context);
3377
+ }
3378
+ async addPlugin(plugin) {
3379
+ let resolvedPlugin = plugin;
3380
+ if (isFunction(plugin.applyToEnvironment)) {
3381
+ const result = await Promise.resolve(plugin.applyToEnvironment(this.environment));
3382
+ if (!result || isObject(result) && Object.keys(result).length === 0) return;
3383
+ if (isPluginConfig(result)) return this.$$internal.addPlugin(result);
3384
+ resolvedPlugin = isPlugin(result) ? result : plugin;
3385
+ }
3386
+ const context = createPluginContext(resolvedPlugin, this);
3387
+ this.plugins.push({
3388
+ plugin: resolvedPlugin,
3389
+ context
3390
+ });
3391
+ this.#hooks = Object.entries(Object.keys(resolvedPlugin).filter((key) => !PLUGIN_NON_HOOK_FIELDS.includes(key)).reduce((ret, key) => extractHooks(context, ret, resolvedPlugin, key), this.hooks)).reduce((ret, [key, value]) => {
3392
+ if (isSetObject(value)) Object.entries(value).forEach(([type, list]) => {
3393
+ ret[key] ??= {};
3394
+ ret[key][type] = dedupeHooklist(list);
3395
+ });
3396
+ return ret;
3397
+ }, {});
3398
+ }
3399
+ /**
3400
+ * Retrieves the hook handlers for a specific hook name
3401
+ */
3402
+ selectHooks(key, options) {
3403
+ const result = [];
3404
+ if (isPluginHookField(key) && this.hooks[key]) {
3405
+ if (this.hooks[key]) if (options?.order) {
3406
+ const mapHooksToResult = (hooksList) => hooksList.map((hook) => {
3407
+ const plugin = this.plugins.find((p) => p.plugin.name === hook.plugin.name);
3408
+ if (!plugin) throw new Error(`Could not find plugin context for plugin "${hook.plugin.name}".`);
3409
+ return {
3410
+ handler: hook.handler,
3411
+ plugin: hook.plugin,
3412
+ context: plugin.context
3413
+ };
3414
+ });
3415
+ if (options?.order === "pre") {
3416
+ result.push(...mapHooksToResult(this.hooks[key].preOrdered ?? []));
3417
+ result.push(...mapHooksToResult(this.hooks[key].preEnforced ?? []));
3418
+ } else if (options?.order === "post") {
3419
+ result.push(...mapHooksToResult(this.hooks[key].postOrdered ?? []));
3420
+ result.push(...mapHooksToResult(this.hooks[key].postEnforced ?? []));
3421
+ } else result.push(...mapHooksToResult(this.hooks[key].normal ?? []));
3422
+ } else {
3423
+ result.push(...this.selectHooks(key, { order: "pre" }));
3424
+ result.push(...this.selectHooks(key, { order: "normal" }));
3425
+ result.push(...this.selectHooks(key, { order: "post" }));
3426
+ }
3427
+ }
3428
+ return result;
3429
+ }
3430
+ constructor(options, config) {
3431
+ super(options);
3432
+ this.resolvedConfig = config;
3433
+ }
3434
+ /**
3435
+ * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.
3436
+ *
3437
+ * @remarks
3438
+ * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.
3439
+ *
3440
+ * @returns The cloned context.
3441
+ */
3442
+ copyTo(context) {
3443
+ context.plugins = this.plugins;
3444
+ return super.copyTo(context);
3445
+ }
3446
+ };
3447
+
3448
+ //#endregion
3449
+ //#region src/context/execution-context.ts
3450
+ var PowerlinesExecutionContext = class PowerlinesExecutionContext extends PowerlinesContext {
3451
+ #environments = {};
3452
+ #plugins = [];
3453
+ /**
3454
+ * Create a new Storm context from the workspace root and user config.
3455
+ *
3456
+ * @param options - The options for resolving the context.
3457
+ * @returns A promise that resolves to the new context.
3458
+ */
3459
+ static async fromOptions(options) {
3460
+ const context = new PowerlinesExecutionContext(options);
3461
+ await context.init(options);
3462
+ const powerlinesPath = await resolvePackage("powerlines");
3463
+ if (!powerlinesPath) throw new Error("Could not resolve `powerlines` package location.");
3464
+ context.powerlinesPath = powerlinesPath;
3465
+ return context;
3466
+ }
3467
+ /**
3468
+ * Create a new Storm context from the workspace root and user config.
3469
+ *
3470
+ * @param options - The options for resolving the context.
3471
+ * @returns A promise that resolves to the new context.
3472
+ */
3473
+ static async fromConfig(options, config) {
3474
+ const context = new PowerlinesExecutionContext(options);
3475
+ await context.init(options);
3476
+ context.config.inlineConfig = config;
3477
+ if (context.config.inlineConfig.command === "new") {
3478
+ const workspacePackageJsonPath = joinPaths$1(context.config.cwd, "package.json");
3479
+ if (!existsSync(workspacePackageJsonPath)) throw new Error(`The workspace package.json file could not be found at ${workspacePackageJsonPath}`);
3480
+ context.packageJson = await readJsonFile(workspacePackageJsonPath);
3481
+ }
3482
+ await context.setup(config);
3483
+ const powerlinesPath = await resolvePackage("powerlines");
3484
+ if (!powerlinesPath) throw new Error("Could not resolve `powerlines` package location.");
3485
+ context.powerlinesPath = powerlinesPath;
3486
+ return context;
3487
+ }
3488
+ /**
3489
+ * Internal context fields and methods
3490
+ *
3491
+ * @danger
3492
+ * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
3493
+ *
3494
+ * @internal
3495
+ */
3496
+ get $$internal() {
3497
+ return super.$$internal;
3498
+ }
3499
+ /**
3500
+ * Internal context fields and methods
3501
+ *
3502
+ * @danger
3503
+ * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
3504
+ *
3505
+ * @internal
3506
+ */
3507
+ set $$internal(value) {
3508
+ super.$$internal = value;
3509
+ for (const environment of Object.values(this.environments)) environment.$$internal = super.$$internal;
3510
+ }
3511
+ /**
3512
+ * A record of all environments by name
3513
+ */
3514
+ get environments() {
3515
+ return this.#environments;
3516
+ }
3517
+ get plugins() {
3518
+ return this.#plugins;
3519
+ }
3520
+ /**
3521
+ * Creates a new instance.
3522
+ *
3523
+ * @param options - The options to use for creating the context, including the resolved configuration and workspace settings.
3524
+ */
3525
+ constructor(options) {
3526
+ super(options);
3527
+ }
3528
+ /**
3529
+ * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.
3530
+ *
3531
+ * @remarks
3532
+ * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.
3533
+ *
3534
+ * @returns A promise that resolves to the cloned context.
3535
+ */
3536
+ async clone() {
3537
+ const clone = await PowerlinesExecutionContext.fromOptions(this.options);
3538
+ clone.config.userConfig = this.config.userConfig;
3539
+ await clone.setup(this.config.inlineConfig);
3540
+ return this.copyTo(clone);
3541
+ }
3542
+ /**
3543
+ * Initialize the context with the provided configuration options
3544
+ *
3545
+ * @param options - The resolved execution options to use for initialization.
3546
+ */
3547
+ async init(options) {
3548
+ await super.init(options);
3549
+ await Promise.all(toArray(this.config.environments && Object.keys(this.config.environments).length > 0 ? Object.keys(this.config.environments).map((name) => createEnvironment(name, this.config)) : createDefaultEnvironment(this.config)).map(async (env) => {
3550
+ this.#environments[env.name] = await this.in(env);
3551
+ }));
3552
+ }
3553
+ /**
3554
+ * A function to copy the context and update the fields for a specific environment
3555
+ *
3556
+ * @param environment - The environment configuration to use.
3557
+ * @returns A new context instance with the updated environment.
3558
+ */
3559
+ async in(environment) {
3560
+ let context;
3561
+ if (this.environments[environment.name]) context = this.environments[environment.name];
3562
+ else context = await PowerlinesEnvironmentContext.fromConfig(this.options, this.config);
3563
+ if (isSetObject(this.config.inlineConfig)) await context.setup(this.config.inlineConfig);
3564
+ context.environment = environment;
3565
+ context.plugins = [];
3566
+ for (const plugin of this.plugins) await context.addPlugin(plugin);
3567
+ return context;
3568
+ }
3569
+ /**
3570
+ * Update the context using a new inline configuration options
3571
+ *
3572
+ * @param config - The new inline configuration options.
3573
+ */
3574
+ async setup(config) {
3575
+ await super.setup(config);
3576
+ await Promise.all(toArray(this.config.environments && Object.keys(this.config.environments).length > 0 ? Object.keys(this.config.environments).map((name) => createEnvironment(name, this.config)) : createDefaultEnvironment(this.config)).map(async (env) => {
3577
+ const context = await this.in(env);
3578
+ await context.setup(config);
3579
+ this.#environments[env.name] = context;
3580
+ }));
3581
+ }
3582
+ /**
3583
+ * Add a plugin to the API context and all environments
3584
+ *
3585
+ * @param plugin - The plugin to add.
3586
+ */
3587
+ async addPlugin(plugin) {
3588
+ this.plugins.push(plugin);
3589
+ await Promise.all(Object.keys(this.environments).map(async (name) => {
3590
+ await this.environments[name].addPlugin(plugin);
3591
+ }));
3592
+ }
3593
+ /**
3594
+ * Get an environment by name, or the default environment if no name is provided
3595
+ *
3596
+ * @param name - The name of the environment to retrieve.
3597
+ * @returns The requested environment context.
3598
+ */
3599
+ async getEnvironment(name) {
3600
+ let environment;
3601
+ if (name) environment = this.environments[name];
3602
+ if (Object.keys(this.environments).length === 1) {
3603
+ environment = this.environments[Object.keys(this.environments)[0]];
3604
+ this.debug(`Applying the only configured environment: ${chalk.bold.cyanBright(environment?.environment.name)}`);
3605
+ }
3606
+ if (!environment) {
3607
+ if (name) throw new Error(`Environment "${name}" not found.`);
3608
+ environment = await this.in(createDefaultEnvironment(this.config.userConfig));
3609
+ this.warn(`No environment specified, and no default environment found. Using a temporary default environment: ${chalk.bold.cyanBright(environment?.environment.name)}`);
3610
+ }
3611
+ return environment;
3612
+ }
3613
+ /**
3614
+ * A safe version of `getEnvironment` that returns `undefined` if the environment is not found
3615
+ *
3616
+ * @param name - The name of the environment to retrieve.
3617
+ * @returns The requested environment context or `undefined` if not found.
3618
+ */
3619
+ async getEnvironmentSafe(name) {
3620
+ try {
3621
+ return await this.getEnvironment(name);
3622
+ } catch {
3623
+ return;
3624
+ }
3625
+ }
3626
+ /**
3627
+ * A function to merge all configured environments into a single context.
3628
+ *
3629
+ * @remarks
3630
+ * If only one environment is configured, that environment will be returned directly.
3631
+ *
3632
+ * @returns A promise that resolves to a merged/global environment context.
3633
+ */
3634
+ async toEnvironment() {
3635
+ let environment;
3636
+ if (Object.keys(this.environments).length > 1) {
3637
+ environment = await this.in(createEnvironment(GLOBAL_ENVIRONMENT, this.config.userConfig));
3638
+ this.debug(`Combined all ${Object.keys(this.environments).length} environments into a single global context.`);
3639
+ } else environment = await this.getEnvironment();
3640
+ return environment;
3641
+ }
3642
+ };
3643
+
3644
+ //#endregion
3645
+ //#region src/typescript/ts-morph.ts
3646
+ var VirtualFileSystemHost = class extends InMemoryFileSystemHost {
3647
+ #context;
3648
+ constructor(context) {
3649
+ super();
3650
+ this.#context = context;
3651
+ }
3652
+ deleteSync(path) {
3653
+ this.#context.fs.removeSync(path);
3654
+ }
3655
+ readDirSync(dirPath) {
3656
+ if (!this.#context.fs.isDirectorySync(dirPath)) return [];
3657
+ return this.#context.fs.listSync(dirPath).reduce((ret, entry) => {
3658
+ const fullPath = this.#context.fs.resolveSync(entry);
3659
+ if (fullPath) ret.push({
3660
+ name: entry,
3661
+ isDirectory: this.#context.fs.isDirectorySync(fullPath),
3662
+ isFile: this.#context.fs.isFileSync(fullPath),
3663
+ isSymlink: false
3664
+ });
3665
+ return ret;
3666
+ }, []);
3667
+ }
3668
+ async readFile(filePath) {
3669
+ if (!this.#context.fs.isFileSync(filePath)) return "";
3670
+ return await this.#context.fs.read(filePath);
3671
+ }
3672
+ readFileSync(filePath) {
3673
+ if (!this.#context.fs.isFileSync(filePath)) return "";
3674
+ return this.#context.fs.readSync(filePath);
3675
+ }
3676
+ async writeFile(filePath, fileText) {
3677
+ return this.#context.fs.write(filePath, fileText);
3678
+ }
3679
+ writeFileSync(filePath, fileText) {
3680
+ this.#context.fs.writeSync(filePath, fileText);
3681
+ }
3682
+ async mkdir(dirPath) {
3683
+ await this.#context.fs.mkdir(dirPath);
3684
+ }
3685
+ mkdirSync(dirPath) {
3686
+ this.#context.fs.mkdirSync(dirPath);
3687
+ }
3688
+ async move(srcPath, destPath) {
3689
+ await this.#context.fs.move(srcPath, destPath);
3690
+ }
3691
+ moveSync(srcPath, destPath) {
3692
+ this.#context.fs.moveSync(srcPath, destPath);
3693
+ }
3694
+ async copy(srcPath, destPath) {
3695
+ await this.#context.fs.copy(srcPath, destPath);
3696
+ }
3697
+ copySync(srcPath, destPath) {
3698
+ this.#context.fs.copySync(srcPath, destPath);
3699
+ }
3700
+ async fileExists(filePath) {
3701
+ return this.#context.fs.isFile(filePath);
3702
+ }
3703
+ fileExistsSync(filePath) {
3704
+ return this.#context.fs.isFileSync(filePath);
3705
+ }
3706
+ async directoryExists(dirPath) {
3707
+ return this.#context.fs.isDirectory(dirPath);
3708
+ }
3709
+ directoryExistsSync(dirPath) {
3710
+ return this.#context.fs.isDirectorySync(dirPath);
3711
+ }
3712
+ realpathSync(path) {
3713
+ return this.#context.fs.resolveSync(path) || path;
3714
+ }
3715
+ getCurrentDirectory() {
3716
+ return this.#context.config.cwd;
3717
+ }
3718
+ async glob(patterns) {
3719
+ return this.#context.fs.glob(patterns);
3720
+ }
3721
+ globSync(patterns) {
3722
+ return this.#context.fs.globSync(patterns);
3723
+ }
3724
+ };
3725
+ /**
3726
+ * Create a ts-morph {@link Project} instance used for type reflection and module manipulation during processing
3727
+ *
3728
+ * @param context - The Powerlines context
3729
+ * @returns A ts-morph {@link Project} instance
3730
+ */
3731
+ function createProgram(context, override) {
3732
+ context.debug(`Creating ts-morph Project instance with configuration from: ${context.tsconfig.tsconfigFilePath}.`);
3733
+ return new Project(defu(override ?? {}, {
3734
+ skipAddingFilesFromTsConfig: false,
3735
+ tsConfigFilePath: context.tsconfig.tsconfigFilePath,
3736
+ fileSystem: new VirtualFileSystemHost(context),
3737
+ compilerOptions: defu(context.tsconfig.options ?? {}, { lib: ["lib.esnext.full.d.ts"] })
3738
+ }));
3739
+ }
3740
+
3741
+ //#endregion
3742
+ //#region src/_internal/helpers/generate-types.ts
3743
+ /**
3744
+ * Formats the generated TypeScript types source code.
3745
+ *
3746
+ * @param code - The generated TypeScript code.
3747
+ * @returns The formatted TypeScript code.
3748
+ */
3749
+ function formatTypes(code = "") {
3750
+ return code.replaceAll("#private;", "").replace(/__Ω/g, "");
3751
+ }
3752
+ async function extractModuleDeclarations(ctx, filePath, name, text) {
3753
+ const imports = [];
3754
+ const exports = [];
3755
+ const comment = text.match(new RegExp(`\\/\\*\\*(?s:.)*?@module\\s+${ctx.context.config.framework}:${name}(?s:.)*?\\*\\/\\s+`))?.find((comment) => isSetString(comment?.trim()));
3756
+ const sourceFile = new Project({ useInMemoryFileSystem: true }).createSourceFile("module.d.ts", text);
3757
+ for (const ref of sourceFile.getTypeReferenceDirectives()) if (ref.getFileName() && !ctx.context.builtins.some((builtin) => ref.getFileName().endsWith(builtin))) imports.push({
3758
+ name: ref.getFileName(),
3759
+ ambient: true
3760
+ });
3761
+ for (const statement of sourceFile.getStatements()) if (Node.isImportDeclaration(statement)) {
3762
+ const moduleSpec = statement.getModuleSpecifierValue();
3763
+ if (statement.getNamespaceImport()) imports.push({
3764
+ name: moduleSpec,
3765
+ specifiers: [{ name: statement.getNamespaceImport().getText() }],
3766
+ all: true
3767
+ });
3768
+ else if (statement.getNamedImports().length > 0 || statement.getDefaultImport()) {
3769
+ const specifiers = [];
3770
+ if (statement.getDefaultImport()) specifiers.push({
3771
+ name: statement.getDefaultImport().getText(),
3772
+ default: true,
3773
+ type: statement.isTypeOnly()
3774
+ });
3775
+ statement.getNamedImports().forEach((named) => {
3776
+ specifiers.push({
3777
+ name: named.getName(),
3778
+ alias: named.getAliasNode()?.getText(),
3779
+ type: statement.isTypeOnly()
3780
+ });
3781
+ });
3782
+ imports.push({
3783
+ name: moduleSpec,
3784
+ specifiers
3785
+ });
3786
+ }
3787
+ } else if (Node.isExportDeclaration(statement)) {
3788
+ const moduleSpec = statement.getModuleSpecifierValue();
3789
+ if (moduleSpec) {
3790
+ let resolvedSpec = moduleSpec;
3791
+ if (!ctx.context.builtins.includes(moduleSpec)) if (ctx.emitted.has(moduleSpec)) resolvedSpec = ctx.emitted.get(moduleSpec);
3792
+ else {
3793
+ const resolvedModule = await ctx.context.resolve(moduleSpec, filePath);
3794
+ if (isSetString(resolvedModule?.id)) resolvedSpec = resolvedModule.id;
3795
+ }
3796
+ const namedExports = statement.getNamedExports();
3797
+ if (namedExports.length > 0) exports.push({
3798
+ name: resolvedSpec,
3799
+ text: statement.getText(),
3800
+ fullText: statement.getFullText(),
3801
+ specifiers: namedExports.map((named) => ({
3802
+ name: named.getName(),
3803
+ alias: named.getAliasNode()?.getText(),
3804
+ type: statement.isTypeOnly()
3805
+ })),
3806
+ comment: statement.getLeadingCommentRanges().filter((c) => isSetString(c.getText().trim()) && !c.getText().includes("@module")).map((c) => c.getText().trim()).join("\n").trim()
3807
+ });
3808
+ else exports.push({
3809
+ name: resolvedSpec,
3810
+ text: statement.getText(),
3811
+ fullText: statement.getFullText(),
3812
+ all: true,
3813
+ comment: statement.getLeadingCommentRanges().filter((c) => isSetString(c.getText().trim()) && !c.getText().includes("@module")).map((c) => c.getText().trim()).join("\n").trim()
3814
+ });
3815
+ } else {
3816
+ const specifiers = statement.getNamedExports().map((named) => ({
3817
+ name: named.getName(),
3818
+ alias: named.getAliasNode()?.getText(),
3819
+ type: statement.isTypeOnly()
3820
+ }));
3821
+ if (specifiers.length > 0) exports.push({
3822
+ text: statement.getText(),
3823
+ fullText: statement.getFullText(),
3824
+ specifiers,
3825
+ comment: statement.getLeadingCommentRanges().filter((c) => isSetString(c.getText().trim()) && !c.getText().includes("@module")).map((c) => c.getText().trim()).join("\n")
3826
+ });
3827
+ }
3828
+ } else if (Node.isExportAssignment(statement)) exports.push({
3829
+ text: statement.getText(),
3830
+ fullText: statement.getFullText(),
3831
+ comment: statement.getLeadingCommentRanges().filter((c) => isSetString(c.getText().trim()) && !c.getText().includes("@module")).map((c) => c.getText().trim()).join("\n")
3832
+ });
3833
+ else if (Node.isFunctionDeclaration(statement) && statement.isExported() && statement.getNameNode()) exports.push({
3834
+ text: statement.getText(),
3835
+ fullText: statement.getFullText(),
3836
+ specifiers: [{ name: statement.getNameNode().getText() }],
3837
+ comment: statement.getLeadingCommentRanges().filter((c) => isSetString(c.getText().trim()) && !c.getText().includes("@module")).map((c) => c.getText().trim()).join("\n")
3838
+ });
3839
+ else if (Node.isVariableStatement(statement) && statement.isExported()) exports.push({
3840
+ text: statement.getText(),
3841
+ fullText: statement.getFullText(),
3842
+ specifiers: statement.getDeclarationList().getDeclarations().filter((decl) => decl.getNameNode() && Node.isIdentifier(decl.getNameNode())).map((decl) => ({ name: decl.getNameNode().getText() })),
3843
+ comment: statement.getLeadingCommentRanges().filter((c) => isSetString(c.getText().trim()) && !c.getText().includes("@module")).map((c) => c.getText().trim()).join("\n")
3844
+ });
3845
+ else if (Node.isClassDeclaration(statement) && statement.isExported()) {
3846
+ const nameNode = statement.getNameNode();
3847
+ exports.push({
3848
+ text: statement.getText(),
3849
+ fullText: statement.getFullText(),
3850
+ specifiers: nameNode ? [{ name: nameNode.getText() }] : void 0,
3851
+ comment: statement.getLeadingCommentRanges().filter((c) => isSetString(c.getText().trim()) && !c.getText().includes("@module")).map((c) => c.getText().trim()).join("\n")
3852
+ });
3853
+ } else if (Node.isInterfaceDeclaration(statement) && statement.isExported()) {
3854
+ const nameNode = statement.getNameNode();
3855
+ exports.push({
3856
+ text: statement.getText(),
3857
+ fullText: statement.getFullText(),
3858
+ specifiers: nameNode ? [{ name: nameNode.getText() }] : void 0,
3859
+ comment: statement.getLeadingCommentRanges().filter((c) => isSetString(c.getText().trim()) && !c.getText().includes("@module")).map((c) => c.getText().trim()).join("\n")
3860
+ });
3861
+ } else if (Node.isTypeAliasDeclaration(statement) && statement.isExported()) {
3862
+ const nameNode = statement.getNameNode();
3863
+ exports.push({
3864
+ text: statement.getText(),
3865
+ fullText: statement.getFullText(),
3866
+ specifiers: nameNode ? [{ name: nameNode.getText() }] : void 0,
3867
+ comment: statement.getLeadingCommentRanges().filter((c) => isSetString(c.getText().trim()) && !c.getText().includes("@module")).map((c) => c.getText().trim()).join("\n")
3868
+ });
3869
+ } else if (ctx.context.config.output.sourceMap || !statement.getFullText().includes("//# sourceMappingURL=")) exports.push({
3870
+ text: statement.getText(),
3871
+ fullText: statement.getFullText(),
3872
+ comment: statement.getLeadingCommentRanges().filter((c) => isSetString(c.getText().trim()) && !c.getText().includes("@module")).map((c) => c.getText().trim()).join("\n")
3873
+ });
3874
+ return {
3875
+ name,
3876
+ text,
3877
+ sourceFile,
3878
+ comment,
3879
+ imports,
3880
+ exports
3881
+ };
3882
+ }
3883
+ /**
3884
+ * Emits TypeScript declaration types for the provided files using the given TypeScript configuration.
3885
+ *
3886
+ * @param context - The context containing options and environment paths.
3887
+ * @param files - The list of files to generate types for.
3888
+ * @returns A promise that resolves to the generated TypeScript declaration types.
3889
+ */
3890
+ async function emitBuiltinTypes(context, files) {
3891
+ if (files.length === 0) {
3892
+ context.debug("No files provided for TypeScript types generation. Typescript compilation for built-in modules will be skipped.");
3893
+ return {
3894
+ code: "",
3895
+ directives: []
3896
+ };
3897
+ }
3898
+ context.debug(`Running the TypeScript compiler for ${files.length} generated built-in module files.`);
3899
+ const program = createProgram(context, {
3900
+ skipAddingFilesFromTsConfig: true,
3901
+ compilerOptions: {
3902
+ declaration: true,
3903
+ declarationMap: false,
3904
+ emitDeclarationOnly: true,
3905
+ sourceMap: false,
3906
+ outDir: replacePath(context.builtinsPath, context.config.cwd),
3907
+ composite: false,
3908
+ incremental: false,
3909
+ tsBuildInfoFile: void 0
3910
+ }
3911
+ });
3912
+ program.addSourceFilesAtPaths(files);
3913
+ const emitResult = program.emitToMemory({ emitOnlyDtsFiles: true });
3914
+ const diagnostics = emitResult.getDiagnostics();
3915
+ if (diagnostics && diagnostics.length > 0) if (diagnostics.some((d) => d.getCategory() === DiagnosticCategory.Error)) throw new Error(`The Typescript emit process failed while generating built-in types: \n ${diagnostics.filter((d) => d.getCategory() === DiagnosticCategory.Error).map((d) => `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : ""} ${String(d.getMessageText())} (at ${d.getStart()}:${d.getLength()})`).join("\n")}`);
3916
+ else if (diagnostics.some((d) => d.getCategory() === DiagnosticCategory.Warning)) context.warn(`The Typescript emit process completed with warnings while generating built-in types: \n ${diagnostics.filter((d) => d.getCategory() === DiagnosticCategory.Warning).map((d) => `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : ""} ${String(d.getMessageText())} (at ${d.getStart()}:${d.getLength()})`).join("\n")}`);
3917
+ else context.debug(`The Typescript emit process completed with diagnostic messages while generating built-in types: \n ${diagnostics.map((d) => `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : ""} ${String(d.getMessageText())} (at ${d.getStart()}:${d.getLength()})`).join("\n")}`);
3918
+ const emittedFiles = emitResult.getFiles();
3919
+ context.debug(`The TypeScript compiler emitted ${emittedFiles.length} files for built-in types.`);
3920
+ if (emittedFiles.length === 0) {
3921
+ context.warn("The TypeScript compiler did not emit any files for built-in types. This may indicate an issue with the TypeScript configuration or the provided files.");
3922
+ return {
3923
+ code: "",
3924
+ directives: []
3925
+ };
3926
+ }
3927
+ const ctx = {
3928
+ context,
3929
+ modules: [],
3930
+ emitted: /* @__PURE__ */ new Map()
3931
+ };
3932
+ await Promise.all(emittedFiles.map(async (emittedFile) => {
3933
+ const filePath = appendPath(emittedFile.filePath, context.config.cwd);
3934
+ if (!filePath.endsWith(".map") && findFileName(filePath) !== "tsconfig.tsbuildinfo" && isParentPath(filePath, context.builtinsPath)) {
3935
+ const moduleName = replaceExtension(replacePath(replacePath(filePath, context.builtinsPath), replacePath(context.builtinsPath, context.config.cwd)), "", { fullExtension: true });
3936
+ if (context.builtins.includes(moduleName)) {
3937
+ ctx.emitted.set(filePath, moduleName);
3938
+ ctx.modules.push(await extractModuleDeclarations(ctx, filePath, moduleName, emittedFile.text));
3939
+ }
3940
+ }
3941
+ }));
3942
+ const commonDeclarations = [];
3943
+ for (const mod of ctx.modules) for (const importRef of mod.imports.filter((importRef) => context.builtins.some((builtin) => importRef.name.endsWith(`:${builtin}`)))) {
3944
+ const moduleRef = ctx.modules.find((moduleRef) => importRef.name.endsWith(`:${moduleRef.name}`));
3945
+ if (moduleRef) {
3946
+ let declaration;
3947
+ for (const decl of moduleRef.exports.filter((decl) => isSetObject(decl))) {
3948
+ const specifiers = decl.specifiers?.filter((specifier) => importRef.specifiers?.some((s) => (specifier.alias ? specifier.alias : specifier.name) === (s.alias ? s.alias : s.name)));
3949
+ if (specifiers && specifiers.length > 0) {
3950
+ importRef.specifiers = importRef.specifiers?.filter((s) => !specifiers.some((specifier) => (specifier.alias ? specifier.alias : specifier.name) === (s.alias ? s.alias : s.name)));
3951
+ if (importRef.specifiers && importRef.specifiers.length === 0 && !importRef.all && !importRef.ambient) mod.imports = mod.imports.filter((imp) => imp.name !== importRef.name);
3952
+ declaration = decl;
3953
+ break;
3954
+ }
3955
+ }
3956
+ if (declaration) {
3957
+ for (const decl of moduleRef.exports.filter((decl) => isSetObject(decl) && !decl.specifiers?.some((s) => declaration?.specifiers?.some((specifier) => (specifier.alias ? specifier.alias : specifier.name) === (s.alias ? s.alias : s.name))))) {
3958
+ const exportModuleRef = decl;
3959
+ if ((exportModuleRef.specifiers?.some((s) => s.alias || s.name) || exportModuleRef.name) && new RegExp(`(^|\\s|\\n|\\r\\n|\\(|\\)|<|>|{|}|\\[|\\]|\\!|\\?|\\.|,|\\*|&|:)(${exportModuleRef.specifiers?.map((s) => `${s.alias ? `${s.alias}|` : ""}${s.name}`).join("|") || exportModuleRef.name})($|\\s|\\n|\\r\\n|\\(|\\)|<|>|{|}|\\[|\\]|\\!|\\?|\\.|,|\\*|&|:|;)`).test(declaration.text)) commonDeclarations.push(exportModuleRef);
3960
+ }
3961
+ commonDeclarations.push(declaration);
3962
+ }
3963
+ }
3964
+ }
3965
+ let code = "";
3966
+ const directives = [];
3967
+ for (const commonDeclaration of commonDeclarations) {
3968
+ code += formatTypes(`${commonDeclaration.comment?.trim() ? commonDeclaration.comment.trim() : ""}${commonDeclaration.comment?.trim() ? "\n" : ""}${formatTypes(commonDeclaration.text.replace(/\s*export\s*/, "").replace(/\s*declare\s*interface\s*/, "interface ").replace(/\s*declare\s*type\s*/, "type "))}`);
3969
+ code += "\n\n";
3970
+ }
3971
+ for (const mod of ctx.modules) {
3972
+ code += mod.comment ? `${mod.comment.trim()}\n` : "";
3973
+ code += `declare module "${context.config.framework}:${mod.name}" { \n`;
3974
+ for (const importRef of mod.imports) if (importRef.ambient) code += directives.push(importRef.name);
3975
+ else if (importRef.all) code += `\timport * as ${findFileName(importRef.name)} from "${importRef.name}";\n`;
3976
+ else if (importRef.specifiers) {
3977
+ const typeOnly = importRef.specifiers.every((s) => s.type) ? " type" : "";
3978
+ const specifiers = importRef.specifiers.map((s) => s.alias ? `${s.name} as ${s.alias}` : s.name).join(", ");
3979
+ code += `\timport${typeOnly} { ${specifiers} } from "${importRef.name}";\n`;
3980
+ }
3981
+ if (mod.imports.length > 0) code += "\n";
3982
+ for (const exportRef of mod.exports.filter((e) => isString(e) || !e.specifiers || !commonDeclarations.some((commonDecl) => commonDecl.specifiers && commonDecl.specifiers.some((specifier) => e.specifiers?.some((s) => (s.alias ? s.alias : s.name) === (specifier.alias ? specifier.alias : specifier.name)))))) if (isSetString(exportRef)) code += `${exportRef}\n`;
3983
+ else if (exportRef.name) {
3984
+ if (exportRef.all) code += `${exportRef.comment?.trim() ? exportRef.comment.trim() : ""}${exportRef.comment?.trim() ? "\n" : ""}export * from "${exportRef.name}";\n`;
3985
+ else if (exportRef.specifiers) {
3986
+ if (exportRef.comment?.trim()) code += `${exportRef.comment.trim()}\n`;
3987
+ code += `\texport${exportRef.specifiers.every((s) => s.type) ? " type" : ""} { ${exportRef.specifiers.map((s) => s.alias ? `${s.name} as ${s.alias}` : s.name).join(", ")} } from "${exportRef.name}";\n`;
3988
+ }
3989
+ } else code += `${exportRef.comment?.trim() ? exportRef.comment.trim() : ""}${exportRef.comment?.trim() ? "\n" : ""}${formatTypes(exportRef.text.replace(/\s*export\s*declare\s*/, "export ").replace(/\s*declare\s*/, " "))}\n`;
3990
+ mod.exports.filter((e) => !isString(e) && e.specifiers && commonDeclarations.some((commonDeclaration) => commonDeclaration.specifiers && commonDeclaration.specifiers.some((specifier) => e.specifiers?.some((s) => (s.alias ? s.alias : s.name) === (specifier.alias ? specifier.alias : specifier.name))))).forEach((e, i, arr) => {
3991
+ if (i === 0) code += "\nexport { ";
3992
+ else code += ", ";
3993
+ code += `${e?.specifiers?.filter((s) => commonDeclarations.some((commonDeclaration) => commonDeclaration.specifiers && commonDeclaration.specifiers.some((specifier) => (s.alias ? s.alias : s.name) === (specifier.alias ? specifier.alias : specifier.name)))).map((s) => s.alias ? `${s.name} as ${s.alias}` : s.name).join(", ") || ""}`;
3994
+ if (i === arr.length - 1) code += ` };\n`;
3995
+ });
3996
+ code += "}";
3997
+ code += "\n\n";
3998
+ }
3999
+ code = await format(context, context.typesPath, code);
4000
+ context.debug(`A TypeScript declaration file (size: ${prettyBytes(new Blob(toArray(code)).size)}) emitted for the built-in modules types.`);
4001
+ return {
4002
+ code,
4003
+ directives
4004
+ };
4005
+ }
4006
+
4007
+ //#endregion
4008
+ //#region src/_internal/helpers/install.ts
4009
+ /**
4010
+ * Installs a package if it is not already installed.
4011
+ *
4012
+ * @param context - The resolved options
4013
+ * @param packageName - The name of the package to install
4014
+ * @param dev - Whether to install the package as a dev dependency
4015
+ */
4016
+ async function installPackage(context, packageName, dev = false) {
4017
+ if (!await isPackageListed(getPackageName(packageName), { cwd: context.config.root })) if (context.config.autoInstall) {
4018
+ context.warn(`The package "${packageName}" is not installed. It will be installed automatically.`);
4019
+ const result = await install(packageName, {
4020
+ cwd: context.config.root,
4021
+ dev
4022
+ });
4023
+ if (isNumber(result.exitCode) && result.exitCode > 0) {
4024
+ context.error(result.stderr);
4025
+ throw new Error(`An error occurred while installing the package "${packageName}"`);
4026
+ }
4027
+ } else context.warn(`The package "${packageName}" is not installed. Since the "autoInstall" option is set to false, it will not be installed automatically.`);
4028
+ else if (hasPackageVersion(packageName) && !process.env.POWERLINES_SKIP_VERSION_CHECK) {
4029
+ if (!await doesPackageMatch(getPackageName(packageName), getPackageVersion(packageName), context.config.root)) {
4030
+ const packageListing = await getPackageListing(getPackageName(packageName), { cwd: context.config.root });
4031
+ if (!packageListing?.version.startsWith("catalog:") && !packageListing?.version.startsWith("workspace:")) context.warn(`The package "${getPackageName(packageName)}" is installed but does not match the expected version ${getPackageVersion(packageName)} (installed version: ${packageListing?.version || "<Unknown>"}). Please ensure this is intentional before proceeding. Note: You can skip this validation with the "STORM_STACK_SKIP_VERSION_CHECK" environment variable.`);
4032
+ }
4033
+ }
4034
+ }
4035
+
4036
+ //#endregion
4037
+ //#region src/_internal/helpers/install-dependencies.ts
4038
+ /**
4039
+ * Install missing project dependencies.
4040
+ *
4041
+ * @param context - The build context.
4042
+ */
4043
+ async function installDependencies(context) {
4044
+ context.debug(`Checking and installing missing project dependencies.`);
4045
+ context.dependencies ??= {};
4046
+ context.devDependencies ??= {};
4047
+ if (Object.keys(context.dependencies).length === 0 && Object.keys(context.devDependencies).length === 0) {
4048
+ context.debug(`No dependencies or devDependencies to install. Skipping installation step.`);
4049
+ return;
4050
+ }
4051
+ context.debug(`The following packages are required: \nDependencies: \n${Object.entries(context.dependencies).map(([name, version]) => `- ${name}@${String(version)}`).join(" \n")}\n\nDevDependencies: \n${Object.entries(context.devDependencies).map(([name, version]) => `- ${name}@${String(version)}`).join(" \n")}`);
4052
+ await Promise.all([Promise.all(Object.entries(context.dependencies).map(async ([name, version]) => installPackage(context, `${getPackageName(name)}@${String(version)}`, false))), Promise.all(Object.entries(context.devDependencies).map(async ([name, version]) => installPackage(context, `${getPackageName(name)}@${String(version)}`, true)))]);
4053
+ }
4054
+
4055
+ //#endregion
4056
+ //#region src/_internal/helpers/resolve-tsconfig.ts
4057
+ function getTsconfigDtsPath(context) {
4058
+ return joinPaths(relativePath(joinPaths(context.config.cwd, context.config.root), findFilePath(context.typesPath)), findFileName(context.typesPath));
4059
+ }
4060
+ async function resolveTsconfigChanges(context) {
4061
+ const tsconfig = getParsedTypeScriptConfig(context.config.cwd, context.config.root, context.config.tsconfig, context.config.tsconfigRaw);
4062
+ const tsconfigJson = await readJsonFile(getTsconfigFilePath(context.config.cwd, context.config.root, context.config.tsconfig));
4063
+ tsconfigJson.compilerOptions ??= {};
4064
+ if (context.config.output.dts !== false) {
4065
+ const dtsRelativePath = getTsconfigDtsPath(context);
4066
+ if (!tsconfigJson.include?.some((filePattern) => isIncludeMatchFound(filePattern, [context.typesPath, dtsRelativePath]))) {
4067
+ tsconfigJson.include ??= [];
4068
+ tsconfigJson.include.push(dtsRelativePath.startsWith("./") ? dtsRelativePath.slice(2) : dtsRelativePath);
4069
+ }
4070
+ }
4071
+ if (!tsconfig.options.lib?.some((lib) => [
4072
+ "lib.esnext.d.ts",
4073
+ "lib.es2021.d.ts",
4074
+ "lib.es2022.d.ts",
4075
+ "lib.es2023.d.ts"
4076
+ ].includes(lib.toLowerCase()))) {
4077
+ tsconfigJson.compilerOptions.lib ??= [];
4078
+ tsconfigJson.compilerOptions.lib.push("esnext");
4079
+ }
4080
+ if (tsconfig.options.esModuleInterop !== true) tsconfigJson.compilerOptions.esModuleInterop = true;
4081
+ if (tsconfig.options.isolatedModules !== true) tsconfigJson.compilerOptions.isolatedModules = true;
4082
+ if (context.config.platform === "node") {
4083
+ if (!tsconfig.options.types?.some((type) => type.toLowerCase() === "node" || type.toLowerCase() === "@types/node")) {
4084
+ tsconfigJson.compilerOptions.types ??= [];
4085
+ tsconfigJson.compilerOptions.types.push("node");
4086
+ }
4087
+ }
4088
+ return tsconfigJson;
4089
+ }
4090
+ async function initializeTsconfig(context) {
4091
+ context.debug("Initializing TypeScript configuration (tsconfig.json) for the Powerlines project.");
4092
+ if (!isPackageExists("typescript")) throw new Error("The TypeScript package is not installed. Please install the package using the command: \"npm install typescript --save-dev\"");
4093
+ const tsconfigFilePath = getTsconfigFilePath(context.config.cwd, context.config.root, context.config.tsconfig);
4094
+ context.tsconfig.originalTsconfigJson = await readJsonFile(tsconfigFilePath);
4095
+ context.tsconfig.tsconfigJson = await resolveTsconfigChanges(context);
4096
+ context.debug("Writing updated TypeScript configuration (tsconfig.json) file to disk.");
4097
+ await context.fs.write(tsconfigFilePath, StormJSON.stringify(context.tsconfig.tsconfigJson));
4098
+ context.tsconfig = getParsedTypeScriptConfig(context.config.cwd, context.config.root, context.config.tsconfig, context.config.tsconfigRaw, context.tsconfig.originalTsconfigJson);
4099
+ }
4100
+ async function resolveTsconfig(context) {
4101
+ const updateTsconfigJson = await readJsonFile(context.tsconfig.tsconfigFilePath);
4102
+ if (updateTsconfigJson?.compilerOptions?.types && Array.isArray(updateTsconfigJson.compilerOptions.types) && !updateTsconfigJson.compilerOptions.types.length) delete updateTsconfigJson.compilerOptions.types;
4103
+ const result = getObjectDiff(context.tsconfig.originalTsconfigJson, updateTsconfigJson, {
4104
+ ignoreArrayOrder: true,
4105
+ showOnly: {
4106
+ statuses: [
4107
+ "added",
4108
+ "deleted",
4109
+ "updated"
4110
+ ],
4111
+ granularity: "deep"
4112
+ }
4113
+ });
4114
+ const changes = [];
4115
+ const getChanges = (difference, property) => {
4116
+ if (difference.status === "added" || difference.status === "deleted" || difference.status === "updated") if (difference.diff) for (const diff of difference.diff) getChanges(diff, property ? `${property}.${difference.property}` : difference.property);
4117
+ else changes.push({
4118
+ field: property ? `${property}.${difference.property}` : difference.property,
4119
+ status: difference.status,
4120
+ previous: difference.status === "added" ? "---" : StormJSON.stringify(difference.previousValue),
4121
+ current: difference.status === "deleted" ? "---" : StormJSON.stringify(difference.currentValue)
4122
+ });
4123
+ };
4124
+ for (const diff of result.diff) getChanges(diff);
4125
+ if (changes.length > 0) context.warn(`Updating the following configuration values in "${context.tsconfig.tsconfigFilePath}" file:
4126
+
4127
+ ${changes.map((change, i) => `${chalk.bold.whiteBright(`${i + 1}. ${titleCase(change.status)} the ${change.field} field: `)}
4128
+ ${chalk.red(` - Previous: ${change.previous} `)}
4129
+ ${chalk.green(` - Updated: ${change.current} `)}
4130
+ `).join("\n")}
4131
+ `);
4132
+ await context.fs.write(context.tsconfig.tsconfigFilePath, StormJSON.stringify(updateTsconfigJson));
4133
+ context.tsconfig = getParsedTypeScriptConfig(context.config.cwd, context.config.root, context.config.tsconfig);
4134
+ if (!context.tsconfig) throw new Error("Failed to parse the TypeScript configuration file.");
4135
+ }
4136
+
4137
+ //#endregion
4138
+ //#region src/_internal/execution.ts
4139
+ /**
4140
+ * The Powerlines Execution API class
4141
+ *
4142
+ * @remarks
4143
+ * This class is responsible for managing the Powerlines project lifecycle, including initialization, building, and finalization.
4144
+ *
4145
+ * @internal
4146
+ */
4147
+ var PowerlinesExecution = class PowerlinesExecution {
4148
+ /**
4149
+ * The Powerlines context
4150
+ */
4151
+ #context;
4152
+ async #handleBuild(context) {
4153
+ await this.callHook("build", {
4154
+ environment: context,
4155
+ order: "pre"
4156
+ });
4157
+ context.debug("Formatting the generated entry files before the build process starts.");
4158
+ await formatFolder(context, context.entryPath);
4159
+ await this.callHook("build", {
4160
+ environment: context,
4161
+ order: "normal"
4162
+ });
4163
+ if (context.config.output.copy) {
4164
+ context.debug("Copying project's files from build output directory.");
4165
+ const destinationPath = isParentPath(appendPath(context.config.output.path, context.config.cwd), appendPath(context.config.root, context.config.cwd)) ? joinPaths(context.config.output.copy.path, relativePath(appendPath(context.config.root, context.config.cwd), appendPath(context.config.output.path, context.config.cwd))) : joinPaths(context.config.output.copy.path, "dist");
4166
+ const sourcePath = context.config.output.path;
4167
+ if (existsSync(sourcePath) && sourcePath !== destinationPath) {
4168
+ context.debug(`Copying files from project's build output directory (${context.config.output.path}) to the project's copy/publish directory (${destinationPath}).`);
4169
+ await copyFiles(sourcePath, destinationPath);
4170
+ } else context.warn(`The source path for the copy operation ${!existsSync(sourcePath) ? "does not exist" : "is the same as the destination path"}. Source: ${sourcePath}, Destination: ${destinationPath}. Skipping copying of build output files.`);
4171
+ if (context.config.output.copy.assets && Array.isArray(context.config.output.copy.assets)) await Promise.all(context.config.output.copy.assets.map(async (asset) => {
4172
+ context.trace(`Copying asset(s): ${chalk.redBright(context.config.cwd === asset.input ? asset.glob : appendPath(asset.glob, replacePath(asset.input, context.config.cwd)))} -> ${chalk.greenBright(appendPath(asset.glob, replacePath(asset.output, context.config.cwd)))} ${Array.isArray(asset.ignore) && asset.ignore.length > 0 ? ` (ignoring: ${asset.ignore.map((i) => chalk.yellowBright(i)).join(", ")})` : ""}`);
4173
+ await context.fs.copy(asset, asset.output);
4174
+ }));
4175
+ } else context.debug("No copy configuration found for the project output. Skipping the copying of build output files.");
4176
+ await this.callHook("build", {
4177
+ environment: context,
4178
+ order: "post"
4179
+ });
4180
+ }
4181
+ /**
4182
+ * Get the configured environments
4183
+ *
4184
+ * @returns The configured environments
4185
+ */
4186
+ async #getEnvironments() {
4187
+ if (!this.context.config.environments || Object.keys(this.context.config.environments).length <= 1) {
4188
+ this.context.debug("No environments are configured for this Powerlines project. Using the default environment.");
4189
+ return [await this.context.getEnvironment()];
4190
+ }
4191
+ this.context.debug(`Found ${Object.keys(this.context.config.environments).length} configured environment(s) for this Powerlines project.`);
4192
+ return (await Promise.all(Object.entries(this.context.config.environments).map(async ([name, config]) => {
4193
+ if (!await this.context.getEnvironmentSafe(name)) {
4194
+ const resolvedEnvironment = await this.callHook("configEnvironment", { environment: name }, name, config);
4195
+ if (resolvedEnvironment) this.context.environments[name] = await this.context.in(resolvedEnvironment);
4196
+ }
4197
+ return this.context.environments[name];
4198
+ }))).filter((context) => isSet(context));
4199
+ }
4200
+ /**
4201
+ * Execute a handler function for each environment
4202
+ *
4203
+ * @param handle - The handler function to execute for each environment
4204
+ */
4205
+ async #executeEnvironments(handle) {
4206
+ await Promise.all((await this.#getEnvironments()).map(async (context) => {
4207
+ return Promise.resolve(handle(context));
4208
+ }));
4209
+ }
4210
+ /**
4211
+ * Initialize a Powerlines plugin
4212
+ *
4213
+ * @param config - The configuration for the plugin
4214
+ * @returns The initialized plugin instance, or null if the plugin was a duplicate
4215
+ * @throws Will throw an error if the plugin cannot be found or is invalid
4216
+ */
4217
+ async #initPlugin(config) {
4218
+ let awaited = config;
4219
+ if (isPromiseLike(config)) awaited = await Promise.resolve(config);
4220
+ if (!isPluginConfig(awaited)) {
4221
+ const invalid = findInvalidPluginConfig(awaited);
4222
+ throw new Error(`Invalid ${invalid && invalid.length > 1 ? "plugins" : "plugin"} specified in the configuration - ${invalid && invalid.length > 0 ? JSON.stringify(awaited) : invalid?.join("\n\n")} \n\nPlease ensure the value is one of the following: \n - an instance of \`Plugin\` \n - a plugin name \n - an object with the \`plugin\` and \`options\` properties \n - a tuple array with the plugin and options \n - a factory function that returns a plugin or array of plugins \n - an array of plugins or plugin configurations`);
4223
+ }
4224
+ let plugins;
4225
+ if (isPlugin(awaited)) plugins = [awaited];
4226
+ else if (isFunction(awaited)) plugins = toArray(await Promise.resolve(awaited()));
4227
+ else if (isString(awaited)) {
4228
+ const resolved = await this.#resolvePlugin(awaited);
4229
+ if (isFunction(resolved)) plugins = toArray(await Promise.resolve(resolved()));
4230
+ else plugins = toArray(resolved);
4231
+ } else if (Array.isArray(awaited) && awaited.every(isPlugin)) plugins = awaited;
4232
+ else if (Array.isArray(awaited) && awaited.every(isPluginConfig)) {
4233
+ plugins = [];
4234
+ for (const pluginConfig of awaited) {
4235
+ const initialized = await this.#initPlugin(pluginConfig);
4236
+ if (initialized) plugins.push(...initialized);
4237
+ }
4238
+ } else if (isPluginConfigTuple(awaited) || isPluginConfigObject(awaited)) {
4239
+ let pluginConfig;
4240
+ let pluginOptions;
4241
+ if (isPluginConfigTuple(awaited)) {
4242
+ pluginConfig = awaited[0];
4243
+ pluginOptions = awaited?.length === 2 ? awaited[1] : void 0;
4244
+ } else {
4245
+ pluginConfig = awaited.plugin;
4246
+ pluginOptions = awaited.options;
4247
+ }
4248
+ if (isSetString(pluginConfig)) {
4249
+ const resolved = await this.#resolvePlugin(pluginConfig);
4250
+ if (isFunction(resolved)) plugins = toArray(await Promise.resolve(pluginOptions ? resolved(pluginOptions) : resolved()));
4251
+ else plugins = toArray(resolved);
4252
+ } else if (isFunction(pluginConfig)) plugins = toArray(await Promise.resolve(pluginConfig(pluginOptions)));
4253
+ else if (Array.isArray(pluginConfig) && pluginConfig.every(isPlugin)) plugins = pluginConfig;
4254
+ else if (isPlugin(pluginConfig)) plugins = toArray(pluginConfig);
4255
+ }
4256
+ if (!plugins) throw new Error(`The plugin configuration ${JSON.stringify(awaited)} is invalid. This configuration must point to a valid Powerlines plugin module.`);
4257
+ if (plugins.length > 0 && !plugins.every(isPlugin)) throw new Error(`The plugin option ${JSON.stringify(plugins)} does not export a valid module. This configuration must point to a valid Powerlines plugin module.`);
4258
+ const result = [];
4259
+ for (const plugin of plugins) if (isDuplicate(plugin, this.context.plugins)) this.context.trace(`Duplicate ${chalk.bold.cyanBright(plugin.name)} plugin dependency detected - Skipping initialization.`);
4260
+ else {
4261
+ result.push(plugin);
4262
+ this.context.trace(`Initializing the ${chalk.bold.cyanBright(plugin.name)} plugin...`);
4263
+ }
4264
+ return result;
4265
+ }
4266
+ async #resolvePlugin(pluginPath) {
4267
+ if (pluginPath.startsWith("@") && pluginPath.split("/").filter(Boolean).length > 2) {
4268
+ const splits = pluginPath.split("/").filter(Boolean);
4269
+ pluginPath = `${splits[0]}/${splits[1]}`;
4270
+ }
4271
+ const isInstalled = isPackageExists(pluginPath, { paths: [this.context.config.cwd, this.context.config.root] });
4272
+ if (!isInstalled && this.context.config.autoInstall) {
4273
+ this.#context.warn(`The plugin package "${pluginPath}" is not installed. It will be installed automatically.`);
4274
+ const result = await install(pluginPath, { cwd: this.context.config.root });
4275
+ if (isNumber(result.exitCode) && result.exitCode > 0) {
4276
+ this.#context.error(result.stderr);
4277
+ throw new Error(`An error occurred while installing the build plugin package "${pluginPath}" `);
4278
+ }
4279
+ }
4280
+ try {
4281
+ const module = await this.context.resolver.plugin.import(this.context.resolver.plugin.esmResolve(joinPaths(pluginPath, "plugin")));
4282
+ const result = module.plugin ?? module.default;
4283
+ if (!result) throw new Error(`The plugin package "${pluginPath}" does not export a valid module.`);
4284
+ return result;
4285
+ } catch (error) {
4286
+ try {
4287
+ const module = await this.context.resolver.plugin.import(this.context.resolver.plugin.esmResolve(pluginPath));
4288
+ const result = module.plugin ?? module.default;
4289
+ if (!result) throw new Error(`The plugin package "${pluginPath}" does not export a valid module.`);
4290
+ return result;
4291
+ } catch {
4292
+ if (!isInstalled) throw new Error(`The plugin package "${pluginPath}" is not installed. Please install the package using the command: "npm install ${pluginPath} --save-dev"`);
4293
+ else throw new Error(`An error occurred while importing the build plugin package "${pluginPath}":
4294
+ ${isError(error) ? error.message : String(error)}
4295
+
4296
+ Note: Please ensure the plugin package's default export is a class that extends \`Plugin\` with a constructor that excepts a single arguments of type \`PluginOptions\`.`);
4297
+ }
4298
+ }
4299
+ }
4300
+ /**
4301
+ * Generate the Powerlines TypeScript declaration file
4302
+ *
4303
+ * @remarks
4304
+ * This method will generate the TypeScript declaration file for the Powerlines project, including any types provided by plugins.
4305
+ *
4306
+ * @param context - The environment context to use for generating the TypeScript declaration file
4307
+ * @returns A promise that resolves when the TypeScript declaration file has been generated
4308
+ */
4309
+ async #types(context) {
4310
+ context.debug(`Preparing the TypeScript definitions for the Powerlines project.`);
4311
+ if (context.fs.existsSync(context.typesPath)) await context.fs.remove(context.typesPath);
4312
+ if (!await resolvePackage("typescript")) throw new Error("Could not resolve TypeScript package location. Please ensure TypeScript is installed.");
4313
+ context.debug("Running TypeScript compiler for built-in runtime module files.");
4314
+ let { code, directives } = await emitBuiltinTypes(context, (await context.getBuiltins()).reduce((ret, builtin) => {
4315
+ const formatted = replacePath(builtin.path, context.config.cwd);
4316
+ if (!ret.includes(formatted)) ret.push(formatted);
4317
+ return ret;
4318
+ }, []));
4319
+ context.debug(`Generating TypeScript declaration file ${context.typesPath}.`);
4320
+ const merge = async (currentResult, previousResult) => {
4321
+ if (!isSetString(currentResult) && !isSetObject(currentResult) && !isSetString(previousResult) && !isSetObject(previousResult)) return {
4322
+ code,
4323
+ directives
4324
+ };
4325
+ const previous = (await format(context, context.typesPath, isSetString(previousResult) ? previousResult : isSetObject(previousResult) ? previousResult.code : "")).trim().replace(code, "").trim();
4326
+ const current = (await format(context, context.typesPath, isSetString(currentResult) ? currentResult : isSetObject(currentResult) ? currentResult.code : "")).trim().replace(previous, "").trim().replace(code, "").trim();
4327
+ return {
4328
+ directives: [...isSetObject(currentResult) && currentResult.directives ? currentResult.directives : [], ...isSetObject(previousResult) && previousResult.directives ? previousResult.directives : []],
4329
+ code: await format(context, context.typesPath, `${!previous.includes(getTypescriptFileHeader(context)) && !current.includes(getTypescriptFileHeader(context)) ? `${code}\n` : ""}${previous}\n${current}`.trim())
4330
+ };
4331
+ };
4332
+ const asNextParam = (previousResult) => isObject(previousResult) ? previousResult.code : previousResult;
4333
+ let result = await this.callHook("types", {
4334
+ environment: context,
4335
+ sequential: true,
4336
+ order: "pre",
4337
+ result: "merge",
4338
+ merge,
4339
+ asNextParam
4340
+ }, code);
4341
+ if (result) {
4342
+ if (isSetObject(result)) {
4343
+ code = result.code;
4344
+ if (Array.isArray(result.directives) && result.directives.length > 0) directives = getUnique([...directives, ...result.directives]).filter(Boolean);
4345
+ } else if (isSetString(result)) code = result;
4346
+ }
4347
+ result = await this.callHook("types", {
4348
+ environment: context,
4349
+ sequential: true,
4350
+ order: "normal",
4351
+ result: "merge",
4352
+ merge,
4353
+ asNextParam
4354
+ }, code);
4355
+ if (result) {
4356
+ if (isSetObject(result)) {
4357
+ code = result.code;
4358
+ if (Array.isArray(result.directives) && result.directives.length > 0) directives = getUnique([...directives, ...result.directives]).filter(Boolean);
4359
+ } else if (isSetString(result)) code = result;
4360
+ }
4361
+ result = await this.callHook("types", {
4362
+ environment: context,
4363
+ sequential: true,
4364
+ order: "post",
4365
+ result: "merge",
4366
+ merge,
4367
+ asNextParam
4368
+ }, code);
4369
+ if (result) {
4370
+ if (isSetObject(result)) {
4371
+ code = result.code;
4372
+ if (Array.isArray(result.directives) && result.directives.length > 0) directives = getUnique([...directives, ...result.directives]).filter(Boolean);
4373
+ } else if (isSetString(result)) code = result;
4374
+ }
4375
+ if (isSetString(code?.trim()) || directives.length > 0) await context.fs.write(context.typesPath, `${directives.length > 0 ? `${directives.map((directive) => `/// <reference types="${directive}" />`).join("\n")}
4376
+
4377
+ ` : ""}${getTypescriptFileHeader(context, {
4378
+ directive: null,
4379
+ prettierIgnore: false
4380
+ })}
4381
+
4382
+ ${formatTypes(code)}
4383
+ `);
4384
+ }
4385
+ /**
4386
+ * The Powerlines context
4387
+ */
4388
+ get context() {
4389
+ return this.#context;
4390
+ }
4391
+ /**
4392
+ * Initialize a Powerlines API instance
4393
+ *
4394
+ * @param options - The options to initialize the API with
4395
+ * @returns A new instance of the Powerlines API
4396
+ */
4397
+ static async fromConfig(options, config) {
4398
+ const api = new PowerlinesExecution(await PowerlinesExecutionContext.fromOptions(options));
4399
+ api.#context.config.inlineConfig = config;
4400
+ await api.#context.setup(config);
4401
+ api.#context.$$internal = {
4402
+ api,
4403
+ addPlugin: api.addPlugin.bind(api)
4404
+ };
4405
+ const timer = api.context.timer("Initialization");
4406
+ for (const plugin of api.context.config.plugins.flat(10) ?? []) await api.addPlugin(plugin);
4407
+ if (api.context.plugins.length === 0) api.context.warn("No Powerlines plugins were specified in the options. Please ensure this is correct, as it is generally not recommended.");
4408
+ else api.context.info(`Loaded ${api.context.plugins.length} ${titleCase(api.context.config.framework)} plugin${api.context.plugins.length > 1 ? "s" : ""}: \n${api.context.plugins.map((plugin, index) => ` ${index + 1}. ${colorText(plugin.name)}`).join("\n")}`);
4409
+ const pluginConfig = await api.callHook("config", {
4410
+ environment: await api.context.getEnvironment(),
4411
+ sequential: true,
4412
+ result: "merge",
4413
+ merge: mergeConfigs
4414
+ });
4415
+ if (pluginConfig) {
4416
+ api.#context.config.pluginConfig = pluginConfig;
4417
+ await api.#context.setup(pluginConfig);
4418
+ }
4419
+ timer();
4420
+ return api;
4421
+ }
4422
+ /**
4423
+ * Generate the Powerlines typescript declaration file
4424
+ *
4425
+ * @remarks
4426
+ * This method will only generate the typescript declaration file for the Powerlines project. It is generally recommended to run the full `prepare` command, which will run this method as part of its process.
4427
+ *
4428
+ * @param inlineConfig - The inline configuration for the types command
4429
+ */
4430
+ async types(inlineConfig = { command: "types" }) {
4431
+ this.context.debug(" Aggregating configuration options for the Powerlines project");
4432
+ inlineConfig.command ??= "types";
4433
+ await this.context.setup(inlineConfig);
4434
+ await this.#executeEnvironments(async (context) => {
4435
+ context.debug(`Initializing the processing options for the Powerlines project.`);
4436
+ await this.callHook("configResolved", {
4437
+ environment: context,
4438
+ order: "pre"
4439
+ });
4440
+ await initializeTsconfig(context);
4441
+ await this.callHook("configResolved", {
4442
+ environment: context,
4443
+ order: "normal"
4444
+ });
4445
+ if (context.entry.length > 0) context.debug(`The configuration provided ${isObject(context.config.input) ? Object.keys(context.config.input).length : toArray(context.config.input).length} entry point(s), Powerlines has found ${context.entry.length} entry files(s) for the ${context.config.title} project${context.entry.length > 0 && context.entry.length < 10 ? `: \n${context.entry.map((entry) => `- ${entry.file}${entry.output ? ` -> ${entry.output}` : ""}`).join(" \n")}` : ""}`);
4446
+ else context.warn(`No entry files were found for the ${context.config.title} project. Please ensure this is correct. Powerlines plugins generally require at least one entry point to function properly.`);
4447
+ await resolveTsconfig(context);
4448
+ await installDependencies(context);
4449
+ await this.callHook("configResolved", {
4450
+ environment: context,
4451
+ order: "post"
4452
+ });
4453
+ context.trace(`Powerlines configuration has been resolved: \n\n${formatLogMessage({
4454
+ ...context.config,
4455
+ userConfig: isSetObject(context.config.userConfig) ? omit(context.config.userConfig, ["plugins"]) : void 0,
4456
+ inlineConfig: isSetObject(context.config.inlineConfig) ? omit(context.config.inlineConfig, ["plugins"]) : void 0,
4457
+ plugins: context.plugins.map((plugin) => plugin.plugin.name)
4458
+ })}`);
4459
+ if (!context.fs.existsSync(context.cachePath)) await createDirectory(context.cachePath);
4460
+ if (!context.fs.existsSync(context.dataPath)) await createDirectory(context.dataPath);
4461
+ if (context.config.skipCache === true || context.persistedMeta?.checksum !== context.meta.checksum) context.debug(`Using previously prepared files as the meta checksum has not changed.`);
4462
+ else {
4463
+ context.info(`Running \`prepare\` command as the meta checksum has changed since the last run.`);
4464
+ await this.prepare(defu({ output: { types: false } }, inlineConfig));
4465
+ }
4466
+ await this.#types(context);
4467
+ this.context.debug("Formatting files generated during the types step.");
4468
+ await format(context, context.typesPath, await context.fs.read(context.typesPath) ?? "");
4469
+ await writeMetaFile(context);
4470
+ context.persistedMeta = context.meta;
4471
+ });
4472
+ }
4473
+ /**
4474
+ * Prepare the Powerlines API
4475
+ *
4476
+ * @remarks
4477
+ * This method will prepare the Powerlines API for use, initializing any necessary resources.
4478
+ *
4479
+ * @param inlineConfig - The inline configuration for the prepare command
4480
+ */
4481
+ async prepare(inlineConfig = { command: "prepare" }) {
4482
+ inlineConfig.command ??= "prepare";
4483
+ await this.context.setup(inlineConfig);
4484
+ await this.#executeEnvironments(async (context) => {
4485
+ context.debug(`Initializing the processing options for the Powerlines project.`);
4486
+ await this.callHook("configResolved", {
4487
+ environment: context,
4488
+ order: "pre"
4489
+ });
4490
+ await initializeTsconfig(context);
4491
+ await this.callHook("configResolved", {
4492
+ environment: context,
4493
+ order: "normal"
4494
+ });
4495
+ if (context.entry.length > 0) context.debug(`The configuration provided ${isObject(context.config.input) ? Object.keys(context.config.input).length : toArray(context.config.input).length} entry point(s), Powerlines has found ${context.entry.length} entry files(s) for the ${context.config.title} project${context.entry.length > 0 && context.entry.length < 10 ? `: \n${context.entry.map((entry) => `- ${entry.file}${entry.output ? ` -> ${entry.output}` : ""}`).join(" \n")}` : ""}`);
4496
+ else context.warn(`No entry files were found for the ${context.config.title} project. Please ensure this is correct. Powerlines plugins generally require at least one entry point to function properly.`);
4497
+ await resolveTsconfig(context);
4498
+ await installDependencies(context);
4499
+ await this.callHook("configResolved", {
4500
+ environment: context,
4501
+ order: "post"
4502
+ });
4503
+ context.trace(`Powerlines configuration has been resolved: \n\n${formatLogMessage({
4504
+ ...context.config,
4505
+ userConfig: isSetObject(context.config.userConfig) ? omit(context.config.userConfig, ["plugins"]) : void 0,
4506
+ inlineConfig: isSetObject(context.config.inlineConfig) ? omit(context.config.inlineConfig, ["plugins"]) : void 0,
4507
+ plugins: context.plugins.map((plugin) => plugin.plugin.name)
4508
+ })}`);
4509
+ if (!context.fs.existsSync(context.cachePath)) await createDirectory(context.cachePath);
4510
+ if (!context.fs.existsSync(context.dataPath)) await createDirectory(context.dataPath);
4511
+ await this.callHook("prepare", {
4512
+ environment: context,
4513
+ order: "pre"
4514
+ });
4515
+ await this.callHook("prepare", {
4516
+ environment: context,
4517
+ order: "normal"
4518
+ });
4519
+ await this.callHook("prepare", {
4520
+ environment: context,
4521
+ order: "post"
4522
+ });
4523
+ if (context.config.output.types !== false) await this.#types(context);
4524
+ this.context.debug("Formatting files generated during the prepare step.");
4525
+ await Promise.all([formatFolder(context, context.builtinsPath), formatFolder(context, context.entryPath)]);
4526
+ await writeMetaFile(context);
4527
+ context.persistedMeta = context.meta;
4528
+ });
4529
+ }
4530
+ /**
4531
+ * Create a new Powerlines project
4532
+ *
4533
+ * @remarks
4534
+ * This method will create a new Powerlines project in the current directory.
4535
+ *
4536
+ * @param inlineConfig - The inline configuration for the new command
4537
+ * @returns A promise that resolves when the project has been created
4538
+ */
4539
+ async new(inlineConfig) {
4540
+ inlineConfig.command ??= "new";
4541
+ await this.prepare(inlineConfig);
4542
+ await this.#executeEnvironments(async (context) => {
4543
+ context.debug("Initializing the processing options for the Powerlines project.");
4544
+ await this.callHook("new", {
4545
+ environment: context,
4546
+ order: "pre"
4547
+ });
4548
+ const files = await listFiles(joinPaths(context.powerlinesPath, "files/common/**/*.hbs"));
4549
+ for (const file of files) {
4550
+ context.trace(`Adding template file to project: ${file}`);
4551
+ const template = Handlebars.compile(file);
4552
+ await context.fs.write(joinPaths(context.config.root, file.replace(".hbs", "")), template(context));
4553
+ }
4554
+ await this.callHook("new", {
4555
+ environment: context,
4556
+ order: "normal"
4557
+ });
4558
+ if (context.config.projectType === "application") {
4559
+ const files = await listFiles(joinPaths(context.powerlinesPath, "files/application/**/*.hbs"));
4560
+ for (const file of files) {
4561
+ context.trace(`Adding application template file: ${file}`);
4562
+ const template = Handlebars.compile(file);
4563
+ await context.fs.write(joinPaths(context.config.root, file.replace(".hbs", "")), template(context));
4564
+ }
4565
+ } else {
4566
+ const files = await listFiles(joinPaths(context.powerlinesPath, "files/library/**/*.hbs"));
4567
+ for (const file of files) {
4568
+ context.trace(`Adding library template file: ${file}`);
4569
+ const template = Handlebars.compile(file);
4570
+ await context.fs.write(joinPaths(context.config.root, file.replace(".hbs", "")), template(context));
4571
+ }
4572
+ }
4573
+ await this.callHook("new", {
4574
+ environment: context,
4575
+ order: "post"
4576
+ });
4577
+ });
4578
+ }
4579
+ /**
4580
+ * Clean any previously prepared artifacts
4581
+ *
4582
+ * @remarks
4583
+ * This method will remove the previous Powerlines artifacts from the project.
4584
+ *
4585
+ * @param inlineConfig - The inline configuration for the clean command
4586
+ * @returns A promise that resolves when the clean command has completed
4587
+ */
4588
+ async clean(inlineConfig = { command: "clean" }) {
4589
+ inlineConfig.command ??= "clean";
4590
+ await this.prepare(inlineConfig);
4591
+ await this.#executeEnvironments(async (context) => {
4592
+ context.debug("Cleaning the project's dist and artifacts directories.");
4593
+ await context.fs.remove(joinPaths(context.config.cwd, context.config.output.path));
4594
+ await context.fs.remove(joinPaths(context.config.cwd, context.config.root, context.config.output.artifactsPath));
4595
+ await this.callHook("clean", {
4596
+ environment: context,
4597
+ sequential: false
4598
+ });
4599
+ });
4600
+ }
4601
+ /**
4602
+ * Lint the project
4603
+ *
4604
+ * @param inlineConfig - The inline configuration for the lint command
4605
+ * @returns A promise that resolves when the lint command has completed
4606
+ */
4607
+ async lint(inlineConfig = { command: "lint" }) {
4608
+ inlineConfig.command ??= "lint";
4609
+ await this.prepare(inlineConfig);
4610
+ await this.#executeEnvironments(async (context) => {
4611
+ await this.callHook("lint", {
4612
+ environment: context,
4613
+ sequential: false
4614
+ });
4615
+ });
4616
+ }
4617
+ /**
4618
+ * Test the project source code
4619
+ *
4620
+ * @param inlineConfig - The inline configuration for the test command
4621
+ * @returns A promise that resolves when the test command has completed
4622
+ */
4623
+ async test(inlineConfig = { command: "test" }) {
4624
+ inlineConfig.command ??= "test";
4625
+ await this.prepare(inlineConfig);
4626
+ await this.#executeEnvironments(async (context) => {
4627
+ await this.callHook("test", {
4628
+ environment: context,
4629
+ sequential: false
4630
+ });
4631
+ });
4632
+ }
4633
+ /**
4634
+ * Build the project
4635
+ *
4636
+ * @remarks
4637
+ * This method will build the Powerlines project, generating the necessary artifacts.
4638
+ *
4639
+ * @param inlineConfig - The inline configuration for the build command
4640
+ * @returns A promise that resolves when the build command has completed
4641
+ */
4642
+ async build(inlineConfig = { command: "build" }) {
4643
+ await this.context.generateChecksum();
4644
+ if (this.context.meta.checksum !== this.context.persistedMeta?.checksum || this.context.config.skipCache) {
4645
+ this.context.info(!this.context.persistedMeta?.checksum ? "No previous build cache found. Preparing the project for the initial build." : this.context.meta.checksum !== this.context.persistedMeta.checksum ? "The project has been modified since the last time `prepare` was ran. Re-preparing the project." : "The project is configured to skip cache. Re-preparing the project.");
4646
+ inlineConfig.command ??= "build";
4647
+ await this.prepare(inlineConfig);
4648
+ }
4649
+ if (this.context.config.singleBuild) await this.#handleBuild(await this.#context.toEnvironment());
4650
+ else await this.#executeEnvironments(async (context) => {
4651
+ await this.#handleBuild(context);
4652
+ });
4653
+ }
4654
+ /**
4655
+ * Prepare the documentation for the project
4656
+ *
4657
+ * @param inlineConfig - The inline configuration for the docs command
4658
+ * @returns A promise that resolves when the documentation generation has completed
4659
+ */
4660
+ async docs(inlineConfig = { command: "docs" }) {
4661
+ inlineConfig.command ??= "docs";
4662
+ await this.prepare(inlineConfig);
4663
+ await this.#executeEnvironments(async (context) => {
4664
+ context.debug("Writing documentation for the Powerlines project artifacts.");
4665
+ await this.callHook("docs", { environment: context });
4666
+ });
4667
+ }
4668
+ /**
4669
+ * Deploy the project source code
4670
+ *
4671
+ * @remarks
4672
+ * This method will prepare and build the Powerlines project, generating the necessary artifacts for the deployment.
4673
+ *
4674
+ * @param inlineConfig - The inline configuration for the deploy command
4675
+ */
4676
+ async deploy(inlineConfig = { command: "deploy" }) {
4677
+ inlineConfig.command ??= "deploy";
4678
+ await this.prepare(inlineConfig);
4679
+ await this.#executeEnvironments(async (context) => {
4680
+ await this.callHook("deploy", { environment: context });
4681
+ });
4682
+ }
4683
+ /**
4684
+ * Finalization/cleanup processing for the Powerlines API
4685
+ *
4686
+ * @remarks
4687
+ * This step includes any final processes or clean up required by Powerlines. It will be run after each Powerlines command.
4688
+ *
4689
+ * @returns A promise that resolves when the finalization process has completed
4690
+ */
4691
+ async finalize() {
4692
+ await this.#executeEnvironments(async (context) => {
4693
+ await this.callHook("finalize", { environment: context });
4694
+ await context.fs.dispose();
4695
+ if (existsSync(context.cachePath) && !(await listFiles(joinPaths(context.cachePath, "**/*")))?.length) await removeDirectory(context.cachePath);
4696
+ });
4697
+ }
4698
+ /**
4699
+ * Invokes the configured plugin hooks
4700
+ *
4701
+ * @remarks
4702
+ * By default, it will call the `"pre"`, `"normal"`, and `"post"` ordered hooks in sequence
4703
+ *
4704
+ * @param hook - The hook to call
4705
+ * @param options - The options to provide to the hook
4706
+ * @param args - The arguments to pass to the hook
4707
+ * @returns The result of the hook call
4708
+ */
4709
+ async callHook(hook, options, ...args) {
4710
+ return callHook(isSetObject(options?.environment) ? options.environment : await this.#context.getEnvironment(options?.environment), hook, {
4711
+ sequential: true,
4712
+ ...options
4713
+ }, ...args);
4714
+ }
4715
+ /**
4716
+ * Create a new Powerlines API instance
4717
+ *
4718
+ * @param context - The Powerlines context
4719
+ */
4720
+ constructor(context) {
4721
+ this.#context = context;
4722
+ }
4723
+ /**
4724
+ * Add a Powerlines plugin used in the build process
4725
+ *
4726
+ * @param config - The import path of the plugin to add
4727
+ */
4728
+ async addPlugin(config) {
4729
+ if (config) {
4730
+ const result = await this.#initPlugin(config);
4731
+ if (!result) return;
4732
+ for (const plugin of result) {
4733
+ this.context.debug(`Successfully initialized the ${chalk.bold.cyanBright(plugin.name)} plugin`);
4734
+ await this.context.addPlugin(plugin);
4735
+ }
4736
+ }
4737
+ }
4738
+ };
4739
+
4740
+ //#endregion
4741
+ //#region src/_internal/worker.ts
4742
+ async function clean({ options, config }) {
4743
+ const execution = await PowerlinesExecution.fromConfig(options, config);
4744
+ await execution.clean(config);
4745
+ await execution.finalize();
4746
+ }
4747
+ async function prepare({ options, config }) {
4748
+ const execution = await PowerlinesExecution.fromConfig(options, config);
4749
+ await execution.prepare(config);
4750
+ await execution.finalize();
4751
+ }
4752
+ async function types({ options, config }) {
4753
+ const execution = await PowerlinesExecution.fromConfig(options, config);
4754
+ await execution.types(config);
4755
+ await execution.finalize();
4756
+ }
4757
+ async function lint({ options, config }) {
4758
+ const execution = await PowerlinesExecution.fromConfig(options, config);
4759
+ await execution.lint(config);
4760
+ await execution.finalize();
4761
+ }
4762
+ async function test({ options, config }) {
4763
+ const execution = await PowerlinesExecution.fromConfig(options, config);
4764
+ await execution.test(config);
4765
+ await execution.finalize();
4766
+ }
4767
+ async function build({ options, config }) {
4768
+ const execution = await PowerlinesExecution.fromConfig(options, config);
4769
+ await execution.build(config);
4770
+ await execution.finalize();
4771
+ }
4772
+ async function docs({ options, config }) {
4773
+ const execution = await PowerlinesExecution.fromConfig(options, config);
4774
+ await execution.docs(config);
4775
+ await execution.finalize();
4776
+ }
4777
+ async function deploy({ options, config }) {
4778
+ const execution = await PowerlinesExecution.fromConfig(options, config);
4779
+ await execution.deploy(config);
4780
+ await execution.finalize();
4781
+ }
4782
+
4783
+ //#endregion
4784
+ export { build, clean, deploy, docs, lint, prepare, test, types };
4785
+ //# sourceMappingURL=worker.mjs.map