@storm-software/unbuild 0.33.9 → 0.33.11

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.
@@ -1,2519 +0,0 @@
1
- import {
2
- cleanDirectories
3
- } from "./chunk-ERYQ4O3N.js";
4
- import {
5
- getDefaultBuildPlugins
6
- } from "./chunk-SRY6IWKG.js";
7
- import {
8
- loadConfig
9
- } from "./chunk-I3ATI525.js";
10
- import {
11
- COLOR_KEYS,
12
- LogLevel,
13
- LogLevelLabel,
14
- STORM_DEFAULT_DOCS,
15
- STORM_DEFAULT_HOMEPAGE,
16
- STORM_DEFAULT_LICENSING,
17
- StormConfigSchema,
18
- correctPaths,
19
- findWorkspaceRoot,
20
- formatLogMessage,
21
- getDefaultConfig,
22
- getLogLevel,
23
- getLogLevelLabel,
24
- getStopwatch,
25
- isVerbose,
26
- joinPaths,
27
- writeDebug,
28
- writeFatal,
29
- writeSuccess,
30
- writeTrace,
31
- writeWarning
32
- } from "./chunk-J4VTEQNQ.js";
33
- import {
34
- __name
35
- } from "./chunk-3GQAWCBQ.js";
36
-
37
- // src/build.ts
38
- import { readCachedProjectGraph as readCachedProjectGraph2, writeJsonFile } from "@nx/devkit";
39
- import { getHelperDependency, HelperDependency } from "@nx/js";
40
- import { calculateProjectBuildableDependencies as calculateProjectBuildableDependencies2 } from "@nx/js/src/utils/buildable-libs-utils";
41
-
42
- // ../build-tools/src/plugins/swc.ts
43
- import { transform } from "@swc/core";
44
-
45
- // ../build-tools/src/plugins/ts-resolve.ts
46
- import fs from "node:fs";
47
- import { builtinModules } from "node:module";
48
- import path from "node:path";
49
- import _resolve from "resolve";
50
-
51
- // ../build-tools/src/plugins/type-definitions.ts
52
- import { stripIndents } from "@nx/devkit";
53
- import { relative } from "path";
54
-
55
- // ../build-tools/src/utilities/copy-assets.ts
56
- import { CopyAssetsHandler } from "@nx/js/src/utils/assets/copy-assets-handler";
57
- import { glob } from "glob";
58
- import { readFile, writeFile } from "node:fs/promises";
59
- var copyAssets = /* @__PURE__ */ __name(async (config, assets, outputPath, projectRoot, sourceRoot, generatePackageJson2 = true, includeSrc = false, banner, footer) => {
60
- const pendingAssets = Array.from(assets ?? []);
61
- pendingAssets.push({
62
- input: projectRoot,
63
- glob: "*.md",
64
- output: "."
65
- });
66
- pendingAssets.push({
67
- input: ".",
68
- glob: "LICENSE",
69
- output: "."
70
- });
71
- if (generatePackageJson2 === false) {
72
- pendingAssets.push({
73
- input: projectRoot,
74
- glob: "package.json",
75
- output: "."
76
- });
77
- }
78
- if (includeSrc === true) {
79
- pendingAssets.push({
80
- input: sourceRoot,
81
- glob: "**/{*.ts,*.tsx,*.js,*.jsx}",
82
- output: "src/"
83
- });
84
- }
85
- writeTrace(`\u{1F4DD} Copying the following assets to the output directory:
86
- ${pendingAssets.map((pendingAsset) => typeof pendingAsset === "string" ? ` - ${pendingAsset} -> ${outputPath}` : ` - ${pendingAsset.input}/${pendingAsset.glob} -> ${joinPaths(outputPath, pendingAsset.output)}`).join("\n")}`, config);
87
- const assetHandler = new CopyAssetsHandler({
88
- projectDir: projectRoot,
89
- rootDir: config.workspaceRoot,
90
- outputDir: outputPath,
91
- assets: pendingAssets
92
- });
93
- await assetHandler.processAllAssetsOnce();
94
- if (includeSrc === true) {
95
- writeDebug(`\u{1F4DD} Adding banner and writing source files: ${joinPaths(outputPath, "src")}`, config);
96
- const files = await glob([
97
- joinPaths(config.workspaceRoot, outputPath, "src/**/*.ts"),
98
- joinPaths(config.workspaceRoot, outputPath, "src/**/*.tsx"),
99
- joinPaths(config.workspaceRoot, outputPath, "src/**/*.js"),
100
- joinPaths(config.workspaceRoot, outputPath, "src/**/*.jsx")
101
- ]);
102
- await Promise.allSettled(files.map(async (file) => writeFile(file, `${banner && typeof banner === "string" ? banner.startsWith("//") ? banner : `// ${banner}` : ""}
103
-
104
- ${await readFile(file, "utf8")}
105
-
106
- ${footer && typeof footer === "string" ? footer.startsWith("//") ? footer : `// ${footer}` : ""}`)));
107
- }
108
- }, "copyAssets");
109
-
110
- // ../build-tools/src/utilities/generate-package-json.ts
111
- import { calculateProjectBuildableDependencies } from "@nx/js/src/utils/buildable-libs-utils";
112
- import { Glob } from "glob";
113
- import { existsSync } from "node:fs";
114
- import { readFile as readFile2 } from "node:fs/promises";
115
- import { readCachedProjectGraph } from "nx/src/project-graph/project-graph";
116
- var addPackageDependencies = /* @__PURE__ */ __name(async (workspaceRoot, projectRoot, projectName, packageJson) => {
117
- const projectDependencies = calculateProjectBuildableDependencies(void 0, readCachedProjectGraph(), workspaceRoot, projectName, process.env.NX_TASK_TARGET_TARGET || "build", process.env.NX_TASK_TARGET_CONFIGURATION || "production", true);
118
- const localPackages = [];
119
- for (const project of projectDependencies.dependencies.filter((dep) => dep.node.type === "lib" && dep.node.data.root !== projectRoot && dep.node.data.root !== workspaceRoot)) {
120
- const projectNode = project.node;
121
- if (projectNode.data.root) {
122
- const projectPackageJsonPath = joinPaths(workspaceRoot, projectNode.data.root, "package.json");
123
- if (existsSync(projectPackageJsonPath)) {
124
- const projectPackageJsonContent = await readFile2(projectPackageJsonPath, "utf8");
125
- const projectPackageJson = JSON.parse(projectPackageJsonContent);
126
- if (projectPackageJson.private !== false) {
127
- localPackages.push(projectPackageJson);
128
- }
129
- }
130
- }
131
- }
132
- if (localPackages.length > 0) {
133
- writeTrace(`\u{1F4E6} Adding local packages to package.json: ${localPackages.map((p) => p.name).join(", ")}`);
134
- packageJson.peerDependencies = localPackages.reduce((ret, localPackage) => {
135
- if (!ret[localPackage.name]) {
136
- ret[localPackage.name] = `>=${localPackage.version || "0.0.1"}`;
137
- }
138
- return ret;
139
- }, packageJson.peerDependencies ?? {});
140
- packageJson.peerDependenciesMeta = localPackages.reduce((ret, localPackage) => {
141
- if (!ret[localPackage.name]) {
142
- ret[localPackage.name] = {
143
- optional: false
144
- };
145
- }
146
- return ret;
147
- }, packageJson.peerDependenciesMeta ?? {});
148
- packageJson.devDependencies = localPackages.reduce((ret, localPackage) => {
149
- if (!ret[localPackage.name]) {
150
- ret[localPackage.name] = localPackage.version || "0.0.1";
151
- }
152
- return ret;
153
- }, packageJson.peerDependencies ?? {});
154
- } else {
155
- writeTrace("\u{1F4E6} No local packages dependencies to add to package.json");
156
- }
157
- return packageJson;
158
- }, "addPackageDependencies");
159
- var addWorkspacePackageJsonFields = /* @__PURE__ */ __name(async (config, projectRoot, sourceRoot, projectName, includeSrc = false, packageJson) => {
160
- const workspaceRoot = config.workspaceRoot ? config.workspaceRoot : findWorkspaceRoot();
161
- const workspacePackageJsonContent = await readFile2(joinPaths(workspaceRoot, "package.json"), "utf8");
162
- const workspacePackageJson = JSON.parse(workspacePackageJsonContent);
163
- packageJson.type ??= "module";
164
- packageJson.sideEffects ??= false;
165
- if (includeSrc === true) {
166
- let distSrc = sourceRoot.replace(projectRoot, "");
167
- if (distSrc.startsWith("/")) {
168
- distSrc = distSrc.substring(1);
169
- }
170
- packageJson.source ??= `${joinPaths(distSrc, "index.ts").replaceAll("\\", "/")}`;
171
- }
172
- packageJson.files ??= [
173
- "dist/**/*"
174
- ];
175
- if (includeSrc === true && !packageJson.files.includes("src")) {
176
- packageJson.files.push("src/**/*");
177
- }
178
- packageJson.publishConfig ??= {
179
- access: "public"
180
- };
181
- packageJson.description ??= workspacePackageJson.description;
182
- packageJson.homepage ??= workspacePackageJson.homepage;
183
- packageJson.bugs ??= workspacePackageJson.bugs;
184
- packageJson.license ??= workspacePackageJson.license;
185
- packageJson.keywords ??= workspacePackageJson.keywords;
186
- packageJson.funding ??= workspacePackageJson.funding;
187
- packageJson.author ??= workspacePackageJson.author;
188
- packageJson.maintainers ??= workspacePackageJson.maintainers;
189
- if (!packageJson.maintainers && packageJson.author) {
190
- packageJson.maintainers = [
191
- packageJson.author
192
- ];
193
- }
194
- packageJson.contributors ??= workspacePackageJson.contributors;
195
- if (!packageJson.contributors && packageJson.author) {
196
- packageJson.contributors = [
197
- packageJson.author
198
- ];
199
- }
200
- packageJson.repository ??= workspacePackageJson.repository;
201
- packageJson.repository.directory ??= projectRoot ? projectRoot : joinPaths("packages", projectName);
202
- return packageJson;
203
- }, "addWorkspacePackageJsonFields");
204
-
205
- // ../config-tools/src/config-file/get-config-file.ts
206
- import { loadConfig as loadConfig2 } from "c12";
207
- import defu from "defu";
208
- var getConfigFileByName = /* @__PURE__ */ __name(async (fileName, filePath, options = {}) => {
209
- const workspacePath = filePath || findWorkspaceRoot(filePath);
210
- const configs = await Promise.all([
211
- loadConfig2({
212
- cwd: workspacePath,
213
- packageJson: true,
214
- name: fileName,
215
- envName: fileName?.toUpperCase(),
216
- jitiOptions: {
217
- debug: false,
218
- fsCache: process.env.STORM_SKIP_CACHE === "true" ? false : joinPaths(process.env.STORM_CACHE_DIR || "node_modules/.cache/storm", "jiti")
219
- },
220
- ...options
221
- }),
222
- loadConfig2({
223
- cwd: workspacePath,
224
- packageJson: true,
225
- name: fileName,
226
- envName: fileName?.toUpperCase(),
227
- jitiOptions: {
228
- debug: false,
229
- fsCache: process.env.STORM_SKIP_CACHE === "true" ? false : joinPaths(process.env.STORM_CACHE_DIR || "node_modules/.cache/storm", "jiti")
230
- },
231
- configFile: fileName,
232
- ...options
233
- })
234
- ]);
235
- return defu(configs[0] ?? {}, configs[1] ?? {});
236
- }, "getConfigFileByName");
237
- var getConfigFile = /* @__PURE__ */ __name(async (filePath, additionalFileNames = []) => {
238
- const workspacePath = filePath ? filePath : findWorkspaceRoot(filePath);
239
- const result = await getConfigFileByName("storm", workspacePath);
240
- let config = result.config;
241
- const configFile = result.configFile;
242
- if (config && configFile && Object.keys(config).length > 0) {
243
- writeTrace(`Found Storm configuration file "${configFile.includes(`${workspacePath}/`) ? configFile.replace(`${workspacePath}/`, "") : configFile}" at "${workspacePath}"`, {
244
- logLevel: "all"
245
- });
246
- }
247
- if (additionalFileNames && additionalFileNames.length > 0) {
248
- const results = await Promise.all(additionalFileNames.map((fileName) => getConfigFileByName(fileName, workspacePath)));
249
- for (const result2 of results) {
250
- if (result2?.config && result2?.configFile && Object.keys(result2.config).length > 0) {
251
- writeTrace(`Found alternative configuration file "${result2.configFile.includes(`${workspacePath}/`) ? result2.configFile.replace(`${workspacePath}/`, "") : result2.configFile}" at "${workspacePath}"`, {
252
- logLevel: "all"
253
- });
254
- config = defu(result2.config ?? {}, config ?? {});
255
- }
256
- }
257
- }
258
- if (!config) {
259
- return void 0;
260
- }
261
- config.configFile = configFile;
262
- return config;
263
- }, "getConfigFile");
264
-
265
- // ../config-tools/src/create-storm-config.ts
266
- import defu2 from "defu";
267
-
268
- // ../config-tools/src/env/get-env.ts
269
- var getExtensionEnv = /* @__PURE__ */ __name((extensionName) => {
270
- const prefix = `STORM_EXTENSION_${extensionName.toUpperCase()}_`;
271
- return Object.keys(process.env).filter((key) => key.startsWith(prefix)).reduce((ret, key) => {
272
- const name = key.replace(prefix, "").split("_").map((i) => i.length > 0 ? i.trim().charAt(0).toUpperCase() + i.trim().slice(1) : "").join("");
273
- if (name) {
274
- ret[name] = process.env[key];
275
- }
276
- return ret;
277
- }, {});
278
- }, "getExtensionEnv");
279
- var getConfigEnv = /* @__PURE__ */ __name(() => {
280
- const prefix = "STORM_";
281
- let config = {
282
- extends: process.env[`${prefix}EXTENDS`] || void 0,
283
- name: process.env[`${prefix}NAME`] || void 0,
284
- namespace: process.env[`${prefix}NAMESPACE`] || void 0,
285
- owner: process.env[`${prefix}OWNER`] || void 0,
286
- bot: {
287
- name: process.env[`${prefix}BOT_NAME`] || void 0,
288
- email: process.env[`${prefix}BOT_EMAIL`] || void 0
289
- },
290
- organization: process.env[`${prefix}ORGANIZATION`] || void 0,
291
- packageManager: process.env[`${prefix}PACKAGE_MANAGER`] || void 0,
292
- license: process.env[`${prefix}LICENSE`] || void 0,
293
- homepage: process.env[`${prefix}HOMEPAGE`] || void 0,
294
- docs: process.env[`${prefix}DOCS`] || void 0,
295
- licensing: process.env[`${prefix}LICENSING`] || void 0,
296
- timezone: process.env[`${prefix}TIMEZONE`] || process.env.TZ || void 0,
297
- locale: process.env[`${prefix}LOCALE`] || process.env.LOCALE || void 0,
298
- configFile: process.env[`${prefix}CONFIG_FILE`] ? correctPaths(process.env[`${prefix}CONFIG_FILE`]) : void 0,
299
- workspaceRoot: process.env[`${prefix}WORKSPACE_ROOT`] ? correctPaths(process.env[`${prefix}WORKSPACE_ROOT`]) : void 0,
300
- directories: {
301
- cache: process.env[`${prefix}CACHE_DIR`] ? correctPaths(process.env[`${prefix}CACHE_DIR`]) : void 0,
302
- data: process.env[`${prefix}DATA_DIR`] ? correctPaths(process.env[`${prefix}DATA_DIR`]) : void 0,
303
- config: process.env[`${prefix}CONFIG_DIR`] ? correctPaths(process.env[`${prefix}CONFIG_DIR`]) : void 0,
304
- temp: process.env[`${prefix}TEMP_DIR`] ? correctPaths(process.env[`${prefix}TEMP_DIR`]) : void 0,
305
- log: process.env[`${prefix}LOG_DIR`] ? correctPaths(process.env[`${prefix}LOG_DIR`]) : void 0,
306
- build: process.env[`${prefix}BUILD_DIR`] ? correctPaths(process.env[`${prefix}BUILD_DIR`]) : void 0
307
- },
308
- skipCache: process.env[`${prefix}SKIP_CACHE`] !== void 0 ? Boolean(process.env[`${prefix}SKIP_CACHE`]) : void 0,
309
- env: (process.env[`${prefix}ENV`] ?? process.env.NODE_ENV ?? process.env.ENVIRONMENT) || void 0,
310
- // ci:
311
- // process.env[`${prefix}CI`] !== undefined
312
- // ? Boolean(
313
- // process.env[`${prefix}CI`] ??
314
- // process.env.CI ??
315
- // process.env.CONTINUOUS_INTEGRATION
316
- // )
317
- // : undefined,
318
- repository: process.env[`${prefix}REPOSITORY`] || void 0,
319
- branch: process.env[`${prefix}BRANCH`] || void 0,
320
- preid: process.env[`${prefix}PRE_ID`] || void 0,
321
- externalPackagePatterns: process.env[`${prefix}EXTERNAL_PACKAGE_PATTERNS`] ? JSON.parse(process.env[`${prefix}EXTERNAL_PACKAGE_PATTERNS`]) : [],
322
- registry: {
323
- github: process.env[`${prefix}REGISTRY_GITHUB`] || void 0,
324
- npm: process.env[`${prefix}REGISTRY_NPM`] || void 0,
325
- cargo: process.env[`${prefix}REGISTRY_CARGO`] || void 0,
326
- cyclone: process.env[`${prefix}REGISTRY_CYCLONE`] || void 0,
327
- container: process.env[`${prefix}REGISTRY_CONTAINER`] || void 0
328
- },
329
- logLevel: process.env[`${prefix}LOG_LEVEL`] !== null && process.env[`${prefix}LOG_LEVEL`] !== void 0 ? process.env[`${prefix}LOG_LEVEL`] && Number.isSafeInteger(Number.parseInt(process.env[`${prefix}LOG_LEVEL`])) ? getLogLevelLabel(Number.parseInt(process.env[`${prefix}LOG_LEVEL`])) : process.env[`${prefix}LOG_LEVEL`] : void 0
330
- };
331
- const themeNames = Object.keys(process.env).filter((envKey) => envKey.startsWith(`${prefix}COLOR_`) && COLOR_KEYS.every((colorKey) => !envKey.startsWith(`${prefix}COLOR_LIGHT_${colorKey}`) && !envKey.startsWith(`${prefix}COLOR_DARK_${colorKey}`)));
332
- config.colors = themeNames.length > 0 ? themeNames.reduce((ret, themeName) => {
333
- ret[themeName] = getThemeColorConfigEnv(prefix, themeName);
334
- return ret;
335
- }, {}) : getThemeColorConfigEnv(prefix);
336
- if (config.docs === STORM_DEFAULT_DOCS) {
337
- if (config.homepage === STORM_DEFAULT_HOMEPAGE) {
338
- config.docs = `${STORM_DEFAULT_HOMEPAGE}/projects/${config.name}/docs`;
339
- } else {
340
- config.docs = `${config.homepage}/docs`;
341
- }
342
- }
343
- if (config.licensing === STORM_DEFAULT_LICENSING) {
344
- if (config.homepage === STORM_DEFAULT_HOMEPAGE) {
345
- config.licensing = `${STORM_DEFAULT_HOMEPAGE}/projects/${config.name}/licensing`;
346
- } else {
347
- config.licensing = `${config.homepage}/docs`;
348
- }
349
- }
350
- const serializedConfig = process.env[`${prefix}CONFIG`];
351
- if (serializedConfig) {
352
- const parsed = JSON.parse(serializedConfig);
353
- config = {
354
- ...config,
355
- ...parsed,
356
- colors: {
357
- ...config.colors,
358
- ...parsed.colors
359
- },
360
- extensions: {
361
- ...config.extensions,
362
- ...parsed.extensions
363
- }
364
- };
365
- }
366
- return config;
367
- }, "getConfigEnv");
368
- var getThemeColorConfigEnv = /* @__PURE__ */ __name((prefix, theme) => {
369
- const themeName = `COLOR_${theme && theme !== "base" ? `${theme}_` : ""}`.toUpperCase();
370
- return process.env[`${prefix}${themeName}LIGHT_BRAND`] || process.env[`${prefix}${themeName}DARK_BRAND`] ? getMultiThemeColorConfigEnv(prefix + themeName) : getSingleThemeColorConfigEnv(prefix + themeName);
371
- }, "getThemeColorConfigEnv");
372
- var getSingleThemeColorConfigEnv = /* @__PURE__ */ __name((prefix) => {
373
- return {
374
- dark: process.env[`${prefix}DARK`],
375
- light: process.env[`${prefix}LIGHT`],
376
- brand: process.env[`${prefix}BRAND`],
377
- alternate: process.env[`${prefix}ALTERNATE`],
378
- accent: process.env[`${prefix}ACCENT`],
379
- link: process.env[`${prefix}LINK`],
380
- help: process.env[`${prefix}HELP`],
381
- success: process.env[`${prefix}SUCCESS`],
382
- info: process.env[`${prefix}INFO`],
383
- warning: process.env[`${prefix}WARNING`],
384
- danger: process.env[`${prefix}DANGER`],
385
- fatal: process.env[`${prefix}FATAL`],
386
- positive: process.env[`${prefix}POSITIVE`],
387
- negative: process.env[`${prefix}NEGATIVE`]
388
- };
389
- }, "getSingleThemeColorConfigEnv");
390
- var getMultiThemeColorConfigEnv = /* @__PURE__ */ __name((prefix) => {
391
- return {
392
- light: getBaseThemeColorConfigEnv(`${prefix}_LIGHT_`),
393
- dark: getBaseThemeColorConfigEnv(`${prefix}_DARK_`)
394
- };
395
- }, "getMultiThemeColorConfigEnv");
396
- var getBaseThemeColorConfigEnv = /* @__PURE__ */ __name((prefix) => {
397
- return {
398
- foreground: process.env[`${prefix}FOREGROUND`],
399
- background: process.env[`${prefix}BACKGROUND`],
400
- brand: process.env[`${prefix}BRAND`],
401
- alternate: process.env[`${prefix}ALTERNATE`],
402
- accent: process.env[`${prefix}ACCENT`],
403
- link: process.env[`${prefix}LINK`],
404
- help: process.env[`${prefix}HELP`],
405
- success: process.env[`${prefix}SUCCESS`],
406
- info: process.env[`${prefix}INFO`],
407
- warning: process.env[`${prefix}WARNING`],
408
- danger: process.env[`${prefix}DANGER`],
409
- fatal: process.env[`${prefix}FATAL`],
410
- positive: process.env[`${prefix}POSITIVE`],
411
- negative: process.env[`${prefix}NEGATIVE`]
412
- };
413
- }, "getBaseThemeColorConfigEnv");
414
-
415
- // ../config-tools/src/env/set-env.ts
416
- var setExtensionEnv = /* @__PURE__ */ __name((extensionName, extension) => {
417
- for (const key of Object.keys(extension ?? {})) {
418
- if (extension[key]) {
419
- const result = key?.replace(/([A-Z])+/g, (input) => input ? input[0]?.toUpperCase() + input.slice(1) : "").split(/(?=[A-Z])|[.\-\s_]/).map((x) => x.toLowerCase()) ?? [];
420
- let extensionKey;
421
- if (result.length === 0) {
422
- return;
423
- }
424
- if (result.length === 1) {
425
- extensionKey = result[0]?.toUpperCase() ?? "";
426
- } else {
427
- extensionKey = result.reduce((ret, part) => {
428
- return `${ret}_${part.toLowerCase()}`;
429
- });
430
- }
431
- process.env[`STORM_EXTENSION_${extensionName.toUpperCase()}_${extensionKey.toUpperCase()}`] = extension[key];
432
- }
433
- }
434
- }, "setExtensionEnv");
435
- var setConfigEnv = /* @__PURE__ */ __name((config) => {
436
- const prefix = "STORM_";
437
- if (config.extends) {
438
- process.env[`${prefix}EXTENDS`] = Array.isArray(config.extends) ? JSON.stringify(config.extends) : config.extends;
439
- }
440
- if (config.name) {
441
- process.env[`${prefix}NAME`] = config.name;
442
- }
443
- if (config.namespace) {
444
- process.env[`${prefix}NAMESPACE`] = config.namespace;
445
- }
446
- if (config.owner) {
447
- process.env[`${prefix}OWNER`] = config.owner;
448
- }
449
- if (config.bot) {
450
- process.env[`${prefix}BOT_NAME`] = config.bot.name;
451
- process.env[`${prefix}BOT_EMAIL`] = config.bot.email;
452
- }
453
- if (config.organization) {
454
- process.env[`${prefix}ORGANIZATION`] = config.organization;
455
- }
456
- if (config.packageManager) {
457
- process.env[`${prefix}PACKAGE_MANAGER`] = config.packageManager;
458
- }
459
- if (config.license) {
460
- process.env[`${prefix}LICENSE`] = config.license;
461
- }
462
- if (config.homepage) {
463
- process.env[`${prefix}HOMEPAGE`] = config.homepage;
464
- }
465
- if (config.docs) {
466
- process.env[`${prefix}DOCS`] = config.docs;
467
- }
468
- if (config.licensing) {
469
- process.env[`${prefix}LICENSING`] = config.licensing;
470
- }
471
- if (config.timezone) {
472
- process.env[`${prefix}TIMEZONE`] = config.timezone;
473
- process.env.TZ = config.timezone;
474
- process.env.DEFAULT_TIMEZONE = config.timezone;
475
- }
476
- if (config.locale) {
477
- process.env[`${prefix}LOCALE`] = config.locale;
478
- process.env.LOCALE = config.locale;
479
- process.env.DEFAULT_LOCALE = config.locale;
480
- process.env.LANG = config.locale ? `${config.locale.replaceAll("-", "_")}.UTF-8` : "en_US.UTF-8";
481
- }
482
- if (config.configFile) {
483
- process.env[`${prefix}CONFIG_FILE`] = correctPaths(config.configFile);
484
- }
485
- if (config.workspaceRoot) {
486
- process.env[`${prefix}WORKSPACE_ROOT`] = correctPaths(config.workspaceRoot);
487
- process.env.NX_WORKSPACE_ROOT = correctPaths(config.workspaceRoot);
488
- process.env.NX_WORKSPACE_ROOT_PATH = correctPaths(config.workspaceRoot);
489
- }
490
- if (config.directories) {
491
- if (!config.skipCache && config.directories.cache) {
492
- process.env[`${prefix}CACHE_DIR`] = correctPaths(config.directories.cache);
493
- }
494
- if (config.directories.data) {
495
- process.env[`${prefix}DATA_DIR`] = correctPaths(config.directories.data);
496
- }
497
- if (config.directories.config) {
498
- process.env[`${prefix}CONFIG_DIR`] = correctPaths(config.directories.config);
499
- }
500
- if (config.directories.temp) {
501
- process.env[`${prefix}TEMP_DIR`] = correctPaths(config.directories.temp);
502
- }
503
- if (config.directories.log) {
504
- process.env[`${prefix}LOG_DIR`] = correctPaths(config.directories.log);
505
- }
506
- if (config.directories.build) {
507
- process.env[`${prefix}BUILD_DIR`] = correctPaths(config.directories.build);
508
- }
509
- }
510
- if (config.skipCache !== void 0) {
511
- process.env[`${prefix}SKIP_CACHE`] = String(config.skipCache);
512
- if (config.skipCache) {
513
- process.env.NX_SKIP_NX_CACHE ??= String(config.skipCache);
514
- process.env.NX_CACHE_PROJECT_GRAPH ??= String(config.skipCache);
515
- }
516
- }
517
- if (config.env) {
518
- process.env[`${prefix}ENV`] = config.env;
519
- process.env.NODE_ENV = config.env;
520
- process.env.ENVIRONMENT = config.env;
521
- }
522
- if (config.colors?.base?.light || config.colors?.base?.dark) {
523
- for (const key of Object.keys(config.colors)) {
524
- setThemeColorConfigEnv(`${prefix}COLOR_${key}_`, config.colors[key]);
525
- }
526
- } else {
527
- setThemeColorConfigEnv(`${prefix}COLOR_`, config.colors);
528
- }
529
- if (config.repository) {
530
- process.env[`${prefix}REPOSITORY`] = config.repository;
531
- }
532
- if (config.branch) {
533
- process.env[`${prefix}BRANCH`] = config.branch;
534
- }
535
- if (config.preid) {
536
- process.env[`${prefix}PRE_ID`] = String(config.preid);
537
- }
538
- if (config.externalPackagePatterns) {
539
- process.env[`${prefix}EXTERNAL_PACKAGE_PATTERNS`] = JSON.stringify(config.externalPackagePatterns);
540
- }
541
- if (config.registry) {
542
- if (config.registry.github) {
543
- process.env[`${prefix}REGISTRY_GITHUB`] = String(config.registry.github);
544
- }
545
- if (config.registry.npm) {
546
- process.env[`${prefix}REGISTRY_NPM`] = String(config.registry.npm);
547
- }
548
- if (config.registry.cargo) {
549
- process.env[`${prefix}REGISTRY_CARGO`] = String(config.registry.cargo);
550
- }
551
- if (config.registry.cyclone) {
552
- process.env[`${prefix}REGISTRY_CYCLONE`] = String(config.registry.cyclone);
553
- }
554
- if (config.registry.container) {
555
- process.env[`${prefix}REGISTRY_CONTAINER`] = String(config.registry.cyclone);
556
- }
557
- }
558
- if (config.logLevel) {
559
- process.env[`${prefix}LOG_LEVEL`] = String(config.logLevel);
560
- process.env.LOG_LEVEL = String(config.logLevel);
561
- process.env.NX_VERBOSE_LOGGING = String(getLogLevel(config.logLevel) >= LogLevel.DEBUG ? true : false);
562
- process.env.RUST_BACKTRACE = getLogLevel(config.logLevel) >= LogLevel.DEBUG ? "full" : "none";
563
- }
564
- process.env[`${prefix}CONFIG`] = JSON.stringify(config);
565
- for (const key of Object.keys(config.extensions ?? {})) {
566
- config.extensions[key] && Object.keys(config.extensions[key]) && setExtensionEnv(key, config.extensions[key]);
567
- }
568
- }, "setConfigEnv");
569
- var setThemeColorConfigEnv = /* @__PURE__ */ __name((prefix, config) => {
570
- return config?.light?.brand || config?.dark?.brand ? setMultiThemeColorConfigEnv(prefix, config) : setSingleThemeColorConfigEnv(prefix, config);
571
- }, "setThemeColorConfigEnv");
572
- var setSingleThemeColorConfigEnv = /* @__PURE__ */ __name((prefix, config) => {
573
- if (config.dark) {
574
- process.env[`${prefix}DARK`] = config.dark;
575
- }
576
- if (config.light) {
577
- process.env[`${prefix}LIGHT`] = config.light;
578
- }
579
- if (config.brand) {
580
- process.env[`${prefix}BRAND`] = config.brand;
581
- }
582
- if (config.alternate) {
583
- process.env[`${prefix}ALTERNATE`] = config.alternate;
584
- }
585
- if (config.accent) {
586
- process.env[`${prefix}ACCENT`] = config.accent;
587
- }
588
- if (config.link) {
589
- process.env[`${prefix}LINK`] = config.link;
590
- }
591
- if (config.help) {
592
- process.env[`${prefix}HELP`] = config.help;
593
- }
594
- if (config.success) {
595
- process.env[`${prefix}SUCCESS`] = config.success;
596
- }
597
- if (config.info) {
598
- process.env[`${prefix}INFO`] = config.info;
599
- }
600
- if (config.warning) {
601
- process.env[`${prefix}WARNING`] = config.warning;
602
- }
603
- if (config.danger) {
604
- process.env[`${prefix}DANGER`] = config.danger;
605
- }
606
- if (config.fatal) {
607
- process.env[`${prefix}FATAL`] = config.fatal;
608
- }
609
- if (config.positive) {
610
- process.env[`${prefix}POSITIVE`] = config.positive;
611
- }
612
- if (config.negative) {
613
- process.env[`${prefix}NEGATIVE`] = config.negative;
614
- }
615
- }, "setSingleThemeColorConfigEnv");
616
- var setMultiThemeColorConfigEnv = /* @__PURE__ */ __name((prefix, config) => {
617
- return {
618
- light: setBaseThemeColorConfigEnv(`${prefix}LIGHT_`, config.light),
619
- dark: setBaseThemeColorConfigEnv(`${prefix}DARK_`, config.dark)
620
- };
621
- }, "setMultiThemeColorConfigEnv");
622
- var setBaseThemeColorConfigEnv = /* @__PURE__ */ __name((prefix, config) => {
623
- if (config.foreground) {
624
- process.env[`${prefix}FOREGROUND`] = config.foreground;
625
- }
626
- if (config.background) {
627
- process.env[`${prefix}BACKGROUND`] = config.background;
628
- }
629
- if (config.brand) {
630
- process.env[`${prefix}BRAND`] = config.brand;
631
- }
632
- if (config.alternate) {
633
- process.env[`${prefix}ALTERNATE`] = config.alternate;
634
- }
635
- if (config.accent) {
636
- process.env[`${prefix}ACCENT`] = config.accent;
637
- }
638
- if (config.link) {
639
- process.env[`${prefix}LINK`] = config.link;
640
- }
641
- if (config.help) {
642
- process.env[`${prefix}HELP`] = config.help;
643
- }
644
- if (config.success) {
645
- process.env[`${prefix}SUCCESS`] = config.success;
646
- }
647
- if (config.info) {
648
- process.env[`${prefix}INFO`] = config.info;
649
- }
650
- if (config.warning) {
651
- process.env[`${prefix}WARNING`] = config.warning;
652
- }
653
- if (config.danger) {
654
- process.env[`${prefix}DANGER`] = config.danger;
655
- }
656
- if (config.fatal) {
657
- process.env[`${prefix}FATAL`] = config.fatal;
658
- }
659
- if (config.positive) {
660
- process.env[`${prefix}POSITIVE`] = config.positive;
661
- }
662
- if (config.negative) {
663
- process.env[`${prefix}NEGATIVE`] = config.negative;
664
- }
665
- }, "setBaseThemeColorConfigEnv");
666
-
667
- // ../config-tools/src/create-storm-config.ts
668
- var _extension_cache = /* @__PURE__ */ new WeakMap();
669
- var _static_cache = void 0;
670
- var createStormConfig = /* @__PURE__ */ __name(async (extensionName, schema, workspaceRoot, skipLogs = false) => {
671
- let result;
672
- if (!_static_cache?.data || !_static_cache?.timestamp || _static_cache.timestamp < Date.now() - 8e3) {
673
- let _workspaceRoot = workspaceRoot;
674
- if (!_workspaceRoot) {
675
- _workspaceRoot = findWorkspaceRoot();
676
- }
677
- const configEnv = getConfigEnv();
678
- const defaultConfig = await getDefaultConfig(_workspaceRoot);
679
- const configFile = await getConfigFile(_workspaceRoot);
680
- if (!configFile && !skipLogs) {
681
- writeWarning("No Storm config file found in the current workspace. Please ensure this is the expected behavior - you can add a `storm.json` file to the root of your workspace if it is not.\n", {
682
- logLevel: "all"
683
- });
684
- }
685
- result = await StormConfigSchema.parseAsync(defu2(configEnv, configFile, defaultConfig));
686
- result.workspaceRoot ??= _workspaceRoot;
687
- } else {
688
- result = _static_cache.data;
689
- }
690
- if (schema && extensionName) {
691
- result.extensions = {
692
- ...result.extensions,
693
- [extensionName]: createConfigExtension(extensionName, schema)
694
- };
695
- }
696
- _static_cache = {
697
- timestamp: Date.now(),
698
- data: result
699
- };
700
- return result;
701
- }, "createStormConfig");
702
- var createConfigExtension = /* @__PURE__ */ __name((extensionName, schema) => {
703
- const extension_cache_key = {
704
- extensionName
705
- };
706
- if (_extension_cache.has(extension_cache_key)) {
707
- return _extension_cache.get(extension_cache_key);
708
- }
709
- let extension = getExtensionEnv(extensionName);
710
- if (schema) {
711
- extension = schema.parse(extension);
712
- }
713
- _extension_cache.set(extension_cache_key, extension);
714
- return extension;
715
- }, "createConfigExtension");
716
- var loadStormConfig = /* @__PURE__ */ __name(async (workspaceRoot, skipLogs = false) => {
717
- const config = await createStormConfig(void 0, void 0, workspaceRoot, skipLogs);
718
- setConfigEnv(config);
719
- if (!skipLogs) {
720
- writeTrace(`\u2699\uFE0F Using Storm configuration:
721
- ${formatLogMessage(config)}`, config);
722
- }
723
- return config;
724
- }, "loadStormConfig");
725
-
726
- // ../config-tools/src/get-config.ts
727
- var getConfig = /* @__PURE__ */ __name((workspaceRoot, skipLogs = false) => {
728
- return loadStormConfig(workspaceRoot, skipLogs);
729
- }, "getConfig");
730
-
731
- // ../build-tools/src/utilities/get-entry-points.ts
732
- import { glob as glob2 } from "glob";
733
-
734
- // ../build-tools/src/utilities/read-nx-config.ts
735
- import { existsSync as existsSync2 } from "node:fs";
736
- import { readFile as readFile3 } from "node:fs/promises";
737
-
738
- // ../build-tools/src/utilities/task-graph.ts
739
- import { createTaskGraph, mapTargetDefaultsToDependencies } from "nx/src/tasks-runner/create-task-graph";
740
-
741
- // src/build.ts
742
- import defu4 from "defu";
743
- import { Glob as Glob2 } from "glob";
744
- import { existsSync as existsSync4 } from "node:fs";
745
- import { readFile as readFile4 } from "node:fs/promises";
746
- import { relative as relative3 } from "node:path";
747
- import { findWorkspaceRoot as findWorkspaceRoot2 } from "nx/src/utils/find-workspace-root";
748
-
749
- // ../../node_modules/.pnpm/unbuild@3.3.1_sass@1.83.4_typescript@5.7.3/node_modules/unbuild/dist/shared/unbuild.B2_7OVir.mjs
750
- import Module from "node:module";
751
- import { existsSync as existsSync3, readdirSync, statSync, promises } from "node:fs";
752
- import { join, resolve, normalize, dirname, relative as relative2, extname, isAbsolute } from "pathe";
753
- import { colors } from "consola/utils";
754
- import consola$1, { consola } from "consola";
755
- import { defu as defu3 } from "defu";
756
- import { createHooks } from "hookable";
757
- import prettyBytes from "pretty-bytes";
758
- import { glob as glob3 } from "tinyglobby";
759
- import fsp, { mkdir, writeFile as writeFile2 } from "node:fs/promises";
760
- import { createJiti } from "jiti";
761
- import { watch, rollup } from "rollup";
762
- import dts from "rollup-plugin-dts";
763
- import commonjs from "@rollup/plugin-commonjs";
764
- import { nodeResolve } from "@rollup/plugin-node-resolve";
765
- import alias from "@rollup/plugin-alias";
766
- import replace from "@rollup/plugin-replace";
767
- import { resolveAlias } from "pathe/utils";
768
- import { findStaticImports, parseNodeModulePath, fileURLToPath, resolvePath, resolveModuleExportNames } from "mlly";
769
- import { transform as transform2 } from "esbuild";
770
- import { createFilter } from "@rollup/pluginutils";
771
- import rollupJSONPlugin from "@rollup/plugin-json";
772
- import MagicString from "magic-string";
773
- import { resolveSchema, generateMarkdown, generateTypes } from "untyped";
774
- import untypedPlugin from "untyped/babel-plugin";
775
- import { pascalCase } from "scule";
776
- import { mkdist } from "mkdist";
777
- function definePreset(preset) {
778
- return preset;
779
- }
780
- __name(definePreset, "definePreset");
781
- var autoPreset = definePreset(() => {
782
- return {
783
- hooks: {
784
- "build:prepare"(ctx) {
785
- if (!ctx.pkg || ctx.options.entries.length > 0) {
786
- return;
787
- }
788
- const sourceFiles = listRecursively(join(ctx.options.rootDir, "src"));
789
- const res = inferEntries(ctx.pkg, sourceFiles, ctx.options.rootDir);
790
- for (const message of res.warnings) {
791
- warn(ctx, message);
792
- }
793
- ctx.options.entries.push(...res.entries);
794
- if (res.cjs) {
795
- ctx.options.rollup.emitCJS = true;
796
- }
797
- if (ctx.options.declaration === void 0) {
798
- ctx.options.declaration = res.dts ? "compatible" : false;
799
- }
800
- consola.info(
801
- "Automatically detected entries:",
802
- colors.cyan(
803
- ctx.options.entries.map(
804
- (e) => colors.bold(
805
- e.input.replace(ctx.options.rootDir + "/", "").replace(/\/$/, "/*")
806
- )
807
- ).join(", ")
808
- ),
809
- colors.gray(
810
- ["esm", res.cjs && "cjs", res.dts && "dts"].filter(Boolean).map((tag) => `[${tag}]`).join(" ")
811
- )
812
- );
813
- }
814
- }
815
- };
816
- });
817
- function inferEntries(pkg, sourceFiles, rootDir) {
818
- const warnings = [];
819
- sourceFiles.sort((a, b) => a.split("/").length - b.split("/").length);
820
- const outputs = extractExportFilenames(pkg.exports);
821
- if (pkg.bin) {
822
- const binaries = typeof pkg.bin === "string" ? [pkg.bin] : Object.values(pkg.bin);
823
- for (const file of binaries) {
824
- outputs.push({ file });
825
- }
826
- }
827
- if (pkg.main) {
828
- outputs.push({ file: pkg.main });
829
- }
830
- if (pkg.module) {
831
- outputs.push({ type: "esm", file: pkg.module });
832
- }
833
- if (pkg.types || pkg.typings) {
834
- outputs.push({ file: pkg.types || pkg.typings });
835
- }
836
- const isESMPkg = pkg.type === "module";
837
- for (const output of outputs.filter((o) => !o.type)) {
838
- const isJS = output.file.endsWith(".js");
839
- if (isESMPkg && isJS || output.file.endsWith(".mjs")) {
840
- output.type = "esm";
841
- } else if (!isESMPkg && isJS || output.file.endsWith(".cjs")) {
842
- output.type = "cjs";
843
- }
844
- }
845
- let cjs = false;
846
- let dts2 = false;
847
- const entries = [];
848
- for (const output of outputs) {
849
- const outputSlug = output.file.replace(
850
- /(\*[^/\\]*|\.d\.(m|c)?ts|\.\w+)$/,
851
- ""
852
- );
853
- const isDir = outputSlug.endsWith("/");
854
- if (isDir && ["./", "/"].includes(outputSlug)) {
855
- continue;
856
- }
857
- const possiblePaths = getEntrypointPaths(outputSlug);
858
- const input = possiblePaths.reduce((source, d) => {
859
- if (source) {
860
- return source;
861
- }
862
- const SOURCE_RE = new RegExp(
863
- `(?<=/|$)${d}${isDir ? "" : String.raw`\.\w+`}$`
864
- );
865
- return sourceFiles.find((i) => SOURCE_RE.test(i))?.replace(/(\.d\.(m|c)?ts|\.\w+)$/, "");
866
- }, void 0);
867
- if (!input) {
868
- if (!existsSync3(resolve(rootDir || ".", output.file))) {
869
- warnings.push(`Could not find entrypoint for \`${output.file}\``);
870
- }
871
- continue;
872
- }
873
- if (output.type === "cjs") {
874
- cjs = true;
875
- }
876
- const entry = entries.find((i) => i.input === input) || entries[entries.push({ input }) - 1];
877
- if (/\.d\.(m|c)?ts$/.test(output.file)) {
878
- dts2 = true;
879
- }
880
- if (isDir) {
881
- entry.outDir = outputSlug;
882
- entry.format = output.type;
883
- }
884
- }
885
- return { entries, cjs, dts: dts2, warnings };
886
- }
887
- __name(inferEntries, "inferEntries");
888
- var getEntrypointPaths = /* @__PURE__ */ __name((path2) => {
889
- const segments = normalize(path2).split("/");
890
- return segments.map((_, index) => segments.slice(index).join("/")).filter(Boolean);
891
- }, "getEntrypointPaths");
892
- async function ensuredir(path2) {
893
- await fsp.mkdir(dirname(path2), { recursive: true });
894
- }
895
- __name(ensuredir, "ensuredir");
896
- function warn(ctx, message) {
897
- if (ctx.warnings.has(message)) {
898
- return;
899
- }
900
- consola.debug("[unbuild] [warn]", message);
901
- ctx.warnings.add(message);
902
- }
903
- __name(warn, "warn");
904
- async function symlink(from, to, force = true) {
905
- await ensuredir(to);
906
- if (force) {
907
- await fsp.unlink(to).catch(() => {
908
- });
909
- }
910
- await fsp.symlink(from, to, "junction");
911
- }
912
- __name(symlink, "symlink");
913
- function dumpObject(obj) {
914
- return "{ " + Object.keys(obj).map((key) => `${key}: ${JSON.stringify(obj[key])}`).join(", ") + " }";
915
- }
916
- __name(dumpObject, "dumpObject");
917
- function getpkg(id = "") {
918
- const s = id.split("/");
919
- return s[0][0] === "@" ? `${s[0]}/${s[1]}` : s[0];
920
- }
921
- __name(getpkg, "getpkg");
922
- async function rmdir(dir) {
923
- await fsp.unlink(dir).catch(() => {
924
- });
925
- await fsp.rm(dir, { recursive: true, force: true }).catch(() => {
926
- });
927
- }
928
- __name(rmdir, "rmdir");
929
- function listRecursively(path2) {
930
- const filenames = /* @__PURE__ */ new Set();
931
- const walk = /* @__PURE__ */ __name((path22) => {
932
- const files = readdirSync(path22);
933
- for (const file of files) {
934
- const fullPath = resolve(path22, file);
935
- if (statSync(fullPath).isDirectory()) {
936
- filenames.add(fullPath + "/");
937
- walk(fullPath);
938
- } else {
939
- filenames.add(fullPath);
940
- }
941
- }
942
- }, "walk");
943
- walk(path2);
944
- return [...filenames];
945
- }
946
- __name(listRecursively, "listRecursively");
947
- async function resolvePreset(preset, rootDir) {
948
- if (preset === "auto") {
949
- preset = autoPreset;
950
- } else if (typeof preset === "string") {
951
- preset = await createJiti(rootDir, { interopDefault: true }).import(preset, {
952
- default: true
953
- }) || {};
954
- }
955
- if (typeof preset === "function") {
956
- preset = preset();
957
- }
958
- return preset;
959
- }
960
- __name(resolvePreset, "resolvePreset");
961
- function inferExportType(condition, previousConditions = [], filename = "") {
962
- if (filename) {
963
- if (filename.endsWith(".d.ts")) {
964
- return "esm";
965
- }
966
- if (filename.endsWith(".mjs")) {
967
- return "esm";
968
- }
969
- if (filename.endsWith(".cjs")) {
970
- return "cjs";
971
- }
972
- }
973
- switch (condition) {
974
- case "import": {
975
- return "esm";
976
- }
977
- case "require": {
978
- return "cjs";
979
- }
980
- default: {
981
- if (previousConditions.length === 0) {
982
- return "esm";
983
- }
984
- const [newCondition, ...rest] = previousConditions;
985
- return inferExportType(newCondition, rest, filename);
986
- }
987
- }
988
- }
989
- __name(inferExportType, "inferExportType");
990
- function extractExportFilenames(exports, conditions = []) {
991
- if (!exports) {
992
- return [];
993
- }
994
- if (typeof exports === "string") {
995
- return [{ file: exports, type: "esm" }];
996
- }
997
- return Object.entries(exports).filter(([subpath]) => !subpath.endsWith(".json")).flatMap(
998
- ([condition, exports2]) => typeof exports2 === "string" ? {
999
- file: exports2,
1000
- type: inferExportType(condition, conditions, exports2)
1001
- } : extractExportFilenames(exports2, [...conditions, condition])
1002
- );
1003
- }
1004
- __name(extractExportFilenames, "extractExportFilenames");
1005
- function arrayIncludes(arr, searchElement) {
1006
- return arr.some(
1007
- (entry) => entry instanceof RegExp ? entry.test(searchElement) : entry === searchElement
1008
- );
1009
- }
1010
- __name(arrayIncludes, "arrayIncludes");
1011
- function removeExtension(filename) {
1012
- return filename.replace(/\.(js|mjs|cjs|ts|mts|cts|json|jsx|tsx)$/, "");
1013
- }
1014
- __name(removeExtension, "removeExtension");
1015
- function inferPkgExternals(pkg) {
1016
- const externals = [
1017
- ...Object.keys(pkg.dependencies || {}),
1018
- ...Object.keys(pkg.peerDependencies || {}),
1019
- ...Object.keys(pkg.devDependencies || {}).filter(
1020
- (dep) => dep.startsWith("@types/")
1021
- ),
1022
- ...Object.keys(pkg.optionalDependencies || {})
1023
- ];
1024
- if (pkg.name) {
1025
- externals.push(pkg.name);
1026
- if (pkg.exports) {
1027
- for (const subpath of Object.keys(pkg.exports)) {
1028
- if (subpath.startsWith("./")) {
1029
- externals.push(pathToRegex(`${pkg.name}/${subpath.slice(2)}`));
1030
- }
1031
- }
1032
- }
1033
- }
1034
- if (pkg.imports) {
1035
- for (const importName of Object.keys(pkg.imports)) {
1036
- if (importName.startsWith("#")) {
1037
- externals.push(pathToRegex(importName));
1038
- }
1039
- }
1040
- }
1041
- return [...new Set(externals)];
1042
- }
1043
- __name(inferPkgExternals, "inferPkgExternals");
1044
- function pathToRegex(path2) {
1045
- return path2.includes("*") ? new RegExp(
1046
- `^${path2.replace(/\./g, String.raw`\.`).replace(/\*/g, ".*")}$`
1047
- ) : path2;
1048
- }
1049
- __name(pathToRegex, "pathToRegex");
1050
- function withTrailingSlash(path2) {
1051
- return path2.endsWith("/") ? path2 : `${path2}/`;
1052
- }
1053
- __name(withTrailingSlash, "withTrailingSlash");
1054
- function validateDependencies(ctx) {
1055
- const usedDependencies = /* @__PURE__ */ new Set();
1056
- const unusedDependencies = new Set(
1057
- Object.keys(ctx.pkg.dependencies || {})
1058
- );
1059
- const implicitDependencies = /* @__PURE__ */ new Set();
1060
- for (const id of ctx.usedImports) {
1061
- unusedDependencies.delete(id);
1062
- usedDependencies.add(id);
1063
- }
1064
- if (Array.isArray(ctx.options.dependencies)) {
1065
- for (const id of ctx.options.dependencies) {
1066
- unusedDependencies.delete(id);
1067
- }
1068
- }
1069
- for (const id of usedDependencies) {
1070
- if (!arrayIncludes(ctx.options.externals, id) && !id.startsWith("chunks/") && !ctx.options.dependencies.includes(getpkg(id)) && !ctx.options.peerDependencies.includes(getpkg(id))) {
1071
- implicitDependencies.add(id);
1072
- }
1073
- }
1074
- if (unusedDependencies.size > 0) {
1075
- warn(
1076
- ctx,
1077
- "Potential unused dependencies found: " + [...unusedDependencies].map((id) => colors.cyan(id)).join(", ")
1078
- );
1079
- }
1080
- if (implicitDependencies.size > 0 && !ctx.options.rollup.inlineDependencies) {
1081
- warn(
1082
- ctx,
1083
- "Potential implicit dependencies found: " + [...implicitDependencies].map((id) => colors.cyan(id)).join(", ")
1084
- );
1085
- }
1086
- }
1087
- __name(validateDependencies, "validateDependencies");
1088
- function validatePackage(pkg, rootDir, ctx) {
1089
- if (!pkg) {
1090
- return;
1091
- }
1092
- const filenames = new Set(
1093
- [
1094
- ...typeof pkg.bin === "string" ? [pkg.bin] : Object.values(pkg.bin || {}),
1095
- pkg.main,
1096
- pkg.module,
1097
- pkg.types,
1098
- pkg.typings,
1099
- ...extractExportFilenames(pkg.exports).map((i) => i.file)
1100
- ].map((i) => i && resolve(rootDir, i.replace(/\/[^/]*\*.*$/, "")))
1101
- );
1102
- const missingOutputs = [];
1103
- for (const filename of filenames) {
1104
- if (filename && !filename.includes("*") && !existsSync3(filename)) {
1105
- missingOutputs.push(filename.replace(rootDir + "/", ""));
1106
- }
1107
- }
1108
- if (missingOutputs.length > 0) {
1109
- warn(
1110
- ctx,
1111
- `Potential missing package.json files: ${missingOutputs.map((o) => colors.cyan(o)).join(", ")}`
1112
- );
1113
- }
1114
- }
1115
- __name(validatePackage, "validatePackage");
1116
- var SHEBANG_RE = /^#![^\n]*/;
1117
- function shebangPlugin() {
1118
- return {
1119
- name: "unbuild-shebang",
1120
- async writeBundle(options, bundle) {
1121
- for (const [fileName, output] of Object.entries(bundle)) {
1122
- if (output.type !== "chunk") {
1123
- continue;
1124
- }
1125
- if (output.code?.match(SHEBANG_RE)) {
1126
- const outFile = resolve(options.dir, fileName);
1127
- await makeExecutable(outFile);
1128
- }
1129
- }
1130
- }
1131
- };
1132
- }
1133
- __name(shebangPlugin, "shebangPlugin");
1134
- function removeShebangPlugin() {
1135
- return {
1136
- name: "unbuild-remove-shebang",
1137
- renderChunk(code) {
1138
- return code.replace(SHEBANG_RE, "");
1139
- }
1140
- };
1141
- }
1142
- __name(removeShebangPlugin, "removeShebangPlugin");
1143
- async function makeExecutable(filePath) {
1144
- await promises.chmod(
1145
- filePath,
1146
- 493
1147
- /* rwx r-x r-x */
1148
- ).catch(() => {
1149
- });
1150
- }
1151
- __name(makeExecutable, "makeExecutable");
1152
- function getShebang(code, append = "\n") {
1153
- const m = code.match(SHEBANG_RE);
1154
- return m ? m + append : "";
1155
- }
1156
- __name(getShebang, "getShebang");
1157
- var DefaultLoaders = {
1158
- ".js": "js",
1159
- ".mjs": "js",
1160
- ".cjs": "js",
1161
- ".ts": "ts",
1162
- ".mts": "ts",
1163
- ".cts": "ts",
1164
- ".tsx": "tsx",
1165
- ".jsx": "jsx"
1166
- };
1167
- function esbuild(options) {
1168
- const {
1169
- include = new RegExp(Object.keys(DefaultLoaders).join("|")),
1170
- exclude = /node_modules/,
1171
- loaders: loaderOptions,
1172
- ...esbuildOptions
1173
- } = options;
1174
- const loaders = { ...DefaultLoaders };
1175
- if (loaderOptions) {
1176
- for (const [key, value] of Object.entries(loaderOptions)) {
1177
- if (typeof value === "string") {
1178
- loaders[key] = value;
1179
- } else if (value === false) {
1180
- delete loaders[key];
1181
- }
1182
- }
1183
- }
1184
- const getLoader = /* @__PURE__ */ __name((id = "") => {
1185
- return loaders[extname(id)];
1186
- }, "getLoader");
1187
- const filter = createFilter(include, exclude);
1188
- return {
1189
- name: "esbuild",
1190
- async transform(code, id) {
1191
- if (!filter(id)) {
1192
- return null;
1193
- }
1194
- const loader = getLoader(id);
1195
- if (!loader) {
1196
- return null;
1197
- }
1198
- const result = await transform2(code, {
1199
- ...esbuildOptions,
1200
- loader,
1201
- sourcefile: id
1202
- });
1203
- printWarnings(id, result, this);
1204
- return {
1205
- code: result.code || "",
1206
- map: result.map || null
1207
- };
1208
- },
1209
- async renderChunk(code, { fileName }) {
1210
- if (!options.minify) {
1211
- return null;
1212
- }
1213
- if (/\.d\.(c|m)?tsx?$/.test(fileName)) {
1214
- return null;
1215
- }
1216
- const loader = getLoader(fileName);
1217
- if (!loader) {
1218
- return null;
1219
- }
1220
- const result = await transform2(code, {
1221
- ...esbuildOptions,
1222
- loader,
1223
- sourcefile: fileName,
1224
- minify: true
1225
- });
1226
- return {
1227
- code: result.code || "",
1228
- map: result.map || null
1229
- };
1230
- }
1231
- };
1232
- }
1233
- __name(esbuild, "esbuild");
1234
- function printWarnings(id, result, plugin) {
1235
- if (result.warnings) {
1236
- for (const warning of result.warnings) {
1237
- let message = "[esbuild]";
1238
- if (warning.location) {
1239
- message += ` (${relative2(process.cwd(), id)}:${warning.location.line}:${warning.location.column})`;
1240
- }
1241
- message += ` ${warning.text}`;
1242
- plugin.warn(message);
1243
- }
1244
- }
1245
- }
1246
- __name(printWarnings, "printWarnings");
1247
- var EXPORT_DEFAULT = "export default ";
1248
- function JSONPlugin(options) {
1249
- const plugin = rollupJSONPlugin(options);
1250
- return {
1251
- ...plugin,
1252
- name: "unbuild-json",
1253
- transform(code, id) {
1254
- const res = plugin.transform.call(this, code, id);
1255
- if (res && typeof res !== "string" && "code" in res && res.code && res.code.startsWith(EXPORT_DEFAULT)) {
1256
- res.code = res.code.replace(EXPORT_DEFAULT, "module.exports = ");
1257
- }
1258
- return res;
1259
- }
1260
- };
1261
- }
1262
- __name(JSONPlugin, "JSONPlugin");
1263
- var defaults = {
1264
- include: [/\.(md|txt|css|htm|html)$/],
1265
- exclude: []
1266
- };
1267
- function rawPlugin(opts = {}) {
1268
- opts = { ...opts, ...defaults };
1269
- const filter = createFilter(opts.include, opts.exclude);
1270
- return {
1271
- name: "unbuild-raw",
1272
- transform(code, id) {
1273
- if (filter(id)) {
1274
- return {
1275
- code: `export default ${JSON.stringify(code)}`,
1276
- map: null
1277
- };
1278
- }
1279
- }
1280
- };
1281
- }
1282
- __name(rawPlugin, "rawPlugin");
1283
- function cjsPlugin(_opts) {
1284
- return {
1285
- name: "unbuild-cjs",
1286
- renderChunk(code, _chunk, opts) {
1287
- if (opts.format === "es") {
1288
- return CJSToESM(code);
1289
- }
1290
- return null;
1291
- }
1292
- };
1293
- }
1294
- __name(cjsPlugin, "cjsPlugin");
1295
- function fixCJSExportTypePlugin() {
1296
- return {
1297
- name: "unbuild-fix-cjs-export-type",
1298
- renderChunk(code, info, opts) {
1299
- if (info.type !== "chunk" || !info.fileName.endsWith(".d.cts") || !info.isEntry || info.exports?.length !== 1 || info.exports[0] !== "default") {
1300
- return;
1301
- }
1302
- return code.replace(
1303
- /(?<=(?<=[;}]|^)\s*export\s*){\s*([\w$]+)\s*as\s+default\s*}/,
1304
- `= $1`
1305
- );
1306
- }
1307
- };
1308
- }
1309
- __name(fixCJSExportTypePlugin, "fixCJSExportTypePlugin");
1310
- var CJSyntaxRe = /__filename|__dirname|require\(|require\.resolve\(/;
1311
- var CJSShim = `
1312
-
1313
- // -- Unbuild CommonJS Shims --
1314
- import __cjs_url__ from 'url';
1315
- import __cjs_path__ from 'path';
1316
- import __cjs_mod__ from 'module';
1317
- const __filename = __cjs_url__.fileURLToPath(import.meta.url);
1318
- const __dirname = __cjs_path__.dirname(__filename);
1319
- const require = __cjs_mod__.createRequire(import.meta.url);
1320
- `;
1321
- function CJSToESM(code) {
1322
- if (code.includes(CJSShim) || !CJSyntaxRe.test(code)) {
1323
- return null;
1324
- }
1325
- const lastESMImport = findStaticImports(code).pop();
1326
- const indexToAppend = lastESMImport ? lastESMImport.end : 0;
1327
- const s = new MagicString(code);
1328
- s.appendRight(indexToAppend, CJSShim);
1329
- return {
1330
- code: s.toString(),
1331
- map: s.generateMap()
1332
- };
1333
- }
1334
- __name(CJSToESM, "CJSToESM");
1335
- var DEFAULT_EXTENSIONS = [
1336
- ".ts",
1337
- ".tsx",
1338
- ".mts",
1339
- ".cts",
1340
- ".mjs",
1341
- ".cjs",
1342
- ".js",
1343
- ".jsx",
1344
- ".json"
1345
- ];
1346
- function resolveAliases(ctx) {
1347
- const aliases = {
1348
- [ctx.pkg.name]: ctx.options.rootDir,
1349
- ...ctx.options.alias
1350
- };
1351
- if (ctx.options.rollup.alias) {
1352
- if (Array.isArray(ctx.options.rollup.alias.entries)) {
1353
- Object.assign(
1354
- aliases,
1355
- Object.fromEntries(
1356
- ctx.options.rollup.alias.entries.map((entry) => {
1357
- return [entry.find, entry.replacement];
1358
- })
1359
- )
1360
- );
1361
- } else {
1362
- Object.assign(
1363
- aliases,
1364
- ctx.options.rollup.alias.entries || ctx.options.rollup.alias
1365
- );
1366
- }
1367
- }
1368
- return aliases;
1369
- }
1370
- __name(resolveAliases, "resolveAliases");
1371
- function getChunkFilename(ctx, chunk, ext) {
1372
- if (chunk.isDynamicEntry) {
1373
- return `chunks/[name].${ext}`;
1374
- }
1375
- return `shared/${ctx.options.name}.[hash].${ext}`;
1376
- }
1377
- __name(getChunkFilename, "getChunkFilename");
1378
- function getRollupOptions(ctx) {
1379
- const _aliases = resolveAliases(ctx);
1380
- return {
1381
- input: Object.fromEntries(
1382
- ctx.options.entries.filter((entry) => entry.builder === "rollup").map((entry) => [
1383
- entry.name,
1384
- resolve(ctx.options.rootDir, entry.input)
1385
- ])
1386
- ),
1387
- output: [
1388
- ctx.options.rollup.emitCJS && {
1389
- dir: resolve(ctx.options.rootDir, ctx.options.outDir),
1390
- entryFileNames: "[name].cjs",
1391
- chunkFileNames: /* @__PURE__ */ __name((chunk) => getChunkFilename(ctx, chunk, "cjs"), "chunkFileNames"),
1392
- format: "cjs",
1393
- exports: "auto",
1394
- interop: "compat",
1395
- generatedCode: { constBindings: true },
1396
- externalLiveBindings: false,
1397
- freeze: false,
1398
- sourcemap: ctx.options.sourcemap,
1399
- ...ctx.options.rollup.output
1400
- },
1401
- {
1402
- dir: resolve(ctx.options.rootDir, ctx.options.outDir),
1403
- entryFileNames: "[name].mjs",
1404
- chunkFileNames: /* @__PURE__ */ __name((chunk) => getChunkFilename(ctx, chunk, "mjs"), "chunkFileNames"),
1405
- format: "esm",
1406
- exports: "auto",
1407
- generatedCode: { constBindings: true },
1408
- externalLiveBindings: false,
1409
- freeze: false,
1410
- sourcemap: ctx.options.sourcemap,
1411
- ...ctx.options.rollup.output
1412
- }
1413
- ].filter(Boolean),
1414
- external(originalId) {
1415
- const resolvedId = resolveAlias(originalId, _aliases);
1416
- const pkgName = parseNodeModulePath(resolvedId)?.name || parseNodeModulePath(originalId)?.name || getpkg(originalId);
1417
- if (arrayIncludes(ctx.options.externals, pkgName) || arrayIncludes(ctx.options.externals, originalId) || arrayIncludes(ctx.options.externals, resolvedId)) {
1418
- return true;
1419
- }
1420
- for (const id of [originalId, resolvedId]) {
1421
- if (id[0] === "." || isAbsolute(id) || /src[/\\]/.test(id) || id.startsWith(ctx.pkg.name)) {
1422
- return false;
1423
- }
1424
- }
1425
- if (ctx.options.rollup.inlineDependencies === true || Array.isArray(ctx.options.rollup.inlineDependencies) && (arrayIncludes(ctx.options.rollup.inlineDependencies, pkgName) || arrayIncludes(ctx.options.rollup.inlineDependencies, originalId) || arrayIncludes(ctx.options.rollup.inlineDependencies, resolvedId))) {
1426
- return false;
1427
- }
1428
- warn(ctx, `Implicitly bundling "${originalId}"`);
1429
- return false;
1430
- },
1431
- onwarn(warning, rollupWarn) {
1432
- if (!warning.code || !["CIRCULAR_DEPENDENCY"].includes(warning.code)) {
1433
- rollupWarn(warning);
1434
- }
1435
- },
1436
- plugins: [
1437
- ctx.options.rollup.replace && replace({
1438
- ...ctx.options.rollup.replace,
1439
- values: {
1440
- ...ctx.options.replace,
1441
- ...ctx.options.rollup.replace.values
1442
- }
1443
- }),
1444
- ctx.options.rollup.alias && alias({
1445
- ...ctx.options.rollup.alias,
1446
- entries: _aliases
1447
- }),
1448
- ctx.options.rollup.resolve && nodeResolve({
1449
- extensions: DEFAULT_EXTENSIONS,
1450
- exportConditions: ["production"],
1451
- ...ctx.options.rollup.resolve
1452
- }),
1453
- ctx.options.rollup.json && JSONPlugin({
1454
- ...ctx.options.rollup.json
1455
- }),
1456
- shebangPlugin(),
1457
- ctx.options.rollup.esbuild && esbuild({
1458
- sourcemap: ctx.options.sourcemap,
1459
- ...ctx.options.rollup.esbuild
1460
- }),
1461
- ctx.options.rollup.commonjs && commonjs({
1462
- extensions: DEFAULT_EXTENSIONS,
1463
- ...ctx.options.rollup.commonjs
1464
- }),
1465
- ctx.options.rollup.preserveDynamicImports && {
1466
- renderDynamicImport() {
1467
- return { left: "import(", right: ")" };
1468
- }
1469
- },
1470
- ctx.options.rollup.cjsBridge && cjsPlugin(),
1471
- rawPlugin()
1472
- ].filter(Boolean)
1473
- };
1474
- }
1475
- __name(getRollupOptions, "getRollupOptions");
1476
- async function rollupStub(ctx) {
1477
- const babelPlugins = ctx.options.stubOptions.jiti.transformOptions?.babel?.plugins;
1478
- const importedBabelPlugins = [];
1479
- const serializedJitiOptions = JSON.stringify(
1480
- {
1481
- ...ctx.options.stubOptions.jiti,
1482
- alias: {
1483
- ...resolveAliases(ctx),
1484
- ...ctx.options.stubOptions.jiti.alias
1485
- },
1486
- transformOptions: {
1487
- ...ctx.options.stubOptions.jiti.transformOptions,
1488
- babel: {
1489
- ...ctx.options.stubOptions.jiti.transformOptions?.babel,
1490
- plugins: "__$BABEL_PLUGINS"
1491
- }
1492
- }
1493
- },
1494
- null,
1495
- 2
1496
- ).replace(
1497
- '"__$BABEL_PLUGINS"',
1498
- Array.isArray(babelPlugins) ? "[" + babelPlugins.map((plugin, i) => {
1499
- if (Array.isArray(plugin)) {
1500
- const [name, ...args] = plugin;
1501
- importedBabelPlugins.push(name);
1502
- return `[` + [
1503
- `plugin${i}`,
1504
- ...args.map((val) => JSON.stringify(val))
1505
- ].join(", ") + "]";
1506
- } else {
1507
- importedBabelPlugins.push(plugin);
1508
- return `plugin${i}`;
1509
- }
1510
- }).join(",") + "]" : "[]"
1511
- );
1512
- for (const entry of ctx.options.entries.filter(
1513
- (entry2) => entry2.builder === "rollup"
1514
- )) {
1515
- const output = resolve(
1516
- ctx.options.rootDir,
1517
- ctx.options.outDir,
1518
- entry.name
1519
- );
1520
- const isESM = ctx.pkg.type === "module";
1521
- const resolvedEntry = fileURLToPath(ctx.jiti.esmResolve(entry.input));
1522
- const resolvedEntryWithoutExt = resolvedEntry.slice(
1523
- 0,
1524
- Math.max(0, resolvedEntry.length - extname(resolvedEntry).length)
1525
- );
1526
- const resolvedEntryForTypeImport = isESM ? `${resolvedEntry.replace(/(\.m?)(ts)$/, "$1js")}` : resolvedEntryWithoutExt;
1527
- const code = await promises.readFile(resolvedEntry, "utf8");
1528
- const shebang = getShebang(code);
1529
- await mkdir(dirname(output), { recursive: true });
1530
- if (ctx.options.rollup.emitCJS) {
1531
- const jitiCJSPath = relative2(
1532
- dirname(output),
1533
- await resolvePath("jiti", {
1534
- url: import.meta.url,
1535
- conditions: ["node", "require"]
1536
- })
1537
- );
1538
- await writeFile2(
1539
- output + ".cjs",
1540
- shebang + [
1541
- `const { createJiti } = require(${JSON.stringify(jitiCJSPath)})`,
1542
- ...importedBabelPlugins.map(
1543
- (plugin, i) => `const plugin${i} = require(${JSON.stringify(plugin)})`
1544
- ),
1545
- "",
1546
- `const jiti = createJiti(__filename, ${serializedJitiOptions})`,
1547
- "",
1548
- `/** @type {import(${JSON.stringify(
1549
- resolvedEntryForTypeImport
1550
- )})} */`,
1551
- `module.exports = jiti(${JSON.stringify(resolvedEntry)})`
1552
- ].join("\n")
1553
- );
1554
- }
1555
- const namedExports = await resolveModuleExportNames(
1556
- resolvedEntry,
1557
- {
1558
- extensions: DEFAULT_EXTENSIONS
1559
- }
1560
- ).catch((error) => {
1561
- warn(ctx, `Cannot analyze ${resolvedEntry} for exports:` + error);
1562
- return [];
1563
- });
1564
- const hasDefaultExport = namedExports.includes("default") || namedExports.length === 0;
1565
- const jitiESMPath = relative2(
1566
- dirname(output),
1567
- await resolvePath("jiti", {
1568
- url: import.meta.url,
1569
- conditions: ["node", "import"]
1570
- })
1571
- );
1572
- await writeFile2(
1573
- output + ".mjs",
1574
- shebang + [
1575
- `import { createJiti } from ${JSON.stringify(jitiESMPath)};`,
1576
- ...importedBabelPlugins.map(
1577
- (plugin, i) => `import plugin${i} from ${JSON.stringify(plugin)}`
1578
- ),
1579
- "",
1580
- `const jiti = createJiti(import.meta.url, ${serializedJitiOptions})`,
1581
- "",
1582
- `/** @type {import(${JSON.stringify(resolvedEntryForTypeImport)})} */`,
1583
- `const _module = await jiti.import(${JSON.stringify(
1584
- resolvedEntry
1585
- )});`,
1586
- hasDefaultExport ? "\nexport default _module?.default ?? _module;" : "",
1587
- ...namedExports.filter((name) => name !== "default").map((name) => `export const ${name} = _module.${name};`)
1588
- ].join("\n")
1589
- );
1590
- if (ctx.options.declaration) {
1591
- const dtsContent = [
1592
- `export * from ${JSON.stringify(resolvedEntryForTypeImport)};`,
1593
- hasDefaultExport ? `export { default } from ${JSON.stringify(resolvedEntryForTypeImport)};` : ""
1594
- ].join("\n");
1595
- await writeFile2(output + ".d.cts", dtsContent);
1596
- await writeFile2(output + ".d.mts", dtsContent);
1597
- if (ctx.options.declaration === "compatible" || ctx.options.declaration === true) {
1598
- await writeFile2(output + ".d.ts", dtsContent);
1599
- }
1600
- }
1601
- if (shebang) {
1602
- await makeExecutable(output + ".cjs");
1603
- await makeExecutable(output + ".mjs");
1604
- }
1605
- }
1606
- }
1607
- __name(rollupStub, "rollupStub");
1608
- function rollupWatch(rollupOptions) {
1609
- const watcher = watch(rollupOptions);
1610
- let inputs;
1611
- if (Array.isArray(rollupOptions.input)) {
1612
- inputs = rollupOptions.input;
1613
- } else if (typeof rollupOptions.input === "string") {
1614
- inputs = [rollupOptions.input];
1615
- } else {
1616
- inputs = Object.keys(rollupOptions.input || {});
1617
- }
1618
- consola$1.info(
1619
- `[unbuild] [rollup] Starting watchers for entries: ${inputs.map((input) => "./" + relative2(process.cwd(), input)).join(", ")}`
1620
- );
1621
- consola$1.warn(
1622
- "[unbuild] [rollup] Watch mode is experimental and may be unstable"
1623
- );
1624
- watcher.on("change", (id, { event }) => {
1625
- consola$1.info(`${colors.cyan(relative2(".", id))} was ${event}d`);
1626
- });
1627
- watcher.on("restart", () => {
1628
- consola$1.info(colors.gray("[unbuild] [rollup] Rebuilding bundle"));
1629
- });
1630
- watcher.on("event", (event) => {
1631
- if (event.code === "END") {
1632
- consola$1.success(colors.green("[unbuild] [rollup] Rebuild finished\n"));
1633
- }
1634
- });
1635
- }
1636
- __name(rollupWatch, "rollupWatch");
1637
- async function rollupBuild(ctx) {
1638
- if (ctx.options.stub) {
1639
- await rollupStub(ctx);
1640
- await ctx.hooks.callHook("rollup:done", ctx);
1641
- return;
1642
- }
1643
- const rollupOptions = getRollupOptions(ctx);
1644
- await ctx.hooks.callHook("rollup:options", ctx, rollupOptions);
1645
- if (Object.keys(rollupOptions.input).length === 0) {
1646
- await ctx.hooks.callHook("rollup:done", ctx);
1647
- return;
1648
- }
1649
- const buildResult = await rollup(rollupOptions);
1650
- await ctx.hooks.callHook("rollup:build", ctx, buildResult);
1651
- const allOutputOptions = rollupOptions.output;
1652
- for (const outputOptions of allOutputOptions) {
1653
- const { output } = await buildResult.write(outputOptions);
1654
- const chunkFileNames = /* @__PURE__ */ new Set();
1655
- const outputChunks = output.filter(
1656
- (e) => e.type === "chunk"
1657
- );
1658
- for (const entry of outputChunks) {
1659
- chunkFileNames.add(entry.fileName);
1660
- for (const id of entry.imports) {
1661
- ctx.usedImports.add(id);
1662
- }
1663
- if (entry.isEntry) {
1664
- ctx.buildEntries.push({
1665
- chunks: entry.imports.filter(
1666
- (i) => outputChunks.find((c) => c.fileName === i)
1667
- ),
1668
- modules: Object.entries(entry.modules).map(([id, mod]) => ({
1669
- id,
1670
- bytes: mod.renderedLength
1671
- })),
1672
- path: entry.fileName,
1673
- bytes: Buffer.byteLength(entry.code, "utf8"),
1674
- exports: entry.exports
1675
- });
1676
- }
1677
- }
1678
- for (const chunkFileName of chunkFileNames) {
1679
- ctx.usedImports.delete(chunkFileName);
1680
- }
1681
- }
1682
- if (ctx.options.watch) {
1683
- rollupWatch(rollupOptions);
1684
- if (ctx.options.declaration && ctx.options.watch) {
1685
- consola$1.warn("`rollup` DTS builder does not support watch mode yet.");
1686
- }
1687
- return;
1688
- }
1689
- if (ctx.options.declaration) {
1690
- rollupOptions.plugins = [
1691
- ...rollupOptions.plugins,
1692
- dts(ctx.options.rollup.dts),
1693
- removeShebangPlugin(),
1694
- ctx.options.rollup.emitCJS && fixCJSExportTypePlugin()
1695
- ].filter(Boolean);
1696
- await ctx.hooks.callHook("rollup:dts:options", ctx, rollupOptions);
1697
- const typesBuild2 = await rollup(rollupOptions);
1698
- await ctx.hooks.callHook("rollup:dts:build", ctx, typesBuild2);
1699
- if (ctx.options.rollup.emitCJS) {
1700
- await typesBuild2.write({
1701
- dir: resolve(ctx.options.rootDir, ctx.options.outDir),
1702
- entryFileNames: "[name].d.cts",
1703
- chunkFileNames: /* @__PURE__ */ __name((chunk) => getChunkFilename(ctx, chunk, "d.cts"), "chunkFileNames")
1704
- });
1705
- }
1706
- await typesBuild2.write({
1707
- dir: resolve(ctx.options.rootDir, ctx.options.outDir),
1708
- entryFileNames: "[name].d.mts",
1709
- chunkFileNames: /* @__PURE__ */ __name((chunk) => getChunkFilename(ctx, chunk, "d.mts"), "chunkFileNames")
1710
- });
1711
- if (ctx.options.declaration === true || ctx.options.declaration === "compatible") {
1712
- await typesBuild2.write({
1713
- dir: resolve(ctx.options.rootDir, ctx.options.outDir),
1714
- entryFileNames: "[name].d.ts",
1715
- chunkFileNames: /* @__PURE__ */ __name((chunk) => getChunkFilename(ctx, chunk, "d.ts"), "chunkFileNames")
1716
- });
1717
- }
1718
- }
1719
- await ctx.hooks.callHook("rollup:done", ctx);
1720
- }
1721
- __name(rollupBuild, "rollupBuild");
1722
- async function typesBuild(ctx) {
1723
- const entries = ctx.options.entries.filter(
1724
- (entry) => entry.builder === "untyped"
1725
- );
1726
- await ctx.hooks.callHook("untyped:entries", ctx, entries);
1727
- for (const entry of entries) {
1728
- const options = {
1729
- jiti: {
1730
- interopDefault: true,
1731
- transformOptions: {
1732
- babel: {
1733
- plugins: [untypedPlugin]
1734
- }
1735
- }
1736
- }
1737
- };
1738
- await ctx.hooks.callHook("untyped:entry:options", ctx, entry, options);
1739
- const untypedJiti = createJiti(ctx.options.rootDir, options.jiti);
1740
- const distDir = entry.outDir;
1741
- let rawSchema = await untypedJiti.import(resolve(ctx.options.rootDir, entry.input), {
1742
- try: true
1743
- }) || {};
1744
- const rawSchemaKeys = Object.keys(rawSchema);
1745
- if (rawSchemaKeys.length === 1 && rawSchemaKeys[0] === "default") {
1746
- rawSchema = rawSchema.default;
1747
- }
1748
- const defaults2 = entry.defaults || {};
1749
- const schema = await resolveSchema(rawSchema, defaults2);
1750
- await ctx.hooks.callHook("untyped:entry:schema", ctx, entry, schema);
1751
- const outputs = {
1752
- markdown: {
1753
- fileName: resolve(distDir, `${entry.name}.md`),
1754
- contents: generateMarkdown(schema)
1755
- },
1756
- schema: {
1757
- fileName: `${entry.name}.schema.json`,
1758
- contents: JSON.stringify(schema, null, 2)
1759
- },
1760
- defaults: {
1761
- fileName: `${entry.name}.defaults.json`,
1762
- contents: JSON.stringify(defaults2, null, 2)
1763
- },
1764
- declaration: entry.declaration ? {
1765
- fileName: `${entry.name}.d.ts`,
1766
- contents: generateTypes(schema, {
1767
- interfaceName: pascalCase(entry.name + "-schema")
1768
- })
1769
- } : void 0
1770
- };
1771
- await ctx.hooks.callHook("untyped:entry:outputs", ctx, entry, outputs);
1772
- for (const output of Object.values(outputs)) {
1773
- if (!output) continue;
1774
- await writeFile2(
1775
- resolve(distDir, output.fileName),
1776
- output.contents,
1777
- "utf8"
1778
- );
1779
- }
1780
- }
1781
- await ctx.hooks.callHook("untyped:done", ctx);
1782
- if (entries.length > 0 && ctx.options.watch) {
1783
- consola$1.warn("`untyped` builder does not support watch mode yet.");
1784
- }
1785
- }
1786
- __name(typesBuild, "typesBuild");
1787
- async function mkdistBuild(ctx) {
1788
- const entries = ctx.options.entries.filter(
1789
- (e) => e.builder === "mkdist"
1790
- );
1791
- await ctx.hooks.callHook("mkdist:entries", ctx, entries);
1792
- for (const entry of entries) {
1793
- const distDir = entry.outDir;
1794
- if (ctx.options.stub) {
1795
- await rmdir(distDir);
1796
- await symlink(entry.input, distDir);
1797
- } else {
1798
- const mkdistOptions = {
1799
- rootDir: ctx.options.rootDir,
1800
- srcDir: entry.input,
1801
- distDir,
1802
- cleanDist: false,
1803
- ...entry
1804
- };
1805
- await ctx.hooks.callHook(
1806
- "mkdist:entry:options",
1807
- ctx,
1808
- entry,
1809
- mkdistOptions
1810
- );
1811
- const output = await mkdist(mkdistOptions);
1812
- ctx.buildEntries.push({
1813
- path: distDir,
1814
- chunks: output.writtenFiles.map((p) => relative2(ctx.options.outDir, p))
1815
- });
1816
- await ctx.hooks.callHook("mkdist:entry:build", ctx, entry, output);
1817
- if (output.errors) {
1818
- for (const error of output.errors) {
1819
- warn(
1820
- ctx,
1821
- `mkdist build failed for \`${relative2(ctx.options.rootDir, error.filename)}\`:
1822
- ${error.errors.map((e) => ` - ${e}`).join("\n")}`
1823
- );
1824
- }
1825
- }
1826
- }
1827
- }
1828
- await ctx.hooks.callHook("mkdist:done", ctx);
1829
- if (entries.length > 0 && ctx.options.watch) {
1830
- consola$1.warn("`mkdist` builder does not support watch mode yet.");
1831
- }
1832
- }
1833
- __name(mkdistBuild, "mkdistBuild");
1834
- var copy = promises.cp || promises.copyFile;
1835
- async function copyBuild(ctx) {
1836
- const entries = ctx.options.entries.filter(
1837
- (e) => e.builder === "copy"
1838
- );
1839
- await ctx.hooks.callHook("copy:entries", ctx, entries);
1840
- for (const entry of entries) {
1841
- const distDir = entry.outDir;
1842
- if (ctx.options.stub) {
1843
- await rmdir(distDir);
1844
- await symlink(entry.input, distDir);
1845
- } else {
1846
- const patterns = Array.isArray(entry.pattern) ? entry.pattern : [entry.pattern || "**"];
1847
- const paths = await glob3(patterns, {
1848
- cwd: resolve(ctx.options.rootDir, entry.input),
1849
- absolute: false
1850
- });
1851
- const outputList = await Promise.allSettled(
1852
- paths.map(async (path2) => {
1853
- const src = resolve(ctx.options.rootDir, entry.input, path2);
1854
- const dist = resolve(ctx.options.rootDir, distDir, path2);
1855
- await copy(src, dist);
1856
- return dist;
1857
- })
1858
- );
1859
- for (const output of outputList) {
1860
- if (output.status === "rejected") {
1861
- warn(ctx, output.reason);
1862
- }
1863
- }
1864
- ctx.buildEntries.push({
1865
- path: distDir,
1866
- chunks: outputList.filter(({ status }) => status === "fulfilled").map(
1867
- (p) => relative2(
1868
- ctx.options.outDir,
1869
- p.value
1870
- )
1871
- )
1872
- });
1873
- }
1874
- }
1875
- await ctx.hooks.callHook("copy:done", ctx);
1876
- if (entries.length > 0 && ctx.options.watch) {
1877
- consola$1.warn("`untyped` builder does not support watch mode yet.");
1878
- }
1879
- }
1880
- __name(copyBuild, "copyBuild");
1881
- async function build(rootDir, stub, inputConfig = {}) {
1882
- rootDir = resolve(process.cwd(), rootDir || ".");
1883
- const jiti = createJiti(rootDir);
1884
- const _buildConfig = await jiti.import(inputConfig?.config || "./build.config", {
1885
- try: !inputConfig.config,
1886
- default: true
1887
- }) || {};
1888
- const buildConfigs = (Array.isArray(_buildConfig) ? _buildConfig : [_buildConfig]).filter(Boolean);
1889
- const pkg = await jiti.import("./package.json", {
1890
- try: true,
1891
- default: true
1892
- }) || {};
1893
- const cleanedDirs = [];
1894
- const _watchMode = inputConfig.watch === true;
1895
- const _stubMode = !_watchMode && (stub || inputConfig.stub === true);
1896
- for (const buildConfig of buildConfigs) {
1897
- await _build(
1898
- rootDir,
1899
- inputConfig,
1900
- buildConfig,
1901
- pkg,
1902
- cleanedDirs,
1903
- _stubMode,
1904
- _watchMode
1905
- );
1906
- }
1907
- }
1908
- __name(build, "build");
1909
- async function _build(rootDir, inputConfig = {}, buildConfig, pkg, cleanedDirs, _stubMode, _watchMode) {
1910
- const preset = await resolvePreset(
1911
- buildConfig.preset || pkg.unbuild?.preset || pkg.build?.preset || inputConfig.preset || "auto",
1912
- rootDir
1913
- );
1914
- const options = defu3(
1915
- buildConfig,
1916
- pkg.unbuild || pkg.build,
1917
- inputConfig,
1918
- preset,
1919
- {
1920
- name: (pkg?.name || "").split("/").pop() || "default",
1921
- rootDir,
1922
- entries: [],
1923
- clean: true,
1924
- declaration: void 0,
1925
- outDir: "dist",
1926
- stub: _stubMode,
1927
- stubOptions: {
1928
- /**
1929
- * See https://github.com/unjs/jiti#%EF%B8%8F-options
1930
- */
1931
- jiti: {
1932
- interopDefault: true,
1933
- alias: {}
1934
- }
1935
- },
1936
- watch: _watchMode,
1937
- watchOptions: _watchMode ? {
1938
- exclude: "node_modules/**",
1939
- include: "src/**"
1940
- } : void 0,
1941
- externals: [
1942
- ...Module.builtinModules,
1943
- ...Module.builtinModules.map((m) => "node:" + m)
1944
- ],
1945
- dependencies: [],
1946
- devDependencies: [],
1947
- peerDependencies: [],
1948
- alias: {},
1949
- replace: {},
1950
- failOnWarn: true,
1951
- sourcemap: false,
1952
- rollup: {
1953
- emitCJS: false,
1954
- watch: false,
1955
- cjsBridge: false,
1956
- inlineDependencies: false,
1957
- preserveDynamicImports: true,
1958
- output: {
1959
- // https://v8.dev/features/import-attributes
1960
- importAttributesKey: "with"
1961
- },
1962
- // Plugins
1963
- replace: {
1964
- preventAssignment: true
1965
- },
1966
- alias: {},
1967
- resolve: {
1968
- preferBuiltins: true
1969
- },
1970
- json: {
1971
- preferConst: true
1972
- },
1973
- commonjs: {
1974
- ignoreTryCatch: true
1975
- },
1976
- esbuild: { target: "esnext" },
1977
- dts: {
1978
- // https://github.com/Swatinem/rollup-plugin-dts/issues/143
1979
- compilerOptions: { preserveSymlinks: false },
1980
- respectExternal: true
1981
- }
1982
- },
1983
- parallel: false
1984
- }
1985
- );
1986
- options.outDir = resolve(options.rootDir, options.outDir);
1987
- const jiti = createJiti(options.rootDir, { interopDefault: true });
1988
- const ctx = {
1989
- options,
1990
- jiti,
1991
- warnings: /* @__PURE__ */ new Set(),
1992
- pkg,
1993
- buildEntries: [],
1994
- usedImports: /* @__PURE__ */ new Set(),
1995
- hooks: createHooks()
1996
- };
1997
- if (preset.hooks) {
1998
- ctx.hooks.addHooks(preset.hooks);
1999
- }
2000
- if (inputConfig.hooks) {
2001
- ctx.hooks.addHooks(inputConfig.hooks);
2002
- }
2003
- if (buildConfig.hooks) {
2004
- ctx.hooks.addHooks(buildConfig.hooks);
2005
- }
2006
- await ctx.hooks.callHook("build:prepare", ctx);
2007
- options.entries = options.entries.map(
2008
- (entry) => typeof entry === "string" ? { input: entry } : entry
2009
- );
2010
- for (const entry of options.entries) {
2011
- if (typeof entry.name !== "string") {
2012
- let relativeInput = isAbsolute(entry.input) ? relative2(rootDir, entry.input) : normalize(entry.input);
2013
- if (relativeInput.startsWith("./")) {
2014
- relativeInput = relativeInput.slice(2);
2015
- }
2016
- entry.name = removeExtension(relativeInput.replace(/^src\//, ""));
2017
- }
2018
- if (!entry.input) {
2019
- throw new Error("Missing entry input: " + dumpObject(entry));
2020
- }
2021
- if (!entry.builder) {
2022
- entry.builder = entry.input.endsWith("/") ? "mkdist" : "rollup";
2023
- }
2024
- if (options.declaration !== void 0 && entry.declaration === void 0) {
2025
- entry.declaration = options.declaration;
2026
- }
2027
- entry.input = resolve(options.rootDir, entry.input);
2028
- entry.outDir = resolve(options.rootDir, entry.outDir || options.outDir);
2029
- }
2030
- options.dependencies = Object.keys(pkg.dependencies || {});
2031
- options.peerDependencies = Object.keys(pkg.peerDependencies || {});
2032
- options.devDependencies = Object.keys(pkg.devDependencies || {});
2033
- options.externals.push(...inferPkgExternals(pkg));
2034
- options.externals = [...new Set(options.externals)];
2035
- await ctx.hooks.callHook("build:before", ctx);
2036
- consola.info(
2037
- colors.cyan(`${options.stub ? "Stubbing" : "Building"} ${options.name}`)
2038
- );
2039
- if (process.env.DEBUG) {
2040
- consola.info(`${colors.bold("Root dir:")} ${options.rootDir}
2041
- ${colors.bold("Entries:")}
2042
- ${options.entries.map((entry) => " " + dumpObject(entry)).join("\n ")}
2043
- `);
2044
- }
2045
- if (options.clean) {
2046
- for (const dir of new Set(
2047
- options.entries.map((e) => e.outDir).filter(Boolean).sort()
2048
- )) {
2049
- if (dir === options.rootDir || options.rootDir.startsWith(withTrailingSlash(dir)) || cleanedDirs.some((c) => dir.startsWith(c))) {
2050
- continue;
2051
- }
2052
- cleanedDirs.push(dir);
2053
- consola.info(
2054
- `Cleaning dist directory: \`./${relative2(process.cwd(), dir)}\``
2055
- );
2056
- await rmdir(dir);
2057
- await promises.mkdir(dir, { recursive: true });
2058
- }
2059
- }
2060
- const buildTasks = [
2061
- typesBuild,
2062
- // untyped
2063
- mkdistBuild,
2064
- // mkdist
2065
- rollupBuild,
2066
- // rollup
2067
- copyBuild
2068
- // copy
2069
- ];
2070
- if (options.parallel) {
2071
- await Promise.all(buildTasks.map((task) => task(ctx)));
2072
- } else {
2073
- for (const task of buildTasks) {
2074
- await task(ctx);
2075
- }
2076
- }
2077
- if (options.stub || options.watch) {
2078
- await ctx.hooks.callHook("build:done", ctx);
2079
- return;
2080
- }
2081
- consola.success(colors.green("Build succeeded for " + options.name));
2082
- const outFiles = await glob3(["**"], { cwd: options.outDir });
2083
- for (const file of outFiles) {
2084
- let entry = ctx.buildEntries.find((e) => e.path === file);
2085
- if (!entry) {
2086
- entry = {
2087
- path: file,
2088
- chunk: true
2089
- };
2090
- ctx.buildEntries.push(entry);
2091
- }
2092
- if (!entry.bytes) {
2093
- const stat = await promises.stat(resolve(options.outDir, file));
2094
- entry.bytes = stat.size;
2095
- }
2096
- }
2097
- const rPath = /* @__PURE__ */ __name((p) => relative2(process.cwd(), resolve(options.outDir, p)), "rPath");
2098
- for (const entry of ctx.buildEntries.filter((e) => !e.chunk)) {
2099
- let totalBytes = entry.bytes || 0;
2100
- for (const chunk of entry.chunks || []) {
2101
- totalBytes += ctx.buildEntries.find((e) => e.path === chunk)?.bytes || 0;
2102
- }
2103
- let line = ` ${colors.bold(rPath(entry.path))} (` + [
2104
- totalBytes && `total size: ${colors.cyan(prettyBytes(totalBytes))}`,
2105
- entry.bytes && `chunk size: ${colors.cyan(prettyBytes(entry.bytes))}`,
2106
- entry.exports?.length && `exports: ${colors.gray(entry.exports.join(", "))}`
2107
- ].filter(Boolean).join(", ") + ")";
2108
- if (entry.chunks?.length) {
2109
- line += "\n" + entry.chunks.map((p) => {
2110
- const chunk = ctx.buildEntries.find((e) => e.path === p) || {};
2111
- return colors.gray(
2112
- " \u2514\u2500 " + rPath(p) + colors.bold(
2113
- chunk.bytes ? ` (${prettyBytes(chunk?.bytes)})` : ""
2114
- )
2115
- );
2116
- }).join("\n");
2117
- }
2118
- if (entry.modules?.length) {
2119
- line += "\n" + entry.modules.filter((m) => m.id.includes("node_modules")).sort((a, b) => (b.bytes || 0) - (a.bytes || 0)).map((m) => {
2120
- return colors.gray(
2121
- " \u{1F4E6} " + rPath(m.id) + colors.bold(m.bytes ? ` (${prettyBytes(m.bytes)})` : "")
2122
- );
2123
- }).join("\n");
2124
- }
2125
- consola.log(entry.chunk ? colors.gray(line) : line);
2126
- }
2127
- console.log(
2128
- "\u03A3 Total dist size (byte size):",
2129
- colors.cyan(
2130
- prettyBytes(ctx.buildEntries.reduce((a, e) => a + (e.bytes || 0), 0))
2131
- )
2132
- );
2133
- validateDependencies(ctx);
2134
- validatePackage(pkg, rootDir, ctx);
2135
- await ctx.hooks.callHook("build:done", ctx);
2136
- consola.log("");
2137
- if (ctx.warnings.size > 0) {
2138
- consola.warn(
2139
- "Build is done with some warnings:\n\n" + [...ctx.warnings].map((msg) => "- " + msg).join("\n")
2140
- );
2141
- if (ctx.options.failOnWarn) {
2142
- consola.error(
2143
- "Exiting with code (1). You can change this behavior by setting `failOnWarn: false` ."
2144
- );
2145
- process.exit(1);
2146
- }
2147
- }
2148
- }
2149
- __name(_build, "_build");
2150
-
2151
- // ../../node_modules/.pnpm/unbuild@3.3.1_sass@1.83.4_typescript@5.7.3/node_modules/unbuild/dist/index.mjs
2152
- import "node:module";
2153
- import "node:fs";
2154
- import "pathe";
2155
- import "consola/utils";
2156
- import "consola";
2157
- import "defu";
2158
- import "hookable";
2159
- import "pretty-bytes";
2160
- import "tinyglobby";
2161
- import "node:fs/promises";
2162
- import "jiti";
2163
- import "rollup";
2164
- import "rollup-plugin-dts";
2165
- import "@rollup/plugin-commonjs";
2166
- import "@rollup/plugin-node-resolve";
2167
- import "@rollup/plugin-alias";
2168
- import "@rollup/plugin-replace";
2169
- import "pathe/utils";
2170
- import "mlly";
2171
- import "esbuild";
2172
- import "@rollup/pluginutils";
2173
- import "@rollup/plugin-json";
2174
- import "magic-string";
2175
- import "untyped";
2176
- import "untyped/babel-plugin";
2177
- import "scule";
2178
- import "mkdist";
2179
-
2180
- // src/build.ts
2181
- async function resolveOptions(options, config) {
2182
- writeDebug(" \u2699\uFE0F Resolving build options", config);
2183
- const stopwatch = getStopwatch("Build options resolution");
2184
- if (options.configPath) {
2185
- const configFile = await loadConfig(options.configPath);
2186
- if (configFile) {
2187
- options = defu4(options, configFile);
2188
- }
2189
- }
2190
- const outputPath = options.outputPath || joinPaths("dist", options.projectRoot);
2191
- const projectGraph = readCachedProjectGraph2();
2192
- const projectJsonPath = joinPaths(config.workspaceRoot, options.projectRoot, "project.json");
2193
- if (!existsSync4(projectJsonPath)) {
2194
- throw new Error("Cannot find project.json configuration");
2195
- }
2196
- const projectJsonContent = await readFile4(projectJsonPath, "utf8");
2197
- const projectJson = JSON.parse(projectJsonContent);
2198
- const projectName = projectJson.name;
2199
- const packageJsonPath = joinPaths(config.workspaceRoot, options.projectRoot, "package.json");
2200
- if (!existsSync4(packageJsonPath)) {
2201
- throw new Error("Cannot find package.json configuration");
2202
- }
2203
- const packageJsonContent = await readFile4(packageJsonPath, "utf8");
2204
- const packageJson = JSON.parse(packageJsonContent);
2205
- let tsconfig = options.tsconfig;
2206
- if (!tsconfig) {
2207
- tsconfig = joinPaths(config.workspaceRoot, options.projectRoot, "tsconfig.json");
2208
- }
2209
- if (!existsSync4(tsconfig)) {
2210
- throw new Error("Cannot find tsconfig.json configuration");
2211
- }
2212
- let sourceRoot = projectJson.sourceRoot;
2213
- if (!sourceRoot) {
2214
- sourceRoot = joinPaths(options.projectRoot, "src");
2215
- }
2216
- if (!existsSync4(sourceRoot)) {
2217
- throw new Error("Cannot find sourceRoot directory");
2218
- }
2219
- const result = calculateProjectBuildableDependencies2(void 0, projectGraph, config.workspaceRoot, projectName, process.env.NX_TASK_TARGET_TARGET || "build", process.env.NX_TASK_TARGET_CONFIGURATION || "production", true);
2220
- let dependencies = result.dependencies;
2221
- const tsLibDependency = getHelperDependency(HelperDependency.tsc, tsconfig, dependencies, projectGraph, true);
2222
- if (tsLibDependency) {
2223
- dependencies = dependencies.filter((deps) => deps.name !== tsLibDependency.name);
2224
- dependencies.push(tsLibDependency);
2225
- }
2226
- const name = options.name || projectName;
2227
- const entries = options.entry ?? [
2228
- sourceRoot
2229
- ];
2230
- const resolvedOptions = {
2231
- name,
2232
- config,
2233
- projectRoot: options.projectRoot,
2234
- sourceRoot,
2235
- projectName,
2236
- tsconfig,
2237
- clean: false,
2238
- entries: entries.reduce((ret, entry) => {
2239
- let entryPath = entry.replace(options.projectRoot, "");
2240
- while (entryPath.startsWith(".")) {
2241
- entryPath = entryPath.substring(1);
2242
- }
2243
- while (entryPath.startsWith("/")) {
2244
- entryPath = entryPath.substring(1);
2245
- }
2246
- const outDir = joinPaths(relative3(joinPaths(config.workspaceRoot, options.projectRoot), config.workspaceRoot), outputPath, "dist");
2247
- ret.push({
2248
- name: `${name}-esm`,
2249
- builder: "mkdist",
2250
- input: `./${entryPath}`,
2251
- outDir,
2252
- declaration: options.emitTypes !== false ? "compatible" : false,
2253
- format: "esm"
2254
- });
2255
- ret.push({
2256
- name: `${name}-cjs`,
2257
- builder: "mkdist",
2258
- input: `./${entryPath}`,
2259
- outDir,
2260
- declaration: options.emitTypes !== false ? "compatible" : false,
2261
- format: "cjs",
2262
- ext: "cjs"
2263
- });
2264
- return ret;
2265
- }, []),
2266
- declaration: options.emitTypes !== false ? "compatible" : false,
2267
- failOnWarn: false,
2268
- sourcemap: options.sourcemap ?? !!options.debug,
2269
- outDir: outputPath,
2270
- parallel: true,
2271
- stub: false,
2272
- stubOptions: {
2273
- jiti: {}
2274
- },
2275
- externals: options.external ?? [],
2276
- dependencies: [],
2277
- peerDependencies: [],
2278
- devDependencies: [],
2279
- hooks: {},
2280
- alias: {},
2281
- replace: {},
2282
- rollup: {
2283
- replace: {},
2284
- alias: {},
2285
- json: {},
2286
- commonjs: {
2287
- sourceMap: options.sourcemap ?? true
2288
- },
2289
- emitCJS: true,
2290
- cjsBridge: true,
2291
- dts: {
2292
- respectExternal: true,
2293
- tsconfig
2294
- },
2295
- output: {
2296
- banner: options.banner || `
2297
- // \u26A1 Built by Storm Software
2298
- `,
2299
- footer: options.footer
2300
- },
2301
- resolve: {
2302
- preferBuiltins: true,
2303
- extensions: [
2304
- ".cjs",
2305
- ".mjs",
2306
- ".js",
2307
- ".jsx",
2308
- ".ts",
2309
- ".tsx",
2310
- ".json"
2311
- ]
2312
- },
2313
- esbuild: {
2314
- minify: options.minify ?? !options.debug,
2315
- sourceMap: options.sourcemap ?? !!options.debug,
2316
- splitting: options.splitting !== false,
2317
- treeShaking: options.treeShaking !== false,
2318
- color: true,
2319
- logLevel: config.logLevel === LogLevelLabel.FATAL ? LogLevelLabel.ERROR : isVerbose() ? "verbose" : config.logLevel
2320
- }
2321
- }
2322
- };
2323
- dependencies = dependencies.filter((dep) => dep.node.type === "npm" || dep.node.type === "lib" || dep.node.type === "app");
2324
- if (dependencies.length > 0) {
2325
- resolvedOptions.dependencies = dependencies.map((dep) => dep.name);
2326
- }
2327
- if (packageJson.devDependencies) {
2328
- resolvedOptions.devDependencies = Object.keys(packageJson.devDependencies);
2329
- }
2330
- if (packageJson.peerDependencies) {
2331
- resolvedOptions.peerDependencies = Object.keys(packageJson.peerDependencies);
2332
- }
2333
- if (options.rollup) {
2334
- let rollup2 = {};
2335
- if (typeof options.rollup === "string") {
2336
- const rollupFile = await loadConfig(options.rollup);
2337
- if (rollupFile) {
2338
- rollup2 = rollupFile;
2339
- }
2340
- } else {
2341
- rollup2 = options.rollup;
2342
- }
2343
- resolvedOptions.rollup = defu4(resolvedOptions.rollup ?? {}, rollup2);
2344
- }
2345
- resolvedOptions.hooks = {
2346
- "rollup:options": /* @__PURE__ */ __name(async (ctx, opts) => {
2347
- opts.plugins = options.plugins ?? await getDefaultBuildPlugins(options, resolvedOptions);
2348
- }, "rollup:options")
2349
- };
2350
- stopwatch();
2351
- return resolvedOptions;
2352
- }
2353
- __name(resolveOptions, "resolveOptions");
2354
- var addPackageJsonExport = /* @__PURE__ */ __name((file, type = "module", sourceRoot, projectRoot) => {
2355
- let root = sourceRoot.replace(projectRoot, "");
2356
- while (root.startsWith(".")) {
2357
- root = root.substring(1);
2358
- }
2359
- while (root.startsWith("/")) {
2360
- root = root.substring(1);
2361
- }
2362
- let entry = file.replaceAll("\\", "/").replace(sourceRoot, "");
2363
- while (entry.startsWith(".")) {
2364
- entry = entry.substring(1);
2365
- }
2366
- while (entry.startsWith("/")) {
2367
- entry = entry.substring(1);
2368
- }
2369
- return {
2370
- "import": {
2371
- "types": `./dist/${entry}.d.ts`,
2372
- "default": `./dist/${entry}.mjs`
2373
- },
2374
- "require": {
2375
- "types": `./dist/${entry}.d.ts`,
2376
- "default": `./dist/${entry}.cjs`
2377
- },
2378
- "default": {
2379
- "types": `./dist/${entry}.d.ts`,
2380
- "default": type === "commonjs" ? `./dist/${entry}.cjs` : `./dist/${entry}.mjs`
2381
- }
2382
- };
2383
- }, "addPackageJsonExport");
2384
- async function generatePackageJson(options) {
2385
- if (options.generatePackageJson !== false && existsSync4(joinPaths(options.projectRoot, "package.json"))) {
2386
- writeDebug(" \u270D\uFE0F Writing package.json file", options.config);
2387
- const stopwatch = getStopwatch("Write package.json file");
2388
- const packageJsonPath = joinPaths(options.projectRoot, "project.json");
2389
- if (!existsSync4(packageJsonPath)) {
2390
- throw new Error("Cannot find package.json configuration");
2391
- }
2392
- let packageJsonContent = await readFile4(joinPaths(options.config.workspaceRoot, options.projectRoot, "package.json"), "utf8");
2393
- if (!packageJsonContent) {
2394
- throw new Error("Cannot find package.json configuration file");
2395
- }
2396
- let packageJson = JSON.parse(packageJsonContent);
2397
- packageJson = await addPackageDependencies(options.config.workspaceRoot, options.projectRoot, options.projectName, packageJson);
2398
- packageJson = await addWorkspacePackageJsonFields(options.config, options.projectRoot, options.sourceRoot, options.projectName, false, packageJson);
2399
- packageJson.exports ??= {};
2400
- await Promise.all(options.entries.reduce((ret, entry) => {
2401
- let entryPath = typeof entry === "string" ? entry : entry.input;
2402
- entryPath = entryPath.replaceAll("\\", "/");
2403
- while (entryPath.startsWith(".")) {
2404
- entryPath = entryPath.substring(1);
2405
- }
2406
- while (entryPath.startsWith("/")) {
2407
- entryPath = entryPath.substring(1);
2408
- }
2409
- entryPath = `./${joinPaths(options.projectRoot, entryPath)}`;
2410
- if (!ret.includes(entryPath)) {
2411
- ret.push(entryPath);
2412
- }
2413
- return ret;
2414
- }, []).map(async (entryPath) => {
2415
- const files = await new Glob2("**/*.{ts,tsx}", {
2416
- absolute: false,
2417
- cwd: entryPath,
2418
- root: entryPath
2419
- }).walk();
2420
- files.forEach((file) => {
2421
- addPackageJsonExport(file, packageJson.type, options.sourceRoot, options.projectRoot);
2422
- const split = file.split(".");
2423
- split.pop();
2424
- const entry = split.join(".").replaceAll("\\", "/");
2425
- packageJson.exports[`./${entry}`] ??= addPackageJsonExport(entry, packageJson.type, options.sourceRoot, options.projectRoot);
2426
- });
2427
- }));
2428
- packageJson.main ??= "./dist/index.cjs";
2429
- packageJson.module ??= "./dist/index.mjs";
2430
- packageJson.types ??= "./dist/index.d.ts";
2431
- packageJson.exports ??= {};
2432
- packageJson.exports = Object.keys(packageJson.exports).reduce((ret, key) => {
2433
- if (key.endsWith("/index") && !ret[key.replace("/index", "")]) {
2434
- ret[key.replace("/index", "")] = packageJson.exports[key];
2435
- }
2436
- return ret;
2437
- }, packageJson.exports);
2438
- packageJson.exports["./package.json"] ??= "./package.json";
2439
- packageJson.exports["."] ??= addPackageJsonExport("index", packageJson.type, options.sourceRoot, options.projectRoot);
2440
- await writeJsonFile(joinPaths(options.outDir, "package.json"), packageJson);
2441
- stopwatch();
2442
- }
2443
- return options;
2444
- }
2445
- __name(generatePackageJson, "generatePackageJson");
2446
- async function executeUnbuild(options) {
2447
- writeDebug(` \u{1F680} Running ${options.name} (${options.projectRoot}) build`, options.config);
2448
- const stopwatch = getStopwatch(`${options.name} (${options.projectRoot}) build`);
2449
- try {
2450
- const config = {
2451
- ...options,
2452
- config: null,
2453
- rootDir: joinPaths(options.config.workspaceRoot, options.projectRoot)
2454
- };
2455
- writeTrace(`Running with unbuild configuration:
2456
- ${formatLogMessage(config)}
2457
- `, options.config);
2458
- await build(options.projectRoot, false, config);
2459
- } finally {
2460
- stopwatch();
2461
- }
2462
- return options;
2463
- }
2464
- __name(executeUnbuild, "executeUnbuild");
2465
- async function copyBuildAssets(options) {
2466
- writeDebug(` \u{1F4CB} Copying asset files to output directory: ${options.outDir}`, options.config);
2467
- const stopwatch = getStopwatch(`${options.name} asset copy`);
2468
- await copyAssets(options.config, options.assets ?? [], options.outDir, options.projectRoot, options.sourceRoot, options.generatePackageJson, options.includeSrc);
2469
- stopwatch();
2470
- return options;
2471
- }
2472
- __name(copyBuildAssets, "copyBuildAssets");
2473
- async function cleanOutputPath(options) {
2474
- if (options.clean !== false && options.outDir) {
2475
- writeDebug(` \u{1F9F9} Cleaning ${options.name} output path: ${options.outDir}`, options.config);
2476
- const stopwatch = getStopwatch(`${options.name} output clean`);
2477
- await cleanDirectories(options.name, options.outDir, options.config);
2478
- stopwatch();
2479
- }
2480
- return options;
2481
- }
2482
- __name(cleanOutputPath, "cleanOutputPath");
2483
- async function build2(options) {
2484
- const projectRoot = options.projectRoot;
2485
- if (!projectRoot) {
2486
- throw new Error("Cannot find project root");
2487
- }
2488
- const workspaceRoot = findWorkspaceRoot2(projectRoot);
2489
- if (!workspaceRoot) {
2490
- throw new Error("Cannot find workspace root");
2491
- }
2492
- const config = await getConfig(workspaceRoot.dir);
2493
- writeDebug(` \u26A1 Executing Storm Unbuild pipeline`, config);
2494
- const stopwatch = getStopwatch("Unbuild pipeline");
2495
- try {
2496
- options.projectRoot = correctPaths(projectRoot);
2497
- const resolvedOptions = await resolveOptions(options, config);
2498
- await cleanOutputPath(resolvedOptions);
2499
- await generatePackageJson(resolvedOptions);
2500
- await executeUnbuild(resolvedOptions);
2501
- await copyBuildAssets(resolvedOptions);
2502
- writeSuccess(` \u{1F3C1} The ${resolvedOptions.name} build completed successfully`, config);
2503
- } catch (error) {
2504
- writeFatal(" \u274C Fatal errors occurred during the build that could not be recovered from. The build process has been terminated.", config);
2505
- throw error;
2506
- } finally {
2507
- stopwatch();
2508
- }
2509
- }
2510
- __name(build2, "build");
2511
-
2512
- export {
2513
- resolveOptions,
2514
- generatePackageJson,
2515
- executeUnbuild,
2516
- copyBuildAssets,
2517
- cleanOutputPath,
2518
- build2 as build
2519
- };