bunup 0.8.3 → 0.8.5

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 CHANGED
@@ -259,7 +259,7 @@ var import_picocolors2, BunupError, BunupBuildError, BunupDTSBuildError, BunupCL
259
259
  }, KNOWN_ERRORS, handleError = (error, context) => {
260
260
  const errorMessage = parseErrorMessage(error);
261
261
  const contextPrefix = context ? `[${context}] ` : "";
262
- let errorType = "";
262
+ let errorType = "UNKNOWN ERROR";
263
263
  if (error instanceof BunupBuildError) {
264
264
  errorType = "BUILD ERROR";
265
265
  } else if (error instanceof BunupDTSBuildError) {
@@ -411,378 +411,6 @@ var init_utils = __esm(() => {
411
411
  init_errors();
412
412
  });
413
413
 
414
- // src/loaders.ts
415
- import path2 from "path";
416
- import { loadConfig } from "coffi";
417
- async function processLoadedConfigs(config, cwd, filter) {
418
- return Array.isArray(config) && "root" in config[0] ? config.filter((c) => filter ? filter.includes(c.name) : true).map((c) => ({
419
- rootDir: path2.resolve(cwd, c.root),
420
- options: addField(c.config, "name", c.name)
421
- })) : [
422
- {
423
- rootDir: cwd,
424
- options: config
425
- }
426
- ];
427
- }
428
- function addField(objectOrArray, field, value) {
429
- return Array.isArray(objectOrArray) ? objectOrArray.map((o) => ({ ...o, [field]: value })) : { ...objectOrArray, [field]: value };
430
- }
431
- async function loadPackageJson(cwd) {
432
- const { config, filepath } = await loadConfig({
433
- name: "package",
434
- cwd,
435
- extensions: [".json"]
436
- });
437
- return {
438
- data: config,
439
- path: filepath
440
- };
441
- }
442
- var init_loaders = () => {};
443
-
444
- // src/helpers/entry.ts
445
- function getProcessableEntries(entry) {
446
- if (typeof entry === "string") {
447
- return [
448
- {
449
- entry,
450
- outputBasePath: getEntryOutputBasePath(entry)
451
- }
452
- ];
453
- }
454
- if (typeof entry === "object" && !Array.isArray(entry)) {
455
- return Object.entries(entry).map(([name, path3]) => ({
456
- entry: path3,
457
- outputBasePath: name
458
- }));
459
- }
460
- return entry.map((_entry) => ({
461
- entry: _entry,
462
- outputBasePath: getEntryOutputBasePath(_entry)
463
- }));
464
- }
465
- function getEntryOutputBasePath(entry) {
466
- const pathSegments = cleanPath(removeExtension(entry)).split("/");
467
- return pathSegments.length > 1 ? pathSegments.slice(1).join("/") : pathSegments.join("/");
468
- }
469
- function getResolvedNaming(outputBasePath, extension) {
470
- return {
471
- entry: `[dir]/${outputBasePath}${extension}`,
472
- chunk: `${outputBasePath}-[hash].[ext]`,
473
- asset: `${outputBasePath}-[name]-[hash].[ext]`
474
- };
475
- }
476
- var init_entry = __esm(() => {
477
- init_utils();
478
- });
479
-
480
- // src/plugins/internal/use-client.ts
481
- function useClient() {
482
- return {
483
- type: "bunup",
484
- name: "use-client",
485
- hooks: {
486
- onBuildDone: async ({ output }) => {
487
- for (const file of output.files) {
488
- let text = await Bun.file(file.fullPath).text();
489
- const hasUseClient = text.split(`
490
- `).some((line) => line.trim().startsWith(`"use client";`));
491
- if (hasUseClient) {
492
- text = text.replaceAll(`"use client";`, "");
493
- text = `"use client";
494
- ${text}`;
495
- }
496
- await Bun.write(file.fullPath, text);
497
- }
498
- }
499
- }
500
- };
501
- }
502
-
503
- // src/options.ts
504
- function createBuildOptions(partialOptions) {
505
- const options = {
506
- ...DEFAULT_OPTIONS,
507
- ...partialOptions
508
- };
509
- return {
510
- ...options,
511
- plugins: [...options.plugins ?? [], useClient()]
512
- };
513
- }
514
- function getResolvedMinify(options) {
515
- const { minify, minifyWhitespace, minifyIdentifiers, minifySyntax } = options;
516
- const defaultValue = minify === true;
517
- return {
518
- whitespace: minifyWhitespace ?? defaultValue,
519
- identifiers: minifyIdentifiers ?? defaultValue,
520
- syntax: minifySyntax ?? defaultValue
521
- };
522
- }
523
- function getResolvedBytecode(bytecode, format) {
524
- return format === "cjs" ? bytecode : undefined;
525
- }
526
- function getResolvedSourcemap(sourcemap) {
527
- if (sourcemap === true) {
528
- return "inline";
529
- }
530
- return typeof sourcemap === "string" ? sourcemap : undefined;
531
- }
532
- function getResolvedDefine(define, env) {
533
- return {
534
- ...typeof env === "object" && Object.keys(env).reduce((acc, key) => {
535
- const value = JSON.stringify(env[key]);
536
- acc[`process.env.${key}`] = value;
537
- acc[`import.meta.env.${key}`] = value;
538
- return acc;
539
- }, {}),
540
- ...define
541
- };
542
- }
543
- function getResolvedSplitting(splitting, format) {
544
- return splitting === undefined ? format === "esm" : splitting;
545
- }
546
- function getResolvedEnv(env) {
547
- return typeof env === "string" ? env : undefined;
548
- }
549
- var DEFAULT_OPTIONS;
550
- var init_options = __esm(() => {
551
- DEFAULT_OPTIONS = {
552
- entry: [],
553
- format: ["cjs"],
554
- outDir: "dist",
555
- target: "node",
556
- clean: true
557
- };
558
- });
559
-
560
- // src/helpers/external.ts
561
- function getPackageDepsPatterns(packageJson) {
562
- return getPackageDeps(packageJson).map((dep) => new RegExp(`^${dep}($|\\/|\\\\)`));
563
- }
564
- function matchesPattern(path3, pattern) {
565
- return typeof pattern === "string" ? pattern === path3 : pattern.test(path3);
566
- }
567
- function isExternal(path3, options, packageJson) {
568
- const packageDepsPatterns = getPackageDepsPatterns(packageJson);
569
- const matchesExternalPattern = packageDepsPatterns.some((pattern) => pattern.test(path3)) || options.external?.some((pattern) => matchesPattern(path3, pattern));
570
- const isExcludedFromExternal = options.noExternal?.some((pattern) => matchesPattern(path3, pattern));
571
- return matchesExternalPattern && !isExcludedFromExternal;
572
- }
573
- var init_external = __esm(() => {
574
- init_utils();
575
- });
576
-
577
- // src/plugins/internal/external-option.ts
578
- function externalOptionPlugin(options, packageJson) {
579
- return {
580
- name: "bunup:external-option-plugin",
581
- setup(build) {
582
- build.onResolve({ filter: /.*/ }, (args) => {
583
- const importPath = args.path;
584
- if (isExternal(importPath, options, packageJson)) {
585
- return {
586
- path: importPath,
587
- external: true
588
- };
589
- }
590
- return null;
591
- });
592
- }
593
- };
594
- }
595
- var init_external_option = __esm(() => {
596
- init_external();
597
- });
598
-
599
- // src/plugins/utils.ts
600
- function filterBunupBunPlugins(plugins) {
601
- if (!plugins)
602
- return [];
603
- return plugins.filter((p) => p.type === "bun");
604
- }
605
- function filterBunupPlugins(plugins) {
606
- if (!plugins)
607
- return [];
608
- return plugins.filter((p) => p.type === "bunup");
609
- }
610
- async function runPluginBuildStartHooks(bunupPlugins, options) {
611
- if (!bunupPlugins)
612
- return;
613
- for (const plugin of bunupPlugins) {
614
- if (plugin.hooks.onBuildStart) {
615
- await plugin.hooks.onBuildStart(options);
616
- }
617
- }
618
- }
619
- async function runPluginBuildDoneHooks(bunupPlugins, options, output, meta) {
620
- if (!bunupPlugins)
621
- return;
622
- for (const plugin of bunupPlugins) {
623
- if (plugin.hooks.onBuildDone) {
624
- await plugin.hooks.onBuildDone({ options, output, meta });
625
- }
626
- }
627
- }
628
-
629
- // src/build.ts
630
- var exports_build = {};
631
- __export(exports_build, {
632
- build: () => build
633
- });
634
- import path3 from "path";
635
- import { generateDts, logIsolatedDeclarationErrors } from "bun-dts";
636
- async function build(partialOptions, rootDir = process.cwd()) {
637
- const buildOutput = {
638
- files: []
639
- };
640
- const options = createBuildOptions(partialOptions);
641
- if (!options.entry || options.entry.length === 0 || !options.outDir) {
642
- throw new BunupBuildError("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");
643
- }
644
- if (options.clean) {
645
- cleanOutDir(rootDir, options.outDir);
646
- }
647
- setSilent(options.silent);
648
- const packageJson = await loadPackageJson(rootDir);
649
- if (packageJson.data && packageJson.path) {
650
- logger.cli(`Using ${getShortFilePath(packageJson.path, 2)}`, {
651
- muted: true,
652
- identifier: options.name,
653
- once: `${packageJson.path}:${options.name}`
654
- });
655
- }
656
- const bunupPlugins = filterBunupPlugins(options.plugins);
657
- await runPluginBuildStartHooks(bunupPlugins, options);
658
- const processableEntries = getProcessableEntries(options.entry);
659
- const packageType = packageJson.data?.type;
660
- const plugins = [
661
- externalOptionPlugin(options, packageJson.data),
662
- ...filterBunupBunPlugins(options.plugins).map((p) => p.plugin)
663
- ];
664
- if (!options.dtsOnly) {
665
- const buildPromises = options.format.flatMap((fmt) => processableEntries.map(async ({ entry, outputBasePath }) => {
666
- const extension = options.outputExtension?.({
667
- format: fmt,
668
- packageType,
669
- options,
670
- entry
671
- }).js ?? getDefaultJsOutputExtension(fmt, packageType);
672
- const result = await Bun.build({
673
- entrypoints: [`${rootDir}/${entry}`],
674
- format: fmt,
675
- naming: getResolvedNaming(outputBasePath, extension),
676
- splitting: getResolvedSplitting(options.splitting, fmt),
677
- bytecode: getResolvedBytecode(options.bytecode, fmt),
678
- define: getResolvedDefine(options.define, options.env),
679
- minify: getResolvedMinify(options),
680
- outdir: `${rootDir}/${options.outDir}`,
681
- target: options.target,
682
- sourcemap: getResolvedSourcemap(options.sourcemap),
683
- loader: options.loader,
684
- drop: options.drop,
685
- banner: options.banner,
686
- footer: options.footer,
687
- publicPath: options.publicPath,
688
- env: getResolvedEnv(options.env),
689
- plugins,
690
- throw: false
691
- });
692
- for (const log of result.logs) {
693
- if (log.level === "error") {
694
- console.log(`
695
- `);
696
- console.log(log);
697
- console.log(`
698
- `);
699
- throw new Error;
700
- }
701
- if (log.level === "warning")
702
- logger.warn(log.message);
703
- else if (log.level === "info")
704
- logger.info(log.message);
705
- }
706
- for (const file of result.outputs) {
707
- const relativePathToRootDir = getRelativePathToRootDir(file.path, rootDir);
708
- if (file.kind === "entry-point") {
709
- logger.progress(fmt.toUpperCase(), relativePathToRootDir, {
710
- identifier: options.name
711
- });
712
- }
713
- buildOutput.files.push({
714
- fullPath: file.path,
715
- relativePathToRootDir,
716
- dts: false,
717
- entry,
718
- outputBasePath,
719
- format: fmt
720
- });
721
- }
722
- }));
723
- await Promise.all(buildPromises);
724
- }
725
- if (options.dts === true || typeof options.dts === "object" || options.dtsOnly) {
726
- const dtsResolve = typeof options.dts === "object" && "resolve" in options.dts ? options.dts.resolve : undefined;
727
- const dtsEntry = typeof options.dts === "object" && "entry" in options.dts ? options.dts.entry : undefined;
728
- const processableDtsEntries = dtsEntry ? getProcessableEntries(dtsEntry) : processableEntries;
729
- const dtsPromises = processableDtsEntries.map(async ({ entry, outputBasePath }) => {
730
- const result = await generateDts(entry, {
731
- cwd: rootDir,
732
- preferredTsConfigPath: options.preferredTsconfigPath,
733
- resolve: dtsResolve
734
- });
735
- for (const fmt of options.format) {
736
- const extension = options.outputExtension?.({
737
- format: fmt,
738
- packageType,
739
- options,
740
- entry
741
- }).dts ?? getDefaultDtsOutputExtension(fmt, packageType);
742
- const filePath = path3.join(rootDir, options.outDir, `${outputBasePath}${extension}`);
743
- const relativePathToRootDir = getRelativePathToRootDir(filePath, rootDir);
744
- buildOutput.files.push({
745
- fullPath: filePath,
746
- relativePathToRootDir,
747
- dts: true,
748
- entry,
749
- outputBasePath,
750
- format: fmt
751
- });
752
- if (result.errors.length > 0) {
753
- logIsolatedDeclarationErrors(result.errors, {
754
- warnInsteadOfError: options.watch,
755
- shouldExit: true
756
- });
757
- }
758
- await Bun.write(filePath, result.dts);
759
- logger.progress("DTS", relativePathToRootDir, {
760
- identifier: options.name
761
- });
762
- }
763
- });
764
- await Promise.all(dtsPromises);
765
- }
766
- await runPluginBuildDoneHooks(bunupPlugins, options, buildOutput, {
767
- packageJson
768
- });
769
- if (options.onSuccess) {
770
- await options.onSuccess(options);
771
- }
772
- }
773
- function getRelativePathToRootDir(filePath, rootDir) {
774
- return filePath.replace(`${rootDir}/`, "");
775
- }
776
- var init_build = __esm(() => {
777
- init_errors();
778
- init_entry();
779
- init_loaders();
780
- init_logger();
781
- init_options();
782
- init_external_option();
783
- init_utils();
784
- });
785
-
786
414
  // src/cli/new.ts
787
415
  var exports_new = {};
788
416
  __export(exports_new, {
@@ -924,7 +552,7 @@ var init_new = __esm(() => {
924
552
  // src/cli/index.ts
925
553
  import { exec } from "tinyexec";
926
554
  // package.json
927
- var version = "0.8.3";
555
+ var version = "0.8.5";
928
556
 
929
557
  // src/cli/index.ts
930
558
  init_errors();
@@ -1069,106 +697,459 @@ var optionConfigs = {
1069
697
  if (entries[name]) {
1070
698
  logger.warn(`Duplicate entry name '${name}' derived from '${value}'. Overwriting previous entry.`);
1071
699
  }
1072
- entries[name] = value;
1073
- }
1074
- options.entry = entries;
700
+ entries[name] = value;
701
+ }
702
+ options.entry = entries;
703
+ }
704
+ },
705
+ resolveDts: {
706
+ flags: ["rd", "resolve-dts"],
707
+ handler: (value, options) => {
708
+ if (!options.dts)
709
+ options.dts = {};
710
+ if (typeof options.dts === "boolean")
711
+ options.dts = {};
712
+ if (typeof value === "string") {
713
+ if (value === "true" || value === "false") {
714
+ options.dts.resolve = value === "true";
715
+ } else {
716
+ options.dts.resolve = value.split(",");
717
+ }
718
+ } else {
719
+ options.dts.resolve = true;
720
+ }
721
+ }
722
+ },
723
+ help: { flags: ["h", "help"], handler: () => showHelp() },
724
+ version: { flags: ["v", "version"], handler: () => showVersion() }
725
+ };
726
+ var flagToHandler = {};
727
+ for (const config of Object.values(optionConfigs)) {
728
+ for (const flag of config.flags) {
729
+ flagToHandler[flag] = config.handler;
730
+ }
731
+ }
732
+ function parseCliOptions(argv) {
733
+ const options = {};
734
+ for (let i = 0;i < argv.length; i++) {
735
+ const arg = argv[i];
736
+ if (arg.startsWith("--")) {
737
+ let key;
738
+ let value;
739
+ if (arg.includes("=")) {
740
+ const [keyPart, valuePart] = arg.slice(2).split("=", 2);
741
+ key = keyPart;
742
+ value = valuePart;
743
+ } else {
744
+ key = arg.slice(2);
745
+ const nextArg = argv[i + 1];
746
+ value = nextArg && !nextArg.startsWith("-") ? nextArg : true;
747
+ if (typeof value === "string")
748
+ i++;
749
+ }
750
+ if (key.includes(".")) {
751
+ const [mainOption, subPath] = key.split(".", 2);
752
+ const handler = flagToHandler[mainOption];
753
+ if (handler) {
754
+ handler(value, options, subPath);
755
+ } else {
756
+ throw new BunupCLIError(`Unknown option: --${key}`);
757
+ }
758
+ } else {
759
+ const handler = flagToHandler[key];
760
+ if (handler) {
761
+ handler(value, options);
762
+ } else {
763
+ throw new BunupCLIError(`Unknown option: --${key}`);
764
+ }
765
+ }
766
+ } else if (arg.startsWith("-")) {
767
+ const key = arg.slice(1);
768
+ const nextArg = argv[i + 1];
769
+ const value = nextArg && !nextArg.startsWith("-") ? nextArg : true;
770
+ if (typeof value === "string")
771
+ i++;
772
+ const handler = flagToHandler[key];
773
+ if (handler) {
774
+ handler(value, options);
775
+ } else {
776
+ throw new BunupCLIError(`Unknown option: -${key}`);
777
+ }
778
+ } else {
779
+ optionConfigs.entry.handler(arg, options, undefined);
780
+ }
781
+ }
782
+ return options;
783
+ }
784
+
785
+ // src/cli/index.ts
786
+ var import_picocolors6 = __toESM(require_picocolors(), 1);
787
+ import { loadConfig as loadConfig2 } from "coffi";
788
+
789
+ // src/build.ts
790
+ init_errors();
791
+ import path3 from "path";
792
+ import { generateDts, logIsolatedDeclarationErrors } from "bun-dts";
793
+
794
+ // src/helpers/entry.ts
795
+ init_utils();
796
+ function getProcessableEntries(entry) {
797
+ if (typeof entry === "string") {
798
+ return [
799
+ {
800
+ entry,
801
+ outputBasePath: getEntryOutputBasePath(entry)
802
+ }
803
+ ];
804
+ }
805
+ if (typeof entry === "object" && !Array.isArray(entry)) {
806
+ return Object.entries(entry).map(([name, path2]) => ({
807
+ entry: path2,
808
+ outputBasePath: name
809
+ }));
810
+ }
811
+ return entry.map((_entry) => ({
812
+ entry: _entry,
813
+ outputBasePath: getEntryOutputBasePath(_entry)
814
+ }));
815
+ }
816
+ function getEntryOutputBasePath(entry) {
817
+ const pathSegments = cleanPath(removeExtension(entry)).split("/");
818
+ return pathSegments.length > 1 ? pathSegments.slice(1).join("/") : pathSegments.join("/");
819
+ }
820
+ function getResolvedNaming(outputBasePath, extension) {
821
+ return {
822
+ entry: `[dir]/${outputBasePath}${extension}`,
823
+ chunk: `${outputBasePath}-[hash].[ext]`,
824
+ asset: `${outputBasePath}-[name]-[hash].[ext]`
825
+ };
826
+ }
827
+
828
+ // src/loaders.ts
829
+ import path2 from "path";
830
+ import { loadConfig } from "coffi";
831
+ async function processLoadedConfigs(config, cwd, filter) {
832
+ return Array.isArray(config) && "root" in config[0] ? config.filter((c) => filter ? filter.includes(c.name) : true).map((c) => ({
833
+ rootDir: path2.resolve(cwd, c.root),
834
+ options: addField(c.config, "name", c.name)
835
+ })) : [
836
+ {
837
+ rootDir: cwd,
838
+ options: config
839
+ }
840
+ ];
841
+ }
842
+ function addField(objectOrArray, field, value) {
843
+ return Array.isArray(objectOrArray) ? objectOrArray.map((o) => ({ ...o, [field]: value })) : { ...objectOrArray, [field]: value };
844
+ }
845
+ async function loadPackageJson(cwd) {
846
+ const { config, filepath } = await loadConfig({
847
+ name: "package",
848
+ cwd,
849
+ extensions: [".json"]
850
+ });
851
+ return {
852
+ data: config,
853
+ path: filepath
854
+ };
855
+ }
856
+
857
+ // src/build.ts
858
+ init_logger();
859
+
860
+ // src/plugins/internal/use-client.ts
861
+ function useClient() {
862
+ return {
863
+ type: "bunup",
864
+ name: "use-client",
865
+ hooks: {
866
+ onBuildDone: async ({ output }) => {
867
+ for (const file of output.files) {
868
+ let text = await Bun.file(file.fullPath).text();
869
+ const hasUseClient = text.split(`
870
+ `).some((line) => line.trim().startsWith(`"use client";`));
871
+ if (hasUseClient) {
872
+ text = text.replaceAll(`"use client";`, "");
873
+ text = `"use client";
874
+ ${text}`;
875
+ }
876
+ await Bun.write(file.fullPath, text);
877
+ }
878
+ }
879
+ }
880
+ };
881
+ }
882
+
883
+ // src/options.ts
884
+ var DEFAULT_OPTIONS = {
885
+ entry: [],
886
+ format: ["cjs"],
887
+ outDir: "dist",
888
+ target: "node",
889
+ clean: true
890
+ };
891
+ function createBuildOptions(partialOptions) {
892
+ const options = {
893
+ ...DEFAULT_OPTIONS,
894
+ ...partialOptions
895
+ };
896
+ return {
897
+ ...options,
898
+ plugins: [...options.plugins ?? [], useClient()]
899
+ };
900
+ }
901
+ function getResolvedMinify(options) {
902
+ const { minify, minifyWhitespace, minifyIdentifiers, minifySyntax } = options;
903
+ const defaultValue = minify === true;
904
+ return {
905
+ whitespace: minifyWhitespace ?? defaultValue,
906
+ identifiers: minifyIdentifiers ?? defaultValue,
907
+ syntax: minifySyntax ?? defaultValue
908
+ };
909
+ }
910
+ function getResolvedBytecode(bytecode, format) {
911
+ return format === "cjs" ? bytecode : undefined;
912
+ }
913
+ function getResolvedSourcemap(sourcemap) {
914
+ if (sourcemap === true) {
915
+ return "inline";
916
+ }
917
+ return typeof sourcemap === "string" ? sourcemap : undefined;
918
+ }
919
+ function getResolvedDefine(define, env) {
920
+ return {
921
+ ...typeof env === "object" && Object.keys(env).reduce((acc, key) => {
922
+ const value = JSON.stringify(env[key]);
923
+ acc[`process.env.${key}`] = value;
924
+ acc[`import.meta.env.${key}`] = value;
925
+ return acc;
926
+ }, {}),
927
+ ...define
928
+ };
929
+ }
930
+ function getResolvedSplitting(splitting, format) {
931
+ return splitting === undefined ? format === "esm" : splitting;
932
+ }
933
+ function getResolvedEnv(env) {
934
+ return typeof env === "string" ? env : undefined;
935
+ }
936
+
937
+ // src/helpers/external.ts
938
+ init_utils();
939
+ function getPackageDepsPatterns(packageJson) {
940
+ return getPackageDeps(packageJson).map((dep) => new RegExp(`^${dep}($|\\/|\\\\)`));
941
+ }
942
+ function matchesPattern(path3, pattern) {
943
+ return typeof pattern === "string" ? pattern === path3 : pattern.test(path3);
944
+ }
945
+ function isExternal(path3, options, packageJson) {
946
+ const packageDepsPatterns = getPackageDepsPatterns(packageJson);
947
+ const matchesExternalPattern = packageDepsPatterns.some((pattern) => pattern.test(path3)) || options.external?.some((pattern) => matchesPattern(path3, pattern));
948
+ const isExcludedFromExternal = options.noExternal?.some((pattern) => matchesPattern(path3, pattern));
949
+ return matchesExternalPattern && !isExcludedFromExternal;
950
+ }
951
+
952
+ // src/plugins/internal/external-option.ts
953
+ function externalOptionPlugin(options, packageJson) {
954
+ return {
955
+ name: "bunup:external-option-plugin",
956
+ setup(build) {
957
+ build.onResolve({ filter: /.*/ }, (args) => {
958
+ const importPath = args.path;
959
+ if (isExternal(importPath, options, packageJson)) {
960
+ return {
961
+ path: importPath,
962
+ external: true
963
+ };
964
+ }
965
+ return null;
966
+ });
1075
967
  }
1076
- },
1077
- resolveDts: {
1078
- flags: ["rd", "resolve-dts"],
1079
- handler: (value, options) => {
1080
- if (!options.dts)
1081
- options.dts = {};
1082
- if (typeof options.dts === "boolean")
1083
- options.dts = {};
1084
- if (typeof value === "string") {
1085
- if (value === "true" || value === "false") {
1086
- options.dts.resolve = value === "true";
1087
- } else {
1088
- options.dts.resolve = value.split(",");
1089
- }
1090
- } else {
1091
- options.dts.resolve = true;
1092
- }
968
+ };
969
+ }
970
+
971
+ // src/plugins/utils.ts
972
+ function filterBunupBunPlugins(plugins) {
973
+ if (!plugins)
974
+ return [];
975
+ return plugins.filter((p) => p.type === "bun");
976
+ }
977
+ function filterBunupPlugins(plugins) {
978
+ if (!plugins)
979
+ return [];
980
+ return plugins.filter((p) => p.type === "bunup");
981
+ }
982
+ async function runPluginBuildStartHooks(bunupPlugins, options) {
983
+ if (!bunupPlugins)
984
+ return;
985
+ for (const plugin of bunupPlugins) {
986
+ if (plugin.hooks.onBuildStart) {
987
+ await plugin.hooks.onBuildStart(options);
1093
988
  }
1094
- },
1095
- help: { flags: ["h", "help"], handler: () => showHelp() },
1096
- version: { flags: ["v", "version"], handler: () => showVersion() }
1097
- };
1098
- var flagToHandler = {};
1099
- for (const config of Object.values(optionConfigs)) {
1100
- for (const flag of config.flags) {
1101
- flagToHandler[flag] = config.handler;
1102
989
  }
1103
990
  }
1104
- function parseCliOptions(argv) {
1105
- const options = {};
1106
- for (let i = 0;i < argv.length; i++) {
1107
- const arg = argv[i];
1108
- if (arg.startsWith("--")) {
1109
- let key;
1110
- let value;
1111
- if (arg.includes("=")) {
1112
- const [keyPart, valuePart] = arg.slice(2).split("=", 2);
1113
- key = keyPart;
1114
- value = valuePart;
1115
- } else {
1116
- key = arg.slice(2);
1117
- const nextArg = argv[i + 1];
1118
- value = nextArg && !nextArg.startsWith("-") ? nextArg : true;
1119
- if (typeof value === "string")
1120
- i++;
1121
- }
1122
- if (key.includes(".")) {
1123
- const [mainOption, subPath] = key.split(".", 2);
1124
- const handler = flagToHandler[mainOption];
1125
- if (handler) {
1126
- handler(value, options, subPath);
1127
- } else {
1128
- throw new BunupCLIError(`Unknown option: --${key}`);
991
+ async function runPluginBuildDoneHooks(bunupPlugins, options, output, meta) {
992
+ if (!bunupPlugins)
993
+ return;
994
+ for (const plugin of bunupPlugins) {
995
+ if (plugin.hooks.onBuildDone) {
996
+ await plugin.hooks.onBuildDone({ options, output, meta });
997
+ }
998
+ }
999
+ }
1000
+
1001
+ // src/build.ts
1002
+ init_utils();
1003
+ async function build(partialOptions, rootDir = process.cwd()) {
1004
+ const buildOutput = {
1005
+ files: []
1006
+ };
1007
+ const options = createBuildOptions(partialOptions);
1008
+ if (!options.entry || options.entry.length === 0 || !options.outDir) {
1009
+ throw new BunupBuildError("Nothing to build. Please make sure you have provided a proper bunup configuration or cli arguments.");
1010
+ }
1011
+ if (options.clean) {
1012
+ cleanOutDir(rootDir, options.outDir);
1013
+ }
1014
+ setSilent(options.silent);
1015
+ const packageJson = await loadPackageJson(rootDir);
1016
+ if (packageJson.data && packageJson.path) {
1017
+ logger.cli(`Using ${getShortFilePath(packageJson.path, 2)}`, {
1018
+ muted: true,
1019
+ identifier: options.name,
1020
+ once: `${packageJson.path}:${options.name}`
1021
+ });
1022
+ }
1023
+ const bunupPlugins = filterBunupPlugins(options.plugins);
1024
+ await runPluginBuildStartHooks(bunupPlugins, options);
1025
+ const processableEntries = getProcessableEntries(options.entry);
1026
+ const packageType = packageJson.data?.type;
1027
+ const plugins = [
1028
+ externalOptionPlugin(options, packageJson.data),
1029
+ ...filterBunupBunPlugins(options.plugins).map((p) => p.plugin)
1030
+ ];
1031
+ if (!options.dtsOnly) {
1032
+ const buildPromises = options.format.flatMap((fmt) => processableEntries.map(async ({ entry, outputBasePath }) => {
1033
+ const extension = options.outputExtension?.({
1034
+ format: fmt,
1035
+ packageType,
1036
+ options,
1037
+ entry
1038
+ }).js ?? getDefaultJsOutputExtension(fmt, packageType);
1039
+ const result = await Bun.build({
1040
+ entrypoints: [`${rootDir}/${entry}`],
1041
+ format: fmt,
1042
+ naming: getResolvedNaming(outputBasePath, extension),
1043
+ splitting: getResolvedSplitting(options.splitting, fmt),
1044
+ bytecode: getResolvedBytecode(options.bytecode, fmt),
1045
+ define: getResolvedDefine(options.define, options.env),
1046
+ minify: getResolvedMinify(options),
1047
+ outdir: `${rootDir}/${options.outDir}`,
1048
+ target: options.target,
1049
+ sourcemap: getResolvedSourcemap(options.sourcemap),
1050
+ loader: options.loader,
1051
+ drop: options.drop,
1052
+ banner: options.banner,
1053
+ footer: options.footer,
1054
+ publicPath: options.publicPath,
1055
+ env: getResolvedEnv(options.env),
1056
+ plugins,
1057
+ throw: false
1058
+ });
1059
+ for (const log of result.logs) {
1060
+ if (log.level === "error") {
1061
+ console.log(`
1062
+ `);
1063
+ console.log(log);
1064
+ console.log(`
1065
+ `);
1066
+ throw new Error;
1129
1067
  }
1130
- } else {
1131
- const handler = flagToHandler[key];
1132
- if (handler) {
1133
- handler(value, options);
1134
- } else {
1135
- throw new BunupCLIError(`Unknown option: --${key}`);
1068
+ if (log.level === "warning")
1069
+ logger.warn(log.message);
1070
+ else if (log.level === "info")
1071
+ logger.info(log.message);
1072
+ }
1073
+ for (const file of result.outputs) {
1074
+ const relativePathToRootDir = getRelativePathToRootDir(file.path, rootDir);
1075
+ if (file.kind === "entry-point") {
1076
+ logger.progress(fmt.toUpperCase(), relativePathToRootDir, {
1077
+ identifier: options.name
1078
+ });
1136
1079
  }
1080
+ buildOutput.files.push({
1081
+ fullPath: file.path,
1082
+ relativePathToRootDir,
1083
+ dts: false,
1084
+ entry,
1085
+ outputBasePath,
1086
+ format: fmt
1087
+ });
1137
1088
  }
1138
- } else if (arg.startsWith("-")) {
1139
- const key = arg.slice(1);
1140
- const nextArg = argv[i + 1];
1141
- const value = nextArg && !nextArg.startsWith("-") ? nextArg : true;
1142
- if (typeof value === "string")
1143
- i++;
1144
- const handler = flagToHandler[key];
1145
- if (handler) {
1146
- handler(value, options);
1147
- } else {
1148
- throw new BunupCLIError(`Unknown option: -${key}`);
1089
+ }));
1090
+ await Promise.all(buildPromises);
1091
+ }
1092
+ if (options.dts === true || typeof options.dts === "object" || options.dtsOnly) {
1093
+ const dtsResolve = typeof options.dts === "object" && "resolve" in options.dts ? options.dts.resolve : undefined;
1094
+ const dtsEntry = typeof options.dts === "object" && "entry" in options.dts ? options.dts.entry : undefined;
1095
+ const processableDtsEntries = dtsEntry ? getProcessableEntries(dtsEntry) : processableEntries;
1096
+ const dtsPromises = processableDtsEntries.map(async ({ entry, outputBasePath }) => {
1097
+ const result = await generateDts(entry, {
1098
+ cwd: rootDir,
1099
+ preferredTsConfigPath: options.preferredTsconfigPath,
1100
+ resolve: dtsResolve
1101
+ });
1102
+ for (const fmt of options.format) {
1103
+ const extension = options.outputExtension?.({
1104
+ format: fmt,
1105
+ packageType,
1106
+ options,
1107
+ entry
1108
+ }).dts ?? getDefaultDtsOutputExtension(fmt, packageType);
1109
+ const filePath = path3.join(rootDir, options.outDir, `${outputBasePath}${extension}`);
1110
+ const relativePathToRootDir = getRelativePathToRootDir(filePath, rootDir);
1111
+ buildOutput.files.push({
1112
+ fullPath: filePath,
1113
+ relativePathToRootDir,
1114
+ dts: true,
1115
+ entry,
1116
+ outputBasePath,
1117
+ format: fmt
1118
+ });
1119
+ if (result.errors.length > 0) {
1120
+ logIsolatedDeclarationErrors(result.errors, {
1121
+ warnInsteadOfError: options.watch,
1122
+ shouldExit: true
1123
+ });
1124
+ }
1125
+ await Bun.write(filePath, result.dts);
1126
+ logger.progress("DTS", relativePathToRootDir, {
1127
+ identifier: options.name
1128
+ });
1149
1129
  }
1150
- } else {
1151
- optionConfigs.entry.handler(arg, options, undefined);
1152
- }
1130
+ });
1131
+ await Promise.all(dtsPromises);
1132
+ }
1133
+ await runPluginBuildDoneHooks(bunupPlugins, options, buildOutput, {
1134
+ packageJson
1135
+ });
1136
+ if (options.onSuccess) {
1137
+ await options.onSuccess(options);
1153
1138
  }
1154
- return options;
1139
+ }
1140
+ function getRelativePathToRootDir(filePath, rootDir) {
1141
+ return filePath.replace(`${rootDir}/`, "");
1155
1142
  }
1156
1143
 
1157
1144
  // src/cli/index.ts
1158
- var import_picocolors6 = __toESM(require_picocolors(), 1);
1159
- init_loaders();
1160
1145
  init_utils();
1161
- import { loadConfig as loadConfig2 } from "coffi";
1162
1146
 
1163
1147
  // src/watch.ts
1164
1148
  var import_picocolors4 = __toESM(require_picocolors(), 1);
1165
- init_build();
1149
+ import path4 from "path";
1166
1150
  init_errors();
1167
- init_entry();
1168
1151
  init_logger();
1169
- init_options();
1170
1152
  init_utils();
1171
- import path4 from "path";
1172
1153
  async function watch(partialOptions, rootDir) {
1173
1154
  const watchPaths = new Set;
1174
1155
  const options = createBuildOptions(partialOptions);
@@ -1186,9 +1167,7 @@ async function watch(partialOptions, rootDir) {
1186
1167
  }
1187
1168
  const chokidar = await import("chokidar");
1188
1169
  const watcher = chokidar.watch(Array.from(watchPaths), {
1189
- persistent: true,
1190
1170
  ignoreInitial: true,
1191
- atomic: true,
1192
1171
  ignorePermissionErrors: true,
1193
1172
  ignored: [
1194
1173
  /[\\/]\.git[\\/]/,
@@ -1198,8 +1177,9 @@ async function watch(partialOptions, rootDir) {
1198
1177
  });
1199
1178
  let isRebuilding = false;
1200
1179
  const triggerRebuild = async (initial = false) => {
1201
- if (isRebuilding)
1180
+ if (isRebuilding) {
1202
1181
  return;
1182
+ }
1203
1183
  isRebuilding = true;
1204
1184
  try {
1205
1185
  const start = performance.now();
@@ -1255,7 +1235,6 @@ async function main(args = Bun.argv.slice(2)) {
1255
1235
  }
1256
1236
  const startTime = performance.now();
1257
1237
  logger.cli("Build started");
1258
- const { build: build2 } = await Promise.resolve().then(() => (init_build(), exports_build));
1259
1238
  await Promise.all(configsToProcess.flatMap(({ options, rootDir }) => {
1260
1239
  const optionsArray = ensureArray(options);
1261
1240
  return optionsArray.map(async (o) => {
@@ -1266,7 +1245,7 @@ async function main(args = Bun.argv.slice(2)) {
1266
1245
  if (partialOptions.watch) {
1267
1246
  await watch(partialOptions, rootDir);
1268
1247
  } else {
1269
- await build2(partialOptions, rootDir);
1248
+ await build(partialOptions, rootDir);
1270
1249
  }
1271
1250
  });
1272
1251
  }));
package/dist/plugins.cjs CHANGED
@@ -416,10 +416,7 @@ function exports2() {
416
416
  const existingExports = packageJson.exports || {};
417
417
  const mergedExports = { ...existingExports };
418
418
  for (const [key, value] of Object.entries(exportsField)) {
419
- mergedExports[key] = {
420
- ...mergedExports[key] || {},
421
- ...value
422
- };
419
+ mergedExports[key] = value;
423
420
  }
424
421
  const newPackageJson = {
425
422
  name: packageJson.name,
package/dist/plugins.js CHANGED
@@ -381,10 +381,7 @@ function exports() {
381
381
  const existingExports = packageJson.exports || {};
382
382
  const mergedExports = { ...existingExports };
383
383
  for (const [key, value] of Object.entries(exportsField)) {
384
- mergedExports[key] = {
385
- ...mergedExports[key] || {},
386
- ...value
387
- };
384
+ mergedExports[key] = value;
388
385
  }
389
386
  const newPackageJson = {
390
387
  name: packageJson.name,
package/package.json CHANGED
@@ -1,9 +1,12 @@
1
1
  {
2
2
  "name": "bunup",
3
3
  "description": "⚡ A blazing-fast build tool for your libraries built with Bun.",
4
- "version": "0.8.3",
4
+ "version": "0.8.5",
5
5
  "type": "module",
6
- "files": ["dist", "bin"],
6
+ "files": [
7
+ "dist",
8
+ "bin"
9
+ ],
7
10
  "module": "./dist/index.js",
8
11
  "main": "./dist/index.cjs",
9
12
  "types": "./dist/index.d.cts",
@@ -34,7 +37,11 @@
34
37
  },
35
38
  "funding": "https://github.com/sponsors/arshad-yaseen",
36
39
  "homepage": "https://bunup.dev",
37
- "keywords": ["bun", "bunup", "bun-bundler"],
40
+ "keywords": [
41
+ "bun",
42
+ "bunup",
43
+ "bun-bundler"
44
+ ],
38
45
  "bin": {
39
46
  "bunup": "bin/bunup.mjs"
40
47
  },
@@ -42,7 +49,7 @@
42
49
  "@clack/prompts": "^0.10.1",
43
50
  "bun-dts": "^0.1.27",
44
51
  "chokidar": "^4.0.3",
45
- "coffi": "^0.1.28",
52
+ "coffi": "^0.1.29",
46
53
  "giget": "^2.0.0",
47
54
  "package-manager-detector": "^1.2.0",
48
55
  "replace-in-file": "^8.3.0",
@@ -89,5 +96,8 @@
89
96
  "*": "bun run format:fix && git add .",
90
97
  "src/**/*.(m|c)?(j|t)s": "bun run tsc"
91
98
  },
92
- "workspaces": ["docs", "tests"]
99
+ "workspaces": [
100
+ "docs",
101
+ "tests"
102
+ ]
93
103
  }