bunup 0.8.28 → 0.8.29

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.
package/dist/cli.js DELETED
@@ -1,1816 +0,0 @@
1
- #!/usr/bin/env bun
2
- // @bun
3
- var __create = Object.create;
4
- var __getProtoOf = Object.getPrototypeOf;
5
- var __defProp = Object.defineProperty;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __toESM = (mod, isNodeMode, target) => {
9
- target = mod != null ? __create(__getProtoOf(mod)) : {};
10
- const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
11
- for (let key of __getOwnPropNames(mod))
12
- if (!__hasOwnProp.call(to, key))
13
- __defProp(to, key, {
14
- get: () => mod[key],
15
- enumerable: true
16
- });
17
- return to;
18
- };
19
- var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
20
- var __export = (target, all) => {
21
- for (var name in all)
22
- __defProp(target, name, {
23
- get: all[name],
24
- enumerable: true,
25
- configurable: true,
26
- set: (newValue) => all[name] = () => newValue
27
- });
28
- };
29
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
30
- var __require = import.meta.require;
31
-
32
- // node_modules/picocolors/picocolors.js
33
- var require_picocolors = __commonJS((exports, module) => {
34
- var p = process || {};
35
- var argv = p.argv || [];
36
- var env = p.env || {};
37
- var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
38
- var formatter = (open, close, replace = open) => (input) => {
39
- let string = "" + input, index = string.indexOf(close, open.length);
40
- return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
41
- };
42
- var replaceClose = (string, close, replace, index) => {
43
- let result = "", cursor = 0;
44
- do {
45
- result += string.substring(cursor, index) + replace;
46
- cursor = index + close.length;
47
- index = string.indexOf(close, cursor);
48
- } while (~index);
49
- return result + string.substring(cursor);
50
- };
51
- var createColors = (enabled = isColorSupported) => {
52
- let f = enabled ? formatter : () => String;
53
- return {
54
- isColorSupported: enabled,
55
- reset: f("\x1B[0m", "\x1B[0m"),
56
- bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
57
- dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
58
- italic: f("\x1B[3m", "\x1B[23m"),
59
- underline: f("\x1B[4m", "\x1B[24m"),
60
- inverse: f("\x1B[7m", "\x1B[27m"),
61
- hidden: f("\x1B[8m", "\x1B[28m"),
62
- strikethrough: f("\x1B[9m", "\x1B[29m"),
63
- black: f("\x1B[30m", "\x1B[39m"),
64
- red: f("\x1B[31m", "\x1B[39m"),
65
- green: f("\x1B[32m", "\x1B[39m"),
66
- yellow: f("\x1B[33m", "\x1B[39m"),
67
- blue: f("\x1B[34m", "\x1B[39m"),
68
- magenta: f("\x1B[35m", "\x1B[39m"),
69
- cyan: f("\x1B[36m", "\x1B[39m"),
70
- white: f("\x1B[37m", "\x1B[39m"),
71
- gray: f("\x1B[90m", "\x1B[39m"),
72
- bgBlack: f("\x1B[40m", "\x1B[49m"),
73
- bgRed: f("\x1B[41m", "\x1B[49m"),
74
- bgGreen: f("\x1B[42m", "\x1B[49m"),
75
- bgYellow: f("\x1B[43m", "\x1B[49m"),
76
- bgBlue: f("\x1B[44m", "\x1B[49m"),
77
- bgMagenta: f("\x1B[45m", "\x1B[49m"),
78
- bgCyan: f("\x1B[46m", "\x1B[49m"),
79
- bgWhite: f("\x1B[47m", "\x1B[49m"),
80
- blackBright: f("\x1B[90m", "\x1B[39m"),
81
- redBright: f("\x1B[91m", "\x1B[39m"),
82
- greenBright: f("\x1B[92m", "\x1B[39m"),
83
- yellowBright: f("\x1B[93m", "\x1B[39m"),
84
- blueBright: f("\x1B[94m", "\x1B[39m"),
85
- magentaBright: f("\x1B[95m", "\x1B[39m"),
86
- cyanBright: f("\x1B[96m", "\x1B[39m"),
87
- whiteBright: f("\x1B[97m", "\x1B[39m"),
88
- bgBlackBright: f("\x1B[100m", "\x1B[49m"),
89
- bgRedBright: f("\x1B[101m", "\x1B[49m"),
90
- bgGreenBright: f("\x1B[102m", "\x1B[49m"),
91
- bgYellowBright: f("\x1B[103m", "\x1B[49m"),
92
- bgBlueBright: f("\x1B[104m", "\x1B[49m"),
93
- bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
94
- bgCyanBright: f("\x1B[106m", "\x1B[49m"),
95
- bgWhiteBright: f("\x1B[107m", "\x1B[49m")
96
- };
97
- };
98
- module.exports = createColors();
99
- module.exports.createColors = createColors;
100
- });
101
-
102
- // src/logger.ts
103
- function setSilent(value) {
104
- silent = value ?? false;
105
- }
106
-
107
- class Logger {
108
- static instance;
109
- loggedOnceMessages = new Set;
110
- MAX_LABEL_LENGTH = 3;
111
- cliColor = import_picocolors.default.blue;
112
- mutedColor = import_picocolors.default.dim;
113
- infoColor = import_picocolors.default.cyan;
114
- warnColor = import_picocolors.default.yellow;
115
- errorColor = import_picocolors.default.red;
116
- defaultColor = import_picocolors.default.white;
117
- progressFgColorMap = {
118
- ESM: import_picocolors.default.yellow,
119
- CJS: import_picocolors.default.green,
120
- IIFE: import_picocolors.default.magenta,
121
- DTS: import_picocolors.default.blue
122
- };
123
- progressIdentifierBgColorMap = {
124
- ESM: import_picocolors.default.bgYellow,
125
- CJS: import_picocolors.default.bgGreen,
126
- IIFE: import_picocolors.default.bgMagenta,
127
- DTS: import_picocolors.default.bgBlue
128
- };
129
- labels = {
130
- cli: "CLI",
131
- info: "INFO",
132
- warn: "WARN",
133
- error: "ERROR"
134
- };
135
- constructor() {}
136
- static getInstance() {
137
- if (!Logger.instance) {
138
- Logger.instance = new Logger;
139
- }
140
- return Logger.instance;
141
- }
142
- dispose() {
143
- this.loggedOnceMessages.clear();
144
- }
145
- shouldLog(options) {
146
- if (!options?.once)
147
- return true;
148
- if (this.loggedOnceMessages.has(options.once))
149
- return false;
150
- this.loggedOnceMessages.add(options.once);
151
- return true;
152
- }
153
- formatMessage({
154
- fgColor,
155
- bgColor,
156
- label,
157
- message,
158
- identifier,
159
- muted
160
- }) {
161
- const padding = " ".repeat(Math.max(0, this.MAX_LABEL_LENGTH - label.length));
162
- const formattedMessage = muted ? this.mutedColor(message) : message;
163
- const identifierPart = identifier ? ` ${bgColor(import_picocolors.default.black(` ${identifier} `))}` : "";
164
- return `${fgColor(label)} ${padding}${formattedMessage}${identifierPart}`;
165
- }
166
- output(message, options = {}, logFn = console.log) {
167
- if (silent || !this.shouldLog(options))
168
- return;
169
- if (options.verticalSpace)
170
- logFn("");
171
- logFn(message);
172
- if (options.verticalSpace)
173
- logFn("");
174
- }
175
- cli(message, options = {}) {
176
- const formattedMessage = this.formatMessage({
177
- fgColor: this.cliColor,
178
- bgColor: import_picocolors.default.bgBlue,
179
- label: this.labels.cli,
180
- message,
181
- identifier: options.identifier,
182
- muted: options.muted
183
- });
184
- this.output(formattedMessage, options);
185
- }
186
- info(message, options = {}) {
187
- const formattedMessage = this.formatMessage({
188
- fgColor: this.infoColor,
189
- bgColor: import_picocolors.default.bgCyan,
190
- label: this.labels.info,
191
- message,
192
- identifier: options.identifier,
193
- muted: options.muted
194
- });
195
- this.output(formattedMessage, options);
196
- }
197
- warn(message, options = {}) {
198
- const formattedMessage = this.formatMessage({
199
- fgColor: this.warnColor,
200
- bgColor: import_picocolors.default.bgYellow,
201
- label: this.labels.warn,
202
- message,
203
- identifier: options.identifier,
204
- muted: options.muted
205
- });
206
- this.output(formattedMessage, options, console.warn);
207
- }
208
- error(message, options = {}) {
209
- const formattedMessage = this.formatMessage({
210
- fgColor: this.errorColor,
211
- bgColor: import_picocolors.default.bgRed,
212
- label: this.labels.error,
213
- message,
214
- identifier: options.identifier,
215
- muted: options.muted
216
- });
217
- this.output(formattedMessage, options, console.error);
218
- }
219
- space() {
220
- if (silent)
221
- return;
222
- console.log("");
223
- }
224
- getProgressFgColor(label) {
225
- for (const [key, colorFn] of Object.entries(this.progressFgColorMap)) {
226
- if (label.includes(key))
227
- return colorFn;
228
- }
229
- return this.defaultColor;
230
- }
231
- getProgressBgColor(label) {
232
- for (const [key, colorFn] of Object.entries(this.progressIdentifierBgColorMap)) {
233
- if (label.includes(key))
234
- return colorFn;
235
- }
236
- return import_picocolors.default.bgWhite;
237
- }
238
- progress(label, message, options = {}) {
239
- const fgColor = this.getProgressFgColor(label);
240
- const bgColor = this.getProgressBgColor(label);
241
- const formattedMessage = this.formatMessage({
242
- fgColor,
243
- bgColor,
244
- label,
245
- message,
246
- identifier: options.identifier,
247
- muted: options.muted
248
- });
249
- this.output(formattedMessage, options);
250
- }
251
- }
252
- function logTable(columns, data, footer) {
253
- if (silent)
254
- return;
255
- const widths = {};
256
- for (const col of columns) {
257
- const headerLength = col.header.length;
258
- const dataLengths = data.map((row) => row[col.header]?.length || 0);
259
- const footerLength = footer ? footer[col.header]?.length || 0 : 0;
260
- widths[col.header] = Math.max(headerLength, ...dataLengths, footerLength);
261
- }
262
- const pad = (str, width, align) => {
263
- return align === "left" ? str.padEnd(width) : str.padStart(width);
264
- };
265
- const headerRow = columns.map((col) => pad(col.header, widths[col.header], col.align)).join(import_picocolors.default.gray(" | "));
266
- console.log(import_picocolors.default.gray(headerRow));
267
- const separator = columns.map((col) => "-".repeat(widths[col.header])).join(" | ");
268
- console.log(import_picocolors.default.gray(separator));
269
- for (const row of data) {
270
- const rowStr = columns.map((col) => {
271
- const value = row[col.header] || "";
272
- const padded = pad(value, widths[col.header], col.align);
273
- return col.color ? col.color(padded) : padded;
274
- }).join(import_picocolors.default.gray(" | "));
275
- console.log(rowStr);
276
- }
277
- console.log(import_picocolors.default.gray(separator));
278
- if (footer) {
279
- const footerRow = columns.map((col) => {
280
- const value = footer[col.header] || "";
281
- const padded = pad(value, widths[col.header], col.align);
282
- return padded;
283
- }).join(import_picocolors.default.gray(" | "));
284
- console.log(footerRow);
285
- }
286
- }
287
- var import_picocolors, silent = false, logger;
288
- var init_logger = __esm(() => {
289
- import_picocolors = __toESM(require_picocolors(), 1);
290
- logger = Logger.getInstance();
291
- });
292
-
293
- // src/errors.ts
294
- var import_picocolors2, BunupError, BunupBuildError, BunupDTSBuildError, BunupCLIError, BunupWatchError, BunupPluginError, parseErrorMessage = (error) => {
295
- if (error instanceof Error) {
296
- return error.message;
297
- }
298
- return String(error);
299
- }, KNOWN_ERRORS, handleError = (error, context) => {
300
- const errorMessage = parseErrorMessage(error);
301
- const contextPrefix = context ? `[${context}] ` : "";
302
- let errorType = "UNKNOWN ERROR";
303
- if (error instanceof BunupBuildError) {
304
- errorType = "BUILD ERROR";
305
- } else if (error instanceof BunupDTSBuildError) {
306
- errorType = "DTS ERROR";
307
- } else if (error instanceof BunupCLIError) {
308
- errorType = "CLI ERROR";
309
- } else if (error instanceof BunupWatchError) {
310
- errorType = "WATCH ERROR";
311
- } else if (error instanceof BunupPluginError) {
312
- errorType = "PLUGIN ERROR";
313
- } else if (error instanceof BunupError) {
314
- errorType = "BUNUP ERROR";
315
- }
316
- const knownError = KNOWN_ERRORS.find((error2) => error2.pattern.test(errorMessage) && (error2.errorType === errorType || !error2.errorType));
317
- if (!knownError && errorType) {
318
- console.error(`${import_picocolors2.default.red(errorType)} ${contextPrefix}${errorMessage}`);
319
- }
320
- if (knownError) {
321
- console.log(`
322
- `);
323
- knownError.logSolution(errorMessage);
324
- console.log(`
325
- `);
326
- } else {
327
- console.error(import_picocolors2.default.dim(import_picocolors2.default.white("If you think this is a bug, please open an issue at: ") + import_picocolors2.default.cyan("https://github.com/arshad-yaseen/bunup/issues/new")));
328
- }
329
- }, handleErrorAndExit = (error, context) => {
330
- handleError(error, context);
331
- process.exit(1);
332
- };
333
- var init_errors = __esm(() => {
334
- import_picocolors2 = __toESM(require_picocolors(), 1);
335
- init_logger();
336
- BunupError = class BunupError extends Error {
337
- constructor(message) {
338
- super(message);
339
- this.name = "BunupError";
340
- }
341
- };
342
- BunupBuildError = class BunupBuildError extends BunupError {
343
- constructor(message) {
344
- super(message);
345
- this.name = "BunupBuildError";
346
- }
347
- };
348
- BunupDTSBuildError = class BunupDTSBuildError extends BunupError {
349
- constructor(message) {
350
- super(message);
351
- this.name = "BunupDTSBuildError";
352
- }
353
- };
354
- BunupCLIError = class BunupCLIError extends BunupError {
355
- constructor(message) {
356
- super(message);
357
- this.name = "BunupCLIError";
358
- }
359
- };
360
- BunupWatchError = class BunupWatchError extends BunupError {
361
- constructor(message) {
362
- super(message);
363
- this.name = "BunupWatchError";
364
- }
365
- };
366
- BunupPluginError = class BunupPluginError extends BunupError {
367
- constructor(message) {
368
- super(message);
369
- this.name = "BunupPluginError";
370
- }
371
- };
372
- KNOWN_ERRORS = [
373
- {
374
- pattern: /Could not resolve: "bun"/i,
375
- errorType: "BUILD ERROR",
376
- logSolution: () => {
377
- logger.error(import_picocolors2.default.white("You're trying to build a project that uses Bun. ") + import_picocolors2.default.white("Please set the target option to ") + import_picocolors2.default.cyan("`bun`") + import_picocolors2.default.white(`.
378
- `) + import_picocolors2.default.white("Example: ") + import_picocolors2.default.green("`bunup --target bun`") + import_picocolors2.default.white(" or in config: ") + import_picocolors2.default.green("{ target: 'bun' }"));
379
- }
380
- }
381
- ];
382
- });
383
-
384
- // src/utils.ts
385
- import fsSync from "fs";
386
- import fs from "fs/promises";
387
- import path, { normalize } from "path";
388
- function ensureArray(value) {
389
- return Array.isArray(value) ? value : [value];
390
- }
391
- function getDefaultJsOutputExtension(format, packageType) {
392
- switch (format) {
393
- case "esm":
394
- return isModulePackage(packageType) ? ".js" : ".mjs";
395
- case "cjs":
396
- return isModulePackage(packageType) ? ".cjs" : ".js";
397
- case "iife":
398
- return ".global.js";
399
- }
400
- }
401
- function getDefaultDtsOutputExtension(format, packageType) {
402
- switch (format) {
403
- case "esm":
404
- return isModulePackage(packageType) ? ".d.ts" : ".d.mts";
405
- case "cjs":
406
- return isModulePackage(packageType) ? ".d.cts" : ".d.ts";
407
- case "iife":
408
- return ".global.d.ts";
409
- }
410
- }
411
- function getBaseFileName(filePath) {
412
- const filename = path.basename(filePath);
413
- const extension = path.extname(filename);
414
- return extension ? filename.slice(0, -extension.length) : filename;
415
- }
416
- function removeExtension(filePath) {
417
- return filePath.replace(path.extname(filePath), "");
418
- }
419
- function cleanPath(filePath) {
420
- return filePath.replace(/\\/g, "/");
421
- }
422
- function isModulePackage(packageType) {
423
- return packageType === "module";
424
- }
425
- function formatTime(ms) {
426
- return ms >= 1000 ? `${(ms / 1000).toFixed(2)}s` : `${Math.round(ms)}ms`;
427
- }
428
- function getPackageDeps(packageJson) {
429
- if (!packageJson)
430
- return [];
431
- return Array.from(new Set([
432
- ...Object.keys(packageJson.dependencies || {}),
433
- ...Object.keys(packageJson.peerDependencies || {})
434
- ]));
435
- }
436
- function formatFileSize(bytes) {
437
- if (bytes === 0)
438
- return "0 B";
439
- const units = ["B", "KB", "MB", "GB"];
440
- const i = Math.floor(Math.log(bytes) / Math.log(1024));
441
- if (i === 0)
442
- return `${bytes} ${units[i]}`;
443
- return `${(bytes / 1024 ** i).toFixed(2)} ${units[i]}`;
444
- }
445
- function getShortFilePath(filePath, maxLength = 3) {
446
- const fileParts = filePath.split("/");
447
- const shortPath = fileParts.slice(-maxLength).join("/");
448
- return shortPath;
449
- }
450
- async function cleanOutDir(rootDir, outDir) {
451
- const outDirPath = path.join(rootDir, outDir);
452
- try {
453
- await fs.rm(outDirPath, { recursive: true, force: true });
454
- } catch (error) {
455
- throw new BunupBuildError(`Failed to clean output directory: ${error}`);
456
- }
457
- await fs.mkdir(outDirPath, { recursive: true });
458
- }
459
- function pathExistsSync(filePath) {
460
- try {
461
- fsSync.accessSync(filePath);
462
- return true;
463
- } catch (error) {
464
- return false;
465
- }
466
- }
467
- function formatListWithAnd(arr) {
468
- return new Intl.ListFormat("en", {
469
- style: "long",
470
- type: "conjunction"
471
- }).format(arr);
472
- }
473
- var init_utils = __esm(() => {
474
- init_errors();
475
- });
476
-
477
- // src/loaders.ts
478
- import path2 from "path";
479
- import { loadConfig } from "coffi";
480
- async function processLoadedConfigs(config, cwd, filter) {
481
- return Array.isArray(config) && "root" in config[0] ? config.filter((c) => filter ? filter.includes(c.name) : true).map((c) => ({
482
- rootDir: path2.resolve(cwd, c.root),
483
- options: addField(c.config, "name", c.name)
484
- })) : [
485
- {
486
- rootDir: cwd,
487
- options: config
488
- }
489
- ];
490
- }
491
- function addField(objectOrArray, field, value) {
492
- return Array.isArray(objectOrArray) ? objectOrArray.map((o) => ({ ...o, [field]: value })) : { ...objectOrArray, [field]: value };
493
- }
494
- async function loadPackageJson(cwd = process.cwd()) {
495
- const { config, filepath } = await loadConfig({
496
- name: "package",
497
- cwd,
498
- extensions: [".json"]
499
- });
500
- return {
501
- data: config,
502
- path: filepath
503
- };
504
- }
505
- var init_loaders = () => {};
506
-
507
- // src/cli/utils.ts
508
- function displayBunupGradientArt() {
509
- const art = `
510
- \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557
511
- \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557
512
- \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D
513
- \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u255D
514
- \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551
515
- \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D
516
- `.trim();
517
- const lines = art.split(`
518
- `);
519
- logger.space();
520
- for (const line of lines) {
521
- logger.output(import_picocolors7.default.cyan(line));
522
- }
523
- logger.space();
524
- }
525
- var import_picocolors7;
526
- var init_utils2 = __esm(() => {
527
- import_picocolors7 = __toESM(require_picocolors(), 1);
528
- init_logger();
529
- });
530
-
531
- // src/cli/new.ts
532
- var exports_new = {};
533
- __export(exports_new, {
534
- newProject: () => newProject
535
- });
536
- import { renameSync } from "fs";
537
- import path5 from "path";
538
- import {
539
- cancel,
540
- confirm,
541
- intro,
542
- outro,
543
- select,
544
- tasks,
545
- text
546
- } from "@clack/prompts";
547
- import { downloadTemplate } from "giget";
548
- import { replaceInFile } from "replace-in-file";
549
- async function newProject() {
550
- displayBunupGradientArt();
551
- intro(import_picocolors8.default.bgCyan(import_picocolors8.default.black(" Scaffold a new project with Bunup ")));
552
- const selectedTemplateDir = await select({
553
- message: "Select a template",
554
- options: TEMPLATES.map((template2) => ({
555
- value: template2.dir,
556
- label: import_picocolors8.default.blue(template2.name)
557
- }))
558
- });
559
- const template = TEMPLATES.find((t) => t.dir === selectedTemplateDir);
560
- if (!template) {
561
- cancel("Invalid template");
562
- process.exit(1);
563
- }
564
- const hasMonorepo = template.monorepoDir !== undefined;
565
- const projectName = await text({
566
- message: "Enter the project name",
567
- placeholder: template.defaultName,
568
- defaultValue: template.defaultName,
569
- validate: (value) => {
570
- if (!value) {
571
- return "Project name is required";
572
- }
573
- if (value.includes(" ")) {
574
- return "Project name cannot contain spaces";
575
- }
576
- if (pathExistsSync(getProjectPath(value))) {
577
- return "Project already exists";
578
- }
579
- }
580
- });
581
- const projectPath = getProjectPath(projectName);
582
- let useMonorepo = false;
583
- let monorepoFirstPackageName;
584
- if (hasMonorepo) {
585
- useMonorepo = await confirm({
586
- message: "Do you want to create a monorepo?",
587
- initialValue: false
588
- });
589
- if (useMonorepo) {
590
- monorepoFirstPackageName = await text({
591
- message: "Enter the name of the first package",
592
- placeholder: MONOREPO_FIRST_PACKAGE_NAME_PLACEHOLDER,
593
- defaultValue: MONOREPO_FIRST_PACKAGE_NAME_PLACEHOLDER
594
- });
595
- }
596
- }
597
- const githubRepoInfo = await text({
598
- message: "GitHub username and repo name (username/repo):",
599
- placeholder: `${GITHUB_USERNAME_PLACEHOLDER}/${GITHUB_REPO_PLACEHOLDER}`,
600
- defaultValue: `${GITHUB_USERNAME_PLACEHOLDER}/${GITHUB_REPO_PLACEHOLDER}`
601
- });
602
- const [githubUsername, githubRepoName] = githubRepoInfo.split("/");
603
- await tasks([
604
- {
605
- title: "Creating project",
606
- task: async () => {
607
- const templatePath = useMonorepo ? template.monorepoDir : template.dir;
608
- await downloadTemplate(`github:${TEMPLATE_OWNER}/${TEMPLATE_REPO}/${templatePath}`, {
609
- dir: projectPath
610
- });
611
- return "Template downloaded";
612
- }
613
- },
614
- {
615
- title: "Making the project yours",
616
- task: async () => {
617
- await replaceInFile({
618
- files: path5.join(projectPath, "**/*"),
619
- from: [
620
- new RegExp(GITHUB_REPO_PLACEHOLDER, "g"),
621
- new RegExp(GITHUB_USERNAME_PLACEHOLDER, "g"),
622
- new RegExp(template.defaultName, "g")
623
- ],
624
- to: [githubRepoName, githubUsername, projectName],
625
- ignore: ["node_modules", "dist", "bun.lock"]
626
- });
627
- if (useMonorepo && monorepoFirstPackageName) {
628
- await replaceInFile({
629
- files: path5.join(projectPath, "**/*"),
630
- from: [new RegExp(MONOREPO_FIRST_PACKAGE_NAME_PLACEHOLDER, "g")],
631
- to: [monorepoFirstPackageName],
632
- ignore: ["node_modules", "dist", "bun.lock"]
633
- });
634
- renameSync(path5.join(projectPath, MONOREPO_PACKAGES_DIR, MONOREPO_FIRST_PACKAGE_NAME_PLACEHOLDER), path5.join(projectPath, MONOREPO_PACKAGES_DIR, monorepoFirstPackageName));
635
- }
636
- }
637
- }
638
- ]);
639
- outro(`
640
- ${import_picocolors8.default.green("\u2728 Project scaffolded successfully! \u2728")}
641
-
642
- ${import_picocolors8.default.bold("Ready to launch your awesome new project?")}
643
-
644
- ${import_picocolors8.default.cyan("cd")} ${projectName}
645
- ${import_picocolors8.default.cyan("bun install")}
646
- ${import_picocolors8.default.cyan("bun run dev")}
647
-
648
- ${import_picocolors8.default.dim("Learn more:")} ${import_picocolors8.default.underline("https://bunup.dev/docs")}
649
-
650
- ${import_picocolors8.default.yellow("Happy coding!")} \uD83D\uDE80
651
- `);
652
- }
653
- function getProjectPath(projectName) {
654
- return path5.join(process.cwd(), projectName);
655
- }
656
- var import_picocolors8, TEMPLATE_OWNER = "arshad-yaseen", TEMPLATE_REPO = "bunup-new", GITHUB_USERNAME_PLACEHOLDER = "username", GITHUB_REPO_PLACEHOLDER = "repo-name", MONOREPO_FIRST_PACKAGE_NAME_PLACEHOLDER = "package-1", MONOREPO_PACKAGES_DIR = "packages", TEMPLATES;
657
- var init_new = __esm(() => {
658
- import_picocolors8 = __toESM(require_picocolors(), 1);
659
- init_utils();
660
- init_utils2();
661
- TEMPLATES = [
662
- {
663
- defaultName: "my-ts-lib",
664
- name: "Typescript Library",
665
- dir: "ts-lib",
666
- monorepoDir: "ts-lib-monorepo"
667
- },
668
- {
669
- defaultName: "my-react-lib",
670
- name: "React Library",
671
- dir: "react-lib"
672
- }
673
- ];
674
- });
675
-
676
- // src/cli/init.ts
677
- var exports_init = {};
678
- __export(exports_init, {
679
- init: () => init
680
- });
681
- import fs2 from "fs";
682
- import path6 from "path";
683
- import {
684
- confirm as confirm2,
685
- intro as intro2,
686
- log,
687
- multiselect,
688
- outro as outro2,
689
- select as select2,
690
- tasks as tasks2,
691
- text as text2
692
- } from "@clack/prompts";
693
- import { exec } from "tinyexec";
694
- async function init() {
695
- displayBunupGradientArt();
696
- intro2(import_picocolors9.default.bgCyan(import_picocolors9.default.black(" Initialize bunup in an existing project ")));
697
- const { path: packageJsonPath } = await loadPackageJson();
698
- if (!packageJsonPath) {
699
- log.error("package.json not found");
700
- process.exit(1);
701
- }
702
- const shouldSetupWorkspace = await promptForWorkspace();
703
- if (shouldSetupWorkspace) {
704
- await initializeWorkspace(packageJsonPath);
705
- } else {
706
- await initializeSinglePackage(packageJsonPath);
707
- }
708
- await tasks2([
709
- {
710
- title: "Installing bunup",
711
- task: async () => {
712
- await installBunup();
713
- return "Bunup installed";
714
- }
715
- }
716
- ]);
717
- showSuccessOutro(shouldSetupWorkspace);
718
- }
719
- async function promptForWorkspace() {
720
- return await confirm2({
721
- message: "Do you want to setup a Bunup workspace? (for building multiple packages with one command)",
722
- initialValue: false
723
- });
724
- }
725
- async function initializeWorkspace(packageJsonPath) {
726
- const workspacePackages = await collectWorkspacePackages();
727
- const configMethod = await selectWorkspaceConfigurationMethod();
728
- await generateWorkspaceConfiguration(configMethod, workspacePackages);
729
- await handleWorkspaceBuildScripts(packageJsonPath);
730
- }
731
- async function initializeSinglePackage(packageJsonPath) {
732
- const entryFiles = await collectEntryFiles();
733
- const outputFormats = await selectOutputFormats();
734
- const shouldGenerateDts = await promptForTypeScriptDeclarations(entryFiles);
735
- const configMethod = await selectConfigurationMethod();
736
- await generateConfiguration(configMethod, entryFiles, outputFormats, shouldGenerateDts, packageJsonPath);
737
- await handleBuildScripts(packageJsonPath, entryFiles, outputFormats, shouldGenerateDts, configMethod);
738
- }
739
- async function collectWorkspacePackages() {
740
- const packages = [];
741
- while (true) {
742
- const packageName = await text2({
743
- message: packages.length > 0 ? "Enter the next package name:" : "Enter the first package name:",
744
- placeholder: "core",
745
- validate: (value) => {
746
- if (!value)
747
- return "Package name is required";
748
- if (packages.some((pkg) => pkg.name === value))
749
- return "Package name already exists";
750
- }
751
- });
752
- const packageRoot = await text2({
753
- message: `Enter the root directory for "${packageName}":`,
754
- placeholder: `packages/${packageName}`,
755
- defaultValue: `packages/${packageName}`,
756
- validate: (value) => {
757
- if (!value)
758
- return "Package root is required";
759
- if (!fs2.existsSync(value))
760
- return "Package root directory does not exist";
761
- if (!fs2.statSync(value).isDirectory())
762
- return "Package root must be a directory";
763
- }
764
- });
765
- const entryFiles = await collectEntryFilesForPackage(packageRoot, packageName);
766
- const outputFormats = await selectOutputFormats();
767
- const shouldGenerateDts = await promptForTypeScriptDeclarations(entryFiles);
768
- packages.push({
769
- name: packageName,
770
- root: packageRoot,
771
- entryFiles,
772
- outputFormats,
773
- shouldGenerateDts
774
- });
775
- const shouldAddMore = await confirm2({
776
- message: "Do you want to add another package?",
777
- initialValue: true
778
- });
779
- if (!shouldAddMore)
780
- break;
781
- }
782
- return packages;
783
- }
784
- async function collectEntryFilesForPackage(packageRoot, packageName) {
785
- const entryFiles = [];
786
- while (true) {
787
- const entryFile = await text2({
788
- message: entryFiles.length > 0 ? `Where is the next entry file for "${packageName}"? (relative to ${packageRoot})` : `Where is the entry file for "${packageName}"? (relative to ${packageRoot})`,
789
- placeholder: "src/index.ts",
790
- defaultValue: "src/index.ts",
791
- validate: (value) => {
792
- if (!value)
793
- return "Entry file is required";
794
- const fullPath = path6.join(packageRoot, value);
795
- if (!fs2.existsSync(fullPath))
796
- return `Entry file does not exist at ${fullPath}`;
797
- if (!fs2.statSync(fullPath).isFile())
798
- return "Entry file must be a file";
799
- if (entryFiles.includes(value))
800
- return "You have already added this entry file";
801
- }
802
- });
803
- entryFiles.push(entryFile);
804
- const shouldAddMore = await confirm2({
805
- message: "Do you want to add another entry file for this package?",
806
- initialValue: false
807
- });
808
- if (!shouldAddMore)
809
- break;
810
- }
811
- return entryFiles;
812
- }
813
- async function collectEntryFiles() {
814
- const entryFiles = [];
815
- while (true) {
816
- const entryFile = await text2({
817
- message: entryFiles.length > 0 ? "Where is your next entry file?" : "Where is your entry file?",
818
- placeholder: "src/index.ts",
819
- defaultValue: "src/index.ts",
820
- validate: (value) => {
821
- if (!value)
822
- return "Entry file is required";
823
- if (!fs2.existsSync(value))
824
- return "Entry file does not exist";
825
- if (!fs2.statSync(value).isFile())
826
- return "Entry file must be a file";
827
- if (entryFiles.includes(value))
828
- return "You have already added this entry file";
829
- }
830
- });
831
- entryFiles.push(entryFile);
832
- const shouldAddMore = await confirm2({
833
- message: "Do you want to add another entry file?",
834
- initialValue: false
835
- });
836
- if (!shouldAddMore)
837
- break;
838
- }
839
- return entryFiles;
840
- }
841
- async function selectOutputFormats() {
842
- return await multiselect({
843
- message: "Select the output formats",
844
- options: [
845
- { value: "esm", label: "ESM (.mjs)" },
846
- { value: "cjs", label: "CommonJS (.cjs)" },
847
- { value: "iife", label: "IIFE (.global.js)" }
848
- ],
849
- initialValues: ["esm", "cjs"]
850
- });
851
- }
852
- async function promptForTypeScriptDeclarations(entryFiles) {
853
- const hasTypeScriptFiles = entryFiles.some((file) => file.endsWith(".ts") || file.endsWith(".tsx"));
854
- if (!hasTypeScriptFiles)
855
- return false;
856
- return await confirm2({
857
- message: "Generate TypeScript declarations?",
858
- initialValue: true
859
- });
860
- }
861
- async function selectWorkspaceConfigurationMethod() {
862
- return await select2({
863
- message: "How would you like to configure your workspace?",
864
- options: [
865
- { value: "ts", label: "bunup.config.ts", hint: "Recommended" },
866
- { value: "js", label: "bunup.config.js" }
867
- ],
868
- initialValue: "ts"
869
- });
870
- }
871
- async function selectConfigurationMethod() {
872
- return await select2({
873
- message: "How would you like to configure Bunup?",
874
- options: [
875
- { value: "ts", label: "bunup.config.ts", hint: "Recommended" },
876
- { value: "js", label: "bunup.config.js" },
877
- { value: "json", label: 'package.json "bunup" property' },
878
- {
879
- value: "none",
880
- label: "No config file",
881
- hint: "Configure via CLI only"
882
- }
883
- ],
884
- initialValue: "ts"
885
- });
886
- }
887
- async function generateWorkspaceConfiguration(configMethod, workspacePackages) {
888
- const configContent = createWorkspaceConfigFileContent(workspacePackages);
889
- await Bun.write(`bunup.config.${configMethod}`, configContent);
890
- }
891
- async function generateConfiguration(configMethod, entryFiles, outputFormats, shouldGenerateDts, packageJsonPath) {
892
- if (configMethod === "none") {
893
- log.info("If you need more control (such as adding plugins or customizing output), you can always create a config file later.");
894
- return;
895
- }
896
- if (configMethod === "ts" || configMethod === "js") {
897
- await Bun.write(`bunup.config.${configMethod}`, createConfigFileContent(entryFiles, outputFormats, shouldGenerateDts));
898
- } else if (configMethod === "json") {
899
- const { data: packageJsonConfig } = await loadPackageJson();
900
- const updatedConfig = {
901
- ...packageJsonConfig,
902
- bunup: createPackageJsonConfig(entryFiles, outputFormats, shouldGenerateDts)
903
- };
904
- await Bun.write(packageJsonPath, JSON.stringify(updatedConfig, null, 2));
905
- }
906
- }
907
- async function handleWorkspaceBuildScripts(packageJsonPath) {
908
- const { data: packageJsonConfig } = await loadPackageJson();
909
- const existingScripts = packageJsonConfig?.scripts ?? {};
910
- const newScripts = createWorkspaceBuildScripts();
911
- const conflictingScripts = Object.keys(newScripts).filter((script) => existingScripts[script]);
912
- if (conflictingScripts.length > 0) {
913
- const shouldOverride = await confirm2({
914
- message: `The ${formatListWithAnd(conflictingScripts)} ${conflictingScripts.length > 1 ? "scripts already exist" : "script already exists"} in package.json. Override ${conflictingScripts.length > 1 ? "them" : "it"}?`,
915
- initialValue: true
916
- });
917
- if (!shouldOverride) {
918
- log.info("Skipped adding build scripts to avoid conflicts.");
919
- return;
920
- }
921
- }
922
- const updatedConfig = {
923
- ...packageJsonConfig,
924
- scripts: { ...existingScripts, ...newScripts }
925
- };
926
- await Bun.write(packageJsonPath, JSON.stringify(updatedConfig, null, 2));
927
- }
928
- async function handleBuildScripts(packageJsonPath, entryFiles, outputFormats, shouldGenerateDts, configMethod) {
929
- const { data: packageJsonConfig } = await loadPackageJson();
930
- const existingScripts = packageJsonConfig?.scripts ?? {};
931
- const newScripts = createBuildScripts(entryFiles, outputFormats, shouldGenerateDts, configMethod);
932
- const conflictingScripts = Object.keys(newScripts).filter((script) => existingScripts[script]);
933
- if (conflictingScripts.length > 0) {
934
- const shouldOverride = await confirm2({
935
- message: `The ${formatListWithAnd(conflictingScripts)} ${conflictingScripts.length > 1 ? "scripts already exist" : "script already exists"} in package.json. Override ${conflictingScripts.length > 1 ? "them" : "it"}?`,
936
- initialValue: true
937
- });
938
- if (!shouldOverride) {
939
- log.info("Skipped adding build scripts to avoid conflicts.");
940
- return;
941
- }
942
- }
943
- const updatedConfig = {
944
- ...packageJsonConfig,
945
- scripts: { ...existingScripts, ...newScripts }
946
- };
947
- await Bun.write(packageJsonPath, JSON.stringify(updatedConfig, null, 2));
948
- }
949
- function createWorkspaceConfigFileContent(workspacePackages) {
950
- const packagesConfig = workspacePackages.map((pkg) => {
951
- return ` {
952
- name: '${pkg.name}',
953
- root: '${pkg.root}',
954
- config: {
955
- entry: [${pkg.entryFiles.map((file) => `'${file}'`).join(", ")}],
956
- format: [${pkg.outputFormats.map((format) => `'${format}'`).join(", ")}],${pkg.shouldGenerateDts ? `
957
- dts: true,` : ""}
958
- },
959
- }`;
960
- }).join(`,
961
- `);
962
- return `import { defineWorkspace } from 'bunup'
963
-
964
- export default defineWorkspace([
965
- ${packagesConfig}
966
- ])
967
- `;
968
- }
969
- function createConfigFileContent(entryFiles, outputFormats, shouldGenerateDts) {
970
- return `import { defineConfig } from 'bunup'
971
-
972
- export default defineConfig({
973
- entry: [${entryFiles.map((file) => `'${file}'`).join(", ")}],
974
- format: [${outputFormats.map((format) => `'${format}'`).join(", ")}],${shouldGenerateDts ? `
975
- dts: true,` : ""}
976
- })
977
- `;
978
- }
979
- function createPackageJsonConfig(entryFiles, outputFormats, shouldGenerateDts) {
980
- return {
981
- entry: entryFiles,
982
- format: outputFormats,
983
- ...shouldGenerateDts && { dts: true }
984
- };
985
- }
986
- function createWorkspaceBuildScripts() {
987
- return {
988
- build: "bunup",
989
- dev: "bunup --watch"
990
- };
991
- }
992
- function createBuildScripts(entryFiles, outputFormats, shouldGenerateDts, configMethod) {
993
- const cliOptions = configMethod === "none" ? ` ${entryFiles.join(" ")} --format ${outputFormats.join(",")}${shouldGenerateDts ? " --dts" : ""}` : "";
994
- return {
995
- build: `bunup${cliOptions}`,
996
- dev: `bunup${cliOptions} --watch`
997
- };
998
- }
999
- function showSuccessOutro(isWorkspace) {
1000
- const buildCommand = isWorkspace ? `${import_picocolors9.default.cyan("bun run build")} - Build all packages in your workspace` : `${import_picocolors9.default.cyan("bun run build")} - Build your library`;
1001
- const devCommand = isWorkspace ? `${import_picocolors9.default.cyan("bun run dev")} - Start development mode (watches all packages)` : `${import_picocolors9.default.cyan("bun run dev")} - Start development mode`;
1002
- const filterCommand = isWorkspace ? `${import_picocolors9.default.cyan("bunup --filter core,utils")} - Build specific packages` : "";
1003
- outro2(`
1004
- ${import_picocolors9.default.green("\u2728 Bunup initialized successfully! \u2728")}
1005
-
1006
- ${buildCommand}
1007
- ${devCommand}${isWorkspace ? `
1008
- ${filterCommand}` : ""}
1009
-
1010
- ${import_picocolors9.default.dim("Learn more:")} ${import_picocolors9.default.underline("https://bunup.dev/docs/")}
1011
-
1012
- ${import_picocolors9.default.yellow("Happy building!")} \uD83D\uDE80
1013
- `);
1014
- }
1015
- async function installBunup() {
1016
- await exec("bun add -d bunup", [], {
1017
- nodeOptions: { shell: true, stdio: "pipe" }
1018
- });
1019
- }
1020
- var import_picocolors9;
1021
- var init_init = __esm(() => {
1022
- import_picocolors9 = __toESM(require_picocolors(), 1);
1023
- init_loaders();
1024
- init_utils();
1025
- init_utils2();
1026
- });
1027
-
1028
- // src/cli/index.ts
1029
- import { exec as exec2 } from "tinyexec";
1030
- // package.json
1031
- var version = "0.8.28";
1032
-
1033
- // src/cli/index.ts
1034
- init_errors();
1035
- init_logger();
1036
-
1037
- // src/cli/options.ts
1038
- var import_picocolors3 = __toESM(require_picocolors(), 1);
1039
-
1040
- // src/constants/index.ts
1041
- var BUNUP_CLI_OPTIONS_URL = "https://bunup.dev/docs/guide/cli-options";
1042
-
1043
- // src/cli/options.ts
1044
- init_errors();
1045
- init_logger();
1046
- init_utils();
1047
- function booleanHandler(optionName) {
1048
- return (value, options) => {
1049
- options[optionName] = value === true || value === "true";
1050
- };
1051
- }
1052
- function stringHandler(optionName) {
1053
- return (value, options) => {
1054
- if (typeof value === "string") {
1055
- options[optionName] = value;
1056
- } else {
1057
- throw new BunupCLIError(`Option --${optionName} requires a string value`);
1058
- }
1059
- };
1060
- }
1061
- function arrayHandler(optionName) {
1062
- return (value, options) => {
1063
- if (typeof value === "string") {
1064
- options[optionName] = value.split(",");
1065
- } else {
1066
- throw new BunupCLIError(`Option --${optionName} requires a string value`);
1067
- }
1068
- };
1069
- }
1070
- function booleanOrStringHandler(optionName) {
1071
- return (value, options) => {
1072
- if (typeof value === "boolean") {
1073
- options[optionName] = value;
1074
- } else if (typeof value === "string") {
1075
- if (value.toLowerCase() === "true" || value.toLowerCase() === "false") {
1076
- options[optionName] = value.toLowerCase() === "true";
1077
- } else {
1078
- options[optionName] = value;
1079
- }
1080
- } else {
1081
- throw new BunupCLIError(`Option --${optionName} requires a boolean or string value`);
1082
- }
1083
- };
1084
- }
1085
- function showHelp() {
1086
- console.log(`
1087
- Bunup - \u26A1\uFE0F A blazing-fast build tool for your libraries built with Bun.
1088
- `);
1089
- console.log("For more information on available options, visit:");
1090
- console.log(`${import_picocolors3.default.cyan(import_picocolors3.default.underline(BUNUP_CLI_OPTIONS_URL))}
1091
- `);
1092
- process.exit(0);
1093
- }
1094
- function showVersion() {
1095
- console.log(version);
1096
- process.exit(0);
1097
- }
1098
- var optionConfigs = {
1099
- name: { flags: ["n", "name"], handler: stringHandler("name") },
1100
- format: {
1101
- flags: ["f", "format"],
1102
- handler: arrayHandler("format")
1103
- },
1104
- outDir: { flags: ["o", "out-dir"], handler: stringHandler("outDir") },
1105
- minify: { flags: ["m", "minify"], handler: booleanHandler("minify") },
1106
- watch: { flags: ["w", "watch"], handler: booleanHandler("watch") },
1107
- dts: { flags: ["d", "dts"], handler: booleanHandler("dts") },
1108
- banner: { flags: ["bn", "banner"], handler: stringHandler("banner") },
1109
- footer: { flags: ["ft", "footer"], handler: stringHandler("footer") },
1110
- external: { flags: ["e", "external"], handler: arrayHandler("external") },
1111
- sourcemap: {
1112
- flags: ["sm", "sourcemap"],
1113
- handler: booleanOrStringHandler("sourcemap")
1114
- },
1115
- target: { flags: ["t", "target"], handler: stringHandler("target") },
1116
- minifyWhitespace: {
1117
- flags: ["mw", "minify-whitespace"],
1118
- handler: booleanHandler("minifyWhitespace")
1119
- },
1120
- minifyIdentifiers: {
1121
- flags: ["mi", "minify-identifiers"],
1122
- handler: booleanHandler("minifyIdentifiers")
1123
- },
1124
- minifySyntax: {
1125
- flags: ["ms", "minify-syntax"],
1126
- handler: booleanHandler("minifySyntax")
1127
- },
1128
- clean: { flags: ["c", "clean"], handler: booleanHandler("clean") },
1129
- splitting: {
1130
- flags: ["s", "splitting"],
1131
- handler: booleanHandler("splitting")
1132
- },
1133
- noExternal: {
1134
- flags: ["ne", "no-external"],
1135
- handler: arrayHandler("noExternal")
1136
- },
1137
- preferredTsconfigPath: {
1138
- flags: ["tsconfig", "preferred-tsconfig-path"],
1139
- handler: stringHandler("preferredTsconfigPath")
1140
- },
1141
- bytecode: {
1142
- flags: ["bc", "bytecode"],
1143
- handler: booleanHandler("bytecode")
1144
- },
1145
- silent: { flags: ["silent"], handler: booleanHandler("silent") },
1146
- config: { flags: ["config"], handler: stringHandler("config") },
1147
- publicPath: {
1148
- flags: ["pp", "public-path"],
1149
- handler: stringHandler("publicPath")
1150
- },
1151
- env: { flags: ["env"], handler: stringHandler("env") },
1152
- onSuccess: {
1153
- flags: ["onSuccess"],
1154
- handler: stringHandler("onSuccess")
1155
- },
1156
- filter: { flags: ["filter"], handler: arrayHandler("filter") },
1157
- new: { flags: ["new"], handler: booleanHandler("new") },
1158
- init: { flags: ["init"], handler: booleanHandler("init") },
1159
- dtsOnly: { flags: ["dts-only"], handler: booleanHandler("dtsOnly") },
1160
- entry: {
1161
- flags: ["entry"],
1162
- handler: (value, options, subPath) => {
1163
- if (typeof value !== "string") {
1164
- throw new BunupCLIError(`Entry${subPath ? ` --entry.${subPath}` : ""} requires a string value`);
1165
- }
1166
- const entries = options.entry || {};
1167
- if (subPath) {
1168
- if (entries[subPath]) {
1169
- logger.warn(`Duplicate entry name '${subPath}' provided via --entry.${subPath}. Overwriting previous entry.`);
1170
- }
1171
- entries[subPath] = value;
1172
- } else {
1173
- const name = getBaseFileName(value);
1174
- if (entries[name]) {
1175
- logger.warn(`Duplicate entry name '${name}' derived from '${value}'. Overwriting previous entry.`);
1176
- }
1177
- entries[name] = value;
1178
- }
1179
- options.entry = entries;
1180
- }
1181
- },
1182
- resolveDts: {
1183
- flags: ["rd", "resolve-dts"],
1184
- handler: (value, options) => {
1185
- if (!options.dts)
1186
- options.dts = {};
1187
- if (typeof options.dts === "boolean")
1188
- options.dts = {};
1189
- if (typeof value === "string") {
1190
- if (value === "true" || value === "false") {
1191
- options.dts.resolve = value === "true";
1192
- } else {
1193
- options.dts.resolve = value.split(",");
1194
- }
1195
- } else {
1196
- options.dts.resolve = true;
1197
- }
1198
- }
1199
- },
1200
- help: { flags: ["h", "help"], handler: () => showHelp() },
1201
- version: { flags: ["v", "version"], handler: () => showVersion() }
1202
- };
1203
- var flagToHandler = {};
1204
- for (const config of Object.values(optionConfigs)) {
1205
- for (const flag of config.flags) {
1206
- flagToHandler[flag] = config.handler;
1207
- }
1208
- }
1209
- function parseCliOptions(argv) {
1210
- const options = {};
1211
- for (let i = 0;i < argv.length; i++) {
1212
- const arg = argv[i];
1213
- if (arg.startsWith("--")) {
1214
- let key;
1215
- let value;
1216
- if (arg.includes("=")) {
1217
- const [keyPart, valuePart] = arg.slice(2).split("=", 2);
1218
- key = keyPart;
1219
- value = valuePart;
1220
- } else {
1221
- key = arg.slice(2);
1222
- const nextArg = argv[i + 1];
1223
- value = nextArg && !nextArg.startsWith("-") ? nextArg : true;
1224
- if (typeof value === "string")
1225
- i++;
1226
- }
1227
- if (key.includes(".")) {
1228
- const [mainOption, subPath] = key.split(".", 2);
1229
- const handler = flagToHandler[mainOption];
1230
- if (handler) {
1231
- handler(value, options, subPath);
1232
- } else {
1233
- throw new BunupCLIError(`Unknown option: --${key}`);
1234
- }
1235
- } else {
1236
- const handler = flagToHandler[key];
1237
- if (handler) {
1238
- handler(value, options);
1239
- } else {
1240
- throw new BunupCLIError(`Unknown option: --${key}`);
1241
- }
1242
- }
1243
- } else if (arg.startsWith("-")) {
1244
- const key = arg.slice(1);
1245
- const nextArg = argv[i + 1];
1246
- const value = nextArg && !nextArg.startsWith("-") ? nextArg : true;
1247
- if (typeof value === "string")
1248
- i++;
1249
- const handler = flagToHandler[key];
1250
- if (handler) {
1251
- handler(value, options);
1252
- } else {
1253
- throw new BunupCLIError(`Unknown option: -${key}`);
1254
- }
1255
- } else {
1256
- optionConfigs.entry.handler(arg, options, undefined);
1257
- }
1258
- }
1259
- return options;
1260
- }
1261
-
1262
- // src/cli/index.ts
1263
- var import_picocolors10 = __toESM(require_picocolors(), 1);
1264
- import { loadConfig as loadConfig2 } from "coffi";
1265
-
1266
- // src/build.ts
1267
- init_errors();
1268
- import path3 from "path";
1269
- import {
1270
- generateDts,
1271
- logIsolatedDeclarationErrors
1272
- } from "bun-dts";
1273
-
1274
- // src/helpers/entry.ts
1275
- init_utils();
1276
- function getProcessableEntries(entry) {
1277
- if (typeof entry === "string") {
1278
- return [
1279
- {
1280
- entry,
1281
- outputBasePath: getEntryOutputBasePath(entry)
1282
- }
1283
- ];
1284
- }
1285
- if (typeof entry === "object" && !Array.isArray(entry)) {
1286
- return Object.entries(entry).map(([name, path2]) => ({
1287
- entry: path2,
1288
- outputBasePath: name
1289
- }));
1290
- }
1291
- return entry.map((_entry) => ({
1292
- entry: _entry,
1293
- outputBasePath: getEntryOutputBasePath(_entry)
1294
- }));
1295
- }
1296
- function getEntryOutputBasePath(entry) {
1297
- const pathSegments = cleanPath(removeExtension(entry)).split("/");
1298
- return pathSegments.length > 1 ? pathSegments.slice(1).join("/") : pathSegments.join("/");
1299
- }
1300
- function getResolvedNaming(outputBasePath, extension) {
1301
- return {
1302
- entry: `[dir]/${outputBasePath}${extension}`,
1303
- chunk: `${outputBasePath}-[hash].[ext]`,
1304
- asset: `${outputBasePath}-[name]-[hash].[ext]`
1305
- };
1306
- }
1307
-
1308
- // src/build.ts
1309
- init_loaders();
1310
- init_logger();
1311
-
1312
- // src/constants/re.ts
1313
- var JS_RE = /\.(js|jsx|cjs|mjs)$/;
1314
- var TS_RE = /\.(ts|tsx|mts|cts)$/;
1315
- var DTS_RE = /\.(d\.(ts|mts|cts))$/;
1316
- var JS_TS_RE = new RegExp(`${JS_RE.source}|${TS_RE.source}`);
1317
- var JS_DTS_RE = new RegExp(`${JS_RE.source}|${DTS_RE.source}`);
1318
- // src/plugins/built-in/productivity/exports.ts
1319
- init_logger();
1320
- init_utils();
1321
- // src/plugins/built-in/css/inject-styles.ts
1322
- init_logger();
1323
-
1324
- // src/plugins/utils.ts
1325
- var import_picocolors4 = __toESM(require_picocolors(), 1);
1326
- init_errors();
1327
- function filterBunupBunPlugins(plugins) {
1328
- if (!plugins)
1329
- return [];
1330
- return plugins.filter((p) => p.type === "bun");
1331
- }
1332
- function filterBunupPlugins(plugins) {
1333
- if (!plugins)
1334
- return [];
1335
- return plugins.filter((p) => p.type === "bunup");
1336
- }
1337
- async function runPluginBuildStartHooks(bunupPlugins, options) {
1338
- if (!bunupPlugins)
1339
- return;
1340
- for (const plugin of bunupPlugins) {
1341
- if (plugin.hooks.onBuildStart) {
1342
- await plugin.hooks.onBuildStart(options);
1343
- }
1344
- }
1345
- }
1346
- async function runPluginBuildDoneHooks(bunupPlugins, options, output, meta) {
1347
- if (!bunupPlugins)
1348
- return;
1349
- for (const plugin of bunupPlugins) {
1350
- if (plugin.hooks.onBuildDone) {
1351
- await plugin.hooks.onBuildDone({ options, output, meta });
1352
- }
1353
- }
1354
- }
1355
- // src/plugins/built-in/productivity/copy.ts
1356
- init_utils();
1357
- // src/plugins/internal/report.ts
1358
- var import_picocolors5 = __toESM(require_picocolors(), 1);
1359
- init_logger();
1360
- init_logger();
1361
- init_utils();
1362
- function report() {
1363
- return {
1364
- type: "bunup",
1365
- name: "report",
1366
- hooks: {
1367
- onBuildDone: async ({ options, output }) => {
1368
- if (options.watch)
1369
- return;
1370
- const files = await Promise.all(output.files.map(async (file) => {
1371
- const name = file.relativePathToRootDir;
1372
- const size = Bun.file(file.fullPath).size;
1373
- const gzipSize = Bun.gzipSync(new Uint8Array(await Bun.file(file.fullPath).arrayBuffer())).length;
1374
- const formattedGzipSize = formatFileSize(gzipSize);
1375
- return {
1376
- name,
1377
- size,
1378
- formattedSize: formatFileSize(size),
1379
- gzipSize,
1380
- formattedGzipSize
1381
- };
1382
- }));
1383
- const totalSize = files.reduce((sum, file) => sum + file.size, 0);
1384
- const formattedTotalSize = formatFileSize(totalSize);
1385
- const totalGzipSize = files.reduce((sum, file) => sum + (file.gzipSize || 0), 0);
1386
- const formattedTotalGzipSize = formatFileSize(totalGzipSize);
1387
- const columns = [
1388
- { header: "File", align: "left", color: import_picocolors5.default.blue },
1389
- { header: "Size", align: "right", color: import_picocolors5.default.green },
1390
- {
1391
- header: "Gzip",
1392
- align: "right",
1393
- color: import_picocolors5.default.magenta
1394
- }
1395
- ];
1396
- const data = files.map((file) => {
1397
- return {
1398
- File: file.name,
1399
- Size: file.formattedSize,
1400
- Gzip: file.formattedGzipSize
1401
- };
1402
- });
1403
- const footer = {
1404
- File: "Total",
1405
- Size: formattedTotalSize,
1406
- Gzip: formattedTotalGzipSize
1407
- };
1408
- logger.space();
1409
- logTable(columns, data, footer);
1410
- logger.space();
1411
- }
1412
- }
1413
- };
1414
- }
1415
- // src/plugins/internal/use-client.ts
1416
- function useClient() {
1417
- return {
1418
- type: "bunup",
1419
- name: "use-client",
1420
- hooks: {
1421
- onBuildDone: async ({ output }) => {
1422
- for (const file of output.files) {
1423
- let text = await Bun.file(file.fullPath).text();
1424
- const hasUseClient = text.split(`
1425
- `).some((line) => line.trim().startsWith(`"use client";`));
1426
- if (hasUseClient) {
1427
- text = text.replaceAll(`"use client";`, "");
1428
- text = `"use client";
1429
- ${text}`;
1430
- }
1431
- await Bun.write(file.fullPath, text);
1432
- }
1433
- }
1434
- }
1435
- };
1436
- }
1437
-
1438
- // src/options.ts
1439
- var DEFAULT_OPTIONS = {
1440
- entry: [],
1441
- format: ["cjs"],
1442
- outDir: "dist",
1443
- target: "node",
1444
- clean: true
1445
- };
1446
- function createBuildOptions(partialOptions) {
1447
- const options = {
1448
- ...DEFAULT_OPTIONS,
1449
- ...partialOptions
1450
- };
1451
- return {
1452
- ...options,
1453
- plugins: [
1454
- ...options.plugins?.filter((p) => p.name !== "report") ?? [],
1455
- useClient(),
1456
- report()
1457
- ]
1458
- };
1459
- }
1460
- function getResolvedMinify(options) {
1461
- const { minify, minifyWhitespace, minifyIdentifiers, minifySyntax } = options;
1462
- const defaultValue = minify === true;
1463
- return {
1464
- whitespace: minifyWhitespace ?? defaultValue,
1465
- identifiers: minifyIdentifiers ?? defaultValue,
1466
- syntax: minifySyntax ?? defaultValue
1467
- };
1468
- }
1469
- function getResolvedBytecode(bytecode, format) {
1470
- return format === "cjs" ? bytecode : undefined;
1471
- }
1472
- function getResolvedSourcemap(sourcemap) {
1473
- if (sourcemap === true) {
1474
- return "inline";
1475
- }
1476
- return typeof sourcemap === "string" ? sourcemap : undefined;
1477
- }
1478
- function getResolvedDefine(define, env) {
1479
- return {
1480
- ...typeof env === "object" && Object.keys(env).reduce((acc, key) => {
1481
- const value = JSON.stringify(env[key]);
1482
- acc[`process.env.${key}`] = value;
1483
- acc[`import.meta.env.${key}`] = value;
1484
- return acc;
1485
- }, {}),
1486
- ...define
1487
- };
1488
- }
1489
- function getResolvedSplitting(splitting, format) {
1490
- return splitting === undefined ? format === "esm" : splitting;
1491
- }
1492
- function getResolvedEnv(env) {
1493
- return typeof env === "string" ? env : undefined;
1494
- }
1495
-
1496
- // src/helpers/external.ts
1497
- init_utils();
1498
- function getPackageDepsPatterns(packageJson) {
1499
- return getPackageDeps(packageJson).map((dep) => new RegExp(`^${dep}($|\\/|\\\\)`));
1500
- }
1501
- function matchesPattern(path3, pattern) {
1502
- return typeof pattern === "string" ? pattern === path3 : pattern.test(path3);
1503
- }
1504
- function isExternal(path3, options, packageJson) {
1505
- const packageDepsPatterns = getPackageDepsPatterns(packageJson);
1506
- const matchesExternalPattern = packageDepsPatterns.some((pattern) => pattern.test(path3)) || options.external?.some((pattern) => matchesPattern(path3, pattern));
1507
- const isExcludedFromExternal = options.noExternal?.some((pattern) => matchesPattern(path3, pattern));
1508
- return matchesExternalPattern && !isExcludedFromExternal;
1509
- }
1510
-
1511
- // src/plugins/internal/external-option.ts
1512
- function externalOptionPlugin(options, packageJson) {
1513
- return {
1514
- name: "bunup:external-option-plugin",
1515
- setup(build) {
1516
- build.onResolve({ filter: /.*/ }, (args) => {
1517
- const importPath = args.path;
1518
- if (isExternal(importPath, options, packageJson)) {
1519
- return {
1520
- path: importPath,
1521
- external: true
1522
- };
1523
- }
1524
- return null;
1525
- });
1526
- }
1527
- };
1528
- }
1529
-
1530
- // src/build.ts
1531
- init_utils();
1532
- async function build(partialOptions, rootDir = process.cwd()) {
1533
- const buildOutput = {
1534
- files: []
1535
- };
1536
- const options = createBuildOptions(partialOptions);
1537
- if (!options.entry || options.entry.length === 0 || !options.outDir) {
1538
- throw new BunupBuildError("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");
1539
- }
1540
- if (options.clean) {
1541
- cleanOutDir(rootDir, options.outDir);
1542
- }
1543
- setSilent(options.silent);
1544
- const packageJson = await loadPackageJson(rootDir);
1545
- if (packageJson.data && packageJson.path) {
1546
- logger.cli(`Using ${getShortFilePath(packageJson.path, 2)}`, {
1547
- muted: true,
1548
- identifier: options.name,
1549
- once: `${packageJson.path}:${options.name}`
1550
- });
1551
- }
1552
- const bunupPlugins = filterBunupPlugins(options.plugins);
1553
- await runPluginBuildStartHooks(bunupPlugins, options);
1554
- const processableEntries = getProcessableEntries(options.entry);
1555
- const packageType = packageJson.data?.type;
1556
- const plugins = [
1557
- externalOptionPlugin(options, packageJson.data),
1558
- ...filterBunupBunPlugins(options.plugins).map((p) => p.plugin)
1559
- ];
1560
- if (!options.dtsOnly) {
1561
- const buildPromises = options.format.flatMap((fmt) => processableEntries.map(async ({ entry, outputBasePath }) => {
1562
- const extension = options.outputExtension?.({
1563
- format: fmt,
1564
- packageType,
1565
- options,
1566
- entry
1567
- }).js ?? getDefaultJsOutputExtension(fmt, packageType);
1568
- const result = await Bun.build({
1569
- entrypoints: [`${rootDir}/${entry}`],
1570
- format: fmt,
1571
- naming: getResolvedNaming(outputBasePath, extension),
1572
- splitting: getResolvedSplitting(options.splitting, fmt),
1573
- bytecode: getResolvedBytecode(options.bytecode, fmt),
1574
- define: getResolvedDefine(options.define, options.env),
1575
- minify: getResolvedMinify(options),
1576
- outdir: `${rootDir}/${options.outDir}`,
1577
- target: options.target,
1578
- sourcemap: getResolvedSourcemap(options.sourcemap),
1579
- loader: options.loader,
1580
- drop: options.drop,
1581
- banner: options.banner,
1582
- footer: options.footer,
1583
- publicPath: options.publicPath,
1584
- env: getResolvedEnv(options.env),
1585
- plugins,
1586
- throw: false
1587
- });
1588
- for (const log of result.logs) {
1589
- if (log.level === "error") {
1590
- throw new BunupBuildError(log.message);
1591
- }
1592
- if (log.level === "warning")
1593
- logger.warn(log.message);
1594
- else if (log.level === "info")
1595
- logger.info(log.message);
1596
- }
1597
- for (const file of result.outputs) {
1598
- const relativePathToRootDir = getRelativePathToRootDir(file.path, rootDir);
1599
- if (file.kind === "entry-point") {
1600
- logger.progress(fmt.toUpperCase(), relativePathToRootDir, {
1601
- identifier: options.name
1602
- });
1603
- }
1604
- buildOutput.files.push({
1605
- fullPath: file.path,
1606
- relativePathToRootDir,
1607
- dts: false,
1608
- entry,
1609
- outputBasePath,
1610
- format: fmt
1611
- });
1612
- }
1613
- }));
1614
- await Promise.all(buildPromises);
1615
- }
1616
- if (options.dts === true || typeof options.dts === "object" || options.dtsOnly) {
1617
- const dtsResolve = typeof options.dts === "object" && "resolve" in options.dts ? options.dts.resolve : undefined;
1618
- const dtsEntry = typeof options.dts === "object" && "entry" in options.dts ? options.dts.entry : undefined;
1619
- const processableDtsEntries = dtsEntry ? getProcessableEntries(dtsEntry) : processableEntries;
1620
- const dtsPromises = processableDtsEntries.map(async ({ entry, outputBasePath }) => {
1621
- let result;
1622
- try {
1623
- result = await generateDts(entry, {
1624
- cwd: rootDir,
1625
- preferredTsConfigPath: options.preferredTsconfigPath,
1626
- resolve: dtsResolve
1627
- });
1628
- } catch (error) {
1629
- throw new BunupDTSBuildError(parseErrorMessage(error));
1630
- }
1631
- for (const fmt of options.format) {
1632
- const extension = options.outputExtension?.({
1633
- format: fmt,
1634
- packageType,
1635
- options,
1636
- entry
1637
- }).dts ?? getDefaultDtsOutputExtension(fmt, packageType);
1638
- const filePath = path3.join(rootDir, options.outDir, `${outputBasePath}${extension}`);
1639
- const relativePathToRootDir = getRelativePathToRootDir(filePath, rootDir);
1640
- buildOutput.files.push({
1641
- fullPath: filePath,
1642
- relativePathToRootDir,
1643
- dts: true,
1644
- entry,
1645
- outputBasePath,
1646
- format: fmt
1647
- });
1648
- if (result.errors.length > 0) {
1649
- logIsolatedDeclarationErrors(result.errors, {
1650
- shouldExit: true
1651
- });
1652
- }
1653
- await Bun.write(filePath, result.dts);
1654
- logger.progress("DTS", relativePathToRootDir, {
1655
- identifier: options.name
1656
- });
1657
- }
1658
- });
1659
- await Promise.all(dtsPromises);
1660
- }
1661
- await runPluginBuildDoneHooks(bunupPlugins, options, buildOutput, {
1662
- packageJson,
1663
- rootDir
1664
- });
1665
- if (options.onSuccess) {
1666
- await options.onSuccess(options);
1667
- }
1668
- }
1669
- function getRelativePathToRootDir(filePath, rootDir) {
1670
- return filePath.replace(`${rootDir}/`, "");
1671
- }
1672
-
1673
- // src/cli/index.ts
1674
- init_loaders();
1675
- init_utils();
1676
-
1677
- // src/watch.ts
1678
- var import_picocolors6 = __toESM(require_picocolors(), 1);
1679
- import path4 from "path";
1680
- init_errors();
1681
- init_logger();
1682
- init_utils();
1683
- async function watch(partialOptions, rootDir) {
1684
- const watchPaths = new Set;
1685
- const options = createBuildOptions(partialOptions);
1686
- const dtsEntry = typeof options.dts === "object" && "entry" in options.dts ? options.dts.entry : undefined;
1687
- const processableDtsEntries = dtsEntry ? getProcessableEntries(dtsEntry) : [];
1688
- const processableEntries = getProcessableEntries(options.entry);
1689
- const uniqueEntries = new Set([
1690
- ...processableDtsEntries.map(({ entry }) => entry),
1691
- ...processableEntries.map(({ entry }) => entry)
1692
- ]);
1693
- for (const entry of uniqueEntries) {
1694
- const entryPath = path4.resolve(rootDir, entry);
1695
- const parentDir = path4.dirname(entryPath);
1696
- watchPaths.add(parentDir);
1697
- }
1698
- const chokidar = await import("chokidar");
1699
- const watcher = chokidar.watch(Array.from(watchPaths), {
1700
- ignoreInitial: true,
1701
- ignorePermissionErrors: true,
1702
- ignored: [
1703
- /[\\/]\.git[\\/]/,
1704
- /[\\/]node_modules[\\/]/,
1705
- path4.join(rootDir, options.outDir)
1706
- ]
1707
- });
1708
- let isRebuilding = false;
1709
- const triggerRebuild = async (initial = false) => {
1710
- if (isRebuilding) {
1711
- return;
1712
- }
1713
- isRebuilding = true;
1714
- try {
1715
- await new Promise((resolve) => setTimeout(resolve, 20));
1716
- const start = performance.now();
1717
- await build(options, rootDir);
1718
- if (!initial) {
1719
- logger.cli(`\uD83D\uDCE6 Rebuild finished in ${import_picocolors6.default.green(formatTime(performance.now() - start))}`);
1720
- }
1721
- } catch (error) {
1722
- handleError(error);
1723
- } finally {
1724
- isRebuilding = false;
1725
- }
1726
- };
1727
- watcher.on("change", (filePath) => {
1728
- const changedFile = path4.relative(rootDir, filePath);
1729
- logger.cli(`File changed: ${changedFile}`, {
1730
- muted: true,
1731
- once: changedFile
1732
- });
1733
- triggerRebuild();
1734
- });
1735
- watcher.on("error", (error) => {
1736
- throw new BunupWatchError(`Watcher error: ${parseErrorMessage(error)}`);
1737
- });
1738
- await triggerRebuild(true);
1739
- }
1740
-
1741
- // src/cli/index.ts
1742
- async function main(args = Bun.argv.slice(2)) {
1743
- const cliOptions = parseCliOptions(args);
1744
- if (cliOptions.new) {
1745
- const { newProject: newProject2 } = await Promise.resolve().then(() => (init_new(), exports_new));
1746
- await newProject2();
1747
- return;
1748
- }
1749
- if (cliOptions.init) {
1750
- const { init: init2 } = await Promise.resolve().then(() => (init_init(), exports_init));
1751
- await init2();
1752
- return;
1753
- }
1754
- setSilent(cliOptions.silent);
1755
- const cwd = process.cwd();
1756
- const { config, filepath } = await loadConfig2({
1757
- name: "bunup.config",
1758
- extensions: [".ts", ".js", ".mjs", ".cjs"],
1759
- maxDepth: 1,
1760
- preferredPath: cliOptions.config,
1761
- packageJsonProperty: "bunup"
1762
- });
1763
- const configsToProcess = !config ? [{ rootDir: cwd, options: cliOptions }] : await processLoadedConfigs(config, cwd, cliOptions.filter);
1764
- logger.cli(`Using bunup v${version} and bun v${Bun.version}`, {
1765
- muted: true
1766
- });
1767
- if (filepath) {
1768
- logger.cli(`Using ${getShortFilePath(filepath, 2)}`, {
1769
- muted: true
1770
- });
1771
- }
1772
- const startTime = performance.now();
1773
- logger.cli("Build started");
1774
- await Promise.all(configsToProcess.flatMap(({ options, rootDir }) => {
1775
- const optionsArray = ensureArray(options);
1776
- return optionsArray.map(async (o) => {
1777
- const partialOptions = {
1778
- ...o,
1779
- ...removeCliOnlyOptions(cliOptions)
1780
- };
1781
- if (partialOptions.watch) {
1782
- await watch(partialOptions, rootDir);
1783
- } else {
1784
- await build(partialOptions, rootDir);
1785
- }
1786
- });
1787
- }));
1788
- const buildTimeMs = performance.now() - startTime;
1789
- const timeDisplay = formatTime(buildTimeMs);
1790
- logger.cli(`\u26A1\uFE0F Build completed in ${import_picocolors10.default.green(timeDisplay)}`);
1791
- if (cliOptions.watch) {
1792
- logger.cli("\uD83D\uDC40 Watching for file changes");
1793
- }
1794
- if (cliOptions.onSuccess) {
1795
- logger.cli(`Running command: ${cliOptions.onSuccess}`, {
1796
- muted: true
1797
- });
1798
- await exec2(cliOptions.onSuccess, [], {
1799
- nodeOptions: { shell: true, stdio: "inherit" }
1800
- });
1801
- }
1802
- if (!cliOptions.watch) {
1803
- process.exit(process.exitCode ?? 0);
1804
- }
1805
- }
1806
- function removeCliOnlyOptions(options) {
1807
- return {
1808
- ...options,
1809
- onSuccess: undefined,
1810
- config: undefined,
1811
- filter: undefined,
1812
- new: undefined,
1813
- init: undefined
1814
- };
1815
- }
1816
- main().catch((error) => handleErrorAndExit(error));