@powerlines/engine 0.14.5 → 0.15.1

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