powerlines 0.42.33 → 0.42.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import { n as createProgram } from "./ts-morph-B85ZbV1Q.mjs";
2
2
  import { t as utils_exports } from "./utils.mjs";
3
3
  import { t as plugin_utils_exports } from "./plugin-utils.mjs";
4
- import { d as writeMetaFile, f as callHook, p as mergeConfigs, t as PowerlinesAPIContext } from "./api-context-DiZCovj6.mjs";
4
+ import { d as writeMetaFile, f as callHook, p as mergeConfigs, t as PowerlinesAPIContext } from "./api-context-CmuOyg7q.mjs";
5
5
  import { a as isIncludeMatchFound, i as getTsconfigFilePath, r as getParsedTypeScriptConfig } from "./tsconfig-DoV1dUYg.mjs";
6
6
  import { formatLogMessage } from "@storm-software/config-tools/logger/console";
7
7
  import { toArray } from "@stryke/convert/to-array";
@@ -33,8 +33,7 @@ import chalk from "chalk";
33
33
  import defu$1 from "defu";
34
34
  import Handlebars from "handlebars";
35
35
  import { prettyBytes } from "@stryke/string-format/pretty-bytes";
36
- import { match } from "bundle-require";
37
- import { DiagnosticCategory } from "ts-morph";
36
+ import { DiagnosticCategory, Node, Project } from "ts-morph";
38
37
  import { getPackageName, getPackageVersion, hasPackageVersion } from "@stryke/string-format/package";
39
38
  import { readJsonFile } from "@stryke/fs/json";
40
39
  import { getObjectDiff } from "@donedeal0/superdiff";
@@ -42,7 +41,7 @@ import { StormJSON } from "@stryke/json/storm-json";
42
41
 
43
42
  //#region package.json
44
43
  var name = "powerlines";
45
- var version = "0.42.33";
44
+ var version = "0.42.34";
46
45
 
47
46
  //#endregion
48
47
  //#region src/_internal/helpers/generate-types.ts
@@ -55,31 +54,96 @@ var version = "0.42.33";
55
54
  function formatTypes(code = "") {
56
55
  return code.replaceAll("#private;", "").replace(/__Ω/g, "");
57
56
  }
58
- /**
59
- * Formats a generated TypeScript module in the types source code.
60
- *
61
- * @param context - The Powerlines context.
62
- * @param id - The module ID for the generated TypeScript module.
63
- * @param code - The generated TypeScript module code.
64
- * @returns The formatted TypeScript module code.
65
- */
66
- async function formatTypesModule(context, id, code) {
67
- const moduleComment = code.match(new RegExp(`\\/\\*\\*(?s:.)*?@module\\s+${context.config.framework}:${id}(?s:.)*?\\*\\/\\s+`))?.find((comment) => isSetString(comment?.trim()));
68
- const ast = await context.parse(code, {
69
- lang: "dts",
70
- astType: "ts"
57
+ async function extractModuleDeclarations(context, filePath, id, code, fileToModuleMap) {
58
+ const mappings = /* @__PURE__ */ new Map();
59
+ const ambient = [];
60
+ const sourceFile = new Project({ useInMemoryFileSystem: true }).createSourceFile("module.d.ts", code);
61
+ for (const ref of sourceFile.getTypeReferenceDirectives()) ambient.push({
62
+ id: ref.getFileName(),
63
+ external: true
71
64
  });
65
+ const importLines = [];
66
+ const reExportLines = [];
67
+ const declarationLines = [];
68
+ for (const statement of sourceFile.getStatements()) {
69
+ if (Node.isImportDeclaration(statement)) {
70
+ const moduleSpec = statement.getModuleSpecifierValue();
71
+ const defaultImport = statement.getDefaultImport();
72
+ const namedImports = statement.getNamedImports();
73
+ const namespaceImport = statement.getNamespaceImport();
74
+ if (!defaultImport && namedImports.length === 0 && !namespaceImport) {
75
+ ambient.push({
76
+ id: moduleSpec,
77
+ external: !context.fs.isResolvableId(moduleSpec, filePath)
78
+ });
79
+ continue;
80
+ }
81
+ let resolvedSpec = moduleSpec;
82
+ if (context.fs.isResolvableId(moduleSpec, filePath)) {
83
+ const resolved = await context.resolve(moduleSpec, filePath);
84
+ if (resolved) {
85
+ const mapped = fileToModuleMap.get(resolved.id);
86
+ if (mapped) resolvedSpec = mapped;
87
+ else context.trace(`Could not resolve relative import '${moduleSpec}' from '${filePath}' to a builtin module. Keeping as-is.`);
88
+ }
89
+ }
90
+ if (namespaceImport) importLines.push(`\timport * as ${namespaceImport.getText()} from '${resolvedSpec}';`);
91
+ else {
92
+ const specifiers = [];
93
+ if (defaultImport) specifiers.push(`default as ${defaultImport.getText()}`);
94
+ for (const named of namedImports) {
95
+ const alias = named.getAliasNode()?.getText();
96
+ specifiers.push(alias ? `${named.getName()} as ${alias}` : named.getName());
97
+ }
98
+ if (specifiers.length > 0) {
99
+ const typeOnly = statement.isTypeOnly() ? " type" : "";
100
+ importLines.push(`\timport${typeOnly} { ${specifiers.join(", ")} } from '${resolvedSpec}';`);
101
+ }
102
+ }
103
+ continue;
104
+ }
105
+ if (Node.isExportDeclaration(statement)) {
106
+ const moduleSpec = statement.getModuleSpecifierValue();
107
+ if (moduleSpec) {
108
+ let resolvedSpec = moduleSpec;
109
+ if (context.fs.isResolvableId(moduleSpec, filePath)) {
110
+ const resolved = await context.resolve(moduleSpec, filePath);
111
+ if (resolved) {
112
+ const mapped = fileToModuleMap.get(resolved.id);
113
+ if (mapped) resolvedSpec = mapped;
114
+ else context.trace(`Could not resolve relative import '${moduleSpec}' from '${filePath}' to a builtin module. Keeping as-is.`);
115
+ }
116
+ }
117
+ const namedExports = statement.getNamedExports();
118
+ if (namedExports.length > 0) {
119
+ const specifiers = namedExports.map((named) => {
120
+ const alias = named.getAliasNode()?.getText();
121
+ return alias ? `${named.getName()} as ${alias}` : named.getName();
122
+ });
123
+ const typeOnly = statement.isTypeOnly() ? " type" : "";
124
+ reExportLines.push(`\texport${typeOnly} { ${specifiers.join(", ")} } from '${resolvedSpec}';`);
125
+ } else reExportLines.push(`\texport * from '${resolvedSpec}';`);
126
+ } else declarationLines.push(`\t${statement.getText()}`);
127
+ continue;
128
+ }
129
+ if (Node.isExportAssignment(statement)) {
130
+ declarationLines.push(`\t${statement.getText()}`);
131
+ continue;
132
+ }
133
+ const text = statement.getText();
134
+ if (text.includes("//# sourceMappingURL=")) continue;
135
+ declarationLines.push(formatTypes(text.replace(/^(export\s+)?declare\s+/, "$1")).split("\n").map((line) => `\t${line}`).join("\n"));
136
+ }
137
+ const moduleComment = code.match(new RegExp(`\\/\\*\\*(?s:.)*?@module\\s+${context.config.framework}:${id}(?s:.)*?\\*\\/\\s+`))?.find((comment) => isSetString(comment?.trim()));
138
+ let content = `${moduleComment ? `${moduleComment.trim()}\n` : ""}declare module "${context.config.framework}:${id}" {`;
139
+ for (const line of importLines) content += `\n${line}`;
140
+ for (const line of reExportLines) content += `\n${line}`;
141
+ for (const line of declarationLines) content += `\n${line}`;
142
+ content += "\n}";
72
143
  return {
73
- code: `${moduleComment ? `
74
- ${moduleComment.trim()}` : ""}
75
- declare module "${context.config.framework}:${id}" {
76
- ${ast.module.staticImports.filter((staticImport) => !match(staticImport.moduleRequest.value, context.config.resolve.external) && !staticImport.moduleRequest.value.startsWith("node:")).reduce((ret, staticImport) => {
77
- return ret.replaceAll(new RegExp(`^import.*from\\s+['"]${staticImport.moduleRequest.value}['"]\\s*;?$`, "gm"), "");
78
- }, code).replace(moduleComment ?? "", "").replaceAll(/^\s*export\s*declare\s*/gm, "export ").replaceAll(/^\s*declare\s*/gm, "").replaceAll(/^\s*export\s*\{\s*\}/gm, "").replaceAll(/^\s*export\s*=\s*/gm, "export default ").replaceAll(/^\s*export\s*\{/gm, "export {").replaceAll(/^\s*export\s*default\s*\{/gm, "export default {").replaceAll(/^\s*export\s*function\s*/gm, "export function ").replaceAll(/^\s*export\s*class\s*/gm, "export class ").replaceAll(/^\s*export\s*interface\s*/gm, "export interface ").replaceAll(/^\s*export\s*type\s*/gm, "export type ").replaceAll(/^\s*export\s*enum\s*/gm, "export enum ").replaceAll(/^\s*export\s*namespace\s*/gm, "export namespace ")}${ast.module.staticExports.length === 0 ? `
79
- export {};` : ""}
80
- }
81
- `,
82
- directives: ast.module.staticImports.filter((staticImport) => match(staticImport.moduleRequest.value, context.config.resolve.external) || staticImport.moduleRequest.value.startsWith("node:")).map((staticImport) => staticImport.moduleRequest.value.startsWith("node:") ? "node" : Object.keys(context.packageJson.dependencies ?? {}).find((dependency) => staticImport.moduleRequest.value.startsWith(dependency) || staticImport.moduleRequest.value.startsWith(dependency.replace(/^@types\//, ""))) || Object.keys(context.packageJson.devDependencies ?? {}).find((dependency) => staticImport.moduleRequest.value.startsWith(dependency) || staticImport.moduleRequest.value.startsWith(dependency.replace(/^@types\//, ""))) || Object.keys(context.packageJson.peerDependencies ?? {}).find((dependency) => staticImport.moduleRequest.value.startsWith(dependency) || staticImport.moduleRequest.value.startsWith(dependency.replace(/^@types\//, ""))) || staticImport.moduleRequest.value).filter(Boolean).map((dependency) => dependency.replace(/^@types\//, ""))
144
+ content,
145
+ mappings,
146
+ ambient
83
147
  };
84
148
  }
85
149
  /**
@@ -126,24 +190,73 @@ async function emitBuiltinTypes(context, files) {
126
190
  directives: []
127
191
  };
128
192
  }
129
- let result = "";
130
- const directives = [];
193
+ const fileToModuleMap = /* @__PURE__ */ new Map();
194
+ const emittedBuiltinFiles = [];
131
195
  for (const emittedFile of emittedFiles) {
132
- context.trace(`Processing emitted type declaration file: ${emittedFile.filePath}`);
133
196
  const filePath = appendPath(emittedFile.filePath, context.workspaceConfig.workspaceRoot);
134
197
  if (!filePath.endsWith(".map") && findFileName(filePath) !== "tsconfig.tsbuildinfo" && isParentPath(filePath, context.builtinsPath)) {
135
198
  const moduleId = replaceExtension(replacePath(replacePath(filePath, context.builtinsPath), replacePath(context.builtinsPath, context.workspaceConfig.workspaceRoot)), "", { fullExtension: true });
136
199
  if (context.builtins.includes(moduleId)) {
137
- const formatted = await formatTypesModule(context, moduleId, emittedFile.text);
138
- result += formatted.code;
139
- directives.push(...formatted.directives);
200
+ fileToModuleMap.set(filePath, moduleId);
201
+ emittedBuiltinFiles.push({
202
+ filePath,
203
+ text: emittedFile.text
204
+ });
140
205
  }
141
206
  }
142
207
  }
143
- result = await (0, utils_exports.format)(context, context.typesPath, formatTypes(result));
144
- context.debug(`A TypeScript declaration file (size: ${prettyBytes(new Blob(toArray(result)).size)}) emitted for the built-in modules types.`);
208
+ const builtins = await context.getBuiltins();
209
+ const emittedContentMap = /* @__PURE__ */ new Map();
210
+ for (const emittedFile of emittedFiles) {
211
+ const filePath = appendPath(emittedFile.filePath, context.workspaceConfig.workspaceRoot);
212
+ if (!filePath.endsWith(".map") && findFileName(filePath) !== "tsconfig.tsbuildinfo") emittedContentMap.set(filePath, emittedFile.text);
213
+ }
214
+ let code = "";
215
+ const directives = [];
216
+ const ambientModules = /* @__PURE__ */ new Set();
217
+ let isFirst = true;
218
+ for (const entry of emittedBuiltinFiles) {
219
+ context.trace(`Processing emitted type declaration file: ${entry.filePath}`);
220
+ const moduleId = fileToModuleMap.get(entry.filePath);
221
+ const moduleDecl = await extractModuleDeclarations(context, entry.filePath, moduleId, entry.text, fileToModuleMap);
222
+ if (!isFirst) code += "\n\n";
223
+ isFirst = false;
224
+ code += moduleDecl.content;
225
+ for (const dep of moduleDecl.ambient) if (dep.external) {
226
+ const directive = dep.id;
227
+ if (!directives.includes(directive)) directives.push(directive);
228
+ } else if (builtins.some((builtin) => builtin.id === dep.id)) ambientModules.add(builtins.find((builtin) => builtin.id === dep.id).path);
229
+ else if (builtins.some((builtin) => replaceExtension(builtin.path) === replaceExtension(dep.id))) ambientModules.add(dep.id);
230
+ else {
231
+ const resolved = await context.resolve(dep.id, entry.filePath);
232
+ if (resolved) {
233
+ for (const name of [
234
+ resolved.id,
235
+ `${resolved.id}.d.ts`,
236
+ `${resolved.id}.d.mts`,
237
+ `${resolved.id}.d.cts`,
238
+ replaceExtension(resolved.id, ".d.ts"),
239
+ replaceExtension(resolved.id, ".d.mts"),
240
+ replaceExtension(resolved.id, ".d.cts"),
241
+ `${resolved.id}/index.d.ts`
242
+ ]) if (emittedContentMap.has(name)) {
243
+ ambientModules.add(name);
244
+ break;
245
+ }
246
+ }
247
+ }
248
+ }
249
+ for (const ambientFile of ambientModules) {
250
+ const dts = emittedContentMap.get(ambientFile);
251
+ if (dts) {
252
+ const cleaned = dts.replace(/\/\/# sourceMappingURL=.*$/m, "").trim();
253
+ if (cleaned) code += `\n\n${formatTypes(cleaned)}`;
254
+ }
255
+ }
256
+ code = await (0, utils_exports.format)(context, context.typesPath, code);
257
+ context.debug(`A TypeScript declaration file (size: ${prettyBytes(new Blob(toArray(code)).size)}) emitted for the built-in modules types.`);
145
258
  return {
146
- code: result,
259
+ code,
147
260
  directives
148
261
  };
149
262
  }
@@ -323,7 +436,7 @@ var PowerlinesAPI = class PowerlinesAPI {
323
436
  api.context.info(`🔌 The Powerlines Engine v${version} has started`);
324
437
  for (const plugin of api.context.config.plugins.flat(10) ?? []) await api.#addPlugin(plugin);
325
438
  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.");
326
- else api.context.info(`🔌 Loaded ${api.context.plugins.length} ${titleCase(api.context.config.framework)} plugin${api.context.plugins.length > 1 ? "s" : ""}: \n\n${api.context.plugins.map((plugin, index) => ` ${index + 1}. ${(0, utils_exports.colorText)(plugin.name)}`).join("\n")}`);
439
+ else api.context.info(`Loaded ${api.context.plugins.length} ${titleCase(api.context.config.framework)} plugin${api.context.plugins.length > 1 ? "s" : ""}: \n${api.context.plugins.map((plugin, index) => ` ${index + 1}. ${(0, utils_exports.colorText)(plugin.name)}`).join("\n")}`);
327
440
  const pluginConfig = await api.callHook("config", {
328
441
  environment: await api.context.getEnvironment(),
329
442
  sequential: true,
@@ -764,7 +877,7 @@ var PowerlinesAPI = class PowerlinesAPI {
764
877
  if (!plugins) throw new Error(`The plugin configuration ${JSON.stringify(awaited)} is invalid. This configuration must point to a valid Powerlines plugin module.`);
765
878
  if (plugins.length > 0 && !plugins.every(plugin_utils_exports.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.`);
766
879
  const result = [];
767
- for (const plugin of plugins) if ((0, plugin_utils_exports.checkDedupe)(plugin, this.context.plugins)) this.context.trace(`Duplicate ${chalk.bold.cyanBright(plugin.name)} plugin dependency detected - Skipping initialization.`);
880
+ for (const plugin of plugins) if ((0, plugin_utils_exports.isDuplicate)(plugin, this.context.plugins)) this.context.trace(`Duplicate ${chalk.bold.cyanBright(plugin.name)} plugin dependency detected - Skipping initialization.`);
768
881
  else {
769
882
  result.push(plugin);
770
883
  this.context.trace(`Initializing the ${chalk.bold.cyanBright(plugin.name)} plugin...`);
@@ -894,4 +1007,4 @@ ${formatTypes(code)}
894
1007
 
895
1008
  //#endregion
896
1009
  export { name as n, version as r, PowerlinesAPI as t };
897
- //# sourceMappingURL=api-KqyZ6kMY.mjs.map
1010
+ //# sourceMappingURL=api-0aKfs398.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-0aKfs398.mjs","names":["#context","#addPlugin","packageJson.version","#executeEnvironments","defu","#types","#handleBuild","#getEnvironments","#initPlugin","#resolvePlugin","isPlugin","isPluginConfig"],"sources":["../package.json","../src/_internal/helpers/generate-types.ts","../src/_internal/helpers/install.ts","../src/_internal/helpers/install-dependencies.ts","../src/_internal/helpers/resolve-tsconfig.ts","../src/api.ts"],"sourcesContent":["","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { appendPath } from \"@stryke/path/append\";\nimport { findFileName } from \"@stryke/path/file-path-fns\";\nimport { isParentPath } from \"@stryke/path/is-parent-path\";\nimport { replaceExtension, replacePath } from \"@stryke/path/replace\";\nimport { prettyBytes } from \"@stryke/string-format/pretty-bytes\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { DiagnosticCategory, Node, Project } from \"ts-morph\";\nimport { Context } from \"../../types\";\nimport { createProgram } from \"../../typescript/ts-morph\";\nimport { format } from \"../../utils\";\n\ninterface ModuleReference {\n id: string;\n external: boolean;\n}\n\ninterface Mapping {\n source: string;\n line: number;\n column: number;\n}\n\ninterface ModuleDeclaration {\n content: string;\n mappings: Map<string, Mapping>;\n ambient: ModuleReference[];\n}\n\n/**\n * Formats the generated TypeScript types source code.\n *\n * @param code - The generated TypeScript code.\n * @returns The formatted TypeScript code.\n */\nexport function formatTypes(code = \"\"): string {\n return code.replaceAll(\"#private;\", \"\").replace(/__Ω/g, \"\");\n}\n\nasync function extractModuleDeclarations(\n context: Context,\n filePath: string,\n id: string,\n code: string,\n fileToModuleMap: Map<string, string>\n): Promise<ModuleDeclaration> {\n const mappings = new Map<string, Mapping>();\n const ambient: ModuleReference[] = [];\n\n // Parse the emitted .d.ts content using an in-memory ts-morph project\n const project = new Project({ useInMemoryFileSystem: true });\n const sourceFile = project.createSourceFile(\"module.d.ts\", code);\n\n // Collect /// <reference types=\"...\" /> directives as ambient dependencies\n for (const ref of sourceFile.getTypeReferenceDirectives()) {\n ambient.push({ id: ref.getFileName(), external: true });\n }\n\n const importLines: string[] = [];\n const reExportLines: string[] = [];\n const declarationLines: string[] = [];\n\n for (const statement of sourceFile.getStatements()) {\n // --- Import declarations ---\n if (Node.isImportDeclaration(statement)) {\n const moduleSpec = statement.getModuleSpecifierValue();\n const defaultImport = statement.getDefaultImport();\n const namedImports = statement.getNamedImports();\n const namespaceImport = statement.getNamespaceImport();\n\n // Side-effect import (no import clause) → ambient dependency\n if (!defaultImport && namedImports.length === 0 && !namespaceImport) {\n ambient.push({\n id: moduleSpec,\n external: !context.fs.isResolvableId(moduleSpec, filePath)\n });\n continue;\n }\n\n // Resolve the module specifier for the output\n let resolvedSpec = moduleSpec;\n if (context.fs.isResolvableId(moduleSpec, filePath)) {\n const resolved = await context.resolve(moduleSpec, filePath);\n if (resolved) {\n const mapped = fileToModuleMap.get(resolved.id);\n if (mapped) {\n resolvedSpec = mapped;\n } else {\n context.trace(\n `Could not resolve relative import '${moduleSpec}' from '${filePath}' to a builtin module. Keeping as-is.`\n );\n }\n }\n }\n\n // Namespace import: import * as X from '...'\n if (namespaceImport) {\n importLines.push(\n `\\timport * as ${namespaceImport.getText()} from '${resolvedSpec}';`\n );\n } else {\n const specifiers: string[] = [];\n\n if (defaultImport) {\n specifiers.push(`default as ${defaultImport.getText()}`);\n }\n\n for (const named of namedImports) {\n const alias = named.getAliasNode()?.getText();\n specifiers.push(\n alias ? `${named.getName()} as ${alias}` : named.getName()\n );\n }\n\n if (specifiers.length > 0) {\n const typeOnly = statement.isTypeOnly() ? \" type\" : \"\";\n importLines.push(\n `\\timport${typeOnly} { ${specifiers.join(\", \")} } from '${resolvedSpec}';`\n );\n }\n }\n\n continue;\n }\n\n // --- Export declarations ---\n if (Node.isExportDeclaration(statement)) {\n const moduleSpec = statement.getModuleSpecifierValue();\n\n if (moduleSpec) {\n // Resolve the module specifier\n let resolvedSpec = moduleSpec;\n if (context.fs.isResolvableId(moduleSpec, filePath)) {\n const resolved = await context.resolve(moduleSpec, filePath);\n if (resolved) {\n const mapped = fileToModuleMap.get(resolved.id);\n if (mapped) {\n resolvedSpec = mapped;\n } else {\n context.trace(\n `Could not resolve relative import '${moduleSpec}' from '${filePath}' to a builtin module. Keeping as-is.`\n );\n }\n }\n }\n\n // Re-export from another module\n const namedExports = statement.getNamedExports();\n if (namedExports.length > 0) {\n const specifiers = namedExports.map(named => {\n const alias = named.getAliasNode()?.getText();\n\n return alias ? `${named.getName()} as ${alias}` : named.getName();\n });\n const typeOnly = statement.isTypeOnly() ? \" type\" : \"\";\n reExportLines.push(\n `\\texport${typeOnly} { ${specifiers.join(\", \")} } from '${resolvedSpec}';`\n );\n } else {\n // export * from '...'\n reExportLines.push(`\\texport * from '${resolvedSpec}';`);\n }\n } else {\n // Local export { foo, bar } — keep as-is\n declarationLines.push(`\\t${statement.getText()}`);\n }\n\n continue;\n }\n\n // --- Export assignments (export default ...) ---\n if (Node.isExportAssignment(statement)) {\n declarationLines.push(`\\t${statement.getText()}`);\n continue;\n }\n\n // --- All other statements (declarations) ---\n const text = statement.getText();\n if (text.includes(\"//# sourceMappingURL=\")) {\n continue;\n }\n\n declarationLines.push(\n formatTypes(text.replace(/^(export\\s+)?declare\\s+/, \"$1\"))\n .split(\"\\n\")\n .map(line => `\\t${line}`)\n .join(\"\\n\")\n );\n }\n\n const moduleComment = code\n .match(\n new RegExp(\n `\\\\/\\\\*\\\\*(?s:.)*?@module\\\\s+${\n context.config.framework\n }:${id}(?s:.)*?\\\\*\\\\/\\\\s+`\n )\n )\n ?.find(comment => isSetString(comment?.trim()));\n\n let content = `${moduleComment ? `${moduleComment.trim()}\\n` : \"\"}declare module \"${context.config.framework}:${id}\" {`;\n for (const line of importLines) {\n content += `\\n${line}`;\n }\n\n for (const line of reExportLines) {\n content += `\\n${line}`;\n }\n\n for (const line of declarationLines) {\n content += `\\n${line}`;\n }\n\n content += \"\\n}\";\n return { content, mappings, ambient };\n}\n\n/**\n * Emits TypeScript declaration types for the provided files using the given TypeScript configuration.\n *\n * @param context - The context containing options and environment paths.\n * @param files - The list of files to generate types for.\n * @returns A promise that resolves to the generated TypeScript declaration types.\n */\nexport async function emitBuiltinTypes<TContext extends Context>(\n context: TContext,\n files: string[]\n): Promise<{ code: string; directives: string[] }> {\n if (files.length === 0) {\n context.debug(\n \"No files provided for TypeScript types generation. Typescript compilation for built-in modules will be skipped.\"\n );\n return { code: \"\", directives: [] };\n }\n\n context.debug(\n `Running the TypeScript compiler for ${\n files.length\n } generated built-in module files.`\n );\n\n const program = createProgram(context, {\n skipAddingFilesFromTsConfig: true,\n compilerOptions: {\n declaration: true,\n declarationMap: false,\n emitDeclarationOnly: true,\n sourceMap: false,\n outDir: replacePath(\n context.builtinsPath,\n context.workspaceConfig.workspaceRoot\n ),\n composite: false,\n incremental: false,\n tsBuildInfoFile: undefined\n }\n });\n\n program.addSourceFilesAtPaths(files);\n const emitResult = program.emitToMemory({ emitOnlyDtsFiles: true });\n\n const diagnostics = emitResult.getDiagnostics();\n if (diagnostics && diagnostics.length > 0) {\n if (diagnostics.some(d => d.getCategory() === DiagnosticCategory.Error)) {\n throw new Error(\n `The Typescript emit process failed while generating built-in types: \\n ${diagnostics\n .filter(d => d.getCategory() === DiagnosticCategory.Error)\n .map(\n d =>\n `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : \"\"} ${String(\n d.getMessageText()\n )} (at ${d.getStart()}:${d.getLength()})`\n )\n .join(\"\\n\")}`\n );\n } else if (\n diagnostics.some(d => d.getCategory() === DiagnosticCategory.Warning)\n ) {\n context.warn(\n `The Typescript emit process completed with warnings while generating built-in types: \\n ${diagnostics\n .filter(d => d.getCategory() === DiagnosticCategory.Warning)\n .map(\n d =>\n `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : \"\"} ${String(\n d.getMessageText()\n )} (at ${d.getStart()}:${d.getLength()})`\n )\n .join(\"\\n\")}`\n );\n } else {\n context.debug(\n `The Typescript emit process completed with diagnostic messages while generating built-in types: \\n ${diagnostics\n .map(\n d =>\n `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : \"\"} ${String(\n d.getMessageText()\n )} (at ${d.getStart()}:${d.getLength()})`\n )\n .join(\"\\n\")}`\n );\n }\n }\n\n const emittedFiles = emitResult.getFiles();\n context.debug(\n `The TypeScript compiler emitted ${emittedFiles.length} files for built-in types.`\n );\n\n if (emittedFiles.length === 0) {\n context.warn(\n \"The TypeScript compiler did not emit any files for built-in types. This may indicate an issue with the TypeScript configuration or the provided files.\"\n );\n return { code: \"\", directives: [] };\n }\n\n // First pass: build a mapping from emitted file paths to builtin module IDs\n // so that relative imports between builtins can be resolved correctly\n const fileToModuleMap = new Map<string, string>();\n const emittedBuiltinFiles: { filePath: string; text: string }[] = [];\n\n for (const emittedFile of emittedFiles) {\n const filePath = appendPath(\n emittedFile.filePath,\n context.workspaceConfig.workspaceRoot\n );\n\n if (\n !filePath.endsWith(\".map\") &&\n findFileName(filePath) !== \"tsconfig.tsbuildinfo\" &&\n isParentPath(filePath, context.builtinsPath)\n ) {\n const moduleId = replaceExtension(\n replacePath(\n replacePath(filePath, context.builtinsPath),\n replacePath(\n context.builtinsPath,\n context.workspaceConfig.workspaceRoot\n )\n ),\n \"\",\n {\n fullExtension: true\n }\n );\n if (context.builtins.includes(moduleId)) {\n fileToModuleMap.set(filePath, moduleId);\n emittedBuiltinFiles.push({ filePath, text: emittedFile.text });\n }\n }\n }\n\n const builtins = await context.getBuiltins();\n\n // Build a content map of all emitted .d.ts files for ambient module resolution\n const emittedContentMap = new Map<string, string>();\n for (const emittedFile of emittedFiles) {\n const filePath = appendPath(\n emittedFile.filePath,\n context.workspaceConfig.workspaceRoot\n );\n if (\n !filePath.endsWith(\".map\") &&\n findFileName(filePath) !== \"tsconfig.tsbuildinfo\"\n ) {\n emittedContentMap.set(filePath, emittedFile.text);\n }\n }\n\n // Second pass: process each builtin module and generate declare module blocks\n let code = \"\";\n const directives: string[] = [];\n const ambientModules = new Set<string>();\n let isFirst = true;\n\n for (const entry of emittedBuiltinFiles) {\n context.trace(\n `Processing emitted type declaration file: ${entry.filePath}`\n );\n\n const moduleId = fileToModuleMap.get(entry.filePath)!;\n const moduleDecl = await extractModuleDeclarations(\n context,\n entry.filePath,\n moduleId,\n entry.text,\n fileToModuleMap\n );\n\n if (!isFirst) {\n code += \"\\n\\n\";\n }\n isFirst = false;\n code += moduleDecl.content;\n\n for (const dep of moduleDecl.ambient) {\n if (dep.external) {\n const directive = dep.id;\n if (!directives.includes(directive)) {\n directives.push(directive);\n }\n } else if (builtins.some(builtin => builtin.id === dep.id)) {\n ambientModules.add(\n builtins.find(builtin => builtin.id === dep.id)!.path\n );\n } else if (\n builtins.some(\n builtin => replaceExtension(builtin.path) === replaceExtension(dep.id)\n )\n ) {\n ambientModules.add(dep.id);\n } else {\n const resolved = await context.resolve(dep.id, entry.filePath);\n if (resolved) {\n for (const name of [\n resolved.id,\n `${resolved.id}.d.ts`,\n `${resolved.id}.d.mts`,\n `${resolved.id}.d.cts`,\n replaceExtension(resolved.id, \".d.ts\"),\n replaceExtension(resolved.id, \".d.mts\"),\n replaceExtension(resolved.id, \".d.cts\"),\n `${resolved.id}/index.d.ts`\n ]) {\n if (emittedContentMap.has(name)) {\n ambientModules.add(name);\n break;\n }\n }\n }\n }\n }\n }\n\n // Inject non-external ambient module declarations wholesale\n for (const ambientFile of ambientModules) {\n const dts = emittedContentMap.get(ambientFile);\n if (dts) {\n const cleaned = dts.replace(/\\/\\/# sourceMappingURL=.*$/m, \"\").trim();\n if (cleaned) {\n code += `\\n\\n${formatTypes(cleaned)}`;\n }\n }\n }\n\n code = await format(context, context.typesPath, code);\n\n context.debug(\n `A TypeScript declaration file (size: ${prettyBytes(\n new Blob(toArray(code)).size\n )}) emitted for the built-in modules types.`\n );\n\n return { code, directives };\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { install } from \"@stryke/fs/install\";\nimport {\n doesPackageMatch,\n getPackageListing,\n isPackageListed\n} from \"@stryke/fs/package-fns\";\nimport {\n getPackageName,\n getPackageVersion,\n hasPackageVersion\n} from \"@stryke/string-format/package\";\nimport { isNumber } from \"@stryke/type-checks/is-number\";\nimport type { Context } from \"../../types\";\n\n/**\n * Installs a package if it is not already installed.\n *\n * @param context - The resolved options\n * @param packageName - The name of the package to install\n * @param dev - Whether to install the package as a dev dependency\n */\nexport async function installPackage(\n context: Context,\n packageName: string,\n dev = false\n) {\n if (\n !(await isPackageListed(getPackageName(packageName), {\n cwd: context.config.root\n }))\n ) {\n if (context.config.autoInstall) {\n context.warn(\n `The package \"${packageName}\" is not installed. It will be installed automatically.`\n );\n\n const result = await install(packageName, {\n cwd: context.config.root,\n dev\n });\n if (isNumber(result.exitCode) && result.exitCode > 0) {\n context.error(result.stderr);\n throw new Error(\n `An error occurred while installing the package \"${packageName}\"`\n );\n }\n } else {\n context.warn(\n `The package \"${packageName}\" is not installed. Since the \"autoInstall\" option is set to false, it will not be installed automatically.`\n );\n }\n } else if (\n hasPackageVersion(packageName) &&\n !process.env.POWERLINES_SKIP_VERSION_CHECK\n ) {\n const isMatching = await doesPackageMatch(\n getPackageName(packageName),\n getPackageVersion(packageName)!,\n context.config.root\n );\n if (!isMatching) {\n const packageListing = await getPackageListing(\n getPackageName(packageName),\n {\n cwd: context.config.root\n }\n );\n if (\n !packageListing?.version.startsWith(\"catalog:\") &&\n !packageListing?.version.startsWith(\"workspace:\")\n ) {\n context.warn(\n `The package \"${getPackageName(packageName)}\" is installed but does not match the expected version ${getPackageVersion(\n packageName\n )} (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.`\n );\n }\n }\n }\n}\n\n/**\n * Installs a package if it is not already installed.\n *\n * @param context - The resolved options\n * @param packages - The list of packages to install\n */\nexport async function installPackages(\n context: Context,\n packages: Array<{ name: string; dev?: boolean }>\n) {\n return Promise.all(\n packages.map(async pkg => installPackage(context, pkg.name, pkg.dev))\n );\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { getPackageName } from \"@stryke/string-format/package\";\nimport { Context } from \"../../types\";\nimport { installPackage } from \"./install\";\n\n/**\n * Install missing project dependencies.\n *\n * @param context - The build context.\n */\nexport async function installDependencies<TContext extends Context = Context>(\n context: TContext\n): Promise<void> {\n context.debug(`Checking and installing missing project dependencies.`);\n\n context.dependencies ??= {};\n context.devDependencies ??= {};\n\n if (\n Object.keys(context.dependencies).length === 0 &&\n Object.keys(context.devDependencies).length === 0\n ) {\n context.debug(\n `No dependencies or devDependencies to install. Skipping installation step.`\n );\n return;\n }\n\n context.debug(\n `The following packages are required: \\nDependencies: \\n${Object.entries(\n context.dependencies\n )\n .map(([name, version]) => `- ${name}@${String(version)}`)\n .join(\" \\n\")}\\n\\nDevDependencies: \\n${Object.entries(\n context.devDependencies\n )\n .map(([name, version]) => `- ${name}@${String(version)}`)\n .join(\" \\n\")}`\n );\n\n await Promise.all([\n Promise.all(\n Object.entries(context.dependencies).map(async ([name, version]) =>\n installPackage(\n context,\n `${getPackageName(name)}@${String(version)}`,\n false\n )\n )\n ),\n Promise.all(\n Object.entries(context.devDependencies).map(async ([name, version]) =>\n installPackage(\n context,\n `${getPackageName(name)}@${String(version)}`,\n true\n )\n )\n )\n ]);\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type { Diff, ObjectData } from \"@donedeal0/superdiff\";\nimport { getObjectDiff } from \"@donedeal0/superdiff\";\nimport { readJsonFile } from \"@stryke/fs/json\";\nimport { isPackageExists } from \"@stryke/fs/package-fns\";\nimport { StormJSON } from \"@stryke/json/storm-json\";\nimport {\n findFileName,\n findFilePath,\n relativePath\n} from \"@stryke/path/file-path-fns\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { titleCase } from \"@stryke/string-format/title-case\";\nimport { TsConfigJson } from \"@stryke/types/tsconfig\";\nimport chalk from \"chalk\";\nimport type { EnvironmentContext } from \"../../types\";\nimport { ResolvedConfig } from \"../../types\";\nimport {\n getParsedTypeScriptConfig,\n getTsconfigFilePath,\n isIncludeMatchFound\n} from \"../../typescript/tsconfig\";\n\nexport function getTsconfigDtsPath<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>(context: EnvironmentContext<TResolvedConfig>): string {\n const dtsRelativePath = joinPaths(\n relativePath(\n joinPaths(context.workspaceConfig.workspaceRoot, context.config.root),\n findFilePath(context.typesPath)\n ),\n findFileName(context.typesPath)\n );\n\n return dtsRelativePath;\n}\n\nasync function resolveTsconfigChanges<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>(context: EnvironmentContext<TResolvedConfig>): Promise<TsConfigJson> {\n const tsconfig = getParsedTypeScriptConfig(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.tsconfig,\n context.config.tsconfigRaw\n );\n\n const tsconfigFilePath = getTsconfigFilePath(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.tsconfig\n );\n\n const tsconfigJson = await readJsonFile<TsConfigJson>(tsconfigFilePath);\n tsconfigJson.compilerOptions ??= {};\n\n if (context.config.output.dts !== false) {\n const dtsRelativePath = getTsconfigDtsPath(context);\n\n if (\n !tsconfigJson.include?.some(filePattern =>\n isIncludeMatchFound(filePattern, [context.typesPath, dtsRelativePath])\n )\n ) {\n tsconfigJson.include ??= [];\n tsconfigJson.include.push(\n dtsRelativePath.startsWith(\"./\")\n ? dtsRelativePath.slice(2)\n : dtsRelativePath\n );\n }\n }\n\n if (\n !tsconfig.options.lib?.some(lib =>\n [\n \"lib.esnext.d.ts\",\n \"lib.es2021.d.ts\",\n \"lib.es2022.d.ts\",\n \"lib.es2023.d.ts\"\n ].includes(lib.toLowerCase())\n )\n ) {\n tsconfigJson.compilerOptions.lib ??= [];\n tsconfigJson.compilerOptions.lib.push(\"esnext\");\n }\n\n // if (tsconfig.options.module !== ts.ModuleKind.ESNext) {\n // tsconfigJson.compilerOptions.module = \"ESNext\";\n // }\n\n // if (\n // !tsconfig.options.target ||\n // ![\n // ts.ScriptTarget.ESNext,\n // ts.ScriptTarget.ES2024,\n // ts.ScriptTarget.ES2023,\n // ts.ScriptTarget.ES2022,\n // ts.ScriptTarget.ES2021\n // ].includes(tsconfig.options.target)\n // ) {\n // tsconfigJson.compilerOptions.target = \"ESNext\";\n // }\n\n // if (tsconfig.options.moduleResolution !== ts.ModuleResolutionKind.Bundler) {\n // tsconfigJson.compilerOptions.moduleResolution = \"Bundler\";\n // }\n\n // if (tsconfig.options.moduleDetection !== ts.ModuleDetectionKind.Force) {\n // tsconfigJson.compilerOptions.moduleDetection = \"force\";\n // }\n\n // if (tsconfig.options.allowSyntheticDefaultImports !== true) {\n // tsconfigJson.compilerOptions.allowSyntheticDefaultImports = true;\n // }\n\n // if (tsconfig.options.noImplicitOverride !== true) {\n // tsconfigJson.compilerOptions.noImplicitOverride = true;\n // }\n\n // if (tsconfig.options.noUncheckedIndexedAccess !== true) {\n // tsconfigJson.compilerOptions.noUncheckedIndexedAccess = true;\n // }\n\n // if (tsconfig.options.skipLibCheck !== true) {\n // tsconfigJson.compilerOptions.skipLibCheck = true;\n // }\n\n // if (tsconfig.options.resolveJsonModule !== true) {\n // tsconfigJson.compilerOptions.resolveJsonModule = true;\n // }\n\n // if (tsconfig.options.verbatimModuleSyntax !== false) {\n // tsconfigJson.compilerOptions.verbatimModuleSyntax = false;\n // }\n\n // if (tsconfig.options.allowJs !== true) {\n // tsconfigJson.compilerOptions.allowJs = true;\n // }\n\n // if (tsconfig.options.declaration !== true) {\n // tsconfigJson.compilerOptions.declaration = true;\n // }\n\n if (tsconfig.options.esModuleInterop !== true) {\n tsconfigJson.compilerOptions.esModuleInterop = true;\n }\n\n if (tsconfig.options.isolatedModules !== true) {\n tsconfigJson.compilerOptions.isolatedModules = true;\n }\n\n if (context.config.platform === \"node\") {\n if (\n !tsconfig.options.types?.some(\n type =>\n type.toLowerCase() === \"node\" || type.toLowerCase() === \"@types/node\"\n )\n ) {\n tsconfigJson.compilerOptions.types ??= [];\n tsconfigJson.compilerOptions.types.push(\"node\");\n }\n }\n\n return tsconfigJson;\n}\n\nexport async function initializeTsconfig<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TContext extends EnvironmentContext<TResolvedConfig> =\n EnvironmentContext<TResolvedConfig>\n>(context: TContext): Promise<void> {\n context.debug(\n \"Initializing TypeScript configuration (tsconfig.json) for the Powerlines project.\"\n );\n\n if (!isPackageExists(\"typescript\")) {\n throw new Error(\n 'The TypeScript package is not installed. Please install the package using the command: \"npm install typescript --save-dev\"'\n );\n }\n\n const tsconfigFilePath = getTsconfigFilePath(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.tsconfig\n );\n\n context.tsconfig.originalTsconfigJson =\n await readJsonFile<TsConfigJson>(tsconfigFilePath);\n\n context.tsconfig.tsconfigJson =\n await resolveTsconfigChanges<TResolvedConfig>(context);\n\n context.debug(\n \"Writing updated TypeScript configuration (tsconfig.json) file to disk.\"\n );\n\n await context.fs.write(\n tsconfigFilePath,\n StormJSON.stringify(context.tsconfig.tsconfigJson)\n );\n\n context.tsconfig = getParsedTypeScriptConfig(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.tsconfig,\n context.config.tsconfigRaw,\n context.tsconfig.originalTsconfigJson\n );\n}\n\nexport async function resolveTsconfig<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TContext extends EnvironmentContext<TResolvedConfig> =\n EnvironmentContext<TResolvedConfig>\n>(context: TContext): Promise<void> {\n const updateTsconfigJson = await readJsonFile<TsConfigJson>(\n context.tsconfig.tsconfigFilePath\n );\n if (\n updateTsconfigJson?.compilerOptions?.types &&\n Array.isArray(updateTsconfigJson.compilerOptions.types) &&\n !updateTsconfigJson.compilerOptions.types.length\n ) {\n // If the types array is empty, we can safely remove it\n delete updateTsconfigJson.compilerOptions.types;\n }\n\n const result = getObjectDiff(\n context.tsconfig.originalTsconfigJson as NonNullable<ObjectData>,\n updateTsconfigJson as ObjectData,\n {\n ignoreArrayOrder: true,\n showOnly: {\n statuses: [\"added\", \"deleted\", \"updated\"],\n granularity: \"deep\"\n }\n }\n );\n\n const changes = [] as {\n field: string;\n status: \"added\" | \"deleted\" | \"updated\";\n previous: string;\n current: string;\n }[];\n const getChanges = (difference: Diff, property?: string) => {\n if (\n difference.status === \"added\" ||\n difference.status === \"deleted\" ||\n difference.status === \"updated\"\n ) {\n if (difference.diff) {\n for (const diff of difference.diff) {\n getChanges(\n diff,\n property\n ? `${property}.${difference.property}`\n : difference.property\n );\n }\n } else {\n changes.push({\n field: property\n ? `${property}.${difference.property}`\n : difference.property,\n status: difference.status,\n previous:\n difference.status === \"added\"\n ? \"---\"\n : StormJSON.stringify(difference.previousValue),\n current:\n difference.status === \"deleted\"\n ? \"---\"\n : StormJSON.stringify(difference.currentValue)\n });\n }\n }\n };\n\n for (const diff of result.diff) {\n getChanges(diff);\n }\n\n if (changes.length > 0) {\n context.warn(\n `Updating the following configuration values in \"${context.tsconfig.tsconfigFilePath}\" file:\n\n ${changes\n .map(\n (change, i) => `${chalk.bold.whiteBright(\n `${i + 1}. ${titleCase(change.status)} the ${change.field} field: `\n )}\n ${chalk.red(` - Previous: ${change.previous} `)}\n ${chalk.green(` - Updated: ${change.current} `)}\n `\n )\n .join(\"\\n\")}\n `\n );\n }\n\n await context.fs.write(\n context.tsconfig.tsconfigFilePath,\n StormJSON.stringify(updateTsconfigJson)\n );\n\n context.tsconfig = getParsedTypeScriptConfig(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.tsconfig\n );\n if (!context.tsconfig) {\n throw new Error(\"Failed to parse the TypeScript configuration file.\");\n }\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { Unstable_APIContext } from \"@powerlines/core/types/_internal\";\nimport { formatLogMessage } from \"@storm-software/config-tools/logger/console\";\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { copyFiles } from \"@stryke/fs/copy-file\";\nimport { existsSync } from \"@stryke/fs/exists\";\nimport { createDirectory, removeDirectory } from \"@stryke/fs/helpers\";\nimport { install } from \"@stryke/fs/install\";\nimport { listFiles } from \"@stryke/fs/list-files\";\nimport { isPackageExists } from \"@stryke/fs/package-fns\";\nimport { resolvePackage } from \"@stryke/fs/resolve\";\nimport { getUnique } from \"@stryke/helpers/get-unique\";\nimport { omit } from \"@stryke/helpers/omit\";\nimport { appendPath } from \"@stryke/path/append\";\nimport { relativePath } from \"@stryke/path/file-path-fns\";\nimport { isParentPath } from \"@stryke/path/is-parent-path\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { replacePath } from \"@stryke/path/replace\";\nimport { titleCase } from \"@stryke/string-format/title-case\";\nimport { isError } from \"@stryke/type-checks/is-error\";\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isNumber } from \"@stryke/type-checks/is-number\";\nimport { isObject } from \"@stryke/type-checks/is-object\";\nimport { isPromiseLike } from \"@stryke/type-checks/is-promise\";\nimport { isSet } from \"@stryke/type-checks/is-set\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { MaybePromise, PartialKeys, RequiredKeys } from \"@stryke/types/base\";\nimport chalk from \"chalk\";\nimport defu from \"defu\";\nimport Handlebars from \"handlebars\";\nimport packageJson from \"../package.json\" assert { type: \"json\" };\nimport {\n emitBuiltinTypes,\n formatTypes\n} from \"./_internal/helpers/generate-types\";\nimport { callHook, mergeConfigs } from \"./_internal/helpers/hooks\";\nimport { installDependencies } from \"./_internal/helpers/install-dependencies\";\nimport { writeMetaFile } from \"./_internal/helpers/meta\";\nimport {\n initializeTsconfig,\n resolveTsconfig\n} from \"./_internal/helpers/resolve-tsconfig\";\nimport { PowerlinesAPIContext } from \"./context/api-context\";\nimport {\n findInvalidPluginConfig,\n isDuplicate,\n isPlugin,\n isPluginConfig,\n isPluginConfigObject,\n isPluginConfigTuple\n} from \"./plugin-utils\";\nimport type {\n API,\n APIContext,\n BuildInlineConfig,\n CallHookOptions,\n CleanInlineConfig,\n DeployInlineConfig,\n DocsInlineConfig,\n EnvironmentContext,\n EnvironmentResolvedConfig,\n InferHookParameters,\n InitialUserConfig,\n LintInlineConfig,\n NewInlineConfig,\n Plugin,\n PluginConfig,\n PluginConfigObject,\n PluginConfigTuple,\n PluginContext,\n PluginFactory,\n PrepareInlineConfig,\n ResolvedConfig,\n TypesInlineConfig,\n TypesResult\n} from \"./types\";\nimport {\n colorText,\n format,\n formatFolder,\n getTypescriptFileHeader\n} from \"./utils\";\n\n/**\n * The Powerlines API class\n *\n * @remarks\n * This class is responsible for managing the Powerlines project lifecycle, including initialization, building, and finalization.\n *\n * @public\n */\nexport class PowerlinesAPI<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>\n implements API<TResolvedConfig>, AsyncDisposable\n{\n /**\n * The Powerlines context\n */\n #context: Unstable_APIContext<TResolvedConfig>;\n\n /**\n * The Powerlines context\n */\n public get context(): APIContext<TResolvedConfig> {\n return this.#context;\n }\n\n /**\n * Create a new Powerlines API instance\n *\n * @param context - The Powerlines context\n */\n private constructor(context: APIContext<TResolvedConfig>) {\n this.#context = context as Unstable_APIContext<TResolvedConfig>;\n }\n\n /**\n * Initialize a Powerlines API instance\n *\n * @param workspaceRoot - The directory of the underlying workspace the Powerlines project exists in\n * @param config - An object containing the configuration required to run Powerlines tasks.\n * @returns A new instance of the Powerlines API\n */\n public static async from<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n >(\n workspaceRoot: string,\n config: InitialUserConfig<TResolvedConfig[\"userConfig\"]>\n ): Promise<PowerlinesAPI<TResolvedConfig>> {\n const api = new PowerlinesAPI<TResolvedConfig>(\n await PowerlinesAPIContext.from(workspaceRoot, config)\n );\n api.#context.$$internal = {\n api,\n addPlugin: api.#addPlugin.bind(api)\n };\n\n api.context.info(\n `🔌 The Powerlines Engine v${packageJson.version} has started`\n );\n\n for (const plugin of api.context.config.plugins.flat(10) ?? []) {\n await api.#addPlugin(plugin);\n }\n\n if (api.context.plugins.length === 0) {\n api.context.warn(\n \"No Powerlines plugins were specified in the options. Please ensure this is correct, as it is generally not recommended.\"\n );\n } else {\n api.context.info(\n `Loaded ${api.context.plugins.length} ${titleCase(\n api.context.config.framework\n )} plugin${api.context.plugins.length > 1 ? \"s\" : \"\"}: \\n${api.context.plugins\n .map((plugin, index) => ` ${index + 1}. ${colorText(plugin.name)}`)\n .join(\"\\n\")}`\n );\n }\n\n const pluginConfig = await api.callHook(\"config\", {\n environment: await api.context.getEnvironment(),\n sequential: true,\n result: \"merge\",\n merge: mergeConfigs\n });\n await api.context.withUserConfig(\n pluginConfig as TResolvedConfig[\"userConfig\"],\n { isHighPriority: false }\n );\n\n return api;\n }\n\n /**\n * Generate the Powerlines typescript declaration file\n *\n * @remarks\n * This method will only generate the typescript declaration file for the Powerlines project. It is generally recommended to run the full `prepare` command, which will run this method as part of its process.\n *\n * @param inlineConfig - The inline configuration for the types command\n */\n public async types(\n inlineConfig: PartialKeys<TypesInlineConfig, \"command\"> = {\n command: \"types\"\n }\n ) {\n this.context.info(\n \" 🏗️ Generating typescript declarations for the Powerlines project\"\n );\n\n this.context.debug(\n \" Aggregating configuration options for the Powerlines project\"\n );\n\n inlineConfig.command ??= \"types\";\n\n await this.context.withInlineConfig(\n inlineConfig as RequiredKeys<TypesInlineConfig, \"command\">\n );\n await this.#executeEnvironments(async context => {\n context.debug(\n `Initializing the processing options for the Powerlines project.`\n );\n\n await this.callHook(\"configResolved\", {\n environment: context,\n order: \"pre\"\n });\n\n await initializeTsconfig<TResolvedConfig>(context);\n\n await this.callHook(\"configResolved\", {\n environment: context,\n order: \"normal\"\n });\n\n if (context.entry.length > 0) {\n context.debug(\n `The configuration provided ${\n isObject(context.config.input)\n ? Object.keys(context.config.input).length\n : toArray(context.config.input).length\n } entry point(s), Powerlines has found ${\n context.entry.length\n } entry files(s) for the ${context.config.title} project${\n context.entry.length > 0 && context.entry.length < 10\n ? `: \\n${context.entry\n .map(\n entry =>\n `- ${entry.file}${\n entry.output ? ` -> ${entry.output}` : \"\"\n }`\n )\n .join(\" \\n\")}`\n : \"\"\n }`\n );\n } else {\n context.warn(\n `No entry files were found for the ${\n context.config.title\n } project. Please ensure this is correct. Powerlines plugins generally require at least one entry point to function properly.`\n );\n }\n\n await resolveTsconfig<TResolvedConfig>(context);\n await installDependencies(context);\n\n await this.callHook(\"configResolved\", {\n environment: context,\n order: \"post\"\n });\n\n context.trace(\n `Powerlines configuration has been resolved: \\n\\n${formatLogMessage({\n ...context.config,\n userConfig: isSetObject(context.config.userConfig)\n ? omit(context.config.userConfig, [\"plugins\"])\n : undefined,\n inlineConfig: isSetObject(context.config.inlineConfig)\n ? omit(context.config.inlineConfig, [\"plugins\"])\n : undefined,\n plugins: context.plugins.map(plugin => plugin.plugin.name)\n })}`\n );\n\n if (!context.fs.existsSync(context.cachePath)) {\n await createDirectory(context.cachePath);\n }\n\n if (!context.fs.existsSync(context.dataPath)) {\n await createDirectory(context.dataPath);\n }\n\n if (\n context.config.skipCache === true ||\n context.persistedMeta?.checksum !== context.meta.checksum\n ) {\n context.debug(\n `Using previously prepared files as the meta checksum has not changed.`\n );\n } else {\n context.info(\n `Running \\`prepare\\` command as the meta checksum has changed since the last run.`\n );\n\n await this.prepare(\n defu(\n {\n output: {\n types: false\n }\n },\n inlineConfig\n ) as PrepareInlineConfig<TResolvedConfig>\n );\n }\n\n await this.#types(context);\n\n this.context.debug(\"Formatting files generated during the types step.\");\n\n await format(\n context,\n context.typesPath,\n (await context.fs.read(context.typesPath)) ?? \"\"\n );\n\n await writeMetaFile(context);\n context.persistedMeta = context.meta;\n });\n\n this.context.debug(\n \"✔ Powerlines types generation has completed successfully\"\n );\n }\n\n /**\n * Prepare the Powerlines API\n *\n * @remarks\n * This method will prepare the Powerlines API for use, initializing any necessary resources.\n *\n * @param inlineConfig - The inline configuration for the prepare command\n */\n public async prepare(\n inlineConfig:\n | PartialKeys<PrepareInlineConfig, \"command\">\n | PartialKeys<TypesInlineConfig, \"command\">\n | PartialKeys<NewInlineConfig, \"command\">\n | PartialKeys<CleanInlineConfig, \"command\">\n | PartialKeys<BuildInlineConfig, \"command\">\n | PartialKeys<LintInlineConfig, \"command\">\n | PartialKeys<DocsInlineConfig, \"command\">\n | PartialKeys<DeployInlineConfig, \"command\"> = { command: \"prepare\" }\n ) {\n this.context.info(\" 🏗️ Preparing the Powerlines project\");\n\n this.context.debug(\n \" Aggregating configuration options for the Powerlines project\"\n );\n\n inlineConfig.command ??= \"prepare\";\n\n await this.context.withInlineConfig(\n inlineConfig as RequiredKeys<PrepareInlineConfig, \"command\">\n );\n await this.#executeEnvironments(async context => {\n context.debug(\n `Initializing the processing options for the Powerlines project.`\n );\n\n await this.callHook(\"configResolved\", {\n environment: context,\n order: \"pre\"\n });\n\n await initializeTsconfig<TResolvedConfig>(context);\n\n await this.callHook(\"configResolved\", {\n environment: context,\n order: \"normal\"\n });\n\n if (context.entry.length > 0) {\n context.debug(\n `The configuration provided ${\n isObject(context.config.input)\n ? Object.keys(context.config.input).length\n : toArray(context.config.input).length\n } entry point(s), Powerlines has found ${\n context.entry.length\n } entry files(s) for the ${context.config.title} project${\n context.entry.length > 0 && context.entry.length < 10\n ? `: \\n${context.entry\n .map(\n entry =>\n `- ${entry.file}${\n entry.output ? ` -> ${entry.output}` : \"\"\n }`\n )\n .join(\" \\n\")}`\n : \"\"\n }`\n );\n } else {\n context.warn(\n `No entry files were found for the ${\n context.config.title\n } project. Please ensure this is correct. Powerlines plugins generally require at least one entry point to function properly.`\n );\n }\n\n await resolveTsconfig<TResolvedConfig>(context);\n await installDependencies(context);\n\n await this.callHook(\"configResolved\", {\n environment: context,\n order: \"post\"\n });\n\n context.trace(\n `Powerlines configuration has been resolved: \\n\\n${formatLogMessage({\n ...context.config,\n userConfig: isSetObject(context.config.userConfig)\n ? omit(context.config.userConfig, [\"plugins\"])\n : undefined,\n inlineConfig: isSetObject(context.config.inlineConfig)\n ? omit(context.config.inlineConfig, [\"plugins\"])\n : undefined,\n plugins: context.plugins.map(plugin => plugin.plugin.name)\n })}`\n );\n\n if (!context.fs.existsSync(context.cachePath)) {\n await createDirectory(context.cachePath);\n }\n\n if (!context.fs.existsSync(context.dataPath)) {\n await createDirectory(context.dataPath);\n }\n\n await this.callHook(\"prepare\", {\n environment: context,\n order: \"pre\"\n });\n await this.callHook(\"prepare\", {\n environment: context,\n order: \"normal\"\n });\n\n await this.callHook(\"prepare\", {\n environment: context,\n order: \"post\"\n });\n\n if (context.config.output.types !== false) {\n await this.#types(context);\n }\n\n this.context.debug(\"Formatting files generated during the prepare step.\");\n\n await Promise.all([\n formatFolder(context, context.builtinsPath),\n formatFolder(context, context.entryPath)\n ]);\n\n await writeMetaFile(context);\n context.persistedMeta = context.meta;\n });\n\n this.context.debug(\"✔ Powerlines preparation has completed successfully\");\n }\n\n /**\n * Create a new Powerlines project\n *\n * @remarks\n * This method will create a new Powerlines project in the current directory.\n *\n * @param inlineConfig - The inline configuration for the new command\n * @returns A promise that resolves when the project has been created\n */\n public async new(inlineConfig: PartialKeys<NewInlineConfig, \"command\">) {\n this.context.info(\" 🆕 Creating a new Powerlines project\");\n\n inlineConfig.command ??= \"new\";\n\n await this.prepare(\n inlineConfig as RequiredKeys<NewInlineConfig, \"command\">\n );\n await this.#executeEnvironments(async context => {\n context.debug(\n \"Initializing the processing options for the Powerlines project.\"\n );\n\n await this.callHook(\"new\", {\n environment: context,\n order: \"pre\"\n });\n\n const files = await listFiles(\n joinPaths(context.powerlinesPath, \"files/common/**/*.hbs\")\n );\n for (const file of files) {\n context.trace(`Adding template file to project: ${file}`);\n\n const template = Handlebars.compile(file);\n await context.fs.write(\n joinPaths(context.config.root, file.replace(\".hbs\", \"\")),\n template(context)\n );\n }\n\n await this.callHook(\"new\", {\n environment: context,\n order: \"normal\"\n });\n\n if (context.config.projectType === \"application\") {\n const files = await listFiles(\n joinPaths(context.powerlinesPath, \"files/application/**/*.hbs\")\n );\n for (const file of files) {\n context.trace(`Adding application template file: ${file}`);\n\n const template = Handlebars.compile(file);\n await context.fs.write(\n joinPaths(context.config.root, file.replace(\".hbs\", \"\")),\n template(context)\n );\n }\n } else {\n const files = await listFiles(\n joinPaths(context.powerlinesPath, \"files/library/**/*.hbs\")\n );\n for (const file of files) {\n context.trace(`Adding library template file: ${file}`);\n\n const template = Handlebars.compile(file);\n await context.fs.write(\n joinPaths(context.config.root, file.replace(\".hbs\", \"\")),\n template(context)\n );\n }\n }\n\n await this.callHook(\"new\", {\n environment: context,\n order: \"post\"\n });\n });\n\n this.context.debug(\"✔ Powerlines new command completed successfully\");\n }\n\n /**\n * Clean any previously prepared artifacts\n *\n * @remarks\n * This method will remove the previous Powerlines artifacts from the project.\n *\n * @param inlineConfig - The inline configuration for the clean command\n * @returns A promise that resolves when the clean command has completed\n */\n public async clean(\n inlineConfig:\n | PartialKeys<CleanInlineConfig, \"command\">\n | PartialKeys<PrepareInlineConfig, \"command\"> = {\n command: \"clean\"\n }\n ) {\n this.context.info(\" 🧹 Cleaning the previous Powerlines artifacts\");\n\n inlineConfig.command ??= \"clean\";\n\n await this.prepare(\n inlineConfig as RequiredKeys<CleanInlineConfig, \"command\">\n );\n await this.#executeEnvironments(async context => {\n context.debug(\"Cleaning the project's dist and artifacts directories.\");\n\n await context.fs.remove(\n joinPaths(\n context.workspaceConfig.workspaceRoot,\n context.config.output.path\n )\n );\n await context.fs.remove(\n joinPaths(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.output.artifactsPath\n )\n );\n\n await this.callHook(\"clean\", {\n environment: context,\n sequential: false\n });\n });\n\n this.context.debug(\"✔ Powerlines cleaning completed successfully\");\n }\n\n /**\n * Lint the project\n *\n * @param inlineConfig - The inline configuration for the lint command\n * @returns A promise that resolves when the lint command has completed\n */\n public async lint(\n inlineConfig:\n | PartialKeys<LintInlineConfig, \"command\">\n | PartialKeys<BuildInlineConfig, \"command\"> = { command: \"lint\" }\n ) {\n this.context.info(\" 📝 Linting the Powerlines project\");\n\n inlineConfig.command ??= \"lint\";\n await this.prepare(\n inlineConfig as RequiredKeys<LintInlineConfig, \"command\">\n );\n await this.#executeEnvironments(async context => {\n await this.callHook(\"lint\", {\n environment: context,\n sequential: false\n });\n });\n\n this.context.debug(\"✔ Powerlines linting completed successfully\");\n }\n\n /**\n * Build the project\n *\n * @remarks\n * This method will build the Powerlines project, generating the necessary artifacts.\n *\n * @param inlineConfig - The inline configuration for the build command\n * @returns A promise that resolves when the build command has completed\n */\n public async build(\n inlineConfig: PartialKeys<BuildInlineConfig, \"command\"> = {\n command: \"build\"\n }\n ) {\n this.context.info(\" 📦 Building the Powerlines project\");\n\n await this.context.generateChecksum();\n if (\n this.context.meta.checksum !== this.context.persistedMeta?.checksum ||\n this.context.config.skipCache\n ) {\n this.context.info(\n !this.context.persistedMeta?.checksum\n ? \"No previous build cache found. Preparing the project for the initial build.\"\n : this.context.meta.checksum !== this.context.persistedMeta.checksum\n ? \"The project has been modified since the last time `prepare` was ran. Re-preparing the project.\"\n : \"The project is configured to skip cache. Re-preparing the project.\"\n );\n\n inlineConfig.command ??= \"build\";\n\n await this.prepare(\n inlineConfig as RequiredKeys<BuildInlineConfig, \"command\">\n );\n }\n\n if (this.context.config.singleBuild) {\n await this.#handleBuild(await this.#context.toEnvironment());\n } else {\n await this.#executeEnvironments(async context => {\n await this.#handleBuild(context);\n });\n }\n\n this.context.debug(\"✔ Powerlines build completed successfully\");\n }\n\n /**\n * Prepare the documentation for the project\n *\n * @param inlineConfig - The inline configuration for the docs command\n * @returns A promise that resolves when the documentation generation has completed\n */\n public async docs(inlineConfig: DocsInlineConfig = { command: \"docs\" }) {\n this.context.info(\n \" 📓 Generating documentation for the Powerlines project\"\n );\n\n inlineConfig.command ??= \"docs\";\n await this.prepare(\n inlineConfig as RequiredKeys<DocsInlineConfig, \"command\">\n );\n await this.#executeEnvironments(async context => {\n context.debug(\n \"Writing documentation for the Powerlines project artifacts.\"\n );\n\n inlineConfig.command ??= \"docs\";\n\n await this.prepare(\n inlineConfig as RequiredKeys<DocsInlineConfig, \"command\">\n );\n await this.#executeEnvironments(async context => {\n await this.callHook(\"docs\", {\n environment: context\n });\n });\n });\n\n this.context.debug(\n \"✔ Powerlines documentation generation completed successfully\"\n );\n }\n\n /**\n * Deploy the project source code\n *\n * @remarks\n * This method will prepare and build the Powerlines project, generating the necessary artifacts for the deployment.\n *\n * @param inlineConfig - The inline configuration for the deploy command\n */\n public async deploy(\n inlineConfig: PartialKeys<DeployInlineConfig, \"command\"> = {\n command: \"deploy\"\n }\n ) {\n this.context.info(\" 🚀 Deploying the Powerlines project\");\n\n inlineConfig.command ??= \"deploy\";\n\n await this.prepare(\n inlineConfig as RequiredKeys<DeployInlineConfig, \"command\">\n );\n await this.#executeEnvironments(async context => {\n await this.callHook(\"deploy\", { environment: context });\n });\n\n this.context.debug(\"✔ Powerlines deploy completed successfully\");\n }\n\n /**\n * Finalization process\n *\n * @remarks\n * This step includes any final processes or clean up required by Powerlines. It will be run after each Powerlines command.\n *\n * @returns A promise that resolves when the finalization process has completed\n */\n public async finalize() {\n this.context.info(\" 🏁 Powerlines finalization processes started\");\n\n await this.#executeEnvironments(async context => {\n await this.callHook(\"finalize\", { environment: context });\n await context.fs.dispose();\n\n if (\n existsSync(context.cachePath) &&\n !(await listFiles(joinPaths(context.cachePath, \"**/*\")))?.length\n ) {\n await removeDirectory(context.cachePath);\n }\n });\n\n this.context.debug(\"✔ Powerlines finalization completed successfully\");\n }\n\n /**\n * Invokes the configured plugin hooks\n *\n * @remarks\n * By default, it will call the `\"pre\"`, `\"normal\"`, and `\"post\"` ordered hooks in sequence\n *\n * @param hook - The hook to call\n * @param options - The options to provide to the hook\n * @param args - The arguments to pass to the hook\n * @returns The result of the hook call\n */\n public async callHook<TKey extends string>(\n hook: TKey,\n options: CallHookOptions & {\n environment?: string | EnvironmentContext<TResolvedConfig>;\n },\n ...args: InferHookParameters<PluginContext<TResolvedConfig>, TKey>\n ) {\n return callHook<TResolvedConfig, TKey>(\n isSetObject(options?.environment)\n ? options.environment\n : await this.#context.getEnvironment(options?.environment),\n hook,\n { sequential: true, ...options },\n ...args\n );\n }\n\n /**\n * Dispose of the Powerlines API instance\n *\n * @remarks\n * This method will finalize the Powerlines API instance, cleaning up any resources used.\n */\n public async [Symbol.asyncDispose]() {\n await this.finalize();\n }\n\n async #handleBuild(context: EnvironmentContext<TResolvedConfig>) {\n await this.callHook(\"build\", {\n environment: context,\n order: \"pre\"\n });\n\n context.debug(\n \"Formatting the generated entry files before the build process starts.\"\n );\n await formatFolder(context, context.entryPath);\n\n await this.callHook(\"build\", {\n environment: context,\n order: \"normal\"\n });\n\n if (context.config.output.copy) {\n context.debug(\"Copying project's files from build output directory.\");\n\n const destinationPath = isParentPath(\n appendPath(\n context.config.output.path,\n context.workspaceConfig.workspaceRoot\n ),\n appendPath(context.config.root, context.workspaceConfig.workspaceRoot)\n )\n ? joinPaths(\n context.config.output.copy.path,\n relativePath(\n appendPath(\n context.config.root,\n context.workspaceConfig.workspaceRoot\n ),\n appendPath(\n context.config.output.path,\n context.workspaceConfig.workspaceRoot\n )\n )\n )\n : joinPaths(context.config.output.copy.path, \"dist\");\n const sourcePath = appendPath(\n context.config.output.path,\n context.workspaceConfig.workspaceRoot\n );\n\n if (existsSync(sourcePath) && sourcePath !== destinationPath) {\n context.debug(\n `Copying files from project's build output directory (${\n context.config.output.path\n }) to the project's copy/publish directory (${destinationPath}).`\n );\n\n await copyFiles(sourcePath, destinationPath);\n } else {\n context.warn(\n `The source path for the copy operation ${\n !existsSync(sourcePath)\n ? \"does not exist\"\n : \"is the same as the destination path\"\n }. Source: ${sourcePath}, Destination: ${\n destinationPath\n }. Skipping copying of build output files.`\n );\n }\n\n if (\n context.config.output.copy.assets &&\n Array.isArray(context.config.output.copy.assets)\n ) {\n await Promise.all(\n context.config.output.copy.assets.map(async asset => {\n context.trace(\n `Copying asset(s): ${chalk.redBright(\n context.workspaceConfig.workspaceRoot === asset.input\n ? asset.glob\n : appendPath(\n asset.glob,\n replacePath(\n asset.input,\n context.workspaceConfig.workspaceRoot\n )\n )\n )} -> ${chalk.greenBright(\n appendPath(\n asset.glob,\n replacePath(\n asset.output,\n context.workspaceConfig.workspaceRoot\n )\n )\n )} ${\n Array.isArray(asset.ignore) && asset.ignore.length > 0\n ? ` (ignoring: ${asset.ignore\n .map(i => chalk.yellowBright(i))\n .join(\", \")})`\n : \"\"\n }`\n );\n\n await context.fs.copy(asset, asset.output);\n })\n );\n }\n } else {\n context.debug(\n \"No copy configuration found for the project output. Skipping the copying of build output files.\"\n );\n }\n\n await this.callHook(\"build\", {\n environment: context,\n order: \"post\"\n });\n }\n\n /**\n * Get the configured environments\n *\n * @returns The configured environments\n */\n async #getEnvironments() {\n if (\n !this.context.config.environments ||\n Object.keys(this.context.config.environments).length <= 1\n ) {\n this.context.debug(\n \"No environments are configured for this Powerlines project. Using the default environment.\"\n );\n\n return [await this.context.getEnvironment()];\n }\n\n this.context.debug(\n `Found ${Object.keys(this.context.config.environments).length} configured environment(s) for this Powerlines project.`\n );\n\n return (\n await Promise.all(\n Object.entries(this.context.config.environments).map(\n async ([name, config]) => {\n const environment = await this.context.getEnvironmentSafe(name);\n if (!environment) {\n const resolvedEnvironment = await this.callHook(\n \"configEnvironment\",\n {\n environment: name\n },\n name,\n config\n );\n\n if (resolvedEnvironment) {\n this.context.environments[name] = await this.context.in(\n resolvedEnvironment as EnvironmentResolvedConfig\n );\n }\n }\n\n return this.context.environments[name];\n }\n )\n )\n ).filter(context => isSet(context));\n }\n\n /**\n * Execute a handler function for each environment\n *\n * @param handle - The handler function to execute for each environment\n */\n async #executeEnvironments(\n handle: (context: EnvironmentContext<TResolvedConfig>) => MaybePromise<void>\n ) {\n await Promise.all(\n (await this.#getEnvironments()).map(async context => {\n return Promise.resolve(handle(context));\n })\n );\n }\n\n /**\n * Add a Powerlines plugin used in the build process\n *\n * @param config - The import path of the plugin to add\n */\n async #addPlugin(config: PluginConfig<PluginContext<TResolvedConfig>>) {\n if (config) {\n const result = await this.#initPlugin(config);\n if (!result) {\n return;\n }\n\n for (const plugin of result) {\n this.context.debug(\n `Successfully initialized the ${chalk.bold.cyanBright(\n plugin.name\n )} plugin`\n );\n\n await this.context.addPlugin(plugin);\n }\n }\n }\n\n /**\n * Initialize a Powerlines plugin\n *\n * @param config - The configuration for the plugin\n * @returns The initialized plugin instance, or null if the plugin was a duplicate\n * @throws Will throw an error if the plugin cannot be found or is invalid\n */\n async #initPlugin(\n config: PluginConfig<PluginContext<TResolvedConfig>>\n ): Promise<Plugin<PluginContext<TResolvedConfig>>[] | null> {\n let awaited = config;\n if (isPromiseLike(config)) {\n awaited = (await Promise.resolve(config as Promise<any>)) as PluginConfig<\n PluginContext<TResolvedConfig>\n >;\n }\n\n if (!isPluginConfig<PluginContext<TResolvedConfig>>(awaited)) {\n const invalid = findInvalidPluginConfig(awaited);\n\n throw new Error(\n `Invalid ${\n invalid && invalid.length > 1 ? \"plugins\" : \"plugin\"\n } specified in the configuration - ${\n invalid && invalid.length > 0\n ? JSON.stringify(awaited)\n : invalid?.join(\"\\n\\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`\n );\n }\n\n let plugins!: Plugin<PluginContext<TResolvedConfig>>[];\n if (isPlugin<PluginContext<TResolvedConfig>>(awaited)) {\n plugins = [awaited];\n } else if (isFunction(awaited)) {\n plugins = toArray(await Promise.resolve(awaited()));\n } else if (isString(awaited)) {\n const resolved = await this.#resolvePlugin(awaited);\n if (isFunction(resolved)) {\n plugins = toArray(await Promise.resolve(resolved()));\n } else {\n plugins = toArray(resolved);\n }\n } else if (\n Array.isArray(awaited) &&\n (awaited as PluginContext<TResolvedConfig>[]).every(\n isPlugin<PluginContext<TResolvedConfig>>\n )\n ) {\n plugins = awaited as Plugin<PluginContext<TResolvedConfig>>[];\n } else if (\n Array.isArray(awaited) &&\n (awaited as PluginConfig<PluginContext<TResolvedConfig>>[]).every(\n isPluginConfig<PluginContext<TResolvedConfig>>\n )\n ) {\n plugins = [];\n for (const pluginConfig of awaited as PluginConfig<\n PluginContext<TResolvedConfig>\n >[]) {\n const initialized = await this.#initPlugin(pluginConfig);\n if (initialized) {\n plugins.push(...initialized);\n }\n }\n } else if (\n isPluginConfigTuple<PluginContext<TResolvedConfig>>(awaited) ||\n isPluginConfigObject<PluginContext<TResolvedConfig>>(awaited)\n ) {\n let pluginConfig!:\n | string\n | PluginFactory<PluginContext<TResolvedConfig>>\n | Plugin<PluginContext<TResolvedConfig>>;\n let pluginOptions: any;\n\n if (isPluginConfigTuple<PluginContext<TResolvedConfig>>(awaited)) {\n pluginConfig = awaited[0] as Plugin<PluginContext<TResolvedConfig>>;\n pluginOptions =\n (awaited as PluginConfigTuple)?.length === 2 ? awaited[1] : undefined;\n } else {\n pluginConfig = (awaited as PluginConfigObject).plugin as Plugin<\n PluginContext<TResolvedConfig>\n >;\n pluginOptions = (awaited as PluginConfigObject).options;\n }\n\n if (isSetString(pluginConfig)) {\n const resolved = await this.#resolvePlugin(pluginConfig);\n if (isFunction(resolved)) {\n plugins = toArray(\n await Promise.resolve(\n pluginOptions ? resolved(pluginOptions) : resolved()\n )\n );\n } else {\n plugins = toArray(resolved);\n }\n } else if (isFunction(pluginConfig)) {\n plugins = toArray(await Promise.resolve(pluginConfig(pluginOptions)));\n } else if (\n Array.isArray(pluginConfig) &&\n pluginConfig.every(isPlugin<PluginContext<TResolvedConfig>>)\n ) {\n plugins = pluginConfig;\n } else if (isPlugin<PluginContext<TResolvedConfig>>(pluginConfig)) {\n plugins = toArray(pluginConfig);\n }\n }\n\n if (!plugins) {\n throw new Error(\n `The plugin configuration ${JSON.stringify(awaited)} is invalid. This configuration must point to a valid Powerlines plugin module.`\n );\n }\n\n if (\n plugins.length > 0 &&\n !plugins.every(isPlugin<PluginContext<TResolvedConfig>>)\n ) {\n throw new Error(\n `The plugin option ${JSON.stringify(plugins)} does not export a valid module. This configuration must point to a valid Powerlines plugin module.`\n );\n }\n\n const result = [] as Plugin<PluginContext<TResolvedConfig>>[];\n for (const plugin of plugins) {\n if (isDuplicate<TResolvedConfig>(plugin, this.context.plugins)) {\n this.context.trace(\n `Duplicate ${chalk.bold.cyanBright(\n plugin.name\n )} plugin dependency detected - Skipping initialization.`\n );\n } else {\n result.push(plugin);\n\n this.context.trace(\n `Initializing the ${chalk.bold.cyanBright(plugin.name)} plugin...`\n );\n }\n }\n\n return result;\n }\n\n async #resolvePlugin<TOptions>(\n pluginPath: string\n ): Promise<\n | Plugin<PluginContext<TResolvedConfig>>\n | Plugin<PluginContext<TResolvedConfig>>[]\n | ((\n options?: TOptions\n ) => MaybePromise<\n | Plugin<PluginContext<TResolvedConfig>>\n | Plugin<PluginContext<TResolvedConfig>>[]\n >)\n > {\n if (\n pluginPath.startsWith(\"@\") &&\n pluginPath.split(\"/\").filter(Boolean).length > 2\n ) {\n const splits = pluginPath.split(\"/\").filter(Boolean);\n pluginPath = `${splits[0]}/${splits[1]}`;\n }\n\n const isInstalled = isPackageExists(pluginPath, {\n paths: [\n this.context.workspaceConfig.workspaceRoot,\n this.context.config.root\n ]\n });\n if (!isInstalled && this.context.config.autoInstall) {\n this.#context.warn(\n `The plugin package \"${\n pluginPath\n }\" is not installed. It will be installed automatically.`\n );\n\n const result = await install(pluginPath, {\n cwd: this.context.config.root\n });\n if (isNumber(result.exitCode) && result.exitCode > 0) {\n this.#context.error(result.stderr);\n\n throw new Error(\n `An error occurred while installing the build plugin package \"${\n pluginPath\n }\" `\n );\n }\n }\n\n try {\n // First check if the package has a \"plugin\" subdirectory - @scope/package/plugin\n const module = await this.context.resolver.plugin.import<{\n plugin?:\n | Plugin<PluginContext<TResolvedConfig>>\n | ((\n options?: TOptions\n ) => MaybePromise<Plugin<PluginContext<TResolvedConfig>>>);\n default?:\n | Plugin<PluginContext<TResolvedConfig>>\n | ((\n options?: TOptions\n ) => MaybePromise<Plugin<PluginContext<TResolvedConfig>>>);\n }>(\n this.context.resolver.plugin.esmResolve(joinPaths(pluginPath, \"plugin\"))\n );\n\n const result = module.plugin ?? module.default;\n if (!result) {\n throw new Error(\n `The plugin package \"${pluginPath}\" does not export a valid module.`\n );\n }\n\n return result;\n } catch (error) {\n try {\n const module = await this.context.resolver.plugin.import<{\n plugin?:\n | Plugin<PluginContext<TResolvedConfig>>\n | ((\n options?: TOptions\n ) => MaybePromise<Plugin<PluginContext<TResolvedConfig>>>);\n default?:\n | Plugin<PluginContext<TResolvedConfig>>\n | ((\n options?: TOptions\n ) => MaybePromise<Plugin<PluginContext<TResolvedConfig>>>);\n }>(this.context.resolver.plugin.esmResolve(pluginPath));\n\n const result = module.plugin ?? module.default;\n if (!result) {\n throw new Error(\n `The plugin package \"${pluginPath}\" does not export a valid module.`\n );\n }\n\n return result;\n } catch {\n if (!isInstalled) {\n throw new Error(\n `The plugin package \"${\n pluginPath\n }\" is not installed. Please install the package using the command: \"npm install ${\n pluginPath\n } --save-dev\"`\n );\n } else {\n throw new Error(\n `An error occurred while importing the build plugin package \"${\n pluginPath\n }\":\n${isError(error) ? error.message : String(error)}\n\nNote: 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\\`.`\n );\n }\n }\n }\n }\n\n /**\n * Generate the Powerlines TypeScript declaration file\n *\n * @remarks\n * This method will generate the TypeScript declaration file for the Powerlines project, including any types provided by plugins.\n *\n * @param context - The environment context to use for generating the TypeScript declaration file\n * @returns A promise that resolves when the TypeScript declaration file has been generated\n */\n async #types(context: EnvironmentContext<TResolvedConfig>) {\n context.debug(\n `Preparing the TypeScript definitions for the Powerlines project.`\n );\n\n if (context.fs.existsSync(context.typesPath)) {\n await context.fs.remove(context.typesPath);\n }\n\n const typescriptPath = await resolvePackage(\"typescript\");\n if (!typescriptPath) {\n throw new Error(\n \"Could not resolve TypeScript package location. Please ensure TypeScript is installed.\"\n );\n }\n\n context.debug(\n \"Running TypeScript compiler for built-in runtime module files.\"\n );\n\n let { code, directives } = await emitBuiltinTypes(\n context,\n (await context.getBuiltins()).reduce<string[]>((ret, builtin) => {\n const formatted = replacePath(\n builtin.path,\n context.workspaceConfig.workspaceRoot\n );\n if (!ret.includes(formatted)) {\n ret.push(formatted);\n }\n\n return ret;\n }, [])\n );\n\n context.debug(\n `Generating TypeScript declaration file ${context.typesPath}.`\n );\n\n const merge = async (\n currentResult: string | TypesResult,\n previousResult: string | TypesResult\n ): Promise<string | TypesResult> => {\n if (\n !isSetString(currentResult) &&\n !isSetObject(currentResult) &&\n !isSetString(previousResult) &&\n !isSetObject(previousResult)\n ) {\n return { code, directives };\n }\n\n const previous = (\n await format(\n context,\n context.typesPath,\n isSetString(previousResult)\n ? previousResult\n : isSetObject(previousResult)\n ? previousResult.code\n : \"\"\n )\n )\n .trim()\n .replace(code, \"\")\n .trim();\n const current = (\n await format(\n context,\n context.typesPath,\n isSetString(currentResult)\n ? currentResult\n : isSetObject(currentResult)\n ? currentResult.code\n : \"\"\n )\n )\n .trim()\n .replace(previous, \"\")\n .trim()\n .replace(code, \"\")\n .trim();\n\n return {\n directives: [\n ...(isSetObject(currentResult) && currentResult.directives\n ? currentResult.directives\n : []),\n ...(isSetObject(previousResult) && previousResult.directives\n ? previousResult.directives\n : [])\n ],\n code: await format(\n context,\n context.typesPath,\n `${\n !previous.includes(getTypescriptFileHeader(context)) &&\n !current.includes(getTypescriptFileHeader(context))\n ? `${code}\\n`\n : \"\"\n }${previous}\\n${current}`.trim()\n )\n };\n };\n const asNextParam = (\n previousResult: string | TypesResult | null | undefined\n ) => (isObject(previousResult) ? previousResult.code : previousResult);\n\n let result = await this.callHook(\n \"types\",\n {\n environment: context,\n sequential: true,\n order: \"pre\",\n result: \"merge\",\n merge,\n asNextParam\n },\n code\n );\n if (result) {\n if (isSetObject(result)) {\n code = result.code;\n if (Array.isArray(result.directives) && result.directives.length > 0) {\n directives = getUnique([...directives, ...result.directives]).filter(\n Boolean\n );\n }\n } else if (isSetString(result)) {\n code = result;\n }\n }\n\n result = await this.callHook(\n \"types\",\n {\n environment: context,\n sequential: true,\n order: \"normal\",\n result: \"merge\",\n merge,\n asNextParam\n },\n code\n );\n if (result) {\n if (isSetObject(result)) {\n code = result.code;\n if (Array.isArray(result.directives) && result.directives.length > 0) {\n directives = getUnique([...directives, ...result.directives]).filter(\n Boolean\n );\n }\n } else if (isSetString(result)) {\n code = result;\n }\n }\n\n result = await this.callHook(\n \"types\",\n {\n environment: context,\n sequential: true,\n order: \"post\",\n result: \"merge\",\n merge,\n asNextParam\n },\n code\n );\n if (result) {\n if (isSetObject(result)) {\n code = result.code;\n if (Array.isArray(result.directives) && result.directives.length > 0) {\n directives = getUnique([...directives, ...result.directives]).filter(\n Boolean\n );\n }\n } else if (isSetString(result)) {\n code = result;\n }\n }\n\n if (isSetString(code?.trim()) || directives.length > 0) {\n await context.fs.write(\n context.typesPath,\n `${\n directives.length > 0\n ? `${directives.map(directive => `/// <reference types=\"${directive}\" />`).join(\"\\n\")}\n\n`\n : \"\"\n }${getTypescriptFileHeader(context, { directive: null, prettierIgnore: false })}\n\n${formatTypes(code)}\n`\n );\n }\n\n // else {\n // const dtsRelativePath = getTsconfigDtsPath(context);\n // if (\n // context.tsconfig.tsconfigJson.include &&\n // isIncludeMatchFound(\n // dtsRelativePath,\n // context.tsconfig.tsconfigJson.include\n // )\n // ) {\n // const normalizedDtsRelativePath = dtsRelativePath.startsWith(\"./\")\n // ? dtsRelativePath.slice(2)\n // : dtsRelativePath;\n // context.tsconfig.tsconfigJson.include =\n // context.tsconfig.tsconfigJson.include.filter(\n // includeValue =>\n // includeValue?.toString() !== normalizedDtsRelativePath\n // );\n\n // await context.fs.write(\n // context.tsconfig.tsconfigFilePath,\n // JSON.stringify(context.tsconfig.tsconfigJson, null, 2)\n // );\n // }\n // }\n\n // // Re-resolve the tsconfig to ensure it is up to date\n // context.tsconfig = getParsedTypeScriptConfig(\n // context.workspaceConfig.workspaceRoot,\n // context.config.root,\n // context.config.tsconfig\n // );\n // if (!context.tsconfig) {\n // throw new Error(\"Failed to parse the TypeScript configuration file.\");\n // }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACqDA,SAAgB,YAAY,OAAO,IAAY;AAC7C,QAAO,KAAK,WAAW,aAAa,GAAG,CAAC,QAAQ,QAAQ,GAAG;;AAG7D,eAAe,0BACb,SACA,UACA,IACA,MACA,iBAC4B;CAC5B,MAAM,2BAAW,IAAI,KAAsB;CAC3C,MAAM,UAA6B,EAAE;CAIrC,MAAM,aADU,IAAI,QAAQ,EAAE,uBAAuB,MAAM,CAAC,CACjC,iBAAiB,eAAe,KAAK;AAGhE,MAAK,MAAM,OAAO,WAAW,4BAA4B,CACvD,SAAQ,KAAK;EAAE,IAAI,IAAI,aAAa;EAAE,UAAU;EAAM,CAAC;CAGzD,MAAM,cAAwB,EAAE;CAChC,MAAM,gBAA0B,EAAE;CAClC,MAAM,mBAA6B,EAAE;AAErC,MAAK,MAAM,aAAa,WAAW,eAAe,EAAE;AAElD,MAAI,KAAK,o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