@storm-software/unbuild 0.25.2 → 0.25.3

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