@powerlines/plugin-webpack 0.5.129 → 0.5.131

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