powerlines 0.42.41 → 0.43.0

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