@powerlines/nx 0.11.239 → 0.11.241

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