@powerlines/plugin-webpack 0.5.136 → 0.5.138

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