@powerlines/plugin-webpack 0.5.241 → 0.5.243

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 (114) hide show
  1. package/dist/helpers/unplugin.cjs +2 -3
  2. package/dist/helpers/unplugin.mjs +1 -2
  3. package/dist/index.cjs +2 -2
  4. package/dist/index.d.cts +3 -2
  5. package/dist/index.d.mts +1 -1
  6. package/dist/index.mjs +3 -3
  7. package/dist/types/plugin.d.cts +3 -3
  8. package/dist/types/plugin.d.mts +3 -3
  9. package/package.json +96 -15
  10. package/dist/powerlines/package.cjs +0 -11
  11. package/dist/powerlines/package.mjs +0 -5
  12. package/dist/powerlines/schemas/fs.cjs +0 -226
  13. package/dist/powerlines/schemas/fs.mjs +0 -224
  14. package/dist/powerlines/src/api.cjs +0 -568
  15. package/dist/powerlines/src/api.mjs +0 -566
  16. package/dist/powerlines/src/internal/helpers/environment.cjs +0 -50
  17. package/dist/powerlines/src/internal/helpers/environment.mjs +0 -47
  18. package/dist/powerlines/src/internal/helpers/generate-types.cjs +0 -78
  19. package/dist/powerlines/src/internal/helpers/generate-types.mjs +0 -76
  20. package/dist/powerlines/src/internal/helpers/hooks.cjs +0 -65
  21. package/dist/powerlines/src/internal/helpers/hooks.d.cts +0 -47
  22. package/dist/powerlines/src/internal/helpers/hooks.d.mts +0 -49
  23. package/dist/powerlines/src/internal/helpers/hooks.mjs +0 -63
  24. package/dist/powerlines/src/internal/helpers/install-dependencies.cjs +0 -24
  25. package/dist/powerlines/src/internal/helpers/install-dependencies.mjs +0 -23
  26. package/dist/powerlines/src/internal/helpers/install.cjs +0 -36
  27. package/dist/powerlines/src/internal/helpers/install.mjs +0 -35
  28. package/dist/powerlines/src/internal/helpers/resolve-tsconfig.cjs +0 -97
  29. package/dist/powerlines/src/internal/helpers/resolve-tsconfig.mjs +0 -93
  30. package/dist/powerlines/src/internal/helpers/resolver.cjs +0 -43
  31. package/dist/powerlines/src/internal/helpers/resolver.mjs +0 -41
  32. package/dist/powerlines/src/lib/build/webpack.cjs +0 -38
  33. package/dist/powerlines/src/lib/build/webpack.mjs +0 -36
  34. package/dist/powerlines/src/lib/config-file.cjs +0 -79
  35. package/dist/powerlines/src/lib/config-file.mjs +0 -76
  36. package/dist/powerlines/src/lib/constants/environments.cjs +0 -8
  37. package/dist/powerlines/src/lib/constants/environments.mjs +0 -6
  38. package/dist/powerlines/src/lib/contexts/api-context.cjs +0 -184
  39. package/dist/powerlines/src/lib/contexts/api-context.mjs +0 -182
  40. package/dist/powerlines/src/lib/contexts/context.cjs +0 -951
  41. package/dist/powerlines/src/lib/contexts/context.mjs +0 -949
  42. package/dist/powerlines/src/lib/contexts/environment-context.cjs +0 -195
  43. package/dist/powerlines/src/lib/contexts/environment-context.mjs +0 -194
  44. package/dist/powerlines/src/lib/contexts/plugin-context.cjs +0 -78
  45. package/dist/powerlines/src/lib/contexts/plugin-context.mjs +0 -77
  46. package/dist/powerlines/src/lib/entry.cjs +0 -85
  47. package/dist/powerlines/src/lib/entry.mjs +0 -83
  48. package/dist/powerlines/src/lib/fs/helpers.cjs +0 -85
  49. package/dist/powerlines/src/lib/fs/helpers.mjs +0 -81
  50. package/dist/powerlines/src/lib/fs/storage/base.cjs +0 -196
  51. package/dist/powerlines/src/lib/fs/storage/base.mjs +0 -195
  52. package/dist/powerlines/src/lib/fs/storage/file-system.cjs +0 -170
  53. package/dist/powerlines/src/lib/fs/storage/file-system.mjs +0 -169
  54. package/dist/powerlines/src/lib/fs/storage/virtual.cjs +0 -88
  55. package/dist/powerlines/src/lib/fs/storage/virtual.mjs +0 -87
  56. package/dist/powerlines/src/lib/fs/vfs.cjs +0 -912
  57. package/dist/powerlines/src/lib/fs/vfs.mjs +0 -910
  58. package/dist/powerlines/src/lib/logger.cjs +0 -58
  59. package/dist/powerlines/src/lib/logger.mjs +0 -55
  60. package/dist/powerlines/src/lib/typescript/ts-morph.cjs +0 -103
  61. package/dist/powerlines/src/lib/typescript/ts-morph.mjs +0 -101
  62. package/dist/powerlines/src/lib/typescript/tsconfig.cjs +0 -149
  63. package/dist/powerlines/src/lib/typescript/tsconfig.mjs +0 -144
  64. package/dist/powerlines/src/lib/unplugin/factory.cjs +0 -6
  65. package/dist/powerlines/src/lib/unplugin/factory.mjs +0 -8
  66. package/dist/powerlines/src/lib/unplugin/helpers.cjs +0 -29
  67. package/dist/powerlines/src/lib/unplugin/helpers.mjs +0 -27
  68. package/dist/powerlines/src/lib/unplugin/index.cjs +0 -4
  69. package/dist/powerlines/src/lib/unplugin/index.mjs +0 -6
  70. package/dist/powerlines/src/lib/unplugin/module-resolution.cjs +0 -66
  71. package/dist/powerlines/src/lib/unplugin/module-resolution.mjs +0 -65
  72. package/dist/powerlines/src/lib/unplugin/plugin.cjs +0 -71
  73. package/dist/powerlines/src/lib/unplugin/plugin.mjs +0 -70
  74. package/dist/powerlines/src/lib/utilities/file-header.cjs +0 -22
  75. package/dist/powerlines/src/lib/utilities/file-header.mjs +0 -21
  76. package/dist/powerlines/src/lib/utilities/format.cjs +0 -48
  77. package/dist/powerlines/src/lib/utilities/format.mjs +0 -46
  78. package/dist/powerlines/src/lib/utilities/meta.cjs +0 -44
  79. package/dist/powerlines/src/lib/utilities/meta.mjs +0 -40
  80. package/dist/powerlines/src/lib/utilities/source-file.cjs +0 -22
  81. package/dist/powerlines/src/lib/utilities/source-file.mjs +0 -21
  82. package/dist/powerlines/src/plugin-utils/helpers.cjs +0 -167
  83. package/dist/powerlines/src/plugin-utils/helpers.mjs +0 -156
  84. package/dist/powerlines/src/plugin-utils/paths.cjs +0 -36
  85. package/dist/powerlines/src/plugin-utils/paths.mjs +0 -35
  86. package/dist/powerlines/src/types/api.d.cts +0 -104
  87. package/dist/powerlines/src/types/api.d.mts +0 -104
  88. package/dist/powerlines/src/types/babel.d.mts +0 -2
  89. package/dist/powerlines/src/types/build.cjs +0 -23
  90. package/dist/powerlines/src/types/build.d.cts +0 -185
  91. package/dist/powerlines/src/types/build.d.mts +0 -185
  92. package/dist/powerlines/src/types/build.mjs +0 -21
  93. package/dist/powerlines/src/types/commands.cjs +0 -16
  94. package/dist/powerlines/src/types/commands.d.cts +0 -8
  95. package/dist/powerlines/src/types/commands.d.mts +0 -9
  96. package/dist/powerlines/src/types/commands.mjs +0 -15
  97. package/dist/powerlines/src/types/config.d.cts +0 -424
  98. package/dist/powerlines/src/types/config.d.mts +0 -425
  99. package/dist/powerlines/src/types/context.d.cts +0 -514
  100. package/dist/powerlines/src/types/context.d.mts +0 -514
  101. package/dist/powerlines/src/types/fs.d.cts +0 -486
  102. package/dist/powerlines/src/types/fs.d.mts +0 -486
  103. package/dist/powerlines/src/types/hooks.d.cts +0 -32
  104. package/dist/powerlines/src/types/hooks.d.mts +0 -32
  105. package/dist/powerlines/src/types/plugin.cjs +0 -33
  106. package/dist/powerlines/src/types/plugin.d.cts +0 -205
  107. package/dist/powerlines/src/types/plugin.d.mts +0 -205
  108. package/dist/powerlines/src/types/plugin.mjs +0 -32
  109. package/dist/powerlines/src/types/resolved.d.cts +0 -93
  110. package/dist/powerlines/src/types/resolved.d.mts +0 -93
  111. package/dist/powerlines/src/types/tsconfig.d.cts +0 -69
  112. package/dist/powerlines/src/types/tsconfig.d.mts +0 -69
  113. package/dist/powerlines/src/types/unplugin.d.cts +0 -22
  114. package/dist/powerlines/src/types/unplugin.d.mts +0 -23
@@ -1,949 +0,0 @@
1
- import { getTsconfigFilePath } from "../typescript/tsconfig.mjs";
2
- import { loadUserConfigFile, loadWorkspaceConfig } from "../config-file.mjs";
3
- import { createResolver } from "../../internal/helpers/resolver.mjs";
4
- import { checkDedupe, isPlugin } from "../../plugin-utils/helpers.mjs";
5
- import { replacePathTokens } from "../../plugin-utils/paths.mjs";
6
- import { getUniqueEntries, resolveEntriesSync } from "../entry.mjs";
7
- import { createLog, extendLog } from "../logger.mjs";
8
- import { VirtualFileSystem } from "../fs/vfs.mjs";
9
- import { CACHE_HASH_LENGTH, PROJECT_ROOT_HASH_LENGTH, getPrefixedProjectRootHash } from "../utilities/meta.mjs";
10
- import defu$1 from "defu";
11
- import { omit } from "@stryke/helpers/omit";
12
- import { LogLevelLabel } from "@storm-software/config-tools/types";
13
- import { relativeToWorkspaceRoot } from "@stryke/fs/get-workspace-root";
14
- import { toArray } from "@stryke/convert/to-array";
15
- import { resolvePackage } from "@stryke/fs/resolve";
16
- import { appendPath } from "@stryke/path/append";
17
- import { replacePath } from "@stryke/path/replace";
18
- import { isFunction } from "@stryke/type-checks/is-function";
19
- import { isSetObject } from "@stryke/type-checks/is-set-object";
20
- import { isSetString } from "@stryke/type-checks/is-set-string";
21
- import { isString } from "@stryke/type-checks/is-string";
22
- import { findFileDotExtensionSafe, findFileExtensionSafe } from "@stryke/path/file-path-fns";
23
- import { isParentPath } from "@stryke/path/is-parent-path";
24
- import { readJsonFile } from "@stryke/fs/json";
25
- import { StormJSON } from "@stryke/json/storm-json";
26
- import { titleCase } from "@stryke/string-format/title-case";
27
- import { existsSync } from "@stryke/fs/exists";
28
- import { getEnvPaths } from "@stryke/env/get-env-paths";
29
- import { hashDirectory } from "@stryke/hash/hash-files";
30
- import { murmurhash } from "@stryke/hash/murmurhash";
31
- import { getUnique, getUniqueBy } from "@stryke/helpers/get-unique";
32
- import { fetchRequest } from "@stryke/http/fetch";
33
- import { joinPaths } from "@stryke/path/join";
34
- import { isNull } from "@stryke/type-checks/is-null";
35
- import { uuid } from "@stryke/unique-id/uuid";
36
- import { match, tsconfigPathsToRegExp } from "bundle-require";
37
- import { create } from "flat-cache";
38
- import { parse } from "oxc-parser";
39
- import { Agent, Response, interceptors, setGlobalDispatcher } from "undici";
40
-
41
- //#region ../powerlines/src/lib/contexts/context.ts
42
- const configCache = /* @__PURE__ */ new WeakMap();
43
- const envPathCache = /* @__PURE__ */ new WeakMap();
44
- setGlobalDispatcher(new Agent({ keepAliveTimeout: 1e4 }).compose(interceptors.retry({
45
- maxRetries: 3,
46
- minTimeout: 1e3,
47
- maxTimeout: 1e4,
48
- timeoutFactor: 2,
49
- retryAfter: true
50
- })));
51
- var PowerlinesContext = class PowerlinesContext {
52
- /**
53
- * Internal references storage
54
- *
55
- * @danger
56
- * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
57
- *
58
- * @internal
59
- */
60
- #internal = {};
61
- #workspaceConfig;
62
- #checksum = null;
63
- #buildId = uuid();
64
- #releaseId = uuid();
65
- #timestamp = Date.now();
66
- #fs;
67
- #tsconfig;
68
- #parserCache;
69
- #requestCache;
70
- #getConfigProps(config = {}) {
71
- return defu$1({
72
- variant: config.build?.variant,
73
- projectType: config.type,
74
- projectRoot: config.root,
75
- name: config.name,
76
- title: config.title,
77
- organization: config.organization,
78
- compatibilityDate: config.compatibilityDate,
79
- description: config.description,
80
- sourceRoot: config.sourceRoot,
81
- configFile: config.configFile,
82
- customLogger: config.customLogger,
83
- logLevel: config.logLevel,
84
- tsconfig: config.tsconfig,
85
- tsconfigRaw: config.tsconfigRaw,
86
- skipCache: config.skipCache,
87
- autoInstall: config.autoInstall,
88
- entry: config.entry,
89
- output: config.output,
90
- plugins: config.plugins,
91
- mode: config.mode,
92
- lint: config.lint,
93
- transform: config.transform,
94
- build: config.build,
95
- framework: config.framework,
96
- ...config
97
- }, { output: config.framework ? {
98
- artifactsPath: `.${config.framework ?? "powerlines"}`,
99
- dts: joinPaths(config.root ?? this.config.projectRoot, `${config.framework ?? "powerlines"}.d.ts`)
100
- } : {} });
101
- }
102
- /**
103
- * Create a new Storm context from the workspace root and user config.
104
- *
105
- * @param workspaceRoot - The root directory of the workspace.
106
- * @param config - The user configuration options.
107
- * @returns A promise that resolves to the new context.
108
- */
109
- static async from(workspaceRoot, config) {
110
- const context = new PowerlinesContext(await loadWorkspaceConfig(workspaceRoot, config.root));
111
- await context.withUserConfig(config);
112
- const powerlinesPath = await resolvePackage("powerlines");
113
- if (!powerlinesPath) throw new Error("Could not resolve `powerlines` package location.");
114
- context.powerlinesPath = powerlinesPath;
115
- return context;
116
- }
117
- /**
118
- * An object containing the dependencies that should be installed for the project
119
- */
120
- dependencies = {};
121
- /**
122
- * An object containing the development dependencies that should be installed for the project
123
- */
124
- devDependencies = {};
125
- /**
126
- * The persisted meta information about the current build
127
- */
128
- persistedMeta = void 0;
129
- /**
130
- * The path to the Powerlines package
131
- */
132
- powerlinesPath;
133
- /**
134
- * The parsed `package.json` file for the project
135
- */
136
- packageJson;
137
- /**
138
- * The parsed `project.json` file for the project
139
- */
140
- projectJson = void 0;
141
- /**
142
- * The module resolver for the project
143
- */
144
- resolver;
145
- /**
146
- * The resolved configuration options
147
- */
148
- resolvePatterns = [];
149
- /**
150
- * Internal context fields and methods
151
- *
152
- * @danger
153
- * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
154
- *
155
- * @internal
156
- */
157
- get $$internal() {
158
- return this.#internal;
159
- }
160
- /**
161
- * Internal context fields and methods
162
- *
163
- * @danger
164
- * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.
165
- *
166
- * @internal
167
- */
168
- set $$internal(value) {
169
- this.#internal = value;
170
- }
171
- /**
172
- * The resolved entry type definitions for the project
173
- */
174
- get entry() {
175
- const entry = this._entry;
176
- return resolveEntriesSync(this, !entry || entry.length === 0 ? toArray(this.config.entry) : entry);
177
- }
178
- /**
179
- * The TypeScript configuration parsed from the tsconfig file
180
- */
181
- get tsconfig() {
182
- if (!this.#tsconfig) this.tsconfig = { tsconfigFilePath: this.config.tsconfig };
183
- return this.#tsconfig;
184
- }
185
- /**
186
- * Sets the TypeScript configuration parsed from the tsconfig file
187
- */
188
- set tsconfig(value) {
189
- this.#tsconfig = value;
190
- this.resolvePatterns = tsconfigPathsToRegExp(value?.options?.paths ?? {});
191
- }
192
- /**
193
- * The virtual file system interface for the project
194
- */
195
- get fs() {
196
- if (!this.#fs) this.#fs = VirtualFileSystem.createSync(this);
197
- return this.#fs;
198
- }
199
- /**
200
- * Get the checksum of the project's current state
201
- */
202
- get checksum() {
203
- return this.#checksum;
204
- }
205
- /**
206
- * The meta information about the current build
207
- */
208
- get meta() {
209
- return {
210
- buildId: this.#buildId,
211
- releaseId: this.#releaseId,
212
- checksum: this.#checksum,
213
- timestamp: this.#timestamp,
214
- projectRootHash: murmurhash({
215
- workspaceRoot: this.workspaceConfig?.workspaceRoot,
216
- projectRoot: this.config?.projectRoot
217
- }, { maxLength: PROJECT_ROOT_HASH_LENGTH }),
218
- configHash: murmurhash(this.config, { maxLength: CACHE_HASH_LENGTH })
219
- };
220
- }
221
- /**
222
- * The resolved configuration options
223
- */
224
- get config() {
225
- return this.resolvedConfig ?? {};
226
- }
227
- /**
228
- * The logger function
229
- */
230
- get log() {
231
- if (!this.logFn) this.logFn = this.createLog();
232
- return this.logFn;
233
- }
234
- /**
235
- * The workspace configuration
236
- */
237
- get workspaceConfig() {
238
- return this.#workspaceConfig;
239
- }
240
- /**
241
- * The environment paths for the project
242
- */
243
- get envPaths() {
244
- if (envPathCache.has({
245
- workspaceRoot: this.workspaceConfig.workspaceRoot,
246
- framework: this.config?.framework || "powerlines"
247
- })) return envPathCache.get({
248
- workspaceRoot: this.workspaceConfig.workspaceRoot,
249
- framework: this.config?.framework || "powerlines"
250
- });
251
- const envPaths = getEnvPaths({
252
- orgId: "storm-software",
253
- appId: this.config?.framework || "powerlines",
254
- workspaceRoot: this.workspaceConfig.workspaceRoot
255
- });
256
- envPathCache.set({
257
- workspaceRoot: this.workspaceConfig.workspaceRoot,
258
- framework: this.config?.framework || "powerlines"
259
- }, envPaths);
260
- return envPaths;
261
- }
262
- /**
263
- * Get the path to the artifacts directory for the project
264
- */
265
- get artifactsPath() {
266
- return joinPaths(this.workspaceConfig.workspaceRoot, this.config.projectRoot, this.config.output.artifactsPath);
267
- }
268
- /**
269
- * Get the path to the builtin modules used by the project
270
- */
271
- get builtinsPath() {
272
- return joinPaths(this.artifactsPath, "builtins");
273
- }
274
- /**
275
- * Get the path to the entry directory for the project
276
- */
277
- get entryPath() {
278
- return joinPaths(this.artifactsPath, "entry");
279
- }
280
- /**
281
- * Get the path to the data directory for the project
282
- */
283
- get dataPath() {
284
- return joinPaths(this.envPaths.data, "projects", getPrefixedProjectRootHash(this.config.name, this.meta.projectRootHash));
285
- }
286
- /**
287
- * Get the path to the cache directory for the project
288
- */
289
- get cachePath() {
290
- return joinPaths(this.envPaths.cache, "projects", murmurhash({
291
- checksum: this.#checksum,
292
- config: this.meta.configHash
293
- }, { maxLength: CACHE_HASH_LENGTH }));
294
- }
295
- /**
296
- * Get the path to the generated declaration file for the project
297
- */
298
- get dtsPath() {
299
- return this.config.output.dts ? appendPath(this.config.output.dts, this.workspaceConfig.workspaceRoot) : joinPaths(this.workspaceConfig.workspaceRoot, this.config.projectRoot, "powerlines.d.ts");
300
- }
301
- /**
302
- * Get the project root relative to the workspace root
303
- */
304
- get relativeToWorkspaceRoot() {
305
- return relativeToWorkspaceRoot(this.config.projectRoot);
306
- }
307
- /**
308
- * The builtin module id that exist in the Powerlines virtual file system
309
- */
310
- get builtins() {
311
- return Object.values(this.fs.metadata).filter((meta) => meta && meta.type === "builtin").map((meta) => meta?.id).filter(Boolean);
312
- }
313
- /**
314
- * The alias mappings for the project used during module resolution
315
- *
316
- * @remarks
317
- * This includes both the built-in module aliases as well as any custom aliases defined in the build configuration.
318
- */
319
- get alias() {
320
- return this.builtins.reduce((ret, id) => {
321
- const moduleId = `${this.config?.framework || "powerlines"}:${id.replace(/^.*?:/, "")}`;
322
- if (!ret[moduleId]) {
323
- const path = this.fs.paths[id];
324
- if (path) ret[moduleId] = path;
325
- }
326
- return ret;
327
- }, this.config.build.alias ? Array.isArray(this.config.build.alias) ? this.config.build.alias.reduce((ret, alias) => {
328
- if (!ret[alias.find.toString()]) ret[alias.find.toString()] = alias.replacement;
329
- return ret;
330
- }, {}) : this.config.build.alias : {});
331
- }
332
- /**
333
- * Gets the parser cache.
334
- */
335
- get parserCache() {
336
- if (!this.#parserCache) this.#parserCache = create({
337
- cacheId: "parser",
338
- cacheDir: this.cachePath,
339
- ttl: 7200 * 1e3,
340
- lruSize: 5e3,
341
- persistInterval: 250
342
- });
343
- return this.#parserCache;
344
- }
345
- /**
346
- * Gets the request cache.
347
- */
348
- get requestCache() {
349
- if (!this.#requestCache) this.#requestCache = create({
350
- cacheId: "http",
351
- cacheDir: this.cachePath,
352
- ttl: 360 * 60 * 1e3,
353
- lruSize: 5e3,
354
- persistInterval: 250
355
- });
356
- return this.#requestCache;
357
- }
358
- /**
359
- * The entry points that exist in the Powerlines virtual file system
360
- */
361
- get _entry() {
362
- return Object.entries(this.fs.metadata).filter(([, meta]) => meta && meta.type === "entry").map(([path, meta]) => {
363
- const typeDefinition = { file: path };
364
- if (meta.properties) {
365
- if (isSetString(meta.properties.file)) typeDefinition.file = meta.properties.file;
366
- if (isSetString(meta.properties.name)) typeDefinition.name = meta.properties.name;
367
- if (isSetString(meta.properties["input.file"]) || isSetString(meta.properties["input.name"])) {
368
- typeDefinition.input ??= {};
369
- if (isSetString(meta.properties["input.file"])) typeDefinition.input.file = meta.properties["input.file"];
370
- if (isSetString(meta.properties["input.name"])) typeDefinition.input.name = meta.properties["input.name"];
371
- }
372
- if (isSetString(meta.properties.output)) typeDefinition.output = meta.properties.output;
373
- }
374
- return typeDefinition;
375
- }).filter(Boolean);
376
- }
377
- /**
378
- * A function to perform HTTP fetch requests
379
- *
380
- * @remarks
381
- * This function uses a caching layer to avoid duplicate requests during the Powerlines process.
382
- *
383
- * @example
384
- * ```ts
385
- * const response = await context.fetch("https://api.example.com/data");
386
- * const data = await response.json();
387
- * ```
388
- *
389
- * @see https://github.com/nodejs/undici
390
- *
391
- * @param input - The URL to fetch.
392
- * @param options - The fetch request options.
393
- * @returns A promise that resolves to a response returned by the fetch.
394
- */
395
- async fetch(input, options = {}) {
396
- const cacheKey = murmurhash({
397
- input: input.toString(),
398
- options: JSON.stringify(options)
399
- });
400
- if (!this.config.skipCache && !options.skipCache) {
401
- const cached = this.requestCache.get(cacheKey);
402
- if (cached) return new Response(cached.body, {
403
- status: cached.status,
404
- statusText: cached.statusText,
405
- headers: cached.headers
406
- });
407
- }
408
- const response = await fetchRequest(input, {
409
- timeout: 12e3,
410
- ...options
411
- });
412
- const result = {
413
- body: await response.text(),
414
- status: response.status,
415
- statusText: response.statusText,
416
- headers: Object.fromEntries(response.headers.entries())
417
- };
418
- if (!this.config.skipCache && !options.skipCache) try {
419
- this.requestCache.set(cacheKey, result);
420
- } catch {}
421
- return new Response(result.body, {
422
- status: result.status,
423
- statusText: result.statusText,
424
- headers: result.headers
425
- });
426
- }
427
- /**
428
- * Parse code using [Oxc-Parser](https://github.com/oxc/oxc) into an (ESTree-compatible)[https://github.com/estree/estree] AST object.
429
- *
430
- * @remarks
431
- * This function can be used to parse TypeScript code into an AST for further analysis or transformation.
432
- *
433
- * @example
434
- * ```ts
435
- * const ast = context.parse("const x: number = 42;");
436
- * ```
437
- *
438
- * @see https://rollupjs.org/plugin-development/#this-parse
439
- * @see https://github.com/oxc/oxc
440
- *
441
- * @param code - The source code to parse.
442
- * @param options - The options to pass to the parser.
443
- * @returns An (ESTree-compatible)[https://github.com/estree/estree] AST object.
444
- */
445
- async parse(code, options = {}) {
446
- const cacheKey = murmurhash({
447
- code,
448
- options
449
- });
450
- let result;
451
- if (!this.config.skipCache) {
452
- result = this.parserCache.get(cacheKey);
453
- if (result) return result;
454
- }
455
- result = await parse(`source.${options.lang || "ts"}`, code, {
456
- ...options,
457
- sourceType: "module",
458
- showSemanticErrors: this.config.mode === "development"
459
- });
460
- if (!this.config.skipCache) this.parserCache.set(cacheKey, result);
461
- return result;
462
- }
463
- /**
464
- * A helper function to resolve modules in the Virtual File System
465
- *
466
- * @remarks
467
- * This function can be used to resolve modules relative to the project root directory.
468
- *
469
- * @example
470
- * ```ts
471
- * const resolved = await context.resolve("some-module", "/path/to/importer");
472
- * ```
473
- *
474
- * @param id - The module to resolve.
475
- * @param importer - An optional path to the importer module.
476
- * @param options - Additional resolution options.
477
- * @returns A promise that resolves to the resolved module path.
478
- */
479
- async resolve(id, importer, options = {}) {
480
- let moduleId = id;
481
- if (this.config.build.alias) {
482
- if (Array.isArray(this.config.build.alias)) {
483
- const alias = this.config.build.alias.find((a) => match(moduleId, [a.find]));
484
- if (alias) moduleId = alias.replacement;
485
- } else if (isSetObject(this.config.build.alias) && this.config.build.alias[id]) moduleId = this.config.build.alias[id];
486
- }
487
- if (this.fs.isVirtual(moduleId)) {
488
- const result = await this.fs.resolve(moduleId, importer, {
489
- conditions: this.config.build.conditions,
490
- extensions: this.config.build.extensions,
491
- ...options
492
- });
493
- if (!result) return;
494
- return {
495
- id: `\0${result}`,
496
- external: this.config.projectType !== "application"
497
- };
498
- }
499
- if (this.config.build.skipNodeModulesBundle) {
500
- if (match(moduleId, this.resolvePatterns) || match(moduleId, this.config.build.noExternal)) return;
501
- if (match(moduleId, this.config.build.external) || moduleId.startsWith("node:")) return {
502
- id: moduleId,
503
- external: true
504
- };
505
- if (!/^[A-Z]:[/\\]|^\.{0,2}\/|^\.{1,2}$/.test(moduleId)) return {
506
- id: moduleId,
507
- external: true
508
- };
509
- } else {
510
- if (match(moduleId, this.config.build.noExternal)) return;
511
- if (match(moduleId, this.config.build.external) || moduleId.startsWith("node:")) return {
512
- id: moduleId,
513
- external: true
514
- };
515
- }
516
- }
517
- /**
518
- * A helper function to load modules from the Virtual File System
519
- *
520
- * @remarks
521
- * This function can be used to load modules relative to the project root directory.
522
- *
523
- * @example
524
- * ```ts
525
- * const module = await context.load("some-module", "/path/to/importer");
526
- * ```
527
- *
528
- * @param id - The module to load.
529
- * @returns A promise that resolves to the loaded module.
530
- */
531
- async load(id) {
532
- const resolvedId = await this.fs.resolve(id);
533
- if (!resolvedId) return;
534
- const code = await this.fs.read(resolvedId);
535
- if (!code) return;
536
- return {
537
- code,
538
- map: null
539
- };
540
- }
541
- /**
542
- * Get the builtin virtual files that exist in the Powerlines virtual file system
543
- */
544
- async getBuiltins() {
545
- return Promise.all(Object.entries(this.fs.metadata).filter(([, meta]) => meta && meta.type === "builtin").map(async ([id, meta]) => {
546
- const code = await this.fs.read(id);
547
- const path = this.fs.paths[id];
548
- return {
549
- ...meta,
550
- path,
551
- code
552
- };
553
- }));
554
- }
555
- /**
556
- * Resolves a file and writes it to the VFS if it does not already exist
557
- *
558
- * @param code - The source code of the file
559
- * @param path - The path to write the file to
560
- * @param options - Additional options for writing the file
561
- */
562
- async emit(code, path, options = {}) {
563
- 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`;
564
- if (isFunction(this.emitFile) && options.emitWithBundler) return this.emitFile({
565
- needsCodeReference: options.needsCodeReference,
566
- originalFileName: options.originalFileName,
567
- fileName: filePath,
568
- source: code,
569
- type: "asset"
570
- });
571
- return this.fs.write(filePath, code, options);
572
- }
573
- /**
574
- * Synchronously resolves a file and writes it to the VFS if it does not already exist
575
- *
576
- * @param code - The source code of the file
577
- * @param path - The path to write the file to
578
- * @param options - Additional options for writing the file
579
- */
580
- emitSync(code, path, options = {}) {
581
- 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`;
582
- if (isFunction(this.emitFile) && options.emitWithBundler) return this.emitFile({
583
- needsCodeReference: options.needsCodeReference,
584
- originalFileName: options.originalFileName,
585
- fileName: filePath,
586
- source: code,
587
- type: "asset"
588
- });
589
- return this.fs.writeSync(filePath, code, options);
590
- }
591
- /**
592
- * Resolves a entry virtual file and writes it to the VFS if it does not already exist
593
- *
594
- * @param code - The source code of the entry file
595
- * @param path - A path to write the entry file to
596
- * @param options - Optional write file options
597
- */
598
- async emitEntry(code, path, options = {}) {
599
- return this.emit(code, appendPath(path, this.entryPath), defu$1({ meta: {
600
- type: "entry",
601
- properties: {
602
- file: appendPath(path, this.entryPath),
603
- name: options?.name,
604
- output: options?.output,
605
- "input.file": options?.input?.file,
606
- "input.name": options?.input?.name
607
- }
608
- } }, omit(options, ["name"])));
609
- }
610
- /**
611
- * Synchronously resolves a entry virtual file and writes it to the VFS if it does not already exist
612
- *
613
- * @param code - The source code of the entry file
614
- * @param path - A path to write the entry file to
615
- * @param options - Optional write file options
616
- */
617
- emitEntrySync(code, path, options = {}) {
618
- return this.emitSync(code, appendPath(path, this.entryPath), defu$1({ meta: {
619
- type: "entry",
620
- properties: {
621
- file: appendPath(path, this.entryPath),
622
- name: options?.name,
623
- output: options?.output,
624
- "input.file": options?.input?.file,
625
- "input.name": options?.input?.name
626
- }
627
- } }, omit(options, ["name"])));
628
- }
629
- /**
630
- * Resolves a builtin virtual file and writes it to the VFS if it does not already exist
631
- *
632
- * @param code - The source code of the builtin file
633
- * @param id - The unique identifier of the builtin file
634
- * @param options - Optional write file options
635
- */
636
- async emitBuiltin(code, id, options = {}) {
637
- if (!this.builtinsPath) throw new Error(`The builtins path is not set. Cannot emit builtin file with id "${id}".`);
638
- if (!isSetString(id)) throw new Error(`The builtin id must be a non-empty string. Received: ${String(id)}`);
639
- return this.emit(code, appendPath(id, this.builtinsPath), defu$1(options, { meta: {
640
- type: "builtin",
641
- id
642
- } }));
643
- }
644
- /**
645
- * Synchronously resolves a builtin virtual file and writes it to the VFS if it does not already exist
646
- *
647
- * @param code - The source code of the builtin file
648
- * @param id - The unique identifier of the builtin file
649
- * @param options - Optional write file options
650
- */
651
- emitBuiltinSync(code, id, options = {}) {
652
- if (!this.builtinsPath) throw new Error(`The builtins path is not set. Cannot emit builtin file with id "${id}".`);
653
- if (!isSetString(id)) throw new Error(`The builtin id must be a non-empty string. Received: ${String(id)}`);
654
- return this.emitSync(code, appendPath(id, this.builtinsPath), defu$1(options, { meta: {
655
- type: "builtin",
656
- id
657
- } }));
658
- }
659
- /**
660
- * Update the context using a new user configuration options
661
- *
662
- * @param userConfig - The new user configuration options.
663
- */
664
- async withUserConfig(userConfig, options = { isHighPriority: true }) {
665
- this.mergeUserConfig(userConfig);
666
- await this.init(this.config.userConfig, options);
667
- }
668
- /**
669
- * Update the context using a new inline configuration options
670
- *
671
- * @param inlineConfig - The new inline configuration options.
672
- */
673
- async withInlineConfig(inlineConfig, options = { isHighPriority: true }) {
674
- this.config.inlineConfig = inlineConfig;
675
- if (inlineConfig.command === "new") {
676
- const workspacePackageJsonPath = joinPaths(this.workspaceConfig.workspaceRoot, "package.json");
677
- if (!existsSync(workspacePackageJsonPath)) throw new Error(`The workspace package.json file could not be found at ${workspacePackageJsonPath}`);
678
- this.packageJson = await readJsonFile(workspacePackageJsonPath);
679
- this.workspaceConfig.repository ??= isSetString(this.packageJson?.repository) ? this.packageJson.repository : this.packageJson?.repository?.url;
680
- }
681
- await this.init(this.config.inlineConfig, options);
682
- }
683
- /**
684
- * A logging function for fatal messages
685
- *
686
- * @param message - The message to log.
687
- */
688
- fatal(message) {
689
- this.log(LogLevelLabel.FATAL, isString(message) ? message : StormJSON.stringify(message));
690
- }
691
- /**
692
- * A logging function for error messages
693
- *
694
- * @param message - The message to log.
695
- */
696
- error(message) {
697
- this.log(LogLevelLabel.ERROR, isString(message) ? message : StormJSON.stringify(message));
698
- }
699
- /**
700
- * A logging function for warning messages
701
- *
702
- * @param message - The message to log.
703
- */
704
- warn(message) {
705
- this.log(LogLevelLabel.WARN, isString(message) ? message : StormJSON.stringify(message));
706
- }
707
- /**
708
- * A logging function for informational messages
709
- *
710
- * @param message - The message to log.
711
- */
712
- info(message) {
713
- this.log(LogLevelLabel.INFO, isString(message) ? message : StormJSON.stringify(message));
714
- }
715
- /**
716
- * A logging function for debug messages
717
- *
718
- * @param message - The message to log.
719
- */
720
- debug(message) {
721
- this.log(LogLevelLabel.DEBUG, isString(message) ? message : StormJSON.stringify(message));
722
- }
723
- /**
724
- * A logging function for trace messages
725
- *
726
- * @param message - The message to log.
727
- */
728
- trace(message) {
729
- this.log(LogLevelLabel.TRACE, isString(message) ? message : StormJSON.stringify(message));
730
- }
731
- /**
732
- * Create a new logger instance
733
- *
734
- * @param name - The name to use for the logger instance
735
- * @returns A logger function
736
- */
737
- createLog(name = null) {
738
- return createLog(name, {
739
- ...this.config,
740
- logLevel: isNull(this.config.logLevel) ? "silent" : this.config.logLevel
741
- });
742
- }
743
- /**
744
- * Extend the current logger instance with a new name
745
- *
746
- * @param name - The name to use for the extended logger instance
747
- * @returns A logger function
748
- */
749
- extendLog(name) {
750
- return extendLog(this.log, name);
751
- }
752
- /**
753
- * Generates a checksum representing the current context state
754
- *
755
- * @param root - The root directory of the project to generate the checksum for
756
- * @returns A promise that resolves to a string representing the checksum
757
- */
758
- async generateChecksum(root = this.config.projectRoot) {
759
- this.#checksum = await hashDirectory(root, { ignore: [
760
- "node_modules",
761
- ".git",
762
- ".nx",
763
- ".cache",
764
- "tmp",
765
- "dist"
766
- ] });
767
- return this.#checksum;
768
- }
769
- /**
770
- * Creates a new StormContext instance.
771
- *
772
- * @param workspaceConfig - The workspace configuration.
773
- */
774
- constructor(workspaceConfig) {
775
- this.#workspaceConfig = workspaceConfig;
776
- envPathCache.set({
777
- workspaceRoot: workspaceConfig.workspaceRoot,
778
- framework: "powerlines"
779
- }, getEnvPaths({
780
- orgId: (isSetObject(workspaceConfig.organization) ? workspaceConfig.organization.name : workspaceConfig.organization) || "storm-software",
781
- appId: "powerlines",
782
- workspaceRoot: workspaceConfig.workspaceRoot
783
- }));
784
- }
785
- /**
786
- * The resolved configuration for this context
787
- */
788
- resolvedConfig = {};
789
- /**
790
- * A logger function specific to this context
791
- */
792
- logFn;
793
- /**
794
- * Initialize the context with the provided configuration options
795
- *
796
- * @param config - The partial user configuration to use for initialization.
797
- */
798
- async init(config = {}, options = { isHighPriority: true }) {
799
- const cacheKey = {
800
- projectRoot: config.root ?? this.config.projectRoot ?? this.config.userConfig?.root ?? this.config.inlineConfig?.root,
801
- mode: (config.mode ?? this.config.mode) || this.workspaceConfig.mode,
802
- skipCache: config.skipCache ?? this.config.skipCache ?? false,
803
- configFile: config.configFile ?? this.config.configFile,
804
- framework: config.framework ?? this.config.framework ?? "powerlines",
805
- command: this.config.inlineConfig?.command,
806
- alias: this.config.build?.alias ?? config.build?.alias
807
- };
808
- if (configCache.has(cacheKey)) {
809
- const result = configCache.get(cacheKey);
810
- this.projectJson = result.projectJson;
811
- this.packageJson = result.packageJson;
812
- this.#checksum = result.checksum;
813
- this.resolver = result.resolver;
814
- this.mergeUserConfig(result.userConfig.config, this.config.userConfig);
815
- } else {
816
- const projectJsonPath = joinPaths(cacheKey.projectRoot, "project.json");
817
- if (existsSync(projectJsonPath)) this.projectJson = await readJsonFile(projectJsonPath);
818
- const packageJsonPath = joinPaths(cacheKey.projectRoot, "package.json");
819
- if (existsSync(packageJsonPath)) this.packageJson = await readJsonFile(packageJsonPath);
820
- this.#checksum = await this.generateChecksum(cacheKey.projectRoot);
821
- this.resolver = createResolver({
822
- workspaceRoot: this.workspaceConfig.workspaceRoot,
823
- projectRoot: cacheKey.projectRoot,
824
- cacheDir: this.cachePath,
825
- mode: cacheKey.mode,
826
- logLevel: config.logLevel || this.config.logLevel || this.workspaceConfig.logLevel || "info",
827
- skipCache: cacheKey.skipCache,
828
- alias: this.config.build?.alias ? Array.isArray(this.config.build.alias) ? this.config.build.alias.reduce((ret, alias) => {
829
- ret[alias.find.toString()] = alias.replacement;
830
- return ret;
831
- }, {}) : this.config.build.alias : {}
832
- });
833
- const userConfig = await loadUserConfigFile(cacheKey.projectRoot, this.workspaceConfig.workspaceRoot, this.resolver, cacheKey.command, cacheKey.mode, cacheKey.configFile, cacheKey.framework);
834
- this.mergeUserConfig(userConfig.config);
835
- configCache.set(cacheKey, {
836
- projectJson: this.projectJson,
837
- packageJson: this.packageJson,
838
- checksum: this.#checksum,
839
- resolver: this.resolver,
840
- userConfig
841
- });
842
- }
843
- config.tsconfig ??= getTsconfigFilePath(this.workspaceConfig.workspaceRoot, cacheKey.projectRoot, config.tsconfig);
844
- if (isSetObject(config)) this.resolvedConfig = defu$1({
845
- inlineConfig: this.config.inlineConfig,
846
- userConfig: this.config.userConfig
847
- }, options.isHighPriority ? this.#getConfigProps(config) : {}, {
848
- command: this.config.inlineConfig?.command,
849
- ...this.#getConfigProps(this.config.inlineConfig)
850
- }, this.#getConfigProps(this.config.userConfig), {
851
- mode: this.workspaceConfig?.mode,
852
- logLevel: this.workspaceConfig?.logLevel,
853
- skipCache: this.workspaceConfig?.skipCache
854
- }, {
855
- name: this.projectJson?.name || this.packageJson?.name,
856
- version: this.packageJson?.version,
857
- description: this.packageJson?.description,
858
- sourceRoot: this.projectJson?.sourceRoot || appendPath("src", cacheKey.projectRoot),
859
- output: defu$1(config.output ?? {}, {
860
- outputPath: cacheKey.projectRoot ? joinPaths(this.workspaceConfig?.directories?.build || "dist", cacheKey.projectRoot) : this.workspaceConfig?.directories?.build || "dist",
861
- artifactsPath: `.${config.framework ?? "powerlines"}`,
862
- dts: joinPaths(cacheKey.projectRoot, `${config.framework ?? "powerlines"}.d.ts`),
863
- assets: [
864
- { glob: "LICENSE" },
865
- {
866
- input: cacheKey.projectRoot,
867
- glob: "*.md"
868
- },
869
- {
870
- input: cacheKey.projectRoot,
871
- glob: "package.json"
872
- }
873
- ]
874
- })
875
- }, options.isHighPriority ? {} : this.#getConfigProps(config), {
876
- inlineConfig: {},
877
- userConfig: {},
878
- framework: "powerlines",
879
- mode: "production",
880
- projectType: "application",
881
- logLevel: "info",
882
- preview: false,
883
- environments: {},
884
- transform: { babel: {
885
- plugins: [],
886
- presets: []
887
- } },
888
- lint: { eslint: {} },
889
- build: {
890
- target: "esnext",
891
- platform: "neutral",
892
- override: {}
893
- }
894
- });
895
- this.config.entry = getUniqueEntries(this.config.entry);
896
- if (this.config.name?.startsWith("@") && this.config.name.split("/").filter(Boolean).length > 1) this.config.name = this.config.name.split("/").filter(Boolean)[1];
897
- this.config.title ??= titleCase(this.config.name);
898
- 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;
899
- if (this.config.userConfig.build?.external) this.config.userConfig.build.external = getUnique(this.config.userConfig.build.external);
900
- if (this.config.userConfig.build?.noExternal) this.config.userConfig.build.noExternal = getUnique(this.config.userConfig.build.noExternal);
901
- if (this.config.build.external) this.config.build.external = getUnique(this.config.build.external);
902
- if (this.config.build.noExternal) this.config.build.noExternal = getUnique(this.config.build.noExternal);
903
- this.config.output.format = getUnique(toArray(this.config.output?.format ?? (this.config.projectType === "library" ? ["cjs", "esm"] : ["esm"])));
904
- if (this.config.projectRoot && this.config.projectRoot !== "." && this.config.projectRoot !== "./" && this.config.projectRoot !== this.workspaceConfig.workspaceRoot) {
905
- this.config.output.outputPath ??= joinPaths("dist", this.config.projectRoot);
906
- this.config.output.buildPath ??= joinPaths(this.config.projectRoot, "dist");
907
- } else {
908
- this.config.output.outputPath ??= "dist";
909
- this.config.output.buildPath ??= "dist";
910
- }
911
- this.config.output.assets = getUniqueBy(this.config.output.assets.map((asset) => {
912
- return {
913
- glob: isSetObject(asset) ? asset.glob : asset,
914
- 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),
915
- output: isSetObject(asset) && asset.output ? isParentPath(asset.output, this.workspaceConfig.workspaceRoot) ? asset.output : appendPath(joinPaths(this.config.output.outputPath, replacePath(replacePath(asset.output, replacePath(this.config.output.outputPath, this.workspaceConfig.workspaceRoot)), this.config.output.outputPath)), this.workspaceConfig.workspaceRoot) : appendPath(this.config.output.outputPath, this.workspaceConfig.workspaceRoot),
916
- ignore: isSetObject(asset) && asset.ignore ? toArray(asset.ignore) : void 0
917
- };
918
- }), (a) => `${a.input}-${a.glob}-${a.output}`);
919
- this.config.plugins = (this.config.plugins ?? []).filter(Boolean).reduce((ret, plugin) => {
920
- if (isPlugin(plugin) && checkDedupe(plugin, ret.filter((p) => isPlugin(p)))) return ret;
921
- ret.push(plugin);
922
- return ret;
923
- }, []);
924
- if (this.config.tsconfig) this.config.tsconfig = replacePathTokens(this, this.config.tsconfig);
925
- if (this.config.output.dts) if (isSetString(this.config.output.dts)) this.config.output.dts = replacePathTokens(this, this.config.output.dts);
926
- else this.config.output.dts = joinPaths(this.config.projectRoot, `${this.config.framework ?? "powerlines"}.d.ts`);
927
- if (this.config.build.polyfill) this.config.build.polyfill = this.config.build.polyfill.map((polyfill) => replacePathTokens(this, polyfill));
928
- if (this.config.output.assets) this.config.output.assets = this.config.output.assets.map((asset) => ({
929
- ...asset,
930
- glob: replacePathTokens(this, asset.glob),
931
- ignore: asset.ignore ? asset.ignore.map((ignore) => replacePathTokens(this, ignore)) : void 0,
932
- input: replacePathTokens(this, asset.input),
933
- output: replacePathTokens(this, asset.output)
934
- }));
935
- this.#fs ??= await VirtualFileSystem.create(this);
936
- }
937
- mergeUserConfig(from = {}, into = this.config.userConfig ?? {}) {
938
- this.config.userConfig = defu$1({ entry: Array.isArray(from.entry) && from.entry.length > 0 ? from.entry : Array.isArray(into?.entry) && into.entry.length > 0 ? into.entry : [] }, omit(from ?? {}, ["entry"]), omit(into ?? {}, ["entry"]));
939
- if (this.config.userConfig.output?.format) this.config.userConfig.output.format = getUnique(toArray(this.config.userConfig.output?.format));
940
- this.config.userConfig.plugins = (this.config.userConfig.plugins ?? []).filter(Boolean).reduce((ret, plugin) => {
941
- if (isPlugin(plugin) && checkDedupe(plugin, ret.filter((p) => isPlugin(p)))) return ret;
942
- ret.push(plugin);
943
- return ret;
944
- }, []);
945
- }
946
- };
947
-
948
- //#endregion
949
- export { PowerlinesContext };