powerlines 0.42.41 → 0.43.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/dist/{chunk-AIJqnxB6.cjs → _virtual/_rolldown/runtime.cjs} +1 -32
  2. package/dist/{chunk-CtajNgzt.mjs → _virtual/_rolldown/runtime.mjs} +1 -1
  3. package/dist/api.cjs +10 -0
  4. package/dist/api.d.cts +2 -0
  5. package/dist/api.d.mts +2 -0
  6. package/dist/api.mjs +3 -0
  7. package/dist/config.cjs +0 -12
  8. package/dist/config.mjs +1 -10
  9. package/dist/constants.cjs +0 -12
  10. package/dist/constants.mjs +1 -10
  11. package/dist/context.cjs +9 -0
  12. package/dist/context.d.cts +1 -0
  13. package/dist/context.d.mts +1 -0
  14. package/dist/context.mjs +3 -0
  15. package/dist/engine.cjs +30 -0
  16. package/dist/engine.d.cts +24 -0
  17. package/dist/engine.d.cts.map +1 -0
  18. package/dist/engine.d.mts +24 -0
  19. package/dist/engine.d.mts.map +1 -0
  20. package/dist/engine.mjs +29 -0
  21. package/dist/engine.mjs.map +1 -0
  22. package/dist/esbuild.cjs +2 -2
  23. package/dist/esbuild.mjs.map +1 -1
  24. package/dist/farm.cjs +1 -1
  25. package/dist/index.cjs +24 -16
  26. package/dist/index.d.cts +13 -260
  27. package/dist/index.d.cts.map +1 -1
  28. package/dist/index.d.mts +13 -260
  29. package/dist/index.d.mts.map +1 -1
  30. package/dist/index.mjs +14 -8
  31. package/dist/index.mjs.map +1 -1
  32. package/dist/nuxt.cjs +4 -4
  33. package/dist/nuxt.d.cts +1 -1
  34. package/dist/nuxt.d.mts +1 -1
  35. package/dist/nuxt.mjs +1 -1
  36. package/dist/package.cjs +18 -0
  37. package/dist/package.mjs +7 -0
  38. package/dist/package.mjs.map +1 -0
  39. package/dist/plugin-utils.cjs +0 -12
  40. package/dist/plugin-utils.mjs +1 -10
  41. package/dist/rolldown.cjs +2 -2
  42. package/dist/rollup.cjs +2 -2
  43. package/dist/rspack.cjs +2 -2
  44. package/dist/schemas.cjs +9 -0
  45. package/dist/schemas.d.cts +1 -0
  46. package/dist/schemas.d.mts +1 -0
  47. package/dist/schemas.mjs +3 -0
  48. package/dist/storage.cjs +9 -0
  49. package/dist/storage.d.cts +1 -0
  50. package/dist/storage.d.mts +1 -0
  51. package/dist/storage.mjs +3 -0
  52. package/dist/tsdown.cjs +3 -3
  53. package/dist/tsdown.mjs +1 -1
  54. package/dist/tsup.cjs +2 -2
  55. package/dist/types.cjs +0 -0
  56. package/dist/types.d.cts +8 -0
  57. package/dist/types.d.cts.map +1 -0
  58. package/dist/types.d.mts +8 -0
  59. package/dist/types.d.mts.map +1 -0
  60. package/dist/types.mjs +1 -0
  61. package/dist/typescript.cjs +9 -0
  62. package/dist/typescript.d.cts +1 -0
  63. package/dist/typescript.d.mts +1 -0
  64. package/dist/typescript.mjs +3 -0
  65. package/dist/unbuild.cjs +17 -0
  66. package/dist/unbuild.d.cts +2 -0
  67. package/dist/unbuild.d.mts +2 -0
  68. package/dist/unbuild.mjs +3 -0
  69. package/dist/unloader.cjs +1 -1
  70. package/dist/unplugin.cjs +13 -14
  71. package/dist/unplugin.d.cts +3 -2
  72. package/dist/unplugin.d.cts.map +1 -1
  73. package/dist/unplugin.d.mts +3 -2
  74. package/dist/unplugin.d.mts.map +1 -1
  75. package/dist/unplugin.mjs +11 -13
  76. package/dist/unplugin.mjs.map +1 -1
  77. package/dist/utils.cjs +0 -14
  78. package/dist/utils.d.mts +1 -1
  79. package/dist/utils.mjs +2 -15
  80. package/dist/vite.cjs +4 -4
  81. package/dist/vite.mjs +1 -1
  82. package/dist/vite.mjs.map +1 -1
  83. package/dist/webpack.cjs +2 -2
  84. package/package.json +64 -53
  85. package/dist/api-CyXUks49.mjs +0 -1078
  86. package/dist/api-CyXUks49.mjs.map +0 -1
  87. package/dist/api-DITWluqG.cjs +0 -1098
  88. package/dist/api-context-BDFU_IC7.cjs +0 -3066
  89. package/dist/api-context-Cb99qIjE.mjs +0 -2986
  90. package/dist/api-context-Cb99qIjE.mjs.map +0 -1
  91. package/dist/config.mjs.map +0 -1
  92. package/dist/constants.mjs.map +0 -1
  93. package/dist/context/index.cjs +0 -7
  94. package/dist/context/index.d.cts +0 -600
  95. package/dist/context/index.d.cts.map +0 -1
  96. package/dist/context/index.d.mts +0 -600
  97. package/dist/context/index.d.mts.map +0 -1
  98. package/dist/context/index.mjs +0 -3
  99. package/dist/plugin-utils.mjs.map +0 -1
  100. package/dist/storage/index.cjs +0 -9
  101. package/dist/storage/index.d.cts +0 -419
  102. package/dist/storage/index.d.cts.map +0 -1
  103. package/dist/storage/index.d.mts +0 -419
  104. package/dist/storage/index.d.mts.map +0 -1
  105. package/dist/storage/index.mjs +0 -3
  106. package/dist/ts-morph-B85ZbV1Q.mjs +0 -102
  107. package/dist/ts-morph-B85ZbV1Q.mjs.map +0 -1
  108. package/dist/ts-morph-BvE8TMhv.cjs +0 -114
  109. package/dist/tsconfig-BjkktvB9.cjs +0 -198
  110. package/dist/tsconfig-DoV1dUYg.mjs +0 -155
  111. package/dist/tsconfig-DoV1dUYg.mjs.map +0 -1
  112. package/dist/types-9O-s0Fpu.d.mts +0 -4
  113. package/dist/types-9O-s0Fpu.d.mts.map +0 -1
  114. package/dist/types-DerAvFjs.d.cts +0 -4
  115. package/dist/types-DerAvFjs.d.cts.map +0 -1
  116. package/dist/typescript/index.cjs +0 -13
  117. package/dist/typescript/index.d.cts +0 -106
  118. package/dist/typescript/index.d.cts.map +0 -1
  119. package/dist/typescript/index.d.mts +0 -106
  120. package/dist/typescript/index.d.mts.map +0 -1
  121. package/dist/typescript/index.mjs +0 -4
  122. package/dist/utils.mjs.map +0 -1
  123. package/dist/virtual-BNy8T32w.cjs +0 -548
  124. package/dist/virtual-PaZGNIrj.mjs +0 -513
  125. package/dist/virtual-PaZGNIrj.mjs.map +0 -1
@@ -1,3066 +0,0 @@
1
- const require_chunk = require('./chunk-AIJqnxB6.cjs');
2
- const require_utils = require('./utils.cjs');
3
- const require_plugin_utils = require('./plugin-utils.cjs');
4
- const require_constants = require('./constants.cjs');
5
- const require_tsconfig = require('./tsconfig-BjkktvB9.cjs');
6
- const require_config = require('./config.cjs');
7
- const require_virtual = require('./virtual-BNy8T32w.cjs');
8
- let _stryke_fs_get_workspace_root = require("@stryke/fs/get-workspace-root");
9
- let _stryke_convert_to_array = require("@stryke/convert/to-array");
10
- let _stryke_fs_exists = require("@stryke/fs/exists");
11
- let _stryke_fs_resolve = require("@stryke/fs/resolve");
12
- let _stryke_helpers_get_unique = require("@stryke/helpers/get-unique");
13
- let _stryke_helpers_omit = require("@stryke/helpers/omit");
14
- let _stryke_path_append = require("@stryke/path/append");
15
- let _stryke_path_file_path_fns = require("@stryke/path/file-path-fns");
16
- let _stryke_path_is_parent_path = require("@stryke/path/is-parent-path");
17
- let _stryke_path_join_paths = require("@stryke/path/join-paths");
18
- let _stryke_path_replace = require("@stryke/path/replace");
19
- let _stryke_string_format_title_case = require("@stryke/string-format/title-case");
20
- let _stryke_type_checks_is_function = require("@stryke/type-checks/is-function");
21
- let _stryke_type_checks_is_object = require("@stryke/type-checks/is-object");
22
- let _stryke_type_checks_is_set = require("@stryke/type-checks/is-set");
23
- let _stryke_type_checks_is_set_object = require("@stryke/type-checks/is-set-object");
24
- let _stryke_type_checks_is_set_string = require("@stryke/type-checks/is-set-string");
25
- let _stryke_type_checks_is_string = require("@stryke/type-checks/is-string");
26
- let chalk = require("chalk");
27
- chalk = require_chunk.__toESM(chalk, 1);
28
- let defu = require("defu");
29
- defu = require_chunk.__toESM(defu, 1);
30
- let _stryke_string_format_pretty_bytes = require("@stryke/string-format/pretty-bytes");
31
- let _powerlines_core_lib_logger = require("@powerlines/core/lib/logger");
32
- let _stryke_helpers_get_field = require("@stryke/helpers/get-field");
33
- let _stryke_fs_json = require("@stryke/fs/json");
34
- require("@stryke/fs/remove-file");
35
- let _stryke_string_format_kebab_case = require("@stryke/string-format/kebab-case");
36
- let _stryke_json_storm_json = require("@stryke/json/storm-json");
37
- let _storm_software_config_tools_types = require("@storm-software/config-tools/types");
38
- let _stryke_env_get_env_paths = require("@stryke/env/get-env-paths");
39
- let _stryke_hash = require("@stryke/hash");
40
- let _stryke_hash_node = require("@stryke/hash/node");
41
- let _stryke_helpers_deep_clone = require("@stryke/helpers/deep-clone");
42
- let _stryke_http_fetch = require("@stryke/http/fetch");
43
- let _stryke_path_join = require("@stryke/path/join");
44
- let _stryke_type_checks_is_null = require("@stryke/type-checks/is-null");
45
- let _stryke_unique_id_uuid = require("@stryke/unique-id/uuid");
46
- let bundle_require = require("bundle-require");
47
- let compatx = require("compatx");
48
- let date_fns_formatDistanceToNowStrict = require("date-fns/formatDistanceToNowStrict");
49
- let flat_cache = require("flat-cache");
50
- let oxc_parser = require("oxc-parser");
51
- let undici = require("undici");
52
- let jiti = require("jiti");
53
- let _stryke_capnp = require("@stryke/capnp");
54
- _stryke_capnp = require_chunk.__toESM(_stryke_capnp, 1);
55
- let _stryke_fs_buffer = require("@stryke/fs/buffer");
56
- let _stryke_path_correct_path = require("@stryke/path/correct-path");
57
- let _stryke_path_glob_to_regex = require("@stryke/path/glob-to-regex");
58
- let _stryke_path_is_type = require("@stryke/path/is-type");
59
- let _stryke_path_slash = require("@stryke/path/slash");
60
- let _stryke_type_checks_is_regexp = require("@stryke/type-checks/is-regexp");
61
- let node_buffer = require("node:buffer");
62
- let node_url = require("node:url");
63
-
64
- //#region src/_internal/helpers/hooks.ts
65
- const mergeResultObjects = (0, defu.createDefu)((obj, key, value) => {
66
- if ((0, _stryke_type_checks_is_string.isString)(obj[key]) && (0, _stryke_type_checks_is_string.isString)(value)) {
67
- obj[key] = `${obj[key] || ""}\n${value || ""}`.trim();
68
- return true;
69
- }
70
- return false;
71
- });
72
- /**
73
- * Merges the current hook result with the previous results based on their types.
74
- *
75
- * @param currentResult - The current hook result to merge with the previous results.
76
- * @param previousResults - The previous hook results to merge with the current result.
77
- * @returns The merged result.
78
- */
79
- function mergeResults(currentResult, previousResults) {
80
- if (!previousResults || previousResults.length === 0) return [currentResult];
81
- if ((0, _stryke_type_checks_is_set_string.isSetString)(currentResult)) previousResults = [`${(0, _stryke_type_checks_is_set_string.isSetString)(previousResults[0]) ? previousResults[0] || "" : ""}\n${(0, _stryke_type_checks_is_set_string.isSetString)(previousResults[0]) ? currentResult.replace(previousResults[0], "") : currentResult}`.trim()];
82
- else if ((0, _stryke_type_checks_is_object.isObject)(currentResult)) previousResults = [mergeResultObjects(currentResult, previousResults[0] ?? {})];
83
- return previousResults;
84
- }
85
- /**
86
- * Merges multiple hook results together, with special handling for string values and object values.
87
- *
88
- * @param currentResult - The current hook result to merge with the previous results.
89
- * @param previousResults - The previous hook results to merge with the current result.
90
- * @returns The merged result.
91
- */
92
- function mergeConfigs(currentResult, previousResults) {
93
- if ((0, _stryke_type_checks_is_string.isString)(currentResult)) previousResults = `${(0, _stryke_type_checks_is_string.isString)(previousResults) ? previousResults || "" : ""}\n${currentResult || ""}`.trim();
94
- else if ((0, _stryke_type_checks_is_object.isObject)(currentResult)) previousResults = (0, require_plugin_utils.plugin_utils_exports.mergeConfig)(currentResult, previousResults ?? {});
95
- return previousResults;
96
- }
97
- /**
98
- * Calls a hook with the given context, options, and arguments.
99
- *
100
- * @param context - The context to use when calling the hook.
101
- * @param key - The hook to call.
102
- * @param options - Options for calling the hook.
103
- * @param args - Arguments to pass to the hook.
104
- * @returns The return value of the hook.
105
- */
106
- async function callHook(context, key, options, ...args) {
107
- const hooks = context.selectHooks(key, options);
108
- if (hooks.length > 0) {
109
- context.debug(` 🧩 Calling ${hooks.length} ${chalk.default.bold.cyanBright(`${key}${options?.order ? ` (${options.order})` : ""}`)} plugin hook${hooks.length > 1 ? "s" : ""}:\n${hooks.map((hook, index) => ` ${index + 1}. ${(0, require_utils.utils_exports.colorText)(hook.plugin.name)}`).join("\n")}`);
110
- const invokeHook = async (hook, hookArgs) => {
111
- return Reflect.apply(hook.handler, hook.context, hookArgs);
112
- };
113
- let results = [];
114
- if (options?.sequential === false) results = await Promise.all(hooks.map(async (hook) => {
115
- if (!(0, _stryke_type_checks_is_function.isFunction)(hook.handler)) throw new Error(`Plugin hook handler for hook "${key}" is not a function.`);
116
- return invokeHook(hook, [...args]);
117
- }));
118
- else for (const hook of hooks) {
119
- if (!(0, _stryke_type_checks_is_function.isFunction)(hook.handler)) throw new Error(`Plugin hook handler for hook "${key}" is not a function.`);
120
- if (options?.result === "first" || options?.asNextParam === false) {
121
- results.push(await Promise.resolve(invokeHook(hook, [...args])));
122
- if (options?.result === "first" && (0, _stryke_type_checks_is_set.isSet)(results[results.length - 1])) break;
123
- } else {
124
- const sequenceArgs = [...args];
125
- 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];
126
- const result = await Promise.resolve(invokeHook(hook, [...sequenceArgs]));
127
- if (result) if (options.result === "last") results = [result];
128
- else if (options.result === "merge" && options.merge) results = [results.length > 0 && results[0] ? await Promise.resolve(options.merge(result, results[0])) : result];
129
- else results = mergeResults(result, results);
130
- }
131
- }
132
- const definedResults = results.filter((result) => (0, _stryke_type_checks_is_set.isSet)(result));
133
- if (definedResults.length > 0) {
134
- let mergedResult = void 0;
135
- for (const result of definedResults) mergedResult = (0, defu.defu)(result, mergedResult ?? {});
136
- return mergedResult;
137
- }
138
- }
139
- }
140
- function extractHooks(context, hooks, plugin, key, parentKey) {
141
- const combinedKey = parentKey ? `${parentKey}:${key}` : key;
142
- const pluginField = (0, _stryke_helpers_get_field.getField)(plugin, combinedKey.replace(/:/g, "."));
143
- if ((0, require_plugin_utils.plugin_utils_exports.isPluginHookField)(combinedKey) && (0, require_plugin_utils.plugin_utils_exports.isPluginHook)(pluginField)) {
144
- const pluginHook = pluginField;
145
- if (!(0, require_plugin_utils.plugin_utils_exports.isPluginHook)(pluginHook)) return hooks;
146
- hooks[combinedKey] ??= {
147
- preEnforced: [],
148
- preOrdered: [],
149
- normal: [],
150
- postEnforced: [],
151
- postOrdered: []
152
- };
153
- if (plugin.enforce) {
154
- const hookListOrder = `${plugin.enforce}Enforced`;
155
- hooks[combinedKey][hookListOrder] ??= [];
156
- hooks[combinedKey][hookListOrder] = (0, require_plugin_utils.plugin_utils_exports.addPluginHook)(context, plugin, pluginHook, hooks[combinedKey][hookListOrder]);
157
- return hooks;
158
- }
159
- if ((0, _stryke_type_checks_is_function.isFunction)(pluginHook) || !pluginHook.order) {
160
- hooks[combinedKey].normal ??= [];
161
- hooks[combinedKey].normal = (0, require_plugin_utils.plugin_utils_exports.addPluginHook)(context, plugin, pluginHook, hooks[combinedKey].normal);
162
- return hooks;
163
- }
164
- const hookListOrder = `${pluginHook.order}Ordered`;
165
- hooks[combinedKey][hookListOrder] ??= [];
166
- hooks[combinedKey][hookListOrder] = (0, require_plugin_utils.plugin_utils_exports.addPluginHook)(context, plugin, pluginHook, hooks[combinedKey][hookListOrder]);
167
- return hooks;
168
- } else if ((0, _stryke_type_checks_is_set_object.isSetObject)(pluginField)) return Object.keys(pluginField).map((pluginKey) => extractHooks(context, hooks, plugin, pluginKey, combinedKey)).reduce((ret, current) => {
169
- Object.keys(current).forEach((key) => {
170
- ret[key] ??= {
171
- preEnforced: [],
172
- preOrdered: [],
173
- normal: [],
174
- postEnforced: [],
175
- postOrdered: []
176
- };
177
- [
178
- "preEnforced",
179
- "preOrdered",
180
- "normal",
181
- "postEnforced",
182
- "postOrdered"
183
- ].forEach((order) => {
184
- if (current[key]?.[order]) {
185
- ret[key][order] ??= [];
186
- ret[key][order] = ret[key][order].concat(current[key][order]);
187
- }
188
- });
189
- });
190
- return ret;
191
- }, hooks);
192
- return hooks;
193
- }
194
-
195
- //#endregion
196
- //#region src/_internal/helpers/meta.ts
197
- /**
198
- * Generates a prefixed project root hash object.
199
- *
200
- * @remarks
201
- * 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.
202
- *
203
- * @param name - The name of the project.
204
- * @param rootHash - The hash of the project root.
205
- * @returns An object containing the name and project root hash.
206
- */
207
- function getPrefixedRootHash(name, rootHash) {
208
- const combined = `${(0, _stryke_string_format_kebab_case.kebabCase)(name)}_${rootHash}`;
209
- return combined.length > require_constants.constants_exports.ROOT_HASH_LENGTH ? combined.slice(0, require_constants.constants_exports.ROOT_HASH_LENGTH) : combined;
210
- }
211
- /**
212
- * Writes the meta file for the context.
213
- *
214
- * @param context - The context to write the meta file for.
215
- * @returns A promise that resolves when the meta file has been written.
216
- */
217
- async function writeMetaFile(context) {
218
- const metaFilePath = (0, _stryke_path_join_paths.joinPaths)(context.dataPath, "meta.json");
219
- context.debug(`Writing runtime metadata to ${metaFilePath}`);
220
- await context.fs.write(metaFilePath, JSON.stringify(context.meta, null, 2));
221
- }
222
-
223
- //#endregion
224
- //#region src/_internal/helpers/environment.ts
225
- function createEnvironment(name, userConfig) {
226
- return (0, defu.default)(userConfig.environments?.[name] ?? {}, {
227
- name,
228
- title: userConfig.title || (0, _stryke_string_format_title_case.titleCase)(userConfig.name),
229
- ssr: false,
230
- mainFields: userConfig?.platform === "browser" ? [
231
- "browser",
232
- "module",
233
- "jsnext:main",
234
- "jsnext"
235
- ] : [
236
- "module",
237
- "jsnext:main",
238
- "jsnext"
239
- ],
240
- extensions: [
241
- ".mjs",
242
- ".js",
243
- ".mts",
244
- ".ts",
245
- ".jsx",
246
- ".tsx",
247
- ".json"
248
- ],
249
- consumer: userConfig?.platform === "browser" ? "client" : "server",
250
- preview: userConfig?.platform === "browser" ? {
251
- port: 5173,
252
- open: true,
253
- strictPort: false,
254
- host: "localhost",
255
- allowedHosts: ["."],
256
- cors: true,
257
- headers: {}
258
- } : void 0
259
- }, userConfig);
260
- }
261
- function createDefaultEnvironment(userConfig) {
262
- return createEnvironment(require_constants.constants_exports.DEFAULT_ENVIRONMENT, userConfig);
263
- }
264
-
265
- //#endregion
266
- //#region src/_internal/helpers/resolver.ts
267
- /**
268
- * Create a Jiti resolver for the given workspace and project root.
269
- *
270
- * @param options - The options for creating the resolver.
271
- * @returns A Jiti instance configured for the specified workspace and project root.
272
- */
273
- function resolveOptions(options) {
274
- return (0, defu.default)(options, {
275
- interopDefault: true,
276
- fsCache: options.mode !== "development" ? (0, _stryke_path_join_paths.joinPaths)(options.cacheDir, "jiti") : false,
277
- moduleCache: options.mode !== "development"
278
- });
279
- }
280
- /**
281
- * Create a Jiti resolver for the given workspace and project root.
282
- *
283
- * @param options - The options for creating the resolver.
284
- * @returns A Jiti instance configured for the specified workspace and project root.
285
- */
286
- function createResolver(options) {
287
- const baseResolver = (0, jiti.createJiti)((0, _stryke_path_join_paths.joinPaths)(options.workspaceRoot, options.root), resolveOptions(options));
288
- baseResolver.plugin = (0, jiti.createJiti)((0, _stryke_path_join_paths.joinPaths)(options.workspaceRoot, options.root), resolveOptions(options));
289
- return baseResolver;
290
- }
291
-
292
- //#endregion
293
- //#region schemas/fs.ts
294
- const _capnpFileId = BigInt("0xa56c61324b9d6e49");
295
- var FileMetadata_KeyValuePair = class extends _stryke_capnp.Struct {
296
- static _capnp = {
297
- displayName: "KeyValuePair",
298
- id: "eabb26cf58b2a14c",
299
- size: new _stryke_capnp.ObjectSize(0, 2)
300
- };
301
- get key() {
302
- return _stryke_capnp.utils.getText(0, this);
303
- }
304
- set key(value) {
305
- _stryke_capnp.utils.setText(0, value, this);
306
- }
307
- get value() {
308
- return _stryke_capnp.utils.getText(1, this);
309
- }
310
- set value(value) {
311
- _stryke_capnp.utils.setText(1, value, this);
312
- }
313
- toString() {
314
- return "FileMetadata_KeyValuePair_" + super.toString();
315
- }
316
- };
317
- /**
318
- * The identifier for the file data.
319
- *
320
- */
321
- var FileMetadata = class FileMetadata extends _stryke_capnp.Struct {
322
- static KeyValuePair = FileMetadata_KeyValuePair;
323
- static _capnp = {
324
- displayName: "FileMetadata",
325
- id: "8e2cab5d7e28c7b3",
326
- size: new _stryke_capnp.ObjectSize(8, 3),
327
- defaultType: "normal"
328
- };
329
- static _Properties;
330
- /**
331
- * The type of the file.
332
- *
333
- */
334
- get id() {
335
- return _stryke_capnp.utils.getText(0, this);
336
- }
337
- set id(value) {
338
- _stryke_capnp.utils.setText(0, value, this);
339
- }
340
- /**
341
- * The timestamp representing the file's creation date.
342
- *
343
- */
344
- get type() {
345
- return _stryke_capnp.utils.getText(1, this, FileMetadata._capnp.defaultType);
346
- }
347
- set type(value) {
348
- _stryke_capnp.utils.setText(1, value, this);
349
- }
350
- /**
351
- * Additional metadata associated with the file.
352
- *
353
- */
354
- get timestamp() {
355
- return _stryke_capnp.utils.getUint32(0, this);
356
- }
357
- set timestamp(value) {
358
- _stryke_capnp.utils.setUint32(0, value, this);
359
- }
360
- _adoptProperties(value) {
361
- _stryke_capnp.utils.adopt(value, _stryke_capnp.utils.getPointer(2, this));
362
- }
363
- _disownProperties() {
364
- return _stryke_capnp.utils.disown(this.properties);
365
- }
366
- get properties() {
367
- return _stryke_capnp.utils.getList(2, FileMetadata._Properties, this);
368
- }
369
- _hasProperties() {
370
- return !_stryke_capnp.utils.isNull(_stryke_capnp.utils.getPointer(2, this));
371
- }
372
- _initProperties(length) {
373
- return _stryke_capnp.utils.initList(2, FileMetadata._Properties, length, this);
374
- }
375
- set properties(value) {
376
- _stryke_capnp.utils.copyFrom(value, _stryke_capnp.utils.getPointer(2, this));
377
- }
378
- toString() {
379
- return "FileMetadata_" + super.toString();
380
- }
381
- };
382
- /**
383
- * An identifier for the file.
384
- *
385
- */
386
- var FileId = class extends _stryke_capnp.Struct {
387
- static _capnp = {
388
- displayName: "FileId",
389
- id: "990d6a471072f997",
390
- size: new _stryke_capnp.ObjectSize(0, 2)
391
- };
392
- /**
393
- * A virtual (or actual) path to the file in the file system.
394
- *
395
- */
396
- get id() {
397
- return _stryke_capnp.utils.getText(0, this);
398
- }
399
- set id(value) {
400
- _stryke_capnp.utils.setText(0, value, this);
401
- }
402
- get path() {
403
- return _stryke_capnp.utils.getText(1, this);
404
- }
405
- set path(value) {
406
- _stryke_capnp.utils.setText(1, value, this);
407
- }
408
- toString() {
409
- return "FileId_" + super.toString();
410
- }
411
- };
412
- /**
413
- * An identifier for the file.
414
- *
415
- */
416
- var FileStorage = class extends _stryke_capnp.Struct {
417
- static _capnp = {
418
- displayName: "FileStorage",
419
- id: "9dca66ac858c9ebe",
420
- size: new _stryke_capnp.ObjectSize(0, 2)
421
- };
422
- /**
423
- * A virtual (or actual) path to the file in the file system.
424
- *
425
- */
426
- get path() {
427
- return _stryke_capnp.utils.getText(0, this);
428
- }
429
- set path(value) {
430
- _stryke_capnp.utils.setText(0, value, this);
431
- }
432
- get code() {
433
- return _stryke_capnp.utils.getText(1, this);
434
- }
435
- set code(value) {
436
- _stryke_capnp.utils.setText(1, value, this);
437
- }
438
- toString() {
439
- return "FileStorage_" + super.toString();
440
- }
441
- };
442
- var FileSystem = class FileSystem extends _stryke_capnp.Struct {
443
- static _capnp = {
444
- displayName: "FileSystem",
445
- id: "ae0c23d43e56abcf",
446
- size: new _stryke_capnp.ObjectSize(0, 3)
447
- };
448
- static _Ids;
449
- static _Storage;
450
- static _Metadata;
451
- _adoptIds(value) {
452
- _stryke_capnp.utils.adopt(value, _stryke_capnp.utils.getPointer(0, this));
453
- }
454
- _disownIds() {
455
- return _stryke_capnp.utils.disown(this.ids);
456
- }
457
- get ids() {
458
- return _stryke_capnp.utils.getList(0, FileSystem._Ids, this);
459
- }
460
- _hasIds() {
461
- return !_stryke_capnp.utils.isNull(_stryke_capnp.utils.getPointer(0, this));
462
- }
463
- _initIds(length) {
464
- return _stryke_capnp.utils.initList(0, FileSystem._Ids, length, this);
465
- }
466
- set ids(value) {
467
- _stryke_capnp.utils.copyFrom(value, _stryke_capnp.utils.getPointer(0, this));
468
- }
469
- _adoptStorage(value) {
470
- _stryke_capnp.utils.adopt(value, _stryke_capnp.utils.getPointer(1, this));
471
- }
472
- _disownStorage() {
473
- return _stryke_capnp.utils.disown(this.storage);
474
- }
475
- get storage() {
476
- return _stryke_capnp.utils.getList(1, FileSystem._Storage, this);
477
- }
478
- _hasStorage() {
479
- return !_stryke_capnp.utils.isNull(_stryke_capnp.utils.getPointer(1, this));
480
- }
481
- _initStorage(length) {
482
- return _stryke_capnp.utils.initList(1, FileSystem._Storage, length, this);
483
- }
484
- set storage(value) {
485
- _stryke_capnp.utils.copyFrom(value, _stryke_capnp.utils.getPointer(1, this));
486
- }
487
- _adoptMetadata(value) {
488
- _stryke_capnp.utils.adopt(value, _stryke_capnp.utils.getPointer(2, this));
489
- }
490
- _disownMetadata() {
491
- return _stryke_capnp.utils.disown(this.metadata);
492
- }
493
- get metadata() {
494
- return _stryke_capnp.utils.getList(2, FileSystem._Metadata, this);
495
- }
496
- _hasMetadata() {
497
- return !_stryke_capnp.utils.isNull(_stryke_capnp.utils.getPointer(2, this));
498
- }
499
- _initMetadata(length) {
500
- return _stryke_capnp.utils.initList(2, FileSystem._Metadata, length, this);
501
- }
502
- set metadata(value) {
503
- _stryke_capnp.utils.copyFrom(value, _stryke_capnp.utils.getPointer(2, this));
504
- }
505
- toString() {
506
- return "FileSystem_" + super.toString();
507
- }
508
- };
509
- FileMetadata._Properties = _stryke_capnp.CompositeList(FileMetadata_KeyValuePair);
510
- FileSystem._Ids = _stryke_capnp.CompositeList(FileId);
511
- FileSystem._Storage = _stryke_capnp.CompositeList(FileStorage);
512
- FileSystem._Metadata = _stryke_capnp.CompositeList(FileMetadata);
513
-
514
- //#endregion
515
- //#region src/_internal/helpers/constants.ts
516
- const DEFAULT_EXTENSIONS = [
517
- "js",
518
- "ts",
519
- "cjs",
520
- "cts",
521
- "mjs",
522
- "mts",
523
- "tsx",
524
- "jsx",
525
- "json",
526
- "json5",
527
- "jsonc",
528
- "md",
529
- "mdx"
530
- ];
531
-
532
- //#endregion
533
- //#region src/_internal/vfs.ts
534
- function toFilePath(path) {
535
- return (0, _stryke_path_correct_path.correctPath)((0, _stryke_path_slash.slash)(path?.toString() || ".").replace(/^file:\/\//, ""));
536
- }
537
- /**
538
- * Checks if a given file id is valid based on the specified prefix.
539
- *
540
- * @param id - The file ID to check.
541
- * @param prefix - The prefix to use for built-in files. Default is "powerlines".
542
- * @returns `true` if the file ID is valid, otherwise `false`.
543
- */
544
- function isValidId(id, prefix = "powerlines") {
545
- return id.replace(/^\\0/, "").startsWith(`${prefix.replace(/:$/, "")}`);
546
- }
547
- /**
548
- * Formats a file id by removing the file extension and prepended runtime prefix.
549
- *
550
- * @param id - The file ID to format.
551
- * @param prefix - The prefix to use for built-in files. Default is "powerlines".
552
- * @returns The formatted file ID.
553
- */
554
- function normalizeId(id, prefix = "powerlines") {
555
- return (0, _stryke_path_replace.replaceExtension)(toFilePath(id)).replace(/^\\0/, "").replace(/^powerlines:/, "").replace(new RegExp(`^${prefix.replace(/:$/, "")}:`), "");
556
- }
557
- /**
558
- * Normalizes a given path by resolving it against the project root, workspace root, and built-ins path.
559
- *
560
- * @param path - The path to normalize.
561
- * @param builtinsPath - The path to built-in files.
562
- * @param prefix - The prefix to use for built-in files. Default is "powerlines".
563
- * @returns The normalized path.
564
- */
565
- function normalizePath(path, builtinsPath, prefix = "powerlines") {
566
- if (!(0, _stryke_type_checks_is_set_string.isSetString)(path)) {
567
- if (!(0, _stryke_type_checks_is_string.isString)(path)) throw new Error("Path type must be a string or a file descriptor");
568
- throw new Error("Path cannot be empty");
569
- }
570
- return (0, _stryke_path_is_type.isAbsolutePath)(path) ? path : isValidId(toFilePath(path), prefix) ? normalizeId(toFilePath(path), prefix).replace(new RegExp(`^${prefix.replace(/:$/, "")}:`), builtinsPath) : toFilePath(path);
571
- }
572
- /**
573
- * Normalizes glob patterns by resolving them against the workspace root.
574
- *
575
- * @param workspaceRoot - The root directory of the workspace.
576
- * @param patterns - The glob patterns to normalize.
577
- * @returns An array of normalized glob patterns.
578
- */
579
- function normalizeGlobPatterns(workspaceRoot, patterns) {
580
- return (0, _stryke_helpers_get_unique.getUnique)((0, _stryke_convert_to_array.toArray)(patterns).map((pattern) => {
581
- 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 || "**/*");
582
- else if (!(0, _stryke_type_checks_is_set_string.isSetString)(pattern)) return;
583
- return pattern;
584
- }).filter(_stryke_type_checks_is_set_string.isSetString));
585
- }
586
- /**
587
- * Represents a virtual file system (VFS) that stores files and their associated metadata in virtual memory.
588
- *
589
- * @remarks
590
- * 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.
591
- */
592
- var VirtualFileSystem = class VirtualFileSystem {
593
- /**
594
- * A map of virtual file IDs to their associated metadata.
595
- */
596
- #metadata;
597
- /**
598
- * A map of underlying file paths to their virtual file IDs.
599
- */
600
- #ids;
601
- /**
602
- * A map of virtual file IDs to their underlying file paths.
603
- */
604
- #paths;
605
- /**
606
- * The unified volume that combines the virtual file system with the real file system.
607
- *
608
- * @remarks
609
- * This volume allows for seamless access to both virtual and real files.
610
- */
611
- #storage;
612
- /**
613
- * A cache for module resolution results.
614
- */
615
- #resolverCache;
616
- /**
617
- * Indicator specifying if the virtual file system (VFS) is disposed
618
- */
619
- #isDisposed = false;
620
- /**
621
- * The context of the virtual file system.
622
- */
623
- #context;
624
- /**
625
- * The file system's logging function.
626
- */
627
- #log;
628
- /**
629
- * Normalizes a given module id by resolving it against the built-ins path.
630
- *
631
- * @param id - The module id to normalize.
632
- * @returns The normalized module id.
633
- */
634
- #normalizeId(id) {
635
- let normalized = id;
636
- if ((0, _stryke_path_is_parent_path.isParentPath)(normalized, this.#context.builtinsPath)) normalized = (0, _stryke_path_replace.replacePath)(normalized, this.#context.builtinsPath);
637
- return normalizeId(normalized, this.#context.config.framework);
638
- }
639
- /**
640
- * Normalizes a given path by resolving it against the project root, workspace root, and built-ins path.
641
- *
642
- * @param path - The path to normalize.
643
- * @returns The normalized path.
644
- */
645
- #normalizePath(path) {
646
- if (!(0, _stryke_type_checks_is_set_string.isSetString)(path)) {
647
- if (!(0, _stryke_type_checks_is_string.isString)(path)) throw new Error("Path type must be a string or a file descriptor");
648
- throw new Error("Path cannot be empty");
649
- }
650
- return normalizePath(path.includes("{") || path.includes("}") ? (0, require_plugin_utils.plugin_utils_exports.replacePathTokens)(this.#context, path) : path, this.#context.builtinsPath, this.#context.config.framework);
651
- }
652
- /**
653
- * Gets the storage adapter and relative key for a given key.
654
- *
655
- * @remarks
656
- * The `key` can be either a path or a storage adapter name.
657
- *
658
- * @param key - The key to get the storage adapter for.
659
- * @returns The storage adapter and relative key for the given key.
660
- */
661
- #getStorage(key, preset) {
662
- const path = this.resolveSync(this.#normalizePath(key)) || key;
663
- for (const base of Object.keys(this.#storage).filter(Boolean).sort().reverse()) if ((path === base || (0, _stryke_path_is_parent_path.isParentPath)(path, base)) && (!preset || this.#storage[base]?.preset?.toLowerCase() === preset.toLowerCase())) return {
664
- base,
665
- relativeKey: (0, _stryke_path_replace.replacePath)(path, base),
666
- adapter: this.#storage[base]
667
- };
668
- if (!preset || this.#storage[""]?.preset?.toLowerCase() === preset.toLowerCase()) return {
669
- base: "",
670
- relativeKey: path,
671
- adapter: this.#storage[""]
672
- };
673
- this.#storage[path] = preset === "virtual" ? new require_virtual.VirtualStorageAdapter(this.#context, { base: path }) : new require_virtual.FileSystemStorageAdapter(this.#context, { base: path });
674
- return {
675
- base: path,
676
- relativeKey: "",
677
- adapter: this.#storage[path]
678
- };
679
- }
680
- /**
681
- * Gets all storage adapters that match a given base key.
682
- *
683
- * @param base - The base key to match storage adapters against.
684
- * @param includeParent - Whether to include parent storage adapters.
685
- * @returns An array of storage adapters that match the given base key.
686
- */
687
- #getStorages(base = "", includeParent = false) {
688
- const baseKey = this.resolveSync(base) || base;
689
- return Object.keys(this.#storage).sort().reverse().filter((key) => (0, _stryke_path_is_parent_path.isParentPath)(key, baseKey) || includeParent && (0, _stryke_path_is_parent_path.isParentPath)(baseKey, key) || baseKey.includes("*") && ((0, _stryke_path_is_parent_path.isParentPath)((0, _stryke_path_correct_path.stripStars)(baseKey), key) || (0, _stryke_path_glob_to_regex.globToRegex)((0, _stryke_path_replace.replaceExtension)(baseKey)).test(key))).map((key) => ({
690
- relativeBase: baseKey.length > key.length ? baseKey.slice(key.length) : void 0,
691
- base: key,
692
- adapter: this.#storage[key]
693
- }));
694
- }
695
- /**
696
- * A helper function to resolve modules in the virtual file system (VFS).
697
- *
698
- * @remarks
699
- * This function can be used to resolve modules relative to the project root directory.
700
- *
701
- * @example
702
- * ```ts
703
- * const resolved = await context.resolvePath("some-module", "/path/to/importer");
704
- * ```
705
- *
706
- * @param id - The module to resolve.
707
- * @param importer - An optional path to the importer module.
708
- * @param options - Additional resolution options.
709
- * @returns A promise that resolves to the resolved module path.
710
- */
711
- #innerResolve = async (id, importer, options = {}) => {
712
- let path = id;
713
- if (path.includes("{") || path.includes("}")) path = (0, require_plugin_utils.plugin_utils_exports.replacePathTokens)(this.#context, path);
714
- if (options.skipAlias !== true) path = this.resolveAlias(path);
715
- if ((0, _stryke_path_is_type.isAbsolutePath)(path) && (!options.isFile || !await this.isDirectory(path))) return path;
716
- const resolverCacheKey = (0, _stryke_hash.murmurhash)({
717
- path: this.#normalizeId(path),
718
- importer,
719
- options
720
- });
721
- let result;
722
- if (!this.#context.config.skipCache) {
723
- result = this.resolverCache.get(resolverCacheKey);
724
- if (result) return result;
725
- }
726
- result = this.paths[this.#normalizeId(path)];
727
- if (!(0, _stryke_type_checks_is_set_string.isSetString)(result)) {
728
- const paths = options.paths ?? [];
729
- if (importer && !paths.includes(importer)) paths.push(importer);
730
- if (!importer) {
731
- paths.push(this.#context.workspaceConfig.workspaceRoot);
732
- paths.push((0, _stryke_path_append.appendPath)(this.#context.config.root, this.#context.workspaceConfig.workspaceRoot));
733
- paths.push((0, _stryke_path_append.appendPath)((0, _stryke_path_join.joinPaths)(this.#context.config.root, "src"), this.#context.workspaceConfig.workspaceRoot));
734
- }
735
- 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)));
736
- for (const combination of (0, _stryke_fs_resolve.getResolutionCombinations)(path, { paths: (0, _stryke_helpers_get_unique.getUnique)(paths) })) {
737
- const { relativeKey, adapter } = this.#getStorage(combination);
738
- if (await adapter.exists(relativeKey)) {
739
- result = combination;
740
- break;
741
- }
742
- }
743
- if (!(0, _stryke_type_checks_is_set_string.isSetString)(result)) try {
744
- result = await (0, _stryke_fs_resolve.resolve)(path, {
745
- ...options,
746
- paths
747
- });
748
- } catch {}
749
- }
750
- if ((0, _stryke_type_checks_is_set_string.isSetString)(result)) {
751
- if (!this.#context.config.skipCache) this.resolverCache.set(this.#normalizeId(path), result);
752
- return result;
753
- }
754
- };
755
- /**
756
- * A synchronous helper function to resolve modules using the Jiti resolver
757
- *
758
- * @remarks
759
- * This function can be used to resolve modules relative to the project root directory.
760
- *
761
- * @example
762
- * ```ts
763
- * const resolvedPath = context.resolveSync("some-module", "/path/to/importer");
764
- * ```
765
- *
766
- * @param id - The module to resolve.
767
- * @param importer - An optional path to the importer module.
768
- * @param options - Additional resolution options.
769
- * @returns The resolved module path.
770
- */
771
- #innerResolveSync = (id, importer, options = {}) => {
772
- let path = id;
773
- if (path.includes("{") || path.includes("}")) path = (0, require_plugin_utils.plugin_utils_exports.replacePathTokens)(this.#context, path);
774
- if (options.skipAlias !== true) path = this.resolveAlias(path);
775
- if ((0, _stryke_path_is_type.isAbsolutePath)(path) && (!options.isFile || !this.isDirectorySync(path))) return path;
776
- let result;
777
- if (!this.#context.config.skipCache) {
778
- result = this.resolverCache.get(this.#normalizeId(path));
779
- if ((0, _stryke_type_checks_is_set_string.isSetString)(result)) return result;
780
- }
781
- result = this.paths[this.#normalizeId(path)];
782
- if (!(0, _stryke_type_checks_is_set_string.isSetString)(result)) {
783
- const paths = options.paths ?? [];
784
- if (importer && !paths.includes(importer)) paths.push(importer);
785
- if (!importer) {
786
- paths.push(this.#context.workspaceConfig.workspaceRoot);
787
- paths.push((0, _stryke_path_append.appendPath)(this.#context.config.root, this.#context.workspaceConfig.workspaceRoot));
788
- paths.push((0, _stryke_path_append.appendPath)((0, _stryke_path_join.joinPaths)(this.#context.config.root, "src"), this.#context.workspaceConfig.workspaceRoot));
789
- }
790
- 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)));
791
- for (const combination of (0, _stryke_fs_resolve.getResolutionCombinations)(path, { paths })) {
792
- const { relativeKey, adapter } = this.#getStorage(combination);
793
- if (adapter.existsSync(relativeKey)) {
794
- result = combination;
795
- break;
796
- }
797
- }
798
- if (!(0, _stryke_type_checks_is_set_string.isSetString)(result)) try {
799
- result = (0, _stryke_fs_resolve.resolveSync)(path, {
800
- ...options,
801
- paths
802
- });
803
- } catch {}
804
- }
805
- if ((0, _stryke_type_checks_is_set_string.isSetString)(result)) {
806
- if (!this.#context.config.skipCache) this.resolverCache.set(this.#normalizeId(path), result);
807
- return result;
808
- }
809
- };
810
- /**
811
- * Creates a virtual file system (VFS) that is backed up to a Cap'n Proto message buffer.
812
- *
813
- * @param context - The context of the virtual file system, typically containing options and logging functions.
814
- * @returns A promise that resolves to a new virtual file system instance.
815
- */
816
- static async create(context) {
817
- context.debug("Starting virtual file system (VFS) initialization processes...");
818
- let result;
819
- if (!context.config.skipCache && (0, _stryke_fs_exists.existsSync)((0, _stryke_path_join.joinPaths)(context.dataPath, "fs.bin"))) {
820
- const buffer = await (0, _stryke_fs_buffer.readFileBuffer)((0, _stryke_path_join.joinPaths)(context.dataPath, "fs.bin"));
821
- const fs = new _stryke_capnp.Message(buffer, false).getRoot(FileSystem);
822
- result = new VirtualFileSystem(context, fs);
823
- if (fs._hasStorage() && fs.storage.length > 0) await Promise.all(fs.storage.values().map(async (file) => {
824
- if (file.path && file.code) {
825
- let id;
826
- if (fs._hasIds()) id = fs.ids.find((fileId) => fileId.path === file.path);
827
- let metadata;
828
- if (fs._hasMetadata()) metadata = fs.metadata.find((meta) => meta.id === result.#normalizeId(id?.id ?? file.path));
829
- await result.write(file.path, file.code, { meta: {
830
- id: result.#normalizeId(id?.id ?? metadata?.id ?? file.path),
831
- type: metadata?.type || "normal",
832
- properties: metadata?._hasProperties() ? metadata?.properties.values().reduce((ret, kvp) => {
833
- ret[kvp.key] = kvp.value;
834
- return ret;
835
- }, {}) : void 0,
836
- timestamp: metadata?.timestamp
837
- } });
838
- }
839
- }));
840
- } else result = new VirtualFileSystem(context, new _stryke_capnp.Message().initRoot(FileSystem));
841
- result.#log(_storm_software_config_tools_types.LogLevelLabel.DEBUG, "Successfully completed virtual file system (VFS) initialization.");
842
- return result;
843
- }
844
- /**
845
- * Synchronously creates a virtual file system (VFS) that is backed up to a Cap'n Proto message buffer.
846
- *
847
- * @param context - The context of the virtual file system, typically containing options and logging functions.
848
- * @returns A new virtual file system instance.
849
- */
850
- static createSync(context) {
851
- context.debug("Starting virtual file system (VFS) initialization processes...");
852
- let result;
853
- if (!context.config.skipCache && (0, _stryke_fs_exists.existsSync)((0, _stryke_path_join.joinPaths)(context.dataPath, "fs.bin"))) {
854
- const buffer = (0, _stryke_fs_buffer.readFileBufferSync)((0, _stryke_path_join.joinPaths)(context.dataPath, "fs.bin"));
855
- const fs = new _stryke_capnp.Message(buffer, false).getRoot(FileSystem);
856
- result = new VirtualFileSystem(context, fs);
857
- if (fs._hasStorage() && fs.storage.length > 0) fs.storage.values().forEach((file) => {
858
- if (file.path && file.code) {
859
- let id;
860
- if (fs._hasIds()) id = fs.ids.find((fileId) => fileId.path === file.path);
861
- let metadata;
862
- if (fs._hasMetadata()) metadata = fs.metadata.find((meta) => meta.id === result.#normalizeId(id?.id ?? file.path));
863
- result.writeSync(file.path, file.code, { meta: {
864
- id: result.#normalizeId(id?.id ?? metadata?.id ?? file.path),
865
- type: metadata?.type,
866
- properties: metadata?._hasProperties() ? metadata?.properties.values().reduce((ret, kvp) => {
867
- ret[kvp.key] = kvp.value;
868
- return ret;
869
- }, {}) : void 0,
870
- timestamp: metadata?.timestamp
871
- } });
872
- }
873
- });
874
- } else result = new VirtualFileSystem(context, new _stryke_capnp.Message().initRoot(FileSystem));
875
- result.#log(_storm_software_config_tools_types.LogLevelLabel.DEBUG, "Successfully completed virtual file system (VFS) initialization.");
876
- return result;
877
- }
878
- /**
879
- * A map of file ids to their metadata.
880
- */
881
- get metadata() {
882
- return new Proxy(this.#metadata, {
883
- get: (target, prop) => {
884
- return target[this.#normalizeId(prop)];
885
- },
886
- set: (target, prop, value) => {
887
- target[this.#normalizeId(prop)] = value;
888
- return true;
889
- },
890
- deleteProperty: (target, prop) => {
891
- delete target[this.#normalizeId(prop)];
892
- return true;
893
- },
894
- has: (target, prop) => {
895
- return this.#normalizeId(prop) in target;
896
- },
897
- ownKeys: (target) => {
898
- return (0, _stryke_helpers_get_unique.getUnique)(Reflect.ownKeys(target).map((key) => this.#normalizeId(key)));
899
- }
900
- });
901
- }
902
- /**
903
- * A map of file paths to their module ids.
904
- */
905
- get ids() {
906
- return new Proxy(this.#ids, {
907
- get: (target, prop) => {
908
- return target[this.#normalizePath(prop)];
909
- },
910
- set: (target, prop, value) => {
911
- target[this.#normalizePath(prop)] = value;
912
- return true;
913
- },
914
- deleteProperty: (target, prop) => {
915
- delete target[this.#normalizePath(prop)];
916
- return true;
917
- },
918
- has: (target, prop) => {
919
- return this.#normalizePath(prop) in target;
920
- },
921
- ownKeys: (target) => {
922
- return (0, _stryke_helpers_get_unique.getUnique)(Reflect.ownKeys(target).map((key) => this.#normalizePath(key)));
923
- }
924
- });
925
- }
926
- /**
927
- * A map of module ids to their file paths.
928
- */
929
- get paths() {
930
- return new Proxy(this.#paths, {
931
- get: (target, prop) => {
932
- return this.#normalizeId(prop) in target ? target[this.#normalizeId(prop)] : void 0;
933
- },
934
- set: (target, prop, value) => {
935
- target[this.#normalizeId(prop)] = value;
936
- return true;
937
- },
938
- deleteProperty: (target, prop) => {
939
- delete target[this.#normalizeId(prop)];
940
- return true;
941
- },
942
- has: (target, prop) => {
943
- return this.#normalizeId(prop) in target;
944
- },
945
- ownKeys: (target) => {
946
- return (0, _stryke_helpers_get_unique.getUnique)(Reflect.ownKeys(target).map((key) => this.#normalizeId(key)));
947
- }
948
- });
949
- }
950
- /**
951
- * Gets the resolver cache.
952
- */
953
- get resolverCache() {
954
- if (!this.#resolverCache) this.#resolverCache = (0, flat_cache.create)({
955
- cacheId: "module-resolution",
956
- cacheDir: this.#context.cachePath,
957
- ttl: 2.5 * 60 * 1e3,
958
- lruSize: 8e3,
959
- persistInterval: 100
960
- });
961
- return this.#resolverCache;
962
- }
963
- /**
964
- * Creates a new instance of the {@link VirtualFileSystem}.
965
- *
966
- * @param context - The context of the virtual file system, typically containing options and logging functions.
967
- * @param fs - A buffer containing the serialized virtual file system data.
968
- */
969
- constructor(context, fs) {
970
- this.#context = context;
971
- this.#storage = { "": new require_virtual.FileSystemStorageAdapter(context) };
972
- if ((0, _stryke_type_checks_is_set_object.isSetObject)(this.#context.config.output.storage)) this.#storage = {
973
- ...this.#storage,
974
- ...this.#context.config.output.storage
975
- };
976
- this.#storage.virtual ??= new require_virtual.VirtualStorageAdapter(context, { base: "/_virtual" });
977
- this.#storage[this.#context.config.output.path] ??= new require_virtual.FileSystemStorageAdapter(context, { base: this.#context.config.output.path });
978
- if (this.#context.config.output.copy && this.#context.config.output.copy.path) this.#storage[this.#context.config.output.copy.path] ??= new require_virtual.FileSystemStorageAdapter(context, { base: this.#context.config.output.copy.path });
979
- if (this.#context.config.output.storage !== "fs") {
980
- this.#storage[this.#context.artifactsPath] ??= new require_virtual.VirtualStorageAdapter(context, { base: this.#context.artifactsPath });
981
- this.#storage[this.#context.builtinsPath] ??= new require_virtual.VirtualStorageAdapter(context, { base: this.#context.builtinsPath });
982
- this.#storage[this.#context.entryPath] ??= new require_virtual.VirtualStorageAdapter(context, { base: this.#context.entryPath });
983
- }
984
- this.#metadata = {};
985
- if (fs._hasMetadata()) this.#metadata = fs.metadata.values().reduce((ret, metadata) => {
986
- ret[metadata.id] = {
987
- id: metadata.id,
988
- type: metadata.type,
989
- timestamp: metadata.timestamp ?? Date.now(),
990
- properties: metadata._hasProperties() ? metadata.properties.values().reduce((ret, item) => {
991
- ret[item.key] = item.value;
992
- return ret;
993
- }, {}) : {}
994
- };
995
- return ret;
996
- }, {});
997
- this.#ids = {};
998
- this.#paths = {};
999
- if (fs._hasIds()) {
1000
- this.#ids = fs.ids.values().reduce((ret, identifier) => {
1001
- ret[identifier.path] ??= identifier.id;
1002
- return ret;
1003
- }, {});
1004
- this.#paths = fs.ids.values().reduce((ret, identifier) => {
1005
- ret[identifier.id] ??= identifier.path;
1006
- return ret;
1007
- }, {});
1008
- }
1009
- this.#log = (0, require_utils.utils_exports.extendLog)(this.#context.log, "file-system");
1010
- }
1011
- /**
1012
- * Asynchronously checks if a file exists in the virtual file system (VFS).
1013
- *
1014
- * @param path - The path to the file.
1015
- * @returns A promise that resolves to `true` if the file exists, otherwise `false`.
1016
- */
1017
- async exists(path) {
1018
- const { relativeKey, adapter } = this.#getStorage(path);
1019
- return adapter.exists(relativeKey);
1020
- }
1021
- /**
1022
- * Synchronously checks if a file exists in the virtual file system (VFS).
1023
- *
1024
- * @param path - The path to the file.
1025
- * @returns `true` if the file exists, otherwise `false`.
1026
- */
1027
- existsSync(path) {
1028
- const { relativeKey, adapter } = this.#getStorage(path);
1029
- return adapter.existsSync(relativeKey);
1030
- }
1031
- /**
1032
- * Checks if a file is virtual in the virtual file system (VFS).
1033
- *
1034
- * @param path - The path to the file.
1035
- * @param importer - An optional path to the importer module.
1036
- * @param options - Additional resolution options.
1037
- * @returns `true` if the file is virtual, otherwise `false`.
1038
- */
1039
- isVirtual(path, importer, options) {
1040
- const resolved = this.resolveSync(path, importer, options);
1041
- if (!(0, _stryke_type_checks_is_set_string.isSetString)(resolved)) {
1042
- if ((0, _stryke_type_checks_is_set.isSet)(resolved)) throw new Error(`Resolved path is not a string: ${String(resolved)}`);
1043
- return false;
1044
- }
1045
- return this.#getStorage(resolved)?.adapter?.preset === "virtual" || resolved.startsWith(`${this.#context.config.framework}:`) || path.startsWith(`${this.#context.config.framework}:`);
1046
- }
1047
- /**
1048
- * Checks if a path is a directory in the virtual file system (VFS).
1049
- *
1050
- * @param path - The path to check.
1051
- * @param importer - An optional path to the importer module.
1052
- * @param options - Additional resolution options.
1053
- * @returns `true` if the path is a directory, otherwise `false`.
1054
- */
1055
- isDirectorySync(path, importer, options) {
1056
- const resolved = this.resolveSync(path, importer, options);
1057
- if (!(0, _stryke_type_checks_is_set_string.isSetString)(resolved)) {
1058
- if ((0, _stryke_type_checks_is_set.isSet)(resolved)) throw new Error(`Resolved path is not a string: ${String(resolved)}`);
1059
- return false;
1060
- }
1061
- return !!(this.existsSync(resolved) && this.#getStorage(resolved)?.adapter?.isDirectorySync(resolved));
1062
- }
1063
- /**
1064
- * Checks if a path is a directory in the virtual file system (VFS).
1065
- *
1066
- * @param path - The path to check.
1067
- * @param importer - An optional path to the importer module.
1068
- * @param options - Additional resolution options.
1069
- * @returns `true` if the path is a directory, otherwise `false`.
1070
- */
1071
- async isDirectory(path, importer, options) {
1072
- const resolved = await this.resolve(path, importer, options);
1073
- if (!(0, _stryke_type_checks_is_set_string.isSetString)(resolved)) {
1074
- if ((0, _stryke_type_checks_is_set.isSet)(resolved)) throw new Error(`Resolved path is not a string: ${String(resolved)}`);
1075
- return false;
1076
- }
1077
- return !!(await this.exists(resolved) && await this.#getStorage(resolved)?.adapter?.isDirectory(resolved));
1078
- }
1079
- /**
1080
- * Checks if a path is a file in the virtual file system (VFS).
1081
- *
1082
- * @param path - The path to check.
1083
- * @param importer - An optional path to the importer module.
1084
- * @param options - Additional resolution options.
1085
- * @returns `true` if the path is a file, otherwise `false`.
1086
- */
1087
- isFileSync(path, importer, options) {
1088
- const resolved = this.resolveSync(path, importer, options);
1089
- if (!(0, _stryke_type_checks_is_set_string.isSetString)(resolved)) {
1090
- if ((0, _stryke_type_checks_is_set.isSet)(resolved)) throw new Error(`Resolved path is not a string: ${String(resolved)}`);
1091
- return false;
1092
- }
1093
- return this.#getStorage(resolved)?.adapter?.isFileSync(resolved) ?? false;
1094
- }
1095
- /**
1096
- * Checks if a path is a file in the virtual file system (VFS).
1097
- *
1098
- * @param path - The path to check.
1099
- * @param importer - An optional path to the importer module.
1100
- * @param options - Additional resolution options.
1101
- * @returns `true` if the path is a file, otherwise `false`.
1102
- */
1103
- async isFile(path, importer, options) {
1104
- const resolved = await this.resolve(path, importer, options);
1105
- if (!(0, _stryke_type_checks_is_set_string.isSetString)(resolved)) {
1106
- if ((0, _stryke_type_checks_is_set.isSet)(resolved)) throw new Error(`Resolved path is not a string: ${String(resolved)}`);
1107
- return false;
1108
- }
1109
- return await this.#getStorage(resolved)?.adapter?.isFile(resolved) ?? false;
1110
- }
1111
- /**
1112
- * Checks if a file Id must be resolved by the virtual file system (VFS).
1113
- *
1114
- * @remarks
1115
- * Examples of file Ids that would be considered virtual include:
1116
- * - Ids that start with the framework specific prefix (e.g. `powerlines:`)
1117
- * - Ids that match a configured alias for virtual modules (returned true from {@link VirtualFileSystemInterface.isVirtual})
1118
- *
1119
- * @param path - The path or id of the file.
1120
- * @param importer - An optional path to the importer module, used for resolving the file path.
1121
- * @param options - Additional options for resolving the file path.
1122
- * @returns `true` if the file is virtual, otherwise `false`.
1123
- */
1124
- isResolvableId(path, importer, options) {
1125
- return path.startsWith(`${this.#context.config.framework}:`) || this.isVirtual(path, importer, options) || this.isAlias(path) || this.isTsconfigPath(path);
1126
- }
1127
- /**
1128
- * Lists files in a given path.
1129
- *
1130
- * @param path - The path to list files from.
1131
- * @returns An array of file names in the specified path.
1132
- */
1133
- listSync(path) {
1134
- let resolvedPath = path;
1135
- if (resolvedPath.includes("*")) {
1136
- this.#log(_storm_software_config_tools_types.LogLevelLabel.WARN, `Invoking "listSync" with a glob pattern is not supported. It is likely you meant to use "globSync". Path: ${path}`);
1137
- resolvedPath = (0, _stryke_path_correct_path.stripStars)(resolvedPath);
1138
- }
1139
- return (0, _stryke_helpers_get_unique.getUnique)(this.#getStorages(resolvedPath, true).map((storage) => storage.adapter.listSync(storage.relativeBase ? storage.base ? (0, _stryke_path_append.appendPath)(storage.relativeBase, storage.base) : storage.relativeBase : storage.base)).flat().filter(Boolean));
1140
- }
1141
- /**
1142
- * Lists files in a given path.
1143
- *
1144
- * @param path - The path to list files from.
1145
- * @returns An array of file names in the specified path.
1146
- */
1147
- async list(path) {
1148
- let resolvedPath = path;
1149
- if (resolvedPath.includes("*")) {
1150
- this.#log(_storm_software_config_tools_types.LogLevelLabel.WARN, `Invoking "list" with a glob pattern is not supported. It is likely you meant to use "glob". Path: ${path}`);
1151
- resolvedPath = (0, _stryke_path_correct_path.stripStars)(resolvedPath);
1152
- }
1153
- return (0, _stryke_helpers_get_unique.getUnique)((await Promise.all(this.#getStorages(resolvedPath, 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().filter(Boolean));
1154
- }
1155
- /**
1156
- * Removes a file in the virtual file system (VFS).
1157
- *
1158
- * @param path - The path to create the directory at.
1159
- */
1160
- async remove(path) {
1161
- const normalizedPath = this.#normalizePath(path);
1162
- this.#log(_storm_software_config_tools_types.LogLevelLabel.TRACE, `Removing file: ${normalizedPath}`);
1163
- const { relativeKey, adapter } = this.#getStorage(normalizedPath);
1164
- if ((0, _stryke_path_file_path_fns.hasFileExtension)(normalizedPath)) await adapter.remove(relativeKey);
1165
- else await adapter.clear(relativeKey);
1166
- const id = this.#ids[normalizedPath];
1167
- if (id && this.#metadata[id]) {
1168
- delete this.#metadata[id];
1169
- delete this.#ids[normalizedPath];
1170
- delete this.#paths[id];
1171
- }
1172
- }
1173
- /**
1174
- * Removes a file in the virtual file system (VFS).
1175
- *
1176
- * @param path - The path to create the directory at.
1177
- */
1178
- removeSync(path) {
1179
- const normalizedPath = this.#normalizePath(path);
1180
- this.#log(_storm_software_config_tools_types.LogLevelLabel.TRACE, `Removing file: ${normalizedPath}`);
1181
- const { relativeKey, adapter } = this.#getStorage(normalizedPath);
1182
- if ((0, _stryke_path_file_path_fns.hasFileExtension)(normalizedPath)) adapter.removeSync(relativeKey);
1183
- else adapter.clearSync(relativeKey);
1184
- const id = this.#ids[normalizedPath];
1185
- if (id && this.#metadata[id]) {
1186
- delete this.#metadata[id];
1187
- delete this.#ids[normalizedPath];
1188
- delete this.#paths[id];
1189
- }
1190
- }
1191
- /**
1192
- * Glob files in the virtual file system (VFS) based on the provided pattern(s).
1193
- *
1194
- * @param patterns - A pattern (or multiple patterns) to use to determine the file paths to return
1195
- * @returns An array of file paths matching the provided pattern(s)
1196
- */
1197
- async glob(patterns) {
1198
- const results = [];
1199
- for (const pattern of normalizeGlobPatterns(this.#context.workspaceConfig.workspaceRoot, patterns)) {
1200
- const normalized = this.#normalizePath(pattern);
1201
- if (!/[*?[\]{}]/.test(normalized) && !normalized.includes("*")) if (this.isDirectorySync(normalized)) results.push(...await this.list(normalized));
1202
- else {
1203
- const resolved = await this.resolve(normalized);
1204
- if (resolved && !results.includes(resolved)) results.push(resolved);
1205
- }
1206
- else {
1207
- const absPattern = (0, _stryke_path_is_type.isAbsolutePath)(normalized) ? normalized : this.#normalizePath((0, _stryke_path_append.appendPath)(normalized, this.#context.workspaceConfig.workspaceRoot));
1208
- await Promise.all((await this.list((0, _stryke_path_correct_path.stripStars)(absPattern))).map(async (file) => {
1209
- if ((0, _stryke_path_glob_to_regex.globToRegex)(absPattern).test(file)) {
1210
- const resolved = await this.resolve(file);
1211
- if (resolved && !results.includes(resolved)) results.push(resolved);
1212
- }
1213
- }));
1214
- }
1215
- }
1216
- return results;
1217
- }
1218
- /**
1219
- * Synchronously glob files in the virtual file system (VFS) based on the provided pattern(s).
1220
- *
1221
- * @param patterns - A pattern (or multiple patterns) to use to determine the file paths to return
1222
- * @returns An array of file paths matching the provided pattern(s)
1223
- */
1224
- globSync(patterns) {
1225
- const results = [];
1226
- for (const pattern of normalizeGlobPatterns(this.#context.workspaceConfig.workspaceRoot, patterns)) {
1227
- const normalized = this.#normalizePath(pattern);
1228
- if (!/[*?[\]{}]/.test(normalized) && !normalized.includes("*")) if (this.isDirectorySync(normalized)) results.push(...this.listSync(normalized));
1229
- else {
1230
- const resolved = this.resolveSync(normalized);
1231
- if (resolved && !results.includes(resolved)) results.push(resolved);
1232
- }
1233
- else {
1234
- const absPattern = (0, _stryke_path_is_type.isAbsolutePath)(normalized) ? normalized : this.#normalizePath((0, _stryke_path_append.appendPath)(normalized, this.#context.workspaceConfig.workspaceRoot));
1235
- const files = this.listSync((0, _stryke_path_correct_path.stripStars)(absPattern));
1236
- for (const file of files) if ((0, _stryke_path_glob_to_regex.globToRegex)(absPattern).test(file)) {
1237
- const resolved = this.resolveSync(file);
1238
- if (resolved && !results.includes(resolved)) results.push(resolved);
1239
- }
1240
- }
1241
- }
1242
- return results;
1243
- }
1244
- /**
1245
- * Copies a file from one path to another in the virtual file system (VFS).
1246
- *
1247
- * @param srcPath - The source path to copy
1248
- * @param destPath - The destination path to copy to
1249
- */
1250
- async copy(srcPath, destPath) {
1251
- const src = srcPath instanceof URL ? (0, node_url.fileURLToPath)(srcPath) : srcPath;
1252
- const dest = destPath instanceof URL ? (0, node_url.fileURLToPath)(destPath) : destPath;
1253
- 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;
1254
- const sourceStr = (0, _stryke_type_checks_is_string.isString)(src) ? src : src.input ? src.input : this.#context.workspaceConfig.workspaceRoot;
1255
- const source = await this.resolve(sourceStr);
1256
- if (!source) return;
1257
- 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) => {
1258
- return this.copy(file, (0, _stryke_path_append.appendPath)((0, _stryke_path_replace.replacePath)(file, sourceStr), dest));
1259
- }));
1260
- else {
1261
- const content = await this.read(source);
1262
- if (content !== void 0) await this.write(this.#normalizePath(dest), content, { skipFormat: true });
1263
- }
1264
- }
1265
- /**
1266
- * Synchronously copies a file from one path to another in the virtual file system (VFS).
1267
- *
1268
- * @param srcPath - The source path to copy
1269
- * @param destPath - The destination path to copy to
1270
- */
1271
- copySync(srcPath, destPath) {
1272
- const src = srcPath instanceof URL ? (0, node_url.fileURLToPath)(srcPath) : srcPath;
1273
- const dest = destPath instanceof URL ? (0, node_url.fileURLToPath)(destPath) : destPath;
1274
- 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;
1275
- const sourceStr = (0, _stryke_type_checks_is_string.isString)(src) ? src : src.input ? src.input : this.#context.workspaceConfig.workspaceRoot;
1276
- const source = this.resolveSync(sourceStr);
1277
- if (!source) return;
1278
- 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) => {
1279
- return this.copySync(file, (0, _stryke_path_append.appendPath)((0, _stryke_path_file_path_fns.findFilePath)((0, _stryke_path_replace.replacePath)(file, sourceStr)), dest));
1280
- });
1281
- else {
1282
- const content = this.readSync(source);
1283
- 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 });
1284
- }
1285
- }
1286
- /**
1287
- * Moves a file (or files) from one path to another in the virtual file system (VFS).
1288
- *
1289
- * @param srcPath - The source path to move
1290
- * @param destPath - The destination path to move to
1291
- */
1292
- async move(srcPath, destPath) {
1293
- if ((0, _stryke_path_file_path_fns.hasFileExtension)(srcPath)) {
1294
- await this.copy(srcPath, destPath);
1295
- await this.remove(srcPath);
1296
- } else await Promise.all((await this.list(srcPath)).map(async (file) => {
1297
- await this.copy(file, destPath);
1298
- await this.remove(file);
1299
- }));
1300
- }
1301
- /**
1302
- * Synchronously moves a file (or files) from one path to another in the virtual file system (VFS).
1303
- *
1304
- * @param srcPath - The source path to move
1305
- * @param destPath - The destination path to move to
1306
- */
1307
- moveSync(srcPath, destPath) {
1308
- if ((0, _stryke_path_file_path_fns.hasFileExtension)(srcPath)) {
1309
- this.copySync(srcPath, destPath);
1310
- this.removeSync(srcPath);
1311
- } else this.listSync(srcPath).forEach((file) => {
1312
- this.copySync(file, destPath);
1313
- this.removeSync(file);
1314
- });
1315
- }
1316
- /**
1317
- * Asynchronously reads a file from the virtual file system (VFS).
1318
- *
1319
- * @param path - The path or ID of the file to read.
1320
- * @returns A promise that resolves to the contents of the file as a string, or undefined if the file does not exist.
1321
- */
1322
- async read(path) {
1323
- const filePath = await this.resolve(path, void 0, { isFile: true });
1324
- if (!filePath || !this.existsSync(filePath)) return;
1325
- const { adapter } = this.#getStorage(filePath);
1326
- this.#log(_storm_software_config_tools_types.LogLevelLabel.TRACE, `Reading ${adapter.name} file: ${filePath}`);
1327
- return await adapter.get(filePath) ?? void 0;
1328
- }
1329
- /**
1330
- * Synchronously reads a file from the virtual file system (VFS).
1331
- *
1332
- * @param path - The path or ID of the file to read.
1333
- * @returns The contents of the file as a string, or undefined if the file does not exist.
1334
- */
1335
- readSync(path) {
1336
- const filePath = this.resolveSync(path, void 0, { isFile: true });
1337
- if (!filePath || !this.existsSync(filePath)) return;
1338
- const { adapter } = this.#getStorage(filePath);
1339
- this.#log(_storm_software_config_tools_types.LogLevelLabel.TRACE, `Reading ${adapter.name} file: ${filePath}`);
1340
- return adapter.getSync(filePath) ?? void 0;
1341
- }
1342
- /**
1343
- * Writes a file to the virtual file system (VFS).
1344
- *
1345
- * @param path - The path to the file.
1346
- * @param data - The contents of the file.
1347
- * @param options - Optional parameters for writing the file.
1348
- * @returns A promise that resolves when the file is written.
1349
- */
1350
- async write(path, data = "", options = {}) {
1351
- const meta = options.meta ?? {};
1352
- const resolvedPath = await this.resolve(this.#normalizePath(path)) || path;
1353
- const { relativeKey, adapter } = this.#getStorage(resolvedPath, options.storage);
1354
- this.#log(_storm_software_config_tools_types.LogLevelLabel.TRACE, `Writing ${resolvedPath} 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)})`);
1355
- let code = data;
1356
- try {
1357
- if (!options.skipFormat) code = await (0, require_utils.utils_exports.format)(this.#context, resolvedPath, data);
1358
- } catch (err) {
1359
- if (DEFAULT_EXTENSIONS.includes((0, _stryke_path_file_path_fns.findFileExtensionSafe)(resolvedPath, { fullExtension: true }))) this.#log(_storm_software_config_tools_types.LogLevelLabel.WARN, `Failed to format file ${resolvedPath} before writing: ${err.message}`);
1360
- code = data;
1361
- }
1362
- this.#log(_storm_software_config_tools_types.LogLevelLabel.TRACE, `Writing ${resolvedPath} 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)})`);
1363
- const id = this.#normalizeId(meta.id || resolvedPath);
1364
- this.metadata[id] = {
1365
- type: "normal",
1366
- timestamp: Date.now(),
1367
- ...this.metadata[id] ?? {},
1368
- ...meta
1369
- };
1370
- this.paths[id] = resolvedPath;
1371
- this.ids[resolvedPath] = id;
1372
- return adapter.set(relativeKey, code);
1373
- }
1374
- /**
1375
- * Synchronously writes a file to the virtual file system (VFS).
1376
- *
1377
- * @param path - The file to write.
1378
- * @param data - The contents of the file.
1379
- * @param options - Optional parameters for writing the file.
1380
- */
1381
- writeSync(path, data = "", options = {}) {
1382
- const meta = options.meta ?? {};
1383
- const resolvedPath = this.resolveSync(this.#normalizePath(path)) || path;
1384
- const { relativeKey, adapter } = this.#getStorage(resolvedPath, options.storage);
1385
- this.#log(_storm_software_config_tools_types.LogLevelLabel.TRACE, `Writing ${resolvedPath} 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)})`);
1386
- const id = this.#normalizeId(meta.id || resolvedPath);
1387
- this.metadata[id] = {
1388
- type: "normal",
1389
- timestamp: Date.now(),
1390
- ...this.metadata[id] ?? {},
1391
- ...meta
1392
- };
1393
- this.paths[id] = resolvedPath;
1394
- this.ids[resolvedPath] = id;
1395
- return adapter.setSync(relativeKey, data);
1396
- }
1397
- /**
1398
- * Synchronously creates a directory at the specified path.
1399
- *
1400
- * @param dirPath - The path of the directory to create.
1401
- */
1402
- mkdirSync(dirPath) {
1403
- return this.#getStorage(dirPath)?.adapter?.mkdirSync(dirPath);
1404
- }
1405
- /**
1406
- * Creates a directory at the specified path.
1407
- *
1408
- * @param path - The path of the directory to create.
1409
- */
1410
- async mkdir(path) {
1411
- return this.#getStorage(path)?.adapter?.mkdir(path);
1412
- }
1413
- /**
1414
- * Retrieves the metadata of a file in the virtual file system (VFS).
1415
- *
1416
- * @param pathOrId - The path or ID of the file to retrieve metadata for.
1417
- * @returns The metadata of the file, or undefined if the file does not exist.
1418
- */
1419
- getMetadata(pathOrId) {
1420
- const resolved = this.resolveSync(pathOrId);
1421
- if (resolved && this.metadata[resolved]) return this.metadata[resolved];
1422
- }
1423
- /**
1424
- * Resolves a given module ID using the configured aliases.
1425
- *
1426
- * @remarks
1427
- * This function can be used to map module IDs to different paths based on the alias configuration.
1428
- *
1429
- * @param id - The module ID to resolve.
1430
- * @returns The resolved module ID - after applying any configured aliases (this will be the same as the input ID if no aliases match).
1431
- */
1432
- resolveAlias(id) {
1433
- let path = id;
1434
- if (this.#context.config.resolve.alias) {
1435
- if (Array.isArray(this.#context.config.resolve.alias) && this.#context.config.resolve.alias.length > 0) {
1436
- const found = this.#context.config.resolve.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));
1437
- if (found.length > 0) {
1438
- const alias = found.reduce((ret, current) => {
1439
- 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;
1440
- });
1441
- if ((0, _stryke_type_checks_is_set_string.isSetString)(alias.find)) path = path.replace(new RegExp(`^${alias.find}`), alias.replacement);
1442
- else if ((0, _stryke_type_checks_is_regexp.isRegExp)(alias.find)) path = path.replace(alias.find, alias.replacement);
1443
- }
1444
- } else if ((0, _stryke_type_checks_is_set_object.isSetObject)(this.#context.config.resolve.alias)) {
1445
- const found = Object.keys(this.#context.config.resolve.alias).filter((key) => key === path || path.startsWith(`${key}/`));
1446
- if (found.length > 0) {
1447
- const alias = found.reduce((ret, current) => {
1448
- return ret.length > current.length ? ret : current;
1449
- });
1450
- path = path.replace(new RegExp(`^${alias}`), this.#context.config.resolve.alias[alias]);
1451
- }
1452
- }
1453
- }
1454
- return path;
1455
- }
1456
- /**
1457
- * Checks if a given module ID is an alias.
1458
- *
1459
- * @remarks
1460
- * This function can be used to determine if a module ID matches any configured aliases.
1461
- *
1462
- * @param id - The module ID to check.
1463
- * @returns A boolean indicating whether the module ID is an alias.
1464
- */
1465
- isAlias(id) {
1466
- const path = id;
1467
- if (this.#context.config.resolve.alias) {
1468
- if (Array.isArray(this.#context.config.resolve.alias) && this.#context.config.resolve.alias.length > 0) return this.#context.config.resolve.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)).length > 0;
1469
- else if ((0, _stryke_type_checks_is_set_object.isSetObject)(this.#context.config.resolve.alias)) return Object.keys(this.#context.config.resolve.alias).filter((key) => key === path || path.startsWith(`${key}/`)).length > 0;
1470
- }
1471
- return false;
1472
- }
1473
- /**
1474
- * Checks if a given module ID is a tsconfig path.
1475
- *
1476
- * @remarks
1477
- * This function can be used to determine if a module ID matches any configured tsconfig paths.
1478
- *
1479
- * @param id - The module ID to check.
1480
- * @returns A boolean indicating whether the module ID is a tsconfig path.
1481
- */
1482
- isTsconfigPath(id) {
1483
- return !!(this.#context.tsconfig.options.paths && Object.keys(this.#context.tsconfig.options.paths).length > 0 && (0, bundle_require.match)(id, this.#context.resolvePatterns));
1484
- }
1485
- /**
1486
- * A helper function to resolve modules in the virtual file system (VFS).
1487
- *
1488
- * @remarks
1489
- * This function can be used to resolve modules relative to the project root directory.
1490
- *
1491
- * @example
1492
- * ```ts
1493
- * const resolved = await context.resolvePath("some-module", "/path/to/importer");
1494
- * ```
1495
- *
1496
- * @param id - The module to resolve.
1497
- * @param importer - An optional path to the importer module.
1498
- * @param options - Additional resolution options.
1499
- * @returns A promise that resolves to the resolved module path.
1500
- */
1501
- async resolve(id, importer, options = {}) {
1502
- const origResult = await this.#innerResolve(id, importer, options);
1503
- if (origResult && options.isFile && await this.isDirectory(origResult)) {
1504
- const indexResult = await this.resolve((0, _stryke_path_join.joinPaths)(origResult, "index"), importer, options);
1505
- if (indexResult) return indexResult;
1506
- if (!(0, _stryke_path_file_path_fns.hasFileExtension)(origResult)) for (const ext of DEFAULT_EXTENSIONS) {
1507
- const extResult = await this.resolve(`${origResult}.${ext}`, importer, options);
1508
- if (extResult) return extResult;
1509
- }
1510
- return;
1511
- }
1512
- return origResult;
1513
- }
1514
- /**
1515
- * A synchronous helper function to resolve modules using the Jiti resolver
1516
- *
1517
- * @remarks
1518
- * This function can be used to resolve modules relative to the project root directory.
1519
- *
1520
- * @example
1521
- * ```ts
1522
- * const resolvedPath = context.resolveSync("some-module", "/path/to/importer");
1523
- * ```
1524
- *
1525
- * @param id - The module to resolve.
1526
- * @param importer - An optional path to the importer module.
1527
- * @param options - Additional resolution options.
1528
- * @returns The resolved module path.
1529
- */
1530
- resolveSync(id, importer, options = {}) {
1531
- const origResult = this.#innerResolveSync(id, importer, options);
1532
- if (origResult && options.isFile && this.isDirectorySync(origResult)) {
1533
- const indexResult = this.resolveSync((0, _stryke_path_join.joinPaths)(origResult, "index"), importer, options);
1534
- if (indexResult) return indexResult;
1535
- if (!(0, _stryke_path_file_path_fns.hasFileExtension)(origResult)) for (const ext of DEFAULT_EXTENSIONS) {
1536
- const extResult = this.resolveSync(`${origResult}.${ext}`, importer, options);
1537
- if (extResult) return extResult;
1538
- }
1539
- return;
1540
- }
1541
- return origResult;
1542
- }
1543
- /**
1544
- * Disposes of the virtual file system (VFS) by saving its state to disk.
1545
- */
1546
- async dispose() {
1547
- if (!this.#isDisposed) {
1548
- this.#isDisposed = true;
1549
- this.#log(_storm_software_config_tools_types.LogLevelLabel.DEBUG, "Disposing virtual file system...");
1550
- await this.remove((0, _stryke_path_join.joinPaths)(this.#context.dataPath, "fs.bin"));
1551
- const message = new _stryke_capnp.Message();
1552
- const fs = message.initRoot(FileSystem);
1553
- const storage = fs._initStorage(Object.keys(this.#paths).length);
1554
- await Promise.all(Object.values(this.#paths).map(async (path, index) => {
1555
- const code = await this.read(path);
1556
- const fd = storage.get(index);
1557
- fd.path = path;
1558
- fd.code = code || "";
1559
- }));
1560
- const ids = fs._initIds(Object.keys(this.#ids).length);
1561
- Object.entries(this.#ids).filter(([, id]) => id).forEach(([path, id], index) => {
1562
- const fileId = ids.get(index);
1563
- fileId.id = id;
1564
- fileId.path = path;
1565
- });
1566
- const metadata = fs._initMetadata(Object.keys(this.#metadata).length);
1567
- Object.entries(this.#metadata).filter(([, value]) => value).forEach(([id, value], index) => {
1568
- const fileMetadata = metadata.get(index);
1569
- fileMetadata.id = id;
1570
- fileMetadata.type = value.type;
1571
- fileMetadata.timestamp = value.timestamp ?? Date.now();
1572
- if (value.properties) {
1573
- const props = fileMetadata._initProperties(Object.keys(value.properties).length);
1574
- Object.entries(value.properties).filter(([, val]) => (0, _stryke_type_checks_is_set_string.isSetString)(val)).forEach(([key, val], index) => {
1575
- const prop = props.get(index);
1576
- prop.key = key;
1577
- prop.value = val;
1578
- });
1579
- }
1580
- });
1581
- await (0, _stryke_fs_buffer.writeFileBuffer)((0, _stryke_path_join.joinPaths)(this.#context.dataPath, "fs.bin"), message.toArrayBuffer());
1582
- if (!this.#context.config.skipCache) this.resolverCache.save(true);
1583
- await Promise.all(this.#getStorages().map(async (storage) => storage.adapter.dispose()));
1584
- this.#log(_storm_software_config_tools_types.LogLevelLabel.TRACE, "Virtual file system has been disposed.");
1585
- }
1586
- }
1587
- async [Symbol.asyncDispose]() {
1588
- return this.dispose();
1589
- }
1590
- };
1591
-
1592
- //#endregion
1593
- //#region src/context/context.ts
1594
- const configCache = /* @__PURE__ */ new WeakMap();
1595
- const envPathCache = /* @__PURE__ */ new WeakMap();
1596
- (0, undici.setGlobalDispatcher)(new undici.Agent({ keepAliveTimeout: 1e4 }).compose(undici.interceptors.retry({
1597
- maxRetries: 3,
1598
- minTimeout: 1e3,
1599
- maxTimeout: 1e4,
1600
- timeoutFactor: 2,
1601
- retryAfter: true
1602
- })));
1603
- var PowerlinesContext = class PowerlinesContext {
1604
- /**
1605
- * Internal references storage
1606
- *
1607
- * @danger
1608
- * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
1609
- *
1610
- * @internal
1611
- */
1612
- #internal = {};
1613
- #workspaceConfig;
1614
- #checksum = null;
1615
- #buildId = (0, _stryke_unique_id_uuid.uuid)();
1616
- #releaseId = (0, _stryke_unique_id_uuid.uuid)();
1617
- #timestamp = Date.now();
1618
- #fs;
1619
- #tsconfig;
1620
- #parserCache;
1621
- #requestCache;
1622
- #getConfigProps(config = {}) {
1623
- return (0, require_plugin_utils.plugin_utils_exports.mergeConfig)({
1624
- root: config.root,
1625
- name: config.name,
1626
- title: config.title,
1627
- organization: config.organization,
1628
- compatibilityDate: (0, compatx.resolveCompatibilityDates)(config.compatibilityDate, "latest"),
1629
- description: config.description,
1630
- configFile: config.configFile,
1631
- projectType: config.projectType,
1632
- customLogger: config.customLogger,
1633
- logLevel: config.logLevel,
1634
- tsconfig: config.tsconfig,
1635
- tsconfigRaw: config.tsconfigRaw,
1636
- skipCache: config.skipCache,
1637
- autoInstall: config.autoInstall,
1638
- input: (0, _stryke_type_checks_is_set_string.isSetString)(config.input) ? [config.input] : config.input,
1639
- plugins: config.plugins,
1640
- mode: config.mode,
1641
- resolve: config.resolve,
1642
- framework: config.framework,
1643
- ...config,
1644
- output: {
1645
- ...config.output ?? {},
1646
- path: config.output?.path ? (0, _stryke_path_append.appendPath)(config.output.path, config.root) : void 0
1647
- }
1648
- }, { output: config.framework ? {
1649
- artifactsPath: `.${config.framework ?? "powerlines"}`,
1650
- dts: true,
1651
- types: (0, _stryke_path_join.joinPaths)(config.root ?? this.config.root, `${config.framework ?? "powerlines"}.d.ts`)
1652
- } : {} });
1653
- }
1654
- /**
1655
- * Create a new Storm context from the workspace root and user config.
1656
- *
1657
- * @param workspaceRoot - The root directory of the workspace.
1658
- * @param config - The user configuration options.
1659
- * @returns A promise that resolves to the new context.
1660
- */
1661
- static async from(workspaceRoot, config) {
1662
- const context = new PowerlinesContext(await (0, require_config.config_exports.loadWorkspaceConfig)(workspaceRoot, config.root));
1663
- await context.withUserConfig(config);
1664
- const powerlinesPath = await (0, _stryke_fs_resolve.resolvePackage)("powerlines");
1665
- if (!powerlinesPath) throw new Error("Could not resolve `powerlines` package location.");
1666
- context.powerlinesPath = powerlinesPath;
1667
- return context;
1668
- }
1669
- /**
1670
- * An object containing the dependencies that should be installed for the project
1671
- */
1672
- dependencies = {};
1673
- /**
1674
- * An object containing the development dependencies that should be installed for the project
1675
- */
1676
- devDependencies = {};
1677
- /**
1678
- * The persisted meta information about the current build
1679
- */
1680
- persistedMeta = void 0;
1681
- /**
1682
- * The path to the Powerlines package
1683
- */
1684
- powerlinesPath;
1685
- /**
1686
- * The parsed `package.json` file for the project
1687
- */
1688
- packageJson;
1689
- /**
1690
- * The parsed `project.json` file for the project
1691
- */
1692
- projectJson = void 0;
1693
- /**
1694
- * The module resolver for the project
1695
- */
1696
- resolver;
1697
- /**
1698
- * The resolved tsconfig file paths for the project
1699
- */
1700
- resolvePatterns = [];
1701
- /**
1702
- * Internal context fields and methods
1703
- *
1704
- * @danger
1705
- * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
1706
- *
1707
- * @internal
1708
- */
1709
- get $$internal() {
1710
- return this.#internal;
1711
- }
1712
- /**
1713
- * Internal context fields and methods
1714
- *
1715
- * @danger
1716
- * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
1717
- *
1718
- * @internal
1719
- */
1720
- set $$internal(value) {
1721
- this.#internal = value;
1722
- }
1723
- /**
1724
- * The resolved entry type definitions for the project
1725
- */
1726
- get entry() {
1727
- const entry = this.resolvedEntry;
1728
- return (0, require_utils.utils_exports.resolveInputsSync)(this, entry && entry.length > 0 ? entry : Array.isArray(this.config.input) || (0, _stryke_type_checks_is_set_object.isSetObject)(this.config.input) && !(0, require_utils.utils_exports.isTypeDefinition)(this.config.input) ? this.config.input : (0, _stryke_convert_to_array.toArray)(this.config.input).flat());
1729
- }
1730
- /**
1731
- * The TypeScript configuration parsed from the tsconfig file
1732
- */
1733
- get tsconfig() {
1734
- if (!this.#tsconfig) this.tsconfig = { tsconfigFilePath: this.config.tsconfig };
1735
- return this.#tsconfig;
1736
- }
1737
- /**
1738
- * Sets the TypeScript configuration parsed from the tsconfig file
1739
- */
1740
- set tsconfig(value) {
1741
- this.#tsconfig = value;
1742
- this.resolvePatterns = (0, bundle_require.tsconfigPathsToRegExp)(value?.options?.paths ?? {});
1743
- }
1744
- /**
1745
- * The virtual file system interface for the project
1746
- */
1747
- get fs() {
1748
- if (!this.#fs) this.#fs = VirtualFileSystem.createSync(this);
1749
- return this.#fs;
1750
- }
1751
- /**
1752
- * Get the checksum of the project's current state
1753
- */
1754
- get checksum() {
1755
- return this.#checksum;
1756
- }
1757
- /**
1758
- * The meta information about the current build
1759
- */
1760
- get meta() {
1761
- return {
1762
- buildId: this.#buildId,
1763
- releaseId: this.#releaseId,
1764
- checksum: this.#checksum,
1765
- timestamp: this.#timestamp,
1766
- rootHash: (0, _stryke_hash.murmurhash)({
1767
- workspaceRoot: this.workspaceConfig?.workspaceRoot,
1768
- root: this.config?.root
1769
- }, { maxLength: require_constants.constants_exports.ROOT_HASH_LENGTH }),
1770
- configHash: (0, _stryke_hash.murmurhash)(this.config, { maxLength: require_constants.constants_exports.CACHE_HASH_LENGTH })
1771
- };
1772
- }
1773
- /**
1774
- * The resolved configuration options
1775
- */
1776
- get config() {
1777
- return this.resolvedConfig ?? {};
1778
- }
1779
- /**
1780
- * The logger function
1781
- */
1782
- get log() {
1783
- const level = this.config.logLevel || "info";
1784
- if (!this.logger || this.logger.level !== level) this.logger = {
1785
- log: this.createLog(),
1786
- level
1787
- };
1788
- return this.logger.log;
1789
- }
1790
- /**
1791
- * The workspace configuration
1792
- */
1793
- get workspaceConfig() {
1794
- return this.#workspaceConfig;
1795
- }
1796
- /**
1797
- * The environment paths for the project
1798
- */
1799
- get envPaths() {
1800
- if (envPathCache.has({
1801
- workspaceRoot: this.workspaceConfig.workspaceRoot,
1802
- framework: this.config?.framework || "powerlines"
1803
- })) return envPathCache.get({
1804
- workspaceRoot: this.workspaceConfig.workspaceRoot,
1805
- framework: this.config?.framework || "powerlines"
1806
- });
1807
- const envPaths = (0, _stryke_env_get_env_paths.getEnvPaths)({
1808
- orgId: "storm-software",
1809
- appId: this.config?.framework || "powerlines",
1810
- workspaceRoot: this.workspaceConfig.workspaceRoot
1811
- });
1812
- envPathCache.set({
1813
- workspaceRoot: this.workspaceConfig.workspaceRoot,
1814
- framework: this.config?.framework || "powerlines"
1815
- }, envPaths);
1816
- return envPaths;
1817
- }
1818
- /**
1819
- * Get the path to the artifacts directory for the project
1820
- */
1821
- get artifactsPath() {
1822
- return (0, _stryke_path_join.joinPaths)(this.workspaceConfig.workspaceRoot, this.config.root, this.config.output.artifactsPath);
1823
- }
1824
- /**
1825
- * Get the path to the builtin modules used by the project
1826
- */
1827
- get builtinsPath() {
1828
- return (0, _stryke_path_join.joinPaths)(this.artifactsPath, "builtins");
1829
- }
1830
- /**
1831
- * Get the path to the entry directory for the project
1832
- */
1833
- get entryPath() {
1834
- return (0, _stryke_path_join.joinPaths)(this.artifactsPath, "entry");
1835
- }
1836
- /**
1837
- * Get the path to the infrastructure modules used by the project
1838
- */
1839
- get infrastructurePath() {
1840
- return (0, _stryke_path_join.joinPaths)(this.artifactsPath, "infrastructure");
1841
- }
1842
- /**
1843
- * Get the path to the data directory for the project
1844
- */
1845
- get dataPath() {
1846
- return (0, _stryke_path_join.joinPaths)(this.envPaths.data, "projects", getPrefixedRootHash(this.config.name, this.meta.rootHash));
1847
- }
1848
- /**
1849
- * Get the path to the cache directory for the project
1850
- */
1851
- get cachePath() {
1852
- return (0, _stryke_path_join.joinPaths)(this.envPaths.cache, "projects", (0, _stryke_hash.murmurhash)({
1853
- checksum: this.#checksum,
1854
- config: this.meta.configHash
1855
- }, { maxLength: require_constants.constants_exports.CACHE_HASH_LENGTH }));
1856
- }
1857
- /**
1858
- * Get the path to the generated declaration file for the project
1859
- */
1860
- get typesPath() {
1861
- return this.config.output.types ? (0, _stryke_path_append.appendPath)(this.config.output.types, this.workspaceConfig.workspaceRoot) : (0, _stryke_path_join.joinPaths)(this.workspaceConfig.workspaceRoot, this.config.root, "powerlines.d.ts");
1862
- }
1863
- /**
1864
- * Get the project root relative to the workspace root
1865
- */
1866
- get relativeToWorkspaceRoot() {
1867
- return (0, _stryke_fs_get_workspace_root.relativeToWorkspaceRoot)(this.config.root);
1868
- }
1869
- /**
1870
- * The builtin module id that exist in the Powerlines virtual file system
1871
- */
1872
- get builtins() {
1873
- return Object.values(this.fs.metadata).filter((meta) => meta && meta.type === "builtin").map((meta) => meta?.id).filter(Boolean);
1874
- }
1875
- /**
1876
- * The alias mappings for the project used during module resolution
1877
- *
1878
- * @remarks
1879
- * This includes both the built-in module aliases as well as any custom aliases defined in the build configuration.
1880
- */
1881
- get alias() {
1882
- return this.builtins.reduce((ret, id) => {
1883
- const moduleId = `${this.config?.framework || "powerlines"}:${id.replace(/^.*:/, "")}`;
1884
- if (!ret[moduleId]) {
1885
- const path = this.fs.paths[id];
1886
- if (path) ret[moduleId] = path;
1887
- }
1888
- return ret;
1889
- }, this.config.resolve.alias ? Array.isArray(this.config.resolve.alias) ? this.config.resolve.alias.reduce((ret, alias) => {
1890
- if (!ret[alias.find.toString()]) ret[alias.find.toString()] = alias.replacement;
1891
- return ret;
1892
- }, {}) : this.config.resolve.alias : {});
1893
- }
1894
- /**
1895
- * Gets the parser cache.
1896
- */
1897
- get parserCache() {
1898
- if (!this.#parserCache) this.#parserCache = (0, flat_cache.create)({
1899
- cacheId: "parser",
1900
- cacheDir: this.cachePath,
1901
- ttl: 7200 * 1e3,
1902
- lruSize: 5e3,
1903
- persistInterval: 250
1904
- });
1905
- return this.#parserCache;
1906
- }
1907
- /**
1908
- * Gets the request cache.
1909
- */
1910
- get requestCache() {
1911
- if (!this.#requestCache) this.#requestCache = (0, flat_cache.create)({
1912
- cacheId: "http",
1913
- cacheDir: this.cachePath,
1914
- ttl: 360 * 60 * 1e3,
1915
- lruSize: 5e3,
1916
- persistInterval: 250
1917
- });
1918
- return this.#requestCache;
1919
- }
1920
- /**
1921
- * The entry points that exist in the Powerlines virtual file system
1922
- */
1923
- get resolvedEntry() {
1924
- return Object.entries(this.fs.metadata).filter(([, meta]) => meta && meta.type === "entry").map(([path, meta]) => {
1925
- const typeDefinition = { file: path };
1926
- if (meta.properties) {
1927
- if ((0, _stryke_type_checks_is_set_string.isSetString)(meta.properties.file)) typeDefinition.file = meta.properties.file;
1928
- if ((0, _stryke_type_checks_is_set_string.isSetString)(meta.properties.name)) typeDefinition.name = meta.properties.name;
1929
- if ((0, _stryke_type_checks_is_set_string.isSetString)(meta.properties["input.file"]) || (0, _stryke_type_checks_is_set_string.isSetString)(meta.properties["input.name"])) {
1930
- typeDefinition.input ??= {};
1931
- if ((0, _stryke_type_checks_is_set_string.isSetString)(meta.properties["input.file"])) typeDefinition.input.file = meta.properties["input.file"];
1932
- if ((0, _stryke_type_checks_is_set_string.isSetString)(meta.properties["input.name"])) typeDefinition.input.name = meta.properties["input.name"];
1933
- }
1934
- if ((0, _stryke_type_checks_is_set_string.isSetString)(meta.properties.output)) typeDefinition.output = meta.properties.output;
1935
- }
1936
- return typeDefinition;
1937
- }).filter(Boolean);
1938
- }
1939
- /**
1940
- * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.
1941
- *
1942
- * @remarks
1943
- * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.
1944
- *
1945
- * @returns A promise that resolves to the cloned context.
1946
- */
1947
- async clone() {
1948
- const clone = await PowerlinesContext.from(this.workspaceConfig.workspaceRoot, this.config);
1949
- await clone.withUserConfig(this.config);
1950
- return this.copyTo(clone);
1951
- }
1952
- /**
1953
- * A function to perform HTTP fetch requests
1954
- *
1955
- * @remarks
1956
- * This function uses a caching layer to avoid duplicate requests during the Powerlines process.
1957
- *
1958
- * @example
1959
- * ```ts
1960
- * const response = await context.fetch("https://api.example.com/data");
1961
- * const data = await response.json();
1962
- * ```
1963
- *
1964
- * @see https://github.com/nodejs/undici
1965
- *
1966
- * @param input - The URL to fetch.
1967
- * @param options - The fetch request options.
1968
- * @returns A promise that resolves to a response returned by the fetch.
1969
- */
1970
- async fetch(input, options = {}) {
1971
- const cacheKey = (0, _stryke_hash.murmurhash)({
1972
- input: input.toString(),
1973
- options: JSON.stringify(options)
1974
- });
1975
- if (!this.config.skipCache && !options.skipCache) {
1976
- const cached = this.requestCache.get(cacheKey);
1977
- if (cached) return new undici.Response(cached.body, {
1978
- status: cached.status,
1979
- statusText: cached.statusText,
1980
- headers: cached.headers
1981
- });
1982
- }
1983
- const response = await (0, _stryke_http_fetch.fetchRequest)(input, {
1984
- timeout: 12e3,
1985
- ...options
1986
- });
1987
- const result = {
1988
- body: await response.text(),
1989
- status: response.status,
1990
- statusText: response.statusText,
1991
- headers: Object.fromEntries(response.headers.entries())
1992
- };
1993
- if (!this.config.skipCache && !options.skipCache) try {
1994
- this.requestCache.set(cacheKey, result);
1995
- } catch {}
1996
- return new undici.Response(result.body, {
1997
- status: result.status,
1998
- statusText: result.statusText,
1999
- headers: result.headers
2000
- });
2001
- }
2002
- /**
2003
- * Parse code using [Oxc-Parser](https://github.com/oxc/oxc) into an (ESTree-compatible)[https://github.com/estree/estree] AST object.
2004
- *
2005
- * @remarks
2006
- * This function can be used to parse TypeScript code into an AST for further analysis or transformation.
2007
- *
2008
- * @example
2009
- * ```ts
2010
- * const ast = context.parse("const x: number = 42;");
2011
- * ```
2012
- *
2013
- * @see https://rollupjs.org/plugin-development/#this-parse
2014
- * @see https://github.com/oxc/oxc
2015
- *
2016
- * @param code - The source code to parse.
2017
- * @param options - The options to pass to the parser.
2018
- * @returns An (ESTree-compatible)[https://github.com/estree/estree] AST object.
2019
- */
2020
- async parse(code, options = {}) {
2021
- const cacheKey = (0, _stryke_hash.murmurhash)({
2022
- code,
2023
- options
2024
- });
2025
- let result;
2026
- if (!this.config.skipCache) {
2027
- result = this.parserCache.get(cacheKey);
2028
- if (result) return result;
2029
- }
2030
- result = await (0, oxc_parser.parse)(`source.${options.lang || "ts"}`, code, {
2031
- ...options,
2032
- sourceType: "module",
2033
- showSemanticErrors: this.config.mode === "development"
2034
- });
2035
- if (!this.config.skipCache) this.parserCache.set(cacheKey, result);
2036
- return result;
2037
- }
2038
- /**
2039
- * A helper function to resolve modules in the Virtual File System
2040
- *
2041
- * @remarks
2042
- * This function can be used to resolve modules relative to the project root directory.
2043
- *
2044
- * @example
2045
- * ```ts
2046
- * const resolved = await context.resolve("some-module", "/path/to/importer");
2047
- * ```
2048
- *
2049
- * @param id - The module to resolve.
2050
- * @param importer - An optional path to the importer module.
2051
- * @param options - Additional resolution options.
2052
- * @returns A promise that resolves to the resolved module path.
2053
- */
2054
- async resolve(id, importer, options = {}) {
2055
- let moduleId = id;
2056
- if (this.config.resolve.alias) {
2057
- if (Array.isArray(this.config.resolve.alias)) {
2058
- const alias = this.config.resolve.alias.find((a) => (0, bundle_require.match)(moduleId, [a.find]));
2059
- if (alias) moduleId = alias.replacement;
2060
- } else if ((0, _stryke_type_checks_is_set_object.isSetObject)(this.config.resolve.alias) && this.config.resolve.alias[id]) moduleId = this.config.resolve.alias[id];
2061
- }
2062
- if (this.fs.isResolvableId(moduleId) || importer && this.fs.isResolvableId(importer)) {
2063
- let resolvedImporter = importer;
2064
- if (importer && this.fs.isResolvableId(importer)) resolvedImporter = await this.fs.resolve(importer, void 0, (0, defu.default)({
2065
- conditions: this.config.resolve.conditions,
2066
- extensions: this.config.resolve.extensions
2067
- }, options));
2068
- const result = await this.fs.resolve(moduleId, resolvedImporter, (0, defu.default)({
2069
- conditions: this.config.resolve.conditions,
2070
- extensions: this.config.resolve.extensions
2071
- }, options));
2072
- if (!result) return;
2073
- const external = Boolean(!(0, bundle_require.match)(moduleId, this.config.resolve.noExternal) && ((0, bundle_require.match)(moduleId, this.config.resolve.external) || moduleId.startsWith("node:") || (!this.fs.isVirtual(moduleId, importer, options) || this.fs.isVirtual(moduleId, importer, options) && this.config.projectType !== "application") && this.config.resolve.skipNodeModulesBundle && !/^[A-Z]:[/\\]|^\.{0,2}\/|^\.{1,2}$/.test(moduleId)));
2074
- return {
2075
- id: result,
2076
- external,
2077
- virtual: !external
2078
- };
2079
- }
2080
- if (this.config.resolve.skipNodeModulesBundle) {
2081
- if ((0, bundle_require.match)(moduleId, this.resolvePatterns) || (0, bundle_require.match)(moduleId, this.config.resolve.noExternal)) return;
2082
- if ((0, bundle_require.match)(moduleId, this.config.resolve.external) || moduleId.startsWith("node:")) return {
2083
- id: moduleId,
2084
- external: true,
2085
- virtual: false
2086
- };
2087
- if (!/^[A-Z]:[/\\]|^\.{0,2}\/|^\.{1,2}$/.test(moduleId)) return {
2088
- id: moduleId,
2089
- external: true,
2090
- virtual: false
2091
- };
2092
- } else {
2093
- if ((0, bundle_require.match)(moduleId, this.config.resolve.noExternal)) return;
2094
- if ((0, bundle_require.match)(moduleId, this.config.resolve.external) || moduleId.startsWith("node:")) return {
2095
- id: moduleId,
2096
- external: true,
2097
- virtual: false
2098
- };
2099
- }
2100
- }
2101
- /**
2102
- * A helper function to load modules from the Virtual File System
2103
- *
2104
- * @remarks
2105
- * This function can be used to load modules relative to the project root directory.
2106
- *
2107
- * @example
2108
- * ```ts
2109
- * const module = await context.load("some-module", "/path/to/importer");
2110
- * ```
2111
- *
2112
- * @param id - The module to load.
2113
- * @returns A promise that resolves to the loaded module.
2114
- */
2115
- async load(id) {
2116
- const resolvedId = await this.fs.resolve(id);
2117
- if (!resolvedId) return;
2118
- const code = await this.fs.read(resolvedId);
2119
- if (!code) return;
2120
- return {
2121
- code,
2122
- map: null
2123
- };
2124
- }
2125
- /**
2126
- * Get the builtin virtual files that exist in the Powerlines virtual file system
2127
- */
2128
- async getBuiltins() {
2129
- return Promise.all(Object.entries(this.fs.metadata).filter(([, meta]) => meta && meta.type === "builtin").map(async ([id, meta]) => {
2130
- const code = await this.fs.read(id);
2131
- const path = this.fs.paths[id];
2132
- return {
2133
- ...meta,
2134
- path,
2135
- code
2136
- };
2137
- }));
2138
- }
2139
- /**
2140
- * Resolves a file and writes it to the VFS if it does not already exist
2141
- *
2142
- * @param code - The source code of the file
2143
- * @param path - The path to write the file to
2144
- * @param options - Additional options for writing the file
2145
- */
2146
- async emit(code, path, options = {}) {
2147
- const filePath = options.extension ? (0, _stryke_path_file_path_fns.findFileExtensionSafe)(path) ? options.extension.startsWith(".") ? path.replace((0, _stryke_path_file_path_fns.findFileDotExtensionSafe)(path), options.extension) : path.replace((0, _stryke_path_file_path_fns.findFileExtensionSafe)(path), options.extension) : options.extension.startsWith(".") ? `${path}${options.extension}` : `${path}.${options.extension}` : (0, _stryke_path_file_path_fns.findFileExtensionSafe)(path) ? path : `${path}.ts`;
2148
- if ((0, _stryke_type_checks_is_function.isFunction)(this.emitFile) && options.emitWithBundler) return this.emitFile({
2149
- needsCodeReference: options.needsCodeReference,
2150
- originalFileName: options.originalFileName,
2151
- fileName: filePath,
2152
- source: code,
2153
- type: "asset"
2154
- });
2155
- return this.fs.write(filePath, code, options);
2156
- }
2157
- /**
2158
- * Synchronously resolves a file and writes it to the VFS if it does not already exist
2159
- *
2160
- * @param code - The source code of the file
2161
- * @param path - The path to write the file to
2162
- * @param options - Additional options for writing the file
2163
- */
2164
- emitSync(code, path, options = {}) {
2165
- const filePath = options.extension ? (0, _stryke_path_file_path_fns.findFileExtensionSafe)(path) ? options.extension.startsWith(".") ? path.replace((0, _stryke_path_file_path_fns.findFileDotExtensionSafe)(path), options.extension) : path.replace((0, _stryke_path_file_path_fns.findFileExtensionSafe)(path), options.extension) : options.extension.startsWith(".") ? `${path}${options.extension}` : `${path}.${options.extension}` : (0, _stryke_path_file_path_fns.findFileExtensionSafe)(path) ? path : `${path}.ts`;
2166
- if ((0, _stryke_type_checks_is_function.isFunction)(this.emitFile) && options.emitWithBundler) return this.emitFile({
2167
- needsCodeReference: options.needsCodeReference,
2168
- originalFileName: options.originalFileName,
2169
- fileName: filePath,
2170
- source: code,
2171
- type: "asset"
2172
- });
2173
- return this.fs.writeSync(filePath, code, options);
2174
- }
2175
- /**
2176
- * Resolves a entry virtual file and writes it to the VFS if it does not already exist
2177
- *
2178
- * @param code - The source code of the entry file
2179
- * @param path - A path to write the entry file to
2180
- * @param options - Optional write file options
2181
- */
2182
- async emitEntry(code, path, options = {}) {
2183
- return this.emit(code, (0, _stryke_path_append.appendPath)(path, this.entryPath), (0, defu.default)({ meta: {
2184
- type: "entry",
2185
- properties: {
2186
- file: (0, _stryke_path_append.appendPath)(path, this.entryPath),
2187
- name: options?.name,
2188
- output: options?.output,
2189
- "input.file": options?.input?.file,
2190
- "input.name": options?.input?.name
2191
- }
2192
- } }, (0, _stryke_helpers_omit.omit)(options, ["name"])));
2193
- }
2194
- /**
2195
- * Synchronously resolves a entry virtual file and writes it to the VFS if it does not already exist
2196
- *
2197
- * @param code - The source code of the entry file
2198
- * @param path - A path to write the entry file to
2199
- * @param options - Optional write file options
2200
- */
2201
- emitEntrySync(code, path, options = {}) {
2202
- return this.emitSync(code, (0, _stryke_path_append.appendPath)(path, this.entryPath), (0, defu.default)({ meta: {
2203
- type: "entry",
2204
- properties: {
2205
- file: (0, _stryke_path_append.appendPath)(path, this.entryPath),
2206
- name: options?.name,
2207
- output: options?.output,
2208
- "input.file": options?.input?.file,
2209
- "input.name": options?.input?.name
2210
- }
2211
- } }, (0, _stryke_helpers_omit.omit)(options, ["name"])));
2212
- }
2213
- /**
2214
- * Resolves a builtin virtual file and writes it to the VFS if it does not already exist
2215
- *
2216
- * @param code - The source code of the builtin file
2217
- * @param id - The unique identifier of the builtin file
2218
- * @param options - Optional write file options
2219
- */
2220
- async emitBuiltin(code, id, options = {}) {
2221
- if (!this.builtinsPath) throw new Error(`The builtins path is not set. Cannot emit builtin file with id "${id}".`);
2222
- if (!(0, _stryke_type_checks_is_set_string.isSetString)(id)) throw new Error(`The builtin id must be a non-empty string. Received: ${String(id)}`);
2223
- return this.emit(code, (0, _stryke_path_append.appendPath)(id, this.builtinsPath), (0, defu.default)(options, { meta: {
2224
- type: "builtin",
2225
- id
2226
- } }));
2227
- }
2228
- /**
2229
- * Synchronously resolves a builtin virtual file and writes it to the VFS if it does not already exist
2230
- *
2231
- * @param code - The source code of the builtin file
2232
- * @param id - The unique identifier of the builtin file
2233
- * @param options - Optional write file options
2234
- */
2235
- emitBuiltinSync(code, id, options = {}) {
2236
- if (!this.builtinsPath) throw new Error(`The builtins path is not set. Cannot emit builtin file with id "${id}".`);
2237
- if (!(0, _stryke_type_checks_is_set_string.isSetString)(id)) throw new Error(`The builtin id must be a non-empty string. Received: ${String(id)}`);
2238
- return this.emitSync(code, (0, _stryke_path_append.appendPath)(id, this.builtinsPath), (0, defu.default)(options, { meta: {
2239
- type: "builtin",
2240
- id
2241
- } }));
2242
- }
2243
- /**
2244
- * Resolves a builtin virtual file and writes it to the VFS if it does not already exist
2245
- *
2246
- * @param code - The source code of the builtin file
2247
- * @param id - The unique identifier of the builtin file
2248
- * @param options - Optional write file options
2249
- */
2250
- async emitInfrastructure(code, id, options = {}) {
2251
- if (!this.infrastructurePath) throw new Error(`The infrastructure path is not set. Cannot emit infrastructure file with id "${id}".`);
2252
- if (!(0, _stryke_type_checks_is_set_string.isSetString)(id)) throw new Error(`The infrastructure id must be a non-empty string. Received: ${String(id)}`);
2253
- return this.emit(code, (0, _stryke_path_append.appendPath)(id, this.infrastructurePath), (0, defu.default)(options, { meta: {
2254
- type: "infrastructure",
2255
- id
2256
- } }));
2257
- }
2258
- /**
2259
- * Synchronously resolves an infrastructure virtual file and writes it to the VFS if it does not already exist
2260
- *
2261
- * @param code - The source code of the infrastructure file
2262
- * @param id - The unique identifier of the infrastructure file
2263
- * @param options - Optional write file options
2264
- */
2265
- emitInfrastructureSync(code, id, options = {}) {
2266
- if (!this.infrastructurePath) throw new Error(`The infrastructure path is not set. Cannot emit infrastructure file with id "${id}".`);
2267
- if (!(0, _stryke_type_checks_is_set_string.isSetString)(id)) throw new Error(`The infrastructure id must be a non-empty string. Received: ${String(id)}`);
2268
- return this.emitSync(code, (0, _stryke_path_append.appendPath)(id, this.infrastructurePath), (0, defu.default)(options, { meta: {
2269
- type: "infrastructure",
2270
- id
2271
- } }));
2272
- }
2273
- /**
2274
- * Update the context using a new user configuration options
2275
- *
2276
- * @param userConfig - The new user configuration options.
2277
- */
2278
- async withUserConfig(userConfig, options = { isHighPriority: true }) {
2279
- this.mergeUserConfig(userConfig);
2280
- await this.init(this.config.userConfig, options);
2281
- }
2282
- /**
2283
- * Update the context using a new inline configuration options
2284
- *
2285
- * @param inlineConfig - The new inline configuration options.
2286
- */
2287
- async withInlineConfig(inlineConfig, options = { isHighPriority: true }) {
2288
- this.config.inlineConfig = inlineConfig;
2289
- if (inlineConfig.command === "new") {
2290
- const workspacePackageJsonPath = (0, _stryke_path_join.joinPaths)(this.workspaceConfig.workspaceRoot, "package.json");
2291
- if (!(0, _stryke_fs_exists.existsSync)(workspacePackageJsonPath)) throw new Error(`The workspace package.json file could not be found at ${workspacePackageJsonPath}`);
2292
- this.packageJson = await (0, _stryke_fs_json.readJsonFile)(workspacePackageJsonPath);
2293
- this.workspaceConfig.repository ??= (0, _stryke_type_checks_is_set_string.isSetString)(this.packageJson?.repository) ? this.packageJson.repository : this.packageJson?.repository?.url;
2294
- }
2295
- await this.init(this.config.inlineConfig, options);
2296
- }
2297
- /**
2298
- * A logging function for fatal messages
2299
- *
2300
- * @param message - The message to log.
2301
- */
2302
- fatal(message) {
2303
- 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));
2304
- }
2305
- /**
2306
- * A logging function for error messages
2307
- *
2308
- * @param message - The message to log.
2309
- */
2310
- error(message) {
2311
- 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));
2312
- }
2313
- /**
2314
- * A logging function for warning messages
2315
- *
2316
- * @param message - The message to log.
2317
- */
2318
- warn(message) {
2319
- 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));
2320
- }
2321
- /**
2322
- * A logging function for informational messages
2323
- *
2324
- * @param message - The message to log.
2325
- */
2326
- info(message) {
2327
- 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));
2328
- }
2329
- /**
2330
- * A logging function for debug messages
2331
- *
2332
- * @param message - The message to log.
2333
- */
2334
- debug(message) {
2335
- 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));
2336
- }
2337
- /**
2338
- * A logging function for trace messages
2339
- *
2340
- * @param message - The message to log.
2341
- */
2342
- trace(message) {
2343
- 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));
2344
- }
2345
- /**
2346
- * A function to create a timer for measuring the duration of asynchronous operations
2347
- *
2348
- * @example
2349
- * ```ts
2350
- * const stopTimer = context.timer("Your Async Operation");
2351
- * await performAsyncOperation();
2352
- * stopTimer(); // "Your Async Operation completed in 123.45 milliseconds"
2353
- * ```
2354
- *
2355
- * @param name - The name of the timer.
2356
- * @returns A function that, when called, stops the timer and logs the duration.
2357
- */
2358
- timer(name) {
2359
- const startDate = Date.now();
2360
- const startDuration = performance.now();
2361
- return () => {
2362
- const duration = performance.now() - startDuration;
2363
- this.log(_storm_software_config_tools_types.LogLevelLabel.PERFORMANCE, `${chalk.default.bold.cyanBright(name)} completed in ${chalk.default.bold.cyanBright(duration < 1e3 ? `${duration.toFixed(2)} milliseconds` : (0, date_fns_formatDistanceToNowStrict.formatDistanceToNowStrict)(startDate))}`);
2364
- };
2365
- }
2366
- /**
2367
- * Create a new logger instance
2368
- *
2369
- * @param name - The name to use for the logger instance
2370
- * @returns A logger function
2371
- */
2372
- createLog(name = null) {
2373
- return (0, require_utils.utils_exports.createLog)(name, {
2374
- ...this.config,
2375
- logLevel: (0, _stryke_type_checks_is_null.isNull)(this.config.logLevel) ? "silent" : this.config.logLevel,
2376
- command: this.config.command
2377
- });
2378
- }
2379
- /**
2380
- * Extend the current logger instance with a new name
2381
- *
2382
- * @param name - The name to use for the extended logger instance
2383
- * @returns A logger function
2384
- */
2385
- extendLog(name) {
2386
- return (0, require_utils.utils_exports.extendLog)(this.log, name);
2387
- }
2388
- /**
2389
- * Generates a checksum representing the current context state
2390
- *
2391
- * @param root - The root directory of the project to generate the checksum for
2392
- * @returns A promise that resolves to a string representing the checksum
2393
- */
2394
- async generateChecksum(root = this.config.root) {
2395
- this.#checksum = await (0, _stryke_hash_node.hashDirectory)(root, { ignore: [
2396
- "node_modules",
2397
- ".git",
2398
- ".nx",
2399
- ".cache",
2400
- "tmp",
2401
- "dist"
2402
- ] });
2403
- return this.#checksum;
2404
- }
2405
- /**
2406
- * Creates a new StormContext instance.
2407
- *
2408
- * @param workspaceConfig - The workspace configuration.
2409
- */
2410
- constructor(workspaceConfig) {
2411
- this.#workspaceConfig = workspaceConfig;
2412
- envPathCache.set({
2413
- workspaceRoot: workspaceConfig.workspaceRoot,
2414
- framework: "powerlines"
2415
- }, (0, _stryke_env_get_env_paths.getEnvPaths)({
2416
- orgId: ((0, _stryke_type_checks_is_set_object.isSetObject)(workspaceConfig.organization) ? workspaceConfig.organization.name : workspaceConfig.organization) || "storm-software",
2417
- appId: "powerlines",
2418
- workspaceRoot: workspaceConfig.workspaceRoot
2419
- }));
2420
- }
2421
- /**
2422
- * The resolved configuration for this context
2423
- */
2424
- resolvedConfig = {};
2425
- /**
2426
- * A logger function specific to this context
2427
- */
2428
- logger;
2429
- /**
2430
- * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.
2431
- *
2432
- * @remarks
2433
- * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.
2434
- *
2435
- * @returns The cloned context.
2436
- */
2437
- copyTo(context) {
2438
- context.dependencies = (0, _stryke_helpers_deep_clone.deepClone)(this.dependencies);
2439
- context.devDependencies = (0, _stryke_helpers_deep_clone.deepClone)(this.devDependencies);
2440
- context.persistedMeta = this.persistedMeta ? (0, _stryke_helpers_deep_clone.deepClone)(this.persistedMeta) : void 0;
2441
- context.packageJson = (0, _stryke_helpers_deep_clone.deepClone)(this.packageJson);
2442
- context.projectJson = this.projectJson ? (0, _stryke_helpers_deep_clone.deepClone)(this.projectJson) : void 0;
2443
- context.tsconfig = (0, _stryke_helpers_deep_clone.deepClone)(this.tsconfig);
2444
- context.$$internal = this.$$internal;
2445
- return context;
2446
- }
2447
- /**
2448
- * Initialize the context with the provided configuration options
2449
- *
2450
- * @param config - The partial user configuration to use for initialization.
2451
- */
2452
- async init(config = {}, options = { isHighPriority: true }) {
2453
- const cacheKey = {
2454
- root: config.root ?? this.config.root ?? this.config.userConfig?.root ?? this.config.inlineConfig?.root,
2455
- mode: (config.mode ?? this.config.mode) || this.workspaceConfig.mode,
2456
- skipCache: config.skipCache ?? this.config.skipCache ?? false,
2457
- configFile: config.configFile ?? this.config.configFile,
2458
- framework: config.framework ?? this.config.framework ?? "powerlines",
2459
- command: this.config.inlineConfig?.command,
2460
- alias: this.config.resolve?.alias ?? config.resolve?.alias
2461
- };
2462
- if (configCache.has(cacheKey)) {
2463
- const result = configCache.get(cacheKey);
2464
- this.projectJson = result.projectJson;
2465
- this.packageJson = result.packageJson;
2466
- this.#checksum = result.checksum;
2467
- this.resolver = result.resolver;
2468
- this.mergeUserConfig(result.userConfig.config, this.config.userConfig);
2469
- } else {
2470
- const projectJsonPath = (0, _stryke_path_join.joinPaths)(cacheKey.root, "project.json");
2471
- if ((0, _stryke_fs_exists.existsSync)(projectJsonPath)) this.projectJson = await (0, _stryke_fs_json.readJsonFile)(projectJsonPath);
2472
- const packageJsonPath = (0, _stryke_path_join.joinPaths)(cacheKey.root, "package.json");
2473
- if ((0, _stryke_fs_exists.existsSync)(packageJsonPath)) this.packageJson = await (0, _stryke_fs_json.readJsonFile)(packageJsonPath);
2474
- this.#checksum = await this.generateChecksum(cacheKey.root);
2475
- this.resolver = createResolver({
2476
- workspaceRoot: this.workspaceConfig.workspaceRoot,
2477
- root: cacheKey.root,
2478
- cacheDir: this.cachePath,
2479
- mode: cacheKey.mode,
2480
- logLevel: config.logLevel || this.config.logLevel || this.workspaceConfig.logLevel || "info",
2481
- skipCache: cacheKey.skipCache,
2482
- alias: this.config.resolve?.alias ? Array.isArray(this.config.resolve.alias) ? this.config.resolve.alias.reduce((ret, alias) => {
2483
- ret[alias.find.toString()] = alias.replacement;
2484
- return ret;
2485
- }, {}) : this.config.resolve.alias : {}
2486
- });
2487
- const userConfig = await (0, require_config.config_exports.loadUserConfigFile)(cacheKey.root, this.workspaceConfig.workspaceRoot, this.resolver, cacheKey.command, cacheKey.mode, cacheKey.configFile, cacheKey.framework);
2488
- this.mergeUserConfig(userConfig.config);
2489
- configCache.set(cacheKey, {
2490
- projectJson: this.projectJson,
2491
- packageJson: this.packageJson,
2492
- checksum: this.#checksum,
2493
- resolver: this.resolver,
2494
- userConfig
2495
- });
2496
- }
2497
- config.tsconfig ??= require_tsconfig.getTsconfigFilePath(this.workspaceConfig.workspaceRoot, cacheKey.root, config.tsconfig);
2498
- if ((0, _stryke_type_checks_is_set_object.isSetObject)(config)) this.resolvedConfig = (0, require_plugin_utils.plugin_utils_exports.mergeConfig)({
2499
- inlineConfig: this.config.inlineConfig,
2500
- userConfig: this.config.userConfig
2501
- }, options.isHighPriority ? this.#getConfigProps(config) : {}, {
2502
- ...this.#getConfigProps(this.config.inlineConfig),
2503
- command: this.config.inlineConfig?.command
2504
- }, this.#getConfigProps(this.config.userConfig), {
2505
- mode: this.workspaceConfig?.mode,
2506
- logLevel: this.workspaceConfig?.logLevel,
2507
- skipCache: this.workspaceConfig?.skipCache
2508
- }, {
2509
- name: this.projectJson?.name || this.packageJson?.name,
2510
- version: this.packageJson?.version,
2511
- description: this.packageJson?.description,
2512
- output: (0, require_plugin_utils.plugin_utils_exports.mergeConfig)(config.output ?? {}, {
2513
- path: cacheKey.root ? (0, _stryke_path_append.appendPath)((0, _stryke_path_join.joinPaths)(cacheKey.root, "dist"), this.workspaceConfig?.workspaceRoot) : void 0,
2514
- copy: { assets: [
2515
- { glob: "LICENSE" },
2516
- {
2517
- input: cacheKey.root,
2518
- glob: "*.md"
2519
- },
2520
- {
2521
- input: cacheKey.root,
2522
- glob: "package.json"
2523
- }
2524
- ] },
2525
- artifactsPath: `.${config.framework ?? "powerlines"}`,
2526
- dts: true,
2527
- types: (0, _stryke_path_join.joinPaths)(cacheKey.root, `${config.framework ?? "powerlines"}.d.ts`)
2528
- })
2529
- }, options.isHighPriority ? {} : this.#getConfigProps(config), {
2530
- inlineConfig: {},
2531
- userConfig: {},
2532
- framework: "powerlines",
2533
- mode: "production",
2534
- projectType: "application",
2535
- platform: "neutral",
2536
- logLevel: "info",
2537
- preview: false,
2538
- environments: {},
2539
- resolve: {}
2540
- });
2541
- this.config.input = (0, require_utils.utils_exports.getUniqueInputs)(this.config.input);
2542
- if (this.config.name?.startsWith("@") && this.config.name.split("/").filter(Boolean).length > 1) this.config.name = this.config.name.split("/").filter(Boolean)[1];
2543
- this.config.title ??= (0, _stryke_string_format_title_case.titleCase)(this.config.name);
2544
- this.config.organization ??= ((0, _stryke_type_checks_is_set_object.isSetObject)(this.workspaceConfig.organization) ? this.workspaceConfig.organization.name : this.workspaceConfig.organization) || ((0, _stryke_type_checks_is_set_object.isSetObject)(this.packageJson?.author) ? this.packageJson?.author?.name : this.packageJson?.author) || this.config.name;
2545
- if (this.config.userConfig.resolve?.external) this.config.userConfig.resolve.external = (0, _stryke_helpers_get_unique.getUnique)(this.config.userConfig.resolve.external);
2546
- if (this.config.userConfig.resolve?.noExternal) this.config.userConfig.resolve.noExternal = (0, _stryke_helpers_get_unique.getUnique)(this.config.userConfig.resolve.noExternal);
2547
- if (this.config.resolve.external) this.config.resolve.external = (0, _stryke_helpers_get_unique.getUnique)(this.config.resolve.external);
2548
- if (this.config.resolve.noExternal) this.config.resolve.noExternal = (0, _stryke_helpers_get_unique.getUnique)(this.config.resolve.noExternal);
2549
- 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"])));
2550
- if (this.config.output.dts !== false && !this.config.output.types) this.config.output.types = `${this.config.root ? `${this.config.root}/` : ""}${this.config.framework ?? "powerlines"}.d.ts`;
2551
- if (this.config.root && this.config.root !== "." && this.config.root !== "./" && this.config.root !== this.workspaceConfig.workspaceRoot) this.config.output.path ??= (0, _stryke_path_join.joinPaths)(this.config.root, "dist");
2552
- else this.config.output.path ??= "dist";
2553
- if (this.config.root && this.config.output.copy !== false) this.config.output.copy = {
2554
- path: (0, _stryke_path_join.joinPaths)(this.workspaceConfig.workspaceRoot, "dist", (0, _stryke_path_replace.replacePath)(this.config.root, this.workspaceConfig.workspaceRoot)),
2555
- ...this.config.output.copy || {}
2556
- };
2557
- if (this.config.output.copy && this.config.output.copy.path && this.config.output.copy.assets && Array.isArray(this.config.output.copy.assets)) this.config.output.copy.assets = (0, _stryke_helpers_get_unique.getUniqueBy)(this.config.output.copy.assets.map((asset) => {
2558
- return {
2559
- glob: (0, _stryke_type_checks_is_set_object.isSetObject)(asset) ? asset.glob : asset,
2560
- 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),
2561
- 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.copy.path, (0, _stryke_path_replace.replacePath)((0, _stryke_path_replace.replacePath)(asset.output, (0, _stryke_path_replace.replacePath)(this.config.output.copy.path, this.workspaceConfig.workspaceRoot)), this.config.output.copy.path)), this.workspaceConfig.workspaceRoot) : (0, _stryke_path_append.appendPath)(this.config.output.copy.path, this.workspaceConfig.workspaceRoot),
2562
- ignore: (0, _stryke_type_checks_is_set_object.isSetObject)(asset) && asset.ignore ? (0, _stryke_convert_to_array.toArray)(asset.ignore) : void 0
2563
- };
2564
- }), (a) => `${a.input}-${a.glob}-${a.output}`);
2565
- this.config.plugins = (this.config.plugins ?? []).filter(Boolean).reduce((ret, plugin) => {
2566
- if ((0, require_plugin_utils.plugin_utils_exports.isPlugin)(plugin) && (0, require_plugin_utils.plugin_utils_exports.isDuplicate)(plugin, ret.filter((p) => (0, require_plugin_utils.plugin_utils_exports.isPlugin)(p)))) return ret;
2567
- ret.push(plugin);
2568
- return ret;
2569
- }, []);
2570
- if (this.config.tsconfig) this.config.tsconfig = (0, require_plugin_utils.plugin_utils_exports.replacePathTokens)(this, this.config.tsconfig);
2571
- if (this.config.output.types) if ((0, _stryke_type_checks_is_set_string.isSetString)(this.config.output.types)) this.config.output.types = (0, require_plugin_utils.plugin_utils_exports.replacePathTokens)(this, this.config.output.types);
2572
- else this.config.output.types = (0, _stryke_path_join.joinPaths)(this.config.root, `${this.config.framework ?? "powerlines"}.d.ts`);
2573
- if (!this.config.userConfig?.output?.sourceMap && !this.config.inlineConfig?.output?.sourceMap) if (this.config.mode === "development") this.config.output.sourceMap = true;
2574
- else this.config.output.sourceMap = false;
2575
- if (this.config.output.copy && this.config.output.copy.assets) this.config.output.copy.assets = this.config.output.copy.assets.map((asset) => ({
2576
- ...asset,
2577
- glob: (0, require_plugin_utils.plugin_utils_exports.replacePathTokens)(this, asset.glob),
2578
- ignore: asset.ignore ? asset.ignore.map((ignore) => (0, require_plugin_utils.plugin_utils_exports.replacePathTokens)(this, ignore)) : void 0,
2579
- input: (0, require_plugin_utils.plugin_utils_exports.replacePathTokens)(this, asset.input),
2580
- output: (0, require_plugin_utils.plugin_utils_exports.replacePathTokens)(this, asset.output)
2581
- }));
2582
- if ((0, _stryke_type_checks_is_set_string.isSetString)(config.output?.storage) && config.output.storage === "virtual" || (0, _stryke_type_checks_is_set_object.isSetObject)(config.output?.storage) && Object.values(config.output.storage).every((adapter) => adapter.preset === "virtual")) this.config.output.overwrite = true;
2583
- this.#fs ??= await VirtualFileSystem.create(this);
2584
- }
2585
- mergeUserConfig(from = {}, into = this.config.userConfig ?? {}) {
2586
- this.config.userConfig = (0, require_plugin_utils.plugin_utils_exports.mergeConfig)(from, into);
2587
- 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));
2588
- this.config.userConfig.plugins = (this.config.userConfig.plugins ?? []).filter(Boolean).reduce((ret, plugin) => {
2589
- if ((0, require_plugin_utils.plugin_utils_exports.isPlugin)(plugin) && (0, require_plugin_utils.plugin_utils_exports.isDuplicate)(plugin, ret.filter((p) => (0, require_plugin_utils.plugin_utils_exports.isPlugin)(p)))) return ret;
2590
- ret.push(plugin);
2591
- return ret;
2592
- }, []);
2593
- }
2594
- };
2595
-
2596
- //#endregion
2597
- //#region src/context/plugin-context.ts
2598
- /**
2599
- * Create a Proxy-based PluginContext
2600
- *
2601
- * @param plugin - The plugin instance
2602
- * @param environment - The environment context
2603
- * @returns The proxied plugin context
2604
- */
2605
- function createPluginContext(plugin, environment) {
2606
- const normalizeMessage = (message) => {
2607
- return (0, _stryke_type_checks_is_string.isString)(message) ? message : message.message;
2608
- };
2609
- const log = environment.extendLog(plugin.name.replaceAll(":", " - "));
2610
- const callHookFn = async (hook, options, ...args) => {
2611
- return environment.$$internal.api.callHook(hook, {
2612
- sequential: true,
2613
- result: "merge",
2614
- ...options,
2615
- environment
2616
- }, ...args);
2617
- };
2618
- const meta = {};
2619
- return new Proxy({}, {
2620
- get(_, prop) {
2621
- if (prop === "$$internal") return {
2622
- ...environment.$$internal,
2623
- environment,
2624
- callHook: callHookFn,
2625
- meta
2626
- };
2627
- if (prop === "log" || prop === "logger") return log;
2628
- if (prop === "fatal") return (message) => {
2629
- log(_storm_software_config_tools_types.LogLevelLabel.FATAL, normalizeMessage(message));
2630
- };
2631
- if (prop === "error") return (message) => {
2632
- log(_storm_software_config_tools_types.LogLevelLabel.ERROR, normalizeMessage(message));
2633
- };
2634
- if (prop === "warn") return (message) => {
2635
- log(_storm_software_config_tools_types.LogLevelLabel.WARN, normalizeMessage(message));
2636
- };
2637
- if (prop === "info") return (message) => {
2638
- log(_storm_software_config_tools_types.LogLevelLabel.INFO, normalizeMessage(message));
2639
- };
2640
- if (prop === "debug") return (message) => {
2641
- log(_storm_software_config_tools_types.LogLevelLabel.DEBUG, normalizeMessage(message));
2642
- };
2643
- if (prop === "trace") return (message) => {
2644
- log(_storm_software_config_tools_types.LogLevelLabel.TRACE, normalizeMessage(message));
2645
- };
2646
- return environment[prop];
2647
- },
2648
- set(_, prop, value) {
2649
- if ([
2650
- "$$internal",
2651
- "environment",
2652
- "config",
2653
- "log",
2654
- "logger",
2655
- "error",
2656
- "warn",
2657
- "plugins",
2658
- "hooks",
2659
- "addPlugin",
2660
- "selectHooks"
2661
- ].includes(prop)) {
2662
- log(_storm_software_config_tools_types.LogLevelLabel.WARN, `Cannot set read-only property "${String(prop)}"`);
2663
- return false;
2664
- }
2665
- environment[prop] = value;
2666
- return true;
2667
- }
2668
- });
2669
- }
2670
-
2671
- //#endregion
2672
- //#region src/context/environment-context.ts
2673
- var PowerlinesEnvironmentContext = class PowerlinesEnvironmentContext extends PowerlinesContext {
2674
- /**
2675
- * The hooks registered by plugins in this environment
2676
- */
2677
- #hooks = {};
2678
- /**
2679
- * Create a new Storm context from the workspace root and user config.
2680
- *
2681
- * @param workspaceConfig - The root directory of the workspace.
2682
- * @param config - The user configuration options.
2683
- * @returns A promise that resolves to the new context.
2684
- */
2685
- static async fromConfig(workspaceConfig, config) {
2686
- const context = new PowerlinesEnvironmentContext(config, workspaceConfig);
2687
- await context.init();
2688
- const powerlinesPath = await (0, _stryke_fs_resolve.resolvePackage)("powerlines");
2689
- if (!powerlinesPath) throw new Error("Could not resolve `powerlines` package location.");
2690
- context.powerlinesPath = powerlinesPath;
2691
- return context;
2692
- }
2693
- /**
2694
- * The resolved environment configuration
2695
- */
2696
- environment;
2697
- /**
2698
- * The list of plugins applied to this environment
2699
- */
2700
- plugins = [];
2701
- /**
2702
- * The resolved configuration options
2703
- */
2704
- get config() {
2705
- return super.config;
2706
- }
2707
- /**
2708
- * Create a new logger instance
2709
- *
2710
- * @param name - The name to use for the logger instance
2711
- * @returns A logger function
2712
- */
2713
- createLog(name = null) {
2714
- return (0, _powerlines_core_lib_logger.createLog)(name, {
2715
- ...this.config,
2716
- logLevel: (0, _stryke_type_checks_is_null.isNull)(this.config.logLevel) ? "silent" : this.config.logLevel,
2717
- environment: this.environment?.name
2718
- });
2719
- }
2720
- /**
2721
- * The hooks registered by plugins in this environment
2722
- */
2723
- get hooks() {
2724
- return this.#hooks;
2725
- }
2726
- /**
2727
- * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.
2728
- *
2729
- * @remarks
2730
- * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.
2731
- *
2732
- * @returns A promise that resolves to the cloned context.
2733
- */
2734
- async clone() {
2735
- const clone = await PowerlinesEnvironmentContext.fromConfig(this.workspaceConfig, this.config);
2736
- await clone.withUserConfig(this.config);
2737
- return this.copyTo(clone);
2738
- }
2739
- async addPlugin(plugin) {
2740
- let resolvedPlugin = plugin;
2741
- if ((0, _stryke_type_checks_is_function.isFunction)(plugin.applyToEnvironment)) {
2742
- const result = await Promise.resolve(plugin.applyToEnvironment(this.environment));
2743
- if (!result || (0, _stryke_type_checks_is_object.isObject)(result) && Object.keys(result).length === 0) return;
2744
- if ((0, require_plugin_utils.plugin_utils_exports.isPluginConfig)(result)) return this.$$internal.addPlugin(result);
2745
- resolvedPlugin = (0, require_plugin_utils.plugin_utils_exports.isPlugin)(result) ? result : plugin;
2746
- }
2747
- const context = createPluginContext(resolvedPlugin, this);
2748
- this.plugins.push({
2749
- plugin: resolvedPlugin,
2750
- context
2751
- });
2752
- this.#hooks = Object.entries(Object.keys(resolvedPlugin).filter((key) => !require_constants.constants_exports.PLUGIN_NON_HOOK_FIELDS.includes(key)).reduce((ret, key) => extractHooks(context, ret, resolvedPlugin, key), this.hooks)).reduce((ret, [key, value]) => {
2753
- if ((0, _stryke_type_checks_is_set_object.isSetObject)(value)) Object.entries(value).forEach(([type, list]) => {
2754
- ret[key] ??= {};
2755
- ret[key][type] = (0, require_plugin_utils.plugin_utils_exports.dedupeHooklist)(list);
2756
- });
2757
- return ret;
2758
- }, {});
2759
- }
2760
- /**
2761
- * Retrieves the hook handlers for a specific hook name
2762
- */
2763
- selectHooks(key, options) {
2764
- const result = [];
2765
- if ((0, require_plugin_utils.plugin_utils_exports.isPluginHookField)(key) && this.hooks[key]) {
2766
- if (this.hooks[key]) if (options?.order) {
2767
- const mapHooksToResult = (hooksList) => hooksList.map((hook) => {
2768
- const plugin = this.plugins.find((p) => p.plugin.name === hook.plugin.name);
2769
- if (!plugin) throw new Error(`Could not find plugin context for plugin "${hook.plugin.name}".`);
2770
- return {
2771
- handler: hook.handler,
2772
- plugin: hook.plugin,
2773
- context: plugin.context
2774
- };
2775
- });
2776
- if (options?.order === "pre") {
2777
- result.push(...mapHooksToResult(this.hooks[key].preOrdered ?? []));
2778
- result.push(...mapHooksToResult(this.hooks[key].preEnforced ?? []));
2779
- } else if (options?.order === "post") {
2780
- result.push(...mapHooksToResult(this.hooks[key].postOrdered ?? []));
2781
- result.push(...mapHooksToResult(this.hooks[key].postEnforced ?? []));
2782
- } else result.push(...mapHooksToResult(this.hooks[key].normal ?? []));
2783
- } else {
2784
- result.push(...this.selectHooks(key, { order: "pre" }));
2785
- result.push(...this.selectHooks(key, { order: "normal" }));
2786
- result.push(...this.selectHooks(key, { order: "post" }));
2787
- }
2788
- }
2789
- return result;
2790
- }
2791
- constructor(config, workspaceConfig) {
2792
- super(workspaceConfig);
2793
- this.resolvedConfig = config;
2794
- }
2795
- /**
2796
- * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.
2797
- *
2798
- * @remarks
2799
- * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.
2800
- *
2801
- * @returns The cloned context.
2802
- */
2803
- copyTo(context) {
2804
- context.plugins = this.plugins;
2805
- return super.copyTo(context);
2806
- }
2807
- };
2808
-
2809
- //#endregion
2810
- //#region src/context/api-context.ts
2811
- var PowerlinesAPIContext = class PowerlinesAPIContext extends PowerlinesContext {
2812
- #environments = {};
2813
- #plugins = [];
2814
- /**
2815
- * Create a new Storm context from the workspace root and user config.
2816
- *
2817
- * @param workspaceRoot - The root directory of the workspace.
2818
- * @param config - The user configuration options.
2819
- * @returns A promise that resolves to the new context.
2820
- */
2821
- static async from(workspaceRoot, config) {
2822
- const context = new PowerlinesAPIContext(await (0, require_config.config_exports.loadWorkspaceConfig)(workspaceRoot, config.root));
2823
- await context.withUserConfig(config);
2824
- const powerlinesPath = await (0, _stryke_fs_resolve.resolvePackage)("powerlines");
2825
- if (!powerlinesPath) throw new Error("Could not resolve `powerlines` package location.");
2826
- context.powerlinesPath = powerlinesPath;
2827
- return context;
2828
- }
2829
- /**
2830
- * Internal context fields and methods
2831
- *
2832
- * @danger
2833
- * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
2834
- *
2835
- * @internal
2836
- */
2837
- get $$internal() {
2838
- return super.$$internal;
2839
- }
2840
- /**
2841
- * Internal context fields and methods
2842
- *
2843
- * @danger
2844
- * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
2845
- *
2846
- * @internal
2847
- */
2848
- set $$internal(value) {
2849
- super.$$internal = value;
2850
- for (const environment of Object.values(this.environments)) environment.$$internal = super.$$internal;
2851
- }
2852
- /**
2853
- * A record of all environments by name
2854
- */
2855
- get environments() {
2856
- return this.#environments;
2857
- }
2858
- get plugins() {
2859
- return this.#plugins;
2860
- }
2861
- constructor(workspaceConfig) {
2862
- super(workspaceConfig);
2863
- }
2864
- /**
2865
- * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.
2866
- *
2867
- * @remarks
2868
- * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.
2869
- *
2870
- * @returns A promise that resolves to the cloned context.
2871
- */
2872
- async clone() {
2873
- const clone = await PowerlinesAPIContext.from(this.workspaceConfig.workspaceRoot, this.config);
2874
- await clone.withUserConfig(this.config);
2875
- return this.copyTo(clone);
2876
- }
2877
- /**
2878
- * Initialize the context with the provided configuration options
2879
- *
2880
- * @param config - The partial user configuration to use for initialization.
2881
- */
2882
- async init(config = {}) {
2883
- await super.init(config);
2884
- 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) => {
2885
- this.#environments[env.name] = await this.in(env);
2886
- }));
2887
- }
2888
- /**
2889
- * A function to copy the context and update the fields for a specific environment
2890
- *
2891
- * @param environment - The environment configuration to use.
2892
- * @returns A new context instance with the updated environment.
2893
- */
2894
- async in(environment) {
2895
- let context;
2896
- if (this.environments[environment.name]) context = this.environments[environment.name];
2897
- else context = await PowerlinesEnvironmentContext.fromConfig(this.workspaceConfig, this.config);
2898
- if ((0, _stryke_type_checks_is_set_object.isSetObject)(this.config.inlineConfig)) await context.withInlineConfig(this.config.inlineConfig);
2899
- context.environment = environment;
2900
- context.plugins = [];
2901
- for (const plugin of this.plugins) await context.addPlugin(plugin);
2902
- return context;
2903
- }
2904
- /**
2905
- * Update the context using a new user configuration options
2906
- *
2907
- * @param userConfig - The new user configuration options.
2908
- */
2909
- async withUserConfig(userConfig, options = { isHighPriority: true }) {
2910
- await super.withUserConfig(userConfig, options);
2911
- await Promise.all(Object.keys(this.#environments).map(async (name) => {
2912
- await this.#environments[name].withUserConfig(userConfig, options);
2913
- }));
2914
- }
2915
- /**
2916
- * Update the context using a new inline configuration options
2917
- *
2918
- * @param inlineConfig - The new inline configuration options.
2919
- */
2920
- async withInlineConfig(inlineConfig, options = { isHighPriority: true }) {
2921
- await super.withInlineConfig(inlineConfig, options);
2922
- await Promise.all(Object.keys(this.#environments).map(async (name) => {
2923
- await this.#environments[name].withInlineConfig(inlineConfig, options);
2924
- }));
2925
- }
2926
- /**
2927
- * Add a plugin to the API context and all environments
2928
- *
2929
- * @param plugin - The plugin to add.
2930
- */
2931
- async addPlugin(plugin) {
2932
- this.plugins.push(plugin);
2933
- await Promise.all(Object.keys(this.environments).map(async (name) => {
2934
- await this.environments[name].addPlugin(plugin);
2935
- }));
2936
- }
2937
- /**
2938
- * Get an environment by name, or the default environment if no name is provided
2939
- *
2940
- * @param name - The name of the environment to retrieve.
2941
- * @returns The requested environment context.
2942
- */
2943
- async getEnvironment(name) {
2944
- let environment;
2945
- if (name) environment = this.environments[name];
2946
- if (Object.keys(this.environments).length === 1) {
2947
- environment = this.environments[Object.keys(this.environments)[0]];
2948
- this.debug(`Applying the only configured environment: ${chalk.default.bold.cyanBright(environment?.environment.name)}`);
2949
- }
2950
- if (!environment) {
2951
- if (name) throw new Error(`Environment "${name}" not found.`);
2952
- environment = await this.in(createDefaultEnvironment(this.config.userConfig));
2953
- this.warn(`No environment specified, and no default environment found. Using a temporary default environment: ${chalk.default.bold.cyanBright(environment?.environment.name)}`);
2954
- }
2955
- return environment;
2956
- }
2957
- /**
2958
- * A safe version of `getEnvironment` that returns `undefined` if the environment is not found
2959
- *
2960
- * @param name - The name of the environment to retrieve.
2961
- * @returns The requested environment context or `undefined` if not found.
2962
- */
2963
- async getEnvironmentSafe(name) {
2964
- try {
2965
- return await this.getEnvironment(name);
2966
- } catch {
2967
- return;
2968
- }
2969
- }
2970
- /**
2971
- * A function to merge all configured environments into a single context.
2972
- *
2973
- * @remarks
2974
- * If only one environment is configured, that environment will be returned directly.
2975
- *
2976
- * @returns A promise that resolves to a merged/global environment context.
2977
- */
2978
- async toEnvironment() {
2979
- let environment;
2980
- if (Object.keys(this.environments).length > 1) {
2981
- environment = await this.in(createEnvironment(require_constants.constants_exports.GLOBAL_ENVIRONMENT, this.config.userConfig));
2982
- this.debug(`Combined all ${Object.keys(this.environments).length} environments into a single global context.`);
2983
- } else environment = await this.getEnvironment();
2984
- return environment;
2985
- }
2986
- };
2987
-
2988
- //#endregion
2989
- Object.defineProperty(exports, 'FileId', {
2990
- enumerable: true,
2991
- get: function () {
2992
- return FileId;
2993
- }
2994
- });
2995
- Object.defineProperty(exports, 'FileMetadata', {
2996
- enumerable: true,
2997
- get: function () {
2998
- return FileMetadata;
2999
- }
3000
- });
3001
- Object.defineProperty(exports, 'FileMetadata_KeyValuePair', {
3002
- enumerable: true,
3003
- get: function () {
3004
- return FileMetadata_KeyValuePair;
3005
- }
3006
- });
3007
- Object.defineProperty(exports, 'FileStorage', {
3008
- enumerable: true,
3009
- get: function () {
3010
- return FileStorage;
3011
- }
3012
- });
3013
- Object.defineProperty(exports, 'FileSystem', {
3014
- enumerable: true,
3015
- get: function () {
3016
- return FileSystem;
3017
- }
3018
- });
3019
- Object.defineProperty(exports, 'PowerlinesAPIContext', {
3020
- enumerable: true,
3021
- get: function () {
3022
- return PowerlinesAPIContext;
3023
- }
3024
- });
3025
- Object.defineProperty(exports, 'PowerlinesContext', {
3026
- enumerable: true,
3027
- get: function () {
3028
- return PowerlinesContext;
3029
- }
3030
- });
3031
- Object.defineProperty(exports, 'PowerlinesEnvironmentContext', {
3032
- enumerable: true,
3033
- get: function () {
3034
- return PowerlinesEnvironmentContext;
3035
- }
3036
- });
3037
- Object.defineProperty(exports, '_capnpFileId', {
3038
- enumerable: true,
3039
- get: function () {
3040
- return _capnpFileId;
3041
- }
3042
- });
3043
- Object.defineProperty(exports, 'callHook', {
3044
- enumerable: true,
3045
- get: function () {
3046
- return callHook;
3047
- }
3048
- });
3049
- Object.defineProperty(exports, 'createPluginContext', {
3050
- enumerable: true,
3051
- get: function () {
3052
- return createPluginContext;
3053
- }
3054
- });
3055
- Object.defineProperty(exports, 'mergeConfigs', {
3056
- enumerable: true,
3057
- get: function () {
3058
- return mergeConfigs;
3059
- }
3060
- });
3061
- Object.defineProperty(exports, 'writeMetaFile', {
3062
- enumerable: true,
3063
- get: function () {
3064
- return writeMetaFile;
3065
- }
3066
- });