tsdown 0.11.7 → 0.11.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { UserConfig, UserConfigFn } from "./index-DSS5MGRw.js";
1
+ import { UserConfig, UserConfigFn } from "./index-BoDsEHb5.js";
2
2
 
3
3
  //#region src/config.d.ts
4
4
  /**
package/dist/config.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { UserConfig, UserConfigFn } from "./index-DSS5MGRw.js";
2
- import { defineConfig$1 as defineConfig } from "./config-DwXF0PxK.js";
1
+ import { UserConfig, UserConfigFn } from "./index-BoDsEHb5.js";
2
+ import { defineConfig$1 as defineConfig } from "./config-DILVUP_s.js";
3
3
  export { UserConfig, UserConfigFn, defineConfig };
@@ -86,7 +86,7 @@ interface ReportOptions {
86
86
  */
87
87
  maxCompressSize?: number;
88
88
  }
89
- declare function ReportPlugin(options: ReportOptions, cwd: string, cjsDts?: boolean): Plugin;
89
+ declare function ReportPlugin(options: ReportOptions, cwd: string, cjsDts?: boolean, name?: string, isMultiFormat?: boolean): Plugin;
90
90
 
91
91
  //#endregion
92
92
  //#region src/options/index.d.ts
@@ -94,6 +94,23 @@ type Sourcemap = boolean | "inline" | "hidden";
94
94
  type Format = Exclude<ModuleFormat, "experimental-app">;
95
95
  type NormalizedFormat = Exclude<InternalModuleFormat, "app">;
96
96
  type ModuleTypes = Record<string, "js" | "jsx" | "ts" | "tsx" | "json" | "text" | "base64" | "dataurl" | "binary" | "empty" | "css" | "asset">;
97
+ interface Workspace {
98
+ /**
99
+ * Workspace directories. Glob patterns are supported.
100
+ * - `auto`: Automatically detect `package.json` files in the workspace.
101
+ * @default 'auto'
102
+ */
103
+ include?: Arrayable<string> | "auto";
104
+ /**
105
+ * Exclude directories from workspace.
106
+ * Defaults to all `node_modules`, `dist`, `test`, `tests`, `temp`, and `tmp` directories.
107
+ */
108
+ exclude?: Arrayable<string>;
109
+ /**
110
+ * Path to the workspace configuration file.
111
+ */
112
+ config?: boolean | string;
113
+ }
97
114
  /**
98
115
  * Options for tsdown.
99
116
  */
@@ -149,6 +166,11 @@ interface Options$3 {
149
166
  /** @default false */
150
167
  shims?: boolean;
151
168
  /**
169
+ * The name to show in CLI output. This is useful for monorepos or workspaces.
170
+ * Defaults to the package name from `package.json`.
171
+ */
172
+ name?: string;
173
+ /**
152
174
  * Use a fixed extension for output files.
153
175
  * The extension will always be `.cjs` or `.mjs`.
154
176
  * Otherwise, it will depend on the package type.
@@ -164,6 +186,16 @@ interface Options$3 {
164
186
  /** @default true */
165
187
  treeshake?: boolean;
166
188
  plugins?: InputOptions["plugins"];
189
+ /**
190
+ * Sets how input files are processed.
191
+ * For example, use 'js' to treat files as JavaScript or 'base64' for images.
192
+ * Lets you import or require files like images or fonts.
193
+ * @example
194
+ * ```json
195
+ * { '.jpg': 'asset', '.png': 'base64' }
196
+ * ```
197
+ */
198
+ loader?: ModuleTypes;
167
199
  /** @default false */
168
200
  silent?: boolean;
169
201
  /**
@@ -255,26 +287,22 @@ interface Options$3 {
255
287
  hash?: boolean;
256
288
  /**
257
289
  * The working directory of the config file.
258
- * @default process.cwd()
290
+ * - Defaults to `process.cwd()` for root config.
291
+ * - Defaults to the package directory for workspace config.
259
292
  */
260
293
  cwd?: string;
261
294
  /**
262
- * Sets how input files are processed.
263
- * For example, use 'js' to treat files as JavaScript or 'base64' for images.
264
- * Lets you import or require files like images or fonts.
265
- * @example
266
- * ```json
267
- * { '.jpg': 'asset', '.png': 'base64' }
268
- * ```
295
+ * **[experimental]** Enable workspace mode.
296
+ * This allows you to build multiple packages in a monorepo.
269
297
  */
270
- loader?: ModuleTypes;
298
+ workspace?: Workspace | Arrayable<string> | true;
271
299
  }
272
300
  /**
273
301
  * Options without specifying config file path.
274
302
  */
275
303
  type UserConfig = Arrayable<Omit<Options$3, "config">>;
276
304
  type UserConfigFn = (cliOptions: Options$3) => Awaitable<UserConfig>;
277
- type ResolvedOptions = Omit<Overwrite<MarkPartial<Omit<Options$3, "publicDir">, "globalName" | "inputOptions" | "outputOptions" | "minify" | "define" | "alias" | "external" | "noExternal" | "onSuccess" | "fixedExtension" | "outExtensions" | "hooks" | "removeNodeProtocol" | "copy" | "loader">, {
305
+ type ResolvedOptions = Omit<Overwrite<MarkPartial<Omit<Options$3, "publicDir" | "workspace">, "globalName" | "inputOptions" | "outputOptions" | "minify" | "define" | "alias" | "external" | "noExternal" | "onSuccess" | "fixedExtension" | "outExtensions" | "hooks" | "removeNodeProtocol" | "copy" | "loader" | "name">, {
278
306
  format: NormalizedFormat[];
279
307
  target?: string[];
280
308
  clean: string[];
package/dist/index.d.ts CHANGED
@@ -1,10 +1,13 @@
1
- import { BuildContext, Options, ResolvedOptions, TsdownHooks, UserConfig, UserConfigFn } from "./index-DSS5MGRw.js";
2
- import { defineConfig$1 as defineConfig } from "./config-DwXF0PxK.js";
1
+ import { BuildContext, Options, ResolvedOptions, TsdownHooks, UserConfig, UserConfigFn } from "./index-BoDsEHb5.js";
2
+ import { defineConfig$1 as defineConfig } from "./config-DILVUP_s.js";
3
+ import "ansis";
4
+ import { InternalModuleFormat } from "rolldown";
3
5
 
4
6
  //#region src/utils/logger.d.ts
5
7
  declare class Logger {
6
8
  silent: boolean;
7
9
  setSilent(value: boolean): void;
10
+ filter(...args: any[]): any[];
8
11
  info(...args: any[]): void;
9
12
  warn(...args: any[]): void;
10
13
  error(...args: any[]): void;
package/dist/index.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import { defineConfig } from "./config-yiJy1jd0.js";
2
- import { ExternalPlugin, NodeProtocolPlugin, ReportPlugin, ShebangPlugin, fsCopy, fsRemove, fsStat, getPackageType, lowestCommonAncestor, normalizeFormat, prettyFormat, readPackageJson } from "./plugins-CPt-D0Cs.js";
3
- import { debounce, resolveComma, slash, toArray } from "./general-CPYs4M61.js";
4
- import { logger } from "./logger-DYeY_1KP.js";
2
+ import { ExternalPlugin, NodeProtocolPlugin, ReportPlugin, ShebangPlugin, fsCopy, fsRemove, fsStat, lowestCommonAncestor } from "./plugins-G7Z0rtO5.js";
3
+ import { debounce, generateColor, logger, prettyName, resolveComma, slash, toArray } from "./logger-BdIBA2vO.js";
5
4
  import path from "node:path";
6
5
  import process from "node:process";
7
6
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -11,14 +10,16 @@ import { build as build$1 } from "rolldown";
11
10
  import { transformPlugin } from "rolldown/experimental";
12
11
  import { exec } from "tinyexec";
13
12
  import { glob } from "tinyglobby";
13
+ import { readFile } from "node:fs/promises";
14
14
  import { createHooks } from "hookable";
15
+ import { up } from "empathic/package";
15
16
  import readline from "node:readline";
16
17
  import minVersion from "semver/ranges/min-version.js";
17
- import { up } from "empathic/find";
18
+ import { up as up$1 } from "empathic/find";
18
19
  import { loadConfig } from "unconfig";
19
20
 
20
21
  //#region src/features/clean.ts
21
- const debug$3 = Debug("tsdown:clean");
22
+ const debug$4 = Debug("tsdown:clean");
22
23
  const RE_LAST_SLASH = /[/\\]$/;
23
24
  async function cleanOutDir(configs) {
24
25
  const removes = new Set();
@@ -38,10 +39,10 @@ async function cleanOutDir(configs) {
38
39
  if (!removes.size) return;
39
40
  logger.info(`Cleaning ${removes.size} files`);
40
41
  await Promise.all([...removes].map(async (file) => {
41
- debug$3("Removing", file);
42
+ debug$4("Removing", file);
42
43
  await fsRemove(file);
43
44
  }));
44
- debug$3("Removed %d files", removes.size);
45
+ debug$4("Removed %d files", removes.size);
45
46
  }
46
47
  function resolveClean(clean, outDir, cwd) {
47
48
  if (clean === true) clean = [slash(outDir)];
@@ -58,10 +59,10 @@ async function copy(options) {
58
59
  await Promise.all(toArray(copy$1).map((dir) => {
59
60
  const from = typeof dir === "string" ? dir : dir.from;
60
61
  const to = typeof dir === "string" ? path.resolve(options.outDir, path.basename(from)) : dir.to;
61
- return cp(options.cwd, from, to);
62
+ return cp$1(options.cwd, from, to);
62
63
  }));
63
64
  }
64
- function cp(cwd, from, to) {
65
+ function cp$1(cwd, from, to) {
65
66
  return fsCopy(path.resolve(cwd, from), path.resolve(cwd, to));
66
67
  }
67
68
 
@@ -133,6 +134,35 @@ async function LightningCSSPlugin(options) {
133
134
  return LightningCSS.default({ options: { targets } });
134
135
  }
135
136
 
137
+ //#endregion
138
+ //#region src/utils/package.ts
139
+ const debug$3 = Debug("tsdown:package");
140
+ async function readPackageJson(dir) {
141
+ const packageJsonPath = up({ cwd: dir });
142
+ if (!packageJsonPath) return;
143
+ debug$3("Reading package.json:", packageJsonPath);
144
+ const contents = await readFile(packageJsonPath, "utf8");
145
+ return JSON.parse(contents);
146
+ }
147
+ function getPackageType(pkg) {
148
+ if (pkg?.type) {
149
+ if (!["module", "commonjs"].includes(pkg.type)) throw new Error(`Invalid package.json type: ${pkg.type}`);
150
+ return pkg.type;
151
+ }
152
+ }
153
+ function normalizeFormat(format) {
154
+ return resolveComma(toArray(format, "es")).map((format$1) => {
155
+ switch (format$1) {
156
+ case "es":
157
+ case "esm":
158
+ case "module": return "es";
159
+ case "cjs":
160
+ case "commonjs": return "cjs";
161
+ default: return format$1;
162
+ }
163
+ });
164
+ }
165
+
136
166
  //#endregion
137
167
  //#region src/features/output.ts
138
168
  function resolveJsOutputExtension(packageType, format, fixedExtension) {
@@ -294,12 +324,15 @@ async function watchBuild(options, configFile, rebuild, restart) {
294
324
 
295
325
  //#endregion
296
326
  //#region src/features/entry.ts
297
- async function resolveEntry(entry, cwd) {
298
- if (!entry || Object.keys(entry).length === 0) throw new Error(`No input files, try "tsdown <your-file>" instead`);
327
+ async function resolveEntry(entry, cwd, name) {
328
+ if (!entry || Object.keys(entry).length === 0) {
329
+ const nameLabel = name ? `[${name}] ` : "";
330
+ throw new Error(`${nameLabel}No input files, try "tsdown <your-file>" instead`);
331
+ }
299
332
  const entryMap = await toObjectEntry(entry, cwd);
300
333
  const entries = Object.values(entryMap);
301
334
  if (entries.length === 0) throw new Error(`Cannot find entry: ${JSON.stringify(entry)}`);
302
- logger.info(`entry: ${blue(entries.map((entry$1) => path.relative(cwd, entry$1)).join(", "))}`);
335
+ logger.info(prettyName(name), `entry: ${generateColor(name)(entries.map((entry$1) => path.relative(cwd, entry$1)).join(", "))}`);
303
336
  return entryMap;
304
337
  }
305
338
  async function toObjectEntry(entry, cwd) {
@@ -318,7 +351,7 @@ async function toObjectEntry(entry, cwd) {
318
351
 
319
352
  //#endregion
320
353
  //#region src/features/target.ts
321
- function resolveTarget(target, pkg) {
354
+ function resolveTarget(target, pkg, name) {
322
355
  if (target === false) return;
323
356
  if (target == null) {
324
357
  const pkgTarget = resolvePackageTarget(pkg);
@@ -326,7 +359,7 @@ function resolveTarget(target, pkg) {
326
359
  else return;
327
360
  }
328
361
  const targets = resolveComma(toArray(target));
329
- if (targets.length) logger.info(`target${targets.length > 1 ? "s" : ""}: ${blue(targets.join(", "))}`);
362
+ if (targets.length) logger.info(prettyName(name), `target${targets.length > 1 ? "s" : ""}: ${generateColor(name)(targets.join(", "))}`);
330
363
  return targets;
331
364
  }
332
365
  function resolvePackageTarget(pkg) {
@@ -341,9 +374,9 @@ function resolvePackageTarget(pkg) {
341
374
  //#endregion
342
375
  //#region src/features/tsconfig.ts
343
376
  function findTsconfig(cwd, name = "tsconfig.json") {
344
- return up(name, { cwd }) || false;
377
+ return up$1(name, { cwd }) || false;
345
378
  }
346
- async function resolveTsconfig(tsconfig, cwd) {
379
+ async function resolveTsconfig(tsconfig, cwd, name) {
347
380
  const original = tsconfig;
348
381
  if (tsconfig !== false) {
349
382
  if (tsconfig === true || tsconfig == null) {
@@ -351,9 +384,9 @@ async function resolveTsconfig(tsconfig, cwd) {
351
384
  if (original && !tsconfig) logger.warn(`No tsconfig found in ${blue(cwd)}`);
352
385
  } else {
353
386
  const tsconfigPath = path.resolve(cwd, tsconfig);
354
- const stat = await fsStat(tsconfigPath);
355
- if (stat?.isFile()) tsconfig = tsconfigPath;
356
- else if (stat?.isDirectory()) {
387
+ const stat$1 = await fsStat(tsconfigPath);
388
+ if (stat$1?.isFile()) tsconfig = tsconfigPath;
389
+ else if (stat$1?.isDirectory()) {
357
390
  tsconfig = findTsconfig(tsconfigPath);
358
391
  if (!tsconfig) logger.warn(`No tsconfig found in ${blue(tsconfigPath)}`);
359
392
  } else {
@@ -361,7 +394,7 @@ async function resolveTsconfig(tsconfig, cwd) {
361
394
  if (!tsconfig) logger.warn(`tsconfig ${blue(original)} doesn't exist`);
362
395
  }
363
396
  }
364
- if (tsconfig) logger.info(`Using tsconfig: ${underline(path.relative(cwd, tsconfig))}`);
397
+ if (tsconfig) logger.info(prettyName(name), `tsconfig: ${generateColor(name)(path.relative(cwd, tsconfig))}`);
365
398
  }
366
399
  return tsconfig;
367
400
  }
@@ -396,11 +429,11 @@ async function loadViteConfig(prefix, cwd) {
396
429
  return resolved;
397
430
  }
398
431
  let loaded = false;
399
- async function loadConfigFile(options) {
432
+ async function loadConfigFile(options, workspace) {
400
433
  let cwd = options.cwd || process.cwd();
401
434
  let overrideConfig = false;
402
435
  let { config: filePath } = options;
403
- if (filePath === false) return { configs: [] };
436
+ if (filePath === false) return { configs: [{}] };
404
437
  if (typeof filePath === "string") {
405
438
  const stats = await fsStat(filePath);
406
439
  if (stats) {
@@ -440,13 +473,16 @@ async function loadConfigFile(options) {
440
473
  rewrite: (config$1) => config$1?.tsdown
441
474
  }],
442
475
  cwd,
476
+ stopAt: workspace && path.dirname(workspace),
443
477
  defaults: {}
444
478
  }).finally(() => loaded = true);
445
479
  const file = sources[0];
446
480
  if (file) logger.info(`Using tsdown config: ${underline(file)}`);
447
481
  if (typeof config === "function") config = await config(options);
482
+ config = toArray(config);
483
+ if (config.length === 0) config.push({});
448
484
  return {
449
- configs: toArray(config),
485
+ configs: config,
450
486
  file
451
487
  };
452
488
  }
@@ -454,32 +490,76 @@ async function loadConfigFile(options) {
454
490
  //#endregion
455
491
  //#region src/options/index.ts
456
492
  const debug$1 = Debug("tsdown:options");
493
+ const DEFAULT_EXCLUDE_WORKSPACE = [
494
+ "**/node_modules/**",
495
+ "**/dist/**",
496
+ "**/test?(s)/**",
497
+ "**/t?(e)mp/**"
498
+ ];
457
499
  async function resolveOptions(options) {
458
- const { configs: userConfigs, file } = await loadConfigFile(options);
459
- if (userConfigs.length === 0) userConfigs.push({});
500
+ const { configs: rootConfigs, file } = await loadConfigFile(options);
460
501
  if (file) {
461
502
  debug$1("Loaded config file %s", file);
462
- debug$1("User configs %o", userConfigs);
503
+ debug$1("Root configs %o", rootConfigs);
463
504
  }
464
- const configs = await Promise.all(userConfigs.map((userConfig) => resolveConfig(userConfig, options)));
505
+ const configs = (await Promise.all(rootConfigs.map(async (rootConfig) => {
506
+ const workspaceConfigs = await resolveWorkspace(rootConfig, options);
507
+ return Promise.all(workspaceConfigs.map((config) => resolveConfig(config)));
508
+ }))).flat();
509
+ debug$1("Resolved configs %O", configs);
465
510
  return {
466
511
  configs,
467
512
  file
468
513
  };
469
514
  }
470
- async function resolveConfig(userConfig, overrides) {
471
- const subOptions = {
472
- ...userConfig,
473
- ...overrides
515
+ async function resolveWorkspace(config, options) {
516
+ const normalized = {
517
+ ...config,
518
+ ...options
474
519
  };
475
- let { entry, format = ["es"], plugins = [], clean = true, silent = false, treeshake = true, platform = "node", outDir = "dist", sourcemap = false, dts, unused = false, watch = false, shims = false, skipNodeModulesBundle = false, publint: publint$1 = false, fromVite, alias, tsconfig, report = true, target, env = {}, copy: copy$1, publicDir, hash, cwd = process.cwd() } = subOptions;
520
+ const rootCwd = normalized.cwd || process.cwd();
521
+ let { workspace } = normalized;
522
+ if (!workspace) return [normalized];
523
+ if (workspace === true) workspace = {};
524
+ else if (typeof workspace === "string" || Array.isArray(workspace)) workspace = { include: workspace };
525
+ let { include: packages = "auto", exclude = DEFAULT_EXCLUDE_WORKSPACE, config: workspaceConfig } = workspace;
526
+ if (packages === "auto") packages = (await glob({
527
+ patterns: "**/package.json",
528
+ ignore: exclude,
529
+ cwd: rootCwd
530
+ })).filter((file) => file !== "package.json").map((file) => path.resolve(rootCwd, file, ".."));
531
+ else packages = (await glob({
532
+ patterns: packages,
533
+ ignore: exclude,
534
+ cwd: rootCwd,
535
+ onlyDirectories: true,
536
+ absolute: true
537
+ })).map((file) => path.resolve(file));
538
+ if (packages.length === 0) throw new Error("No workspace packages found, please check your config");
539
+ const configs = (await Promise.all(packages.map(async (cwd) => {
540
+ const { configs: configs$1 } = await loadConfigFile({
541
+ ...options,
542
+ config: workspaceConfig,
543
+ cwd
544
+ }, cwd);
545
+ return configs$1.map((config$1) => ({
546
+ ...normalized,
547
+ cwd,
548
+ ...config$1
549
+ }));
550
+ }))).flat();
551
+ return configs;
552
+ }
553
+ async function resolveConfig(userConfig) {
554
+ let { entry, format = ["es"], plugins = [], clean = true, silent = false, treeshake = true, platform = "node", outDir = "dist", sourcemap = false, dts, unused = false, watch = false, shims = false, skipNodeModulesBundle = false, publint: publint$1 = false, fromVite, alias, tsconfig, report = true, target, env = {}, copy: copy$1, publicDir, hash, cwd = process.cwd(), name, workspace } = userConfig;
476
555
  outDir = path.resolve(cwd, outDir);
477
556
  clean = resolveClean(clean, outDir, cwd);
478
557
  const pkg = await readPackageJson(cwd);
479
- entry = await resolveEntry(entry, cwd);
558
+ if (workspace) name ||= pkg?.name;
559
+ entry = await resolveEntry(entry, cwd, name);
480
560
  if (dts == null) dts = !!(pkg?.types || pkg?.typings);
481
- target = resolveTarget(target, pkg);
482
- tsconfig = await resolveTsconfig(tsconfig, cwd);
561
+ target = resolveTarget(target, pkg, name);
562
+ tsconfig = await resolveTsconfig(tsconfig, cwd, name);
483
563
  if (publint$1 === true) publint$1 = {};
484
564
  if (publicDir) if (copy$1) throw new TypeError("`publicDir` is deprecated. Cannot be used with `copy`");
485
565
  else logger.warn(`${blue`publicDir`} is deprecated. Use ${blue`copy`} instead.`);
@@ -493,7 +573,7 @@ async function resolveConfig(userConfig, overrides) {
493
573
  }
494
574
  }
495
575
  const config = {
496
- ...subOptions,
576
+ ...userConfig,
497
577
  entry,
498
578
  plugins,
499
579
  format: normalizeFormat(format),
@@ -517,7 +597,8 @@ async function resolveConfig(userConfig, overrides) {
517
597
  env,
518
598
  pkg,
519
599
  copy: publicDir || copy$1,
520
- hash: hash ?? true
600
+ hash: hash ?? true,
601
+ name
521
602
  };
522
603
  return config;
523
604
  }
@@ -550,6 +631,7 @@ async function build(userOptions = {}) {
550
631
  if (cleanPromise) return cleanPromise;
551
632
  return cleanPromise = cleanOutDir(configs);
552
633
  };
634
+ logger.info("Build start");
553
635
  const rebuilds = await Promise.all(configs.map((options) => buildSingle(options, clean)));
554
636
  const cleanCbs = [];
555
637
  for (const [i, config] of configs.entries()) {
@@ -586,17 +668,16 @@ async function buildSingle(config, clean) {
586
668
  onSuccessCleanup?.();
587
669
  await clean();
588
670
  let hasErrors = false;
671
+ const isMultiFormat = formats.length > 1;
589
672
  await Promise.all(formats.map(async (format) => {
590
673
  try {
591
- const formatLabel = prettyFormat(format);
592
- logger.info(formatLabel, "Build start");
593
- const buildOptions = await getBuildOptions(config, format);
674
+ const buildOptions = await getBuildOptions(config, format, false, isMultiFormat);
594
675
  await hooks.callHook("build:before", {
595
676
  ...context,
596
677
  buildOptions
597
678
  });
598
679
  await build$1(buildOptions);
599
- if (format === "cjs" && dts) await build$1(await getBuildOptions(config, format, true));
680
+ if (format === "cjs" && dts) await build$1(await getBuildOptions(config, format, true, isMultiFormat));
600
681
  } catch (error) {
601
682
  if (watch) {
602
683
  logger.error(error);
@@ -610,7 +691,7 @@ async function buildSingle(config, clean) {
610
691
  await publint(config);
611
692
  await copy(config);
612
693
  await hooks.callHook("build:done", context);
613
- logger.success(`${first ? "Build" : "Rebuild"} complete in ${green(`${Math.round(performance.now() - startTime)}ms`)}`);
694
+ logger.success(prettyName(config.name), `${first ? "Build" : "Rebuild"} complete in ${green(`${Math.round(performance.now() - startTime)}ms`)}`);
614
695
  if (typeof onSuccess === "string") {
615
696
  const p = exec(onSuccess, [], { nodeOptions: {
616
697
  shell: true,
@@ -623,8 +704,8 @@ async function buildSingle(config, clean) {
623
704
  } else await onSuccess?.(config);
624
705
  }
625
706
  }
626
- async function getBuildOptions(config, format, cjsDts) {
627
- const { entry, external, plugins: userPlugins, outDir, platform, alias, treeshake, sourcemap, dts, minify, unused, target, define, shims, tsconfig, cwd, report, env, removeNodeProtocol, loader } = config;
707
+ async function getBuildOptions(config, format, cjsDts, isMultiFormat) {
708
+ const { entry, external, plugins: userPlugins, outDir, platform, alias, treeshake, sourcemap, dts, minify, unused, target, define, shims, tsconfig, cwd, report, env, removeNodeProtocol, loader, name } = config;
628
709
  const plugins = [];
629
710
  if (removeNodeProtocol) plugins.push(NodeProtocolPlugin());
630
711
  if (config.pkg || config.skipNodeModulesBundle) plugins.push(ExternalPlugin(config));
@@ -650,9 +731,9 @@ async function getBuildOptions(config, format, cjsDts) {
650
731
  exclude: /\.d\.[cm]?ts$/,
651
732
  transformOptions: { target }
652
733
  }));
653
- plugins.push(ShebangPlugin(cwd));
734
+ plugins.push(ShebangPlugin(cwd, name, isMultiFormat));
654
735
  }
655
- if (report && !logger.silent) plugins.push(ReportPlugin(report, cwd, cjsDts));
736
+ if (report && !logger.silent) plugins.push(ReportPlugin(report, cwd, cjsDts, name, isMultiFormat));
656
737
  if (target) plugins.push(
657
738
  // Use Lightning CSS to handle CSS input. This is a temporary solution
658
739
  // until Rolldown supports CSS syntax lowering natively.
@@ -0,0 +1,116 @@
1
+ import { bgRed, bgYellow, blue, green, rgb, yellow } from "ansis";
2
+
3
+ //#region src/utils/general.ts
4
+ function toArray(val, defaultValue) {
5
+ if (Array.isArray(val)) return val;
6
+ else if (val == null) {
7
+ if (defaultValue) return [defaultValue];
8
+ return [];
9
+ } else return [val];
10
+ }
11
+ function resolveComma(arr) {
12
+ return arr.flatMap((format) => format.split(","));
13
+ }
14
+ function debounce(fn, wait) {
15
+ let timeout;
16
+ return function(...args) {
17
+ if (timeout) clearTimeout(timeout);
18
+ timeout = setTimeout(() => {
19
+ timeout = void 0;
20
+ fn.apply(this, args);
21
+ }, wait);
22
+ };
23
+ }
24
+ function slash(string) {
25
+ return string.replaceAll("\\", "/");
26
+ }
27
+ const noop = (v) => v;
28
+
29
+ //#endregion
30
+ //#region src/utils/logger.ts
31
+ var Logger = class {
32
+ silent = false;
33
+ setSilent(value) {
34
+ this.silent = value;
35
+ }
36
+ filter(...args) {
37
+ return args.filter((arg) => arg !== void 0 && arg !== false);
38
+ }
39
+ info(...args) {
40
+ if (!this.silent) console.info(blue`ℹ`, ...this.filter(...args));
41
+ }
42
+ warn(...args) {
43
+ if (!this.silent) console.warn("\n", bgYellow` WARN `, ...this.filter(...args), "\n");
44
+ }
45
+ error(...args) {
46
+ if (!this.silent) console.error("\n", bgRed` ERROR `, ...this.filter(...args), "\n");
47
+ }
48
+ success(...args) {
49
+ if (!this.silent) console.info(green`✔`, ...this.filter(...args));
50
+ }
51
+ };
52
+ const logger = new Logger();
53
+ function prettyName(name) {
54
+ if (!name) return void 0;
55
+ return generateColor(name)(`[${name}]`);
56
+ }
57
+ function prettyFormat(format) {
58
+ const formatColor = format === "es" ? blue : format === "cjs" ? yellow : noop;
59
+ let formatText;
60
+ switch (format) {
61
+ case "es":
62
+ formatText = "ESM";
63
+ break;
64
+ default:
65
+ formatText = format.toUpperCase();
66
+ break;
67
+ }
68
+ return formatColor(`[${formatText}]`);
69
+ }
70
+ const colors = new Map();
71
+ function generateColor(name = "default") {
72
+ if (colors.has(name)) return colors.get(name);
73
+ let color;
74
+ if (name === "default") color = blue;
75
+ else {
76
+ let hash = 0;
77
+ for (let i = 0; i < name.length; i++) hash = name.charCodeAt(i) + ((hash << 5) - hash);
78
+ const hue = hash % 360;
79
+ const saturation = 35;
80
+ const lightness = 55;
81
+ color = rgb(...hslToRgb(hue, saturation, lightness));
82
+ }
83
+ colors.set(name, color);
84
+ return color;
85
+ }
86
+ function hslToRgb(h, s, l) {
87
+ h = h % 360;
88
+ h /= 360;
89
+ s /= 100;
90
+ l /= 100;
91
+ let r, g, b;
92
+ if (s === 0) r = g = b = l;
93
+ else {
94
+ const q = l < .5 ? l * (1 + s) : l + s - l * s;
95
+ const p = 2 * l - q;
96
+ r = hue2rgb(p, q, h + 1 / 3);
97
+ g = hue2rgb(p, q, h);
98
+ b = hue2rgb(p, q, h - 1 / 3);
99
+ }
100
+ return [
101
+ Math.max(0, Math.round(r * 255)),
102
+ Math.max(0, Math.round(g * 255)),
103
+ Math.max(0, Math.round(b * 255))
104
+ ];
105
+ }
106
+ function hue2rgb(p, q, t) {
107
+ if (t < 0) t += 1;
108
+ if (t > 1) t -= 1;
109
+ if (t < 1 / 6) return p + (q - p) * 6 * t;
110
+ if (t < 1 / 2) return q;
111
+ if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
112
+ return p;
113
+ }
114
+
115
+ //#endregion
116
+ export { debounce, generateColor, logger, noop, prettyFormat, prettyName, resolveComma, slash, toArray };
@@ -1,5 +1,5 @@
1
- import { logger } from "./logger-DYeY_1KP.js";
2
- import { version } from "./package-DIqr7O5d.js";
1
+ import { logger } from "./logger-BdIBA2vO.js";
2
+ import { version } from "./package-BjzIq4Wm.js";
3
3
  import process from "node:process";
4
4
  import { bold, green, underline } from "ansis";
5
5
  import { readFile, unlink, writeFile } from "node:fs/promises";
@@ -0,0 +1,5 @@
1
+ //#region package.json
2
+ var version = "0.11.8";
3
+
4
+ //#endregion
5
+ export { version };
@@ -1,10 +1,8 @@
1
- import { noop, resolveComma, toArray } from "./general-CPYs4M61.js";
2
- import { logger } from "./logger-DYeY_1KP.js";
1
+ import { logger, noop, prettyFormat, prettyName, toArray } from "./logger-BdIBA2vO.js";
3
2
  import path, { dirname, normalize, sep } from "node:path";
4
- import { blue, bold, dim, green, underline, yellow } from "ansis";
3
+ import { bold, dim, green, underline } from "ansis";
5
4
  import Debug from "debug";
6
- import { access, chmod, cp, readFile, rm, stat } from "node:fs/promises";
7
- import { up } from "empathic/package";
5
+ import { access, chmod, cp, rm, stat } from "node:fs/promises";
8
6
  import { Buffer } from "node:buffer";
9
7
  import { promisify } from "node:util";
10
8
  import { brotliCompress, gzip } from "node:zlib";
@@ -49,7 +47,7 @@ function lowestCommonAncestor(...filepaths) {
49
47
 
50
48
  //#endregion
51
49
  //#region src/features/external.ts
52
- const debug$2 = Debug("tsdown:external");
50
+ const debug$1 = Debug("tsdown:external");
53
51
  function ExternalPlugin(options) {
54
52
  const deps = options.pkg && Array.from(getProductionDeps(options.pkg));
55
53
  return {
@@ -72,7 +70,7 @@ function ExternalPlugin(options) {
72
70
  }
73
71
  if (deps) shouldExternal ||= deps.some((dep) => id === dep || id.startsWith(`${dep}/`));
74
72
  if (shouldExternal) {
75
- debug$2("External dependency:", id);
73
+ debug$1("External dependency:", id);
76
74
  return {
77
75
  id,
78
76
  external: shouldExternal
@@ -108,52 +106,10 @@ function NodeProtocolPlugin() {
108
106
  };
109
107
  }
110
108
 
111
- //#endregion
112
- //#region src/utils/package.ts
113
- const debug$1 = Debug("tsdown:package");
114
- async function readPackageJson(dir) {
115
- const packageJsonPath = up({ cwd: dir });
116
- if (!packageJsonPath) return;
117
- debug$1("Reading package.json:", packageJsonPath);
118
- const contents = await readFile(packageJsonPath, "utf8");
119
- return JSON.parse(contents);
120
- }
121
- function getPackageType(pkg) {
122
- if (pkg?.type) {
123
- if (!["module", "commonjs"].includes(pkg.type)) throw new Error(`Invalid package.json type: ${pkg.type}`);
124
- return pkg.type;
125
- }
126
- }
127
- function normalizeFormat(format) {
128
- return resolveComma(toArray(format, "es")).map((format$1) => {
129
- switch (format$1) {
130
- case "es":
131
- case "esm":
132
- case "module": return "es";
133
- case "cjs":
134
- case "commonjs": return "cjs";
135
- default: return format$1;
136
- }
137
- });
138
- }
139
- function prettyFormat(format) {
140
- const formatColor = format === "es" ? blue : format === "cjs" ? yellow : noop;
141
- let formatText;
142
- switch (format) {
143
- case "es":
144
- formatText = "ESM";
145
- break;
146
- default:
147
- formatText = format.toUpperCase();
148
- break;
149
- }
150
- return formatColor(`[${formatText}]`);
151
- }
152
-
153
109
  //#endregion
154
110
  //#region src/utils/format.ts
155
111
  function formatBytes(bytes) {
156
- if (bytes === Infinity) return "too large";
112
+ if (bytes === Infinity) return void 0;
157
113
  const numberFormatter = new Intl.NumberFormat("en", {
158
114
  maximumFractionDigits: 2,
159
115
  minimumFractionDigits: 2
@@ -167,7 +123,7 @@ const debug = Debug("tsdown:report");
167
123
  const brotliCompressAsync = promisify(brotliCompress);
168
124
  const gzipAsync = promisify(gzip);
169
125
  const RE_DTS = /\.d\.[cm]?ts$/;
170
- function ReportPlugin(options, cwd, cjsDts) {
126
+ function ReportPlugin(options, cwd, cjsDts, name, isMultiFormat) {
171
127
  return {
172
128
  name: "tsdown:report",
173
129
  async writeBundle(outputOptions, bundle) {
@@ -179,13 +135,13 @@ function ReportPlugin(options, cwd, cjsDts) {
179
135
  }
180
136
  const filenameLength = Math.max(...sizes.map((size) => size.filename.length));
181
137
  const rawTextLength = Math.max(...sizes.map((size) => size.rawText.length));
182
- const gzipTextLength = Math.max(...sizes.map((size) => size.gzipText.length));
183
- const brotliTextLength = Math.max(...sizes.map((size) => size.brotliText.length));
138
+ const gzipTextLength = Math.max(...sizes.map((size) => size.gzipText == null ? 0 : size.gzipText.length));
139
+ const brotliTextLength = Math.max(...sizes.map((size) => size.brotliText == null ? 0 : size.brotliText.length));
184
140
  let totalRaw = 0;
185
141
  for (const size of sizes) {
186
142
  size.rawText = size.rawText.padStart(rawTextLength);
187
- size.gzipText = size.gzipText.padStart(gzipTextLength);
188
- size.brotliText = size.brotliText.padStart(brotliTextLength);
143
+ size.gzipText = size.gzipText?.padStart(gzipTextLength);
144
+ size.brotliText = size.brotliText?.padStart(brotliTextLength);
189
145
  totalRaw += size.raw;
190
146
  }
191
147
  sizes.sort((a, b) => {
@@ -193,13 +149,14 @@ function ReportPlugin(options, cwd, cjsDts) {
193
149
  if (a.isEntry !== b.isEntry) return a.isEntry ? -1 : 1;
194
150
  return b.raw - a.raw;
195
151
  });
196
- const formatLabel = prettyFormat(cjsDts ? "cjs" : outputOptions.format);
152
+ const nameLabel = prettyName(name);
153
+ const formatLabel = isMultiFormat && prettyFormat(cjsDts ? "cjs" : outputOptions.format);
197
154
  for (const size of sizes) {
198
155
  const filenameColor = size.dts ? green : noop;
199
- logger.info(formatLabel, dim(`${outDir}/`) + filenameColor((size.isEntry ? bold : noop)(size.filename)), ` `.repeat(filenameLength - size.filename.length), dim`${size.rawText} gzip: ${size.gzipText}`, options.brotli ? dim` brotli: ${size.brotliText}` : "");
156
+ logger.info(nameLabel, formatLabel, dim(`${outDir}/`) + filenameColor((size.isEntry ? bold : noop)(size.filename)), ` `.repeat(filenameLength - size.filename.length), dim(size.rawText), size.gzipText && dim`│ gzip: ${size.gzipText}`, options.brotli && size.brotliText && dim`│ brotli: ${size.brotliText}`);
200
157
  }
201
158
  const totalSizeText = formatBytes(totalRaw);
202
- logger.info(formatLabel, `${sizes.length} files, total: ${totalSizeText}`);
159
+ logger.info(nameLabel, formatLabel, `${sizes.length} files, total: ${totalSizeText}`);
203
160
  }
204
161
  };
205
162
  }
@@ -235,7 +192,7 @@ async function calcSize(options, chunk) {
235
192
  //#endregion
236
193
  //#region src/features/shebang.ts
237
194
  const RE_SHEBANG = /^#!.*/;
238
- function ShebangPlugin(cwd) {
195
+ function ShebangPlugin(cwd, name, isMultiFormat) {
239
196
  return {
240
197
  name: "tsdown:shebang",
241
198
  async writeBundle(options, bundle) {
@@ -244,7 +201,7 @@ function ShebangPlugin(cwd) {
244
201
  if (!RE_SHEBANG.test(chunk.code)) continue;
245
202
  const filepath = path.resolve(cwd, options.file || path.join(options.dir, chunk.fileName));
246
203
  if (await fsExists(filepath)) {
247
- logger.info(prettyFormat(options.format), `Granting execute permission to ${underline(path.relative(cwd, filepath))}`);
204
+ logger.info(prettyName(name), isMultiFormat && prettyFormat(options.format), `Granting execute permission to ${underline(path.relative(cwd, filepath))}`);
248
205
  await chmod(filepath, 493);
249
206
  }
250
207
  }
@@ -253,4 +210,4 @@ function ShebangPlugin(cwd) {
253
210
  }
254
211
 
255
212
  //#endregion
256
- export { ExternalPlugin, NodeProtocolPlugin, ReportPlugin, ShebangPlugin, fsCopy, fsRemove, fsStat, getPackageType, lowestCommonAncestor, normalizeFormat, prettyFormat, readPackageJson };
213
+ export { ExternalPlugin, NodeProtocolPlugin, ReportPlugin, ShebangPlugin, fsCopy, fsRemove, fsStat, lowestCommonAncestor };
package/dist/plugins.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ReportPlugin$1 as ReportPlugin, ResolvedOptions } from "./index-DSS5MGRw.js";
1
+ import { ReportPlugin$1 as ReportPlugin, ResolvedOptions } from "./index-BoDsEHb5.js";
2
2
  import { Plugin } from "rolldown";
3
3
  import { PackageJson } from "pkg-types";
4
4
 
@@ -7,7 +7,7 @@ declare function ExternalPlugin(options: ResolvedOptions): Plugin;
7
7
 
8
8
  //#endregion
9
9
  //#region src/features/shebang.d.ts
10
- declare function ShebangPlugin(cwd: string): Plugin;
10
+ declare function ShebangPlugin(cwd: string, name?: string, isMultiFormat?: boolean): Plugin;
11
11
 
12
12
  //#endregion
13
13
  //#region src/features/node-protocol.d.ts
package/dist/plugins.js CHANGED
@@ -1,5 +1,4 @@
1
- import { ExternalPlugin, NodeProtocolPlugin, ReportPlugin, ShebangPlugin } from "./plugins-CPt-D0Cs.js";
2
- import "./general-CPYs4M61.js";
3
- import "./logger-DYeY_1KP.js";
1
+ import { ExternalPlugin, NodeProtocolPlugin, ReportPlugin, ShebangPlugin } from "./plugins-G7Z0rtO5.js";
2
+ import "./logger-BdIBA2vO.js";
4
3
 
5
4
  export { ExternalPlugin, NodeProtocolPlugin, ReportPlugin, ShebangPlugin };
package/dist/run.js CHANGED
@@ -1,7 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { resolveComma, toArray } from "./general-CPYs4M61.js";
3
- import { logger } from "./logger-DYeY_1KP.js";
4
- import { version } from "./package-DIqr7O5d.js";
2
+ import { logger, resolveComma, toArray } from "./logger-BdIBA2vO.js";
3
+ import { version } from "./package-BjzIq4Wm.js";
5
4
  import module from "node:module";
6
5
  import process from "node:process";
7
6
  import { dim } from "ansis";
@@ -12,7 +11,10 @@ import { cac } from "cac";
12
11
  //#region src/cli.ts
13
12
  const cli = cac("tsdown");
14
13
  cli.help().version(version);
15
- cli.command("[...files]", "Bundle files", { ignoreOptionDefaultValue: true }).option("-c, --config <filename>", "Use a custom config file").option("--no-config", "Disable config file").option("--format <format>", "Bundle format: esm, cjs, iife", { default: "esm" }).option("--clean", "Clean output directory").option("--external <module>", "Mark dependencies as external").option("--minify", "Minify output").option("--debug [scope]", "Show debug logs").option("--target <target>", "Bundle target, e.g \"es2015\", \"esnext\"").option("--silent", "Suppress non-error logs").option("-d, --out-dir <dir>", "Output directory", { default: "dist" }).option("--treeshake", "Tree-shake bundle", { default: true }).option("--sourcemap", "Generate source map", { default: false }).option("--shims", "Enable cjs and esm shims ", { default: false }).option("--platform <platform>", "Target platform", { default: "node" }).option("--dts", "Generate dts files").option("--publint", "Enable publint", { default: false }).option("--unused", "Enable unused dependencies check", { default: false }).option("-w, --watch [path]", "Watch mode").option("--from-vite [vitest]", "Reuse config from Vite or Vitest").option("--report", "Size report", { default: true }).option("--env.* <value>", "Define compile-time env variables").option("--on-success <command>", "Command to run on success").option("--copy <dir>", "Copy files to output dir").option("--public-dir <dir>", "Alias for --copy, deprecated").option("--tsconfig <tsconfig>", "Set tsconfig path").action(async (input, flags) => {
14
+ cli.command("[...files]", "Bundle files", {
15
+ ignoreOptionDefaultValue: true,
16
+ allowUnknownOptions: true
17
+ }).option("-c, --config <filename>", "Use a custom config file").option("--no-config", "Disable config file").option("--format <format>", "Bundle format: esm, cjs, iife", { default: "esm" }).option("--clean", "Clean output directory").option("--external <module>", "Mark dependencies as external").option("--minify", "Minify output").option("--debug [scope]", "Show debug logs").option("--target <target>", "Bundle target, e.g \"es2015\", \"esnext\"").option("--silent", "Suppress non-error logs").option("-d, --out-dir <dir>", "Output directory", { default: "dist" }).option("--treeshake", "Tree-shake bundle", { default: true }).option("--sourcemap", "Generate source map", { default: false }).option("--shims", "Enable cjs and esm shims ", { default: false }).option("--platform <platform>", "Target platform", { default: "node" }).option("--dts", "Generate dts files").option("--publint", "Enable publint", { default: false }).option("--unused", "Enable unused dependencies check", { default: false }).option("-w, --watch [path]", "Watch mode").option("--from-vite [vitest]", "Reuse config from Vite or Vitest").option("--report", "Size report", { default: true }).option("--env.* <value>", "Define compile-time env variables").option("--on-success <command>", "Command to run on success").option("--copy <dir>", "Copy files to output dir").option("--public-dir <dir>", "Alias for --copy, deprecated").option("--tsconfig <tsconfig>", "Set tsconfig path").option("-W, --workspace [dir]", "Enable workspace mode").action(async (input, flags) => {
16
18
  logger.setSilent(!!flags.silent);
17
19
  logger.info(`tsdown ${dim`v${version}`} powered by rolldown ${dim`v${VERSION}`}`);
18
20
  const { build: build$1 } = await import("./index.js");
@@ -20,7 +22,7 @@ cli.command("[...files]", "Bundle files", { ignoreOptionDefaultValue: true }).op
20
22
  await build$1(flags);
21
23
  });
22
24
  cli.command("migrate", "Migrate from tsup to tsdown").option("-c, --cwd <dir>", "Working directory").option("-d, --dry-run", "Dry run").action(async (args) => {
23
- const { migrate } = await import("./migrate-iRKeD4mW.js");
25
+ const { migrate } = await import("./migrate-DJbJNdWb.js");
24
26
  await migrate(args);
25
27
  });
26
28
  async function runCLI() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tsdown",
3
- "version": "0.11.7",
3
+ "version": "0.11.8",
4
4
  "description": "The Elegant Bundler for Libraries",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -1,28 +0,0 @@
1
- //#region src/utils/general.ts
2
- function toArray(val, defaultValue) {
3
- if (Array.isArray(val)) return val;
4
- else if (val == null) {
5
- if (defaultValue) return [defaultValue];
6
- return [];
7
- } else return [val];
8
- }
9
- function resolveComma(arr) {
10
- return arr.flatMap((format) => format.split(","));
11
- }
12
- function debounce(fn, wait) {
13
- let timeout;
14
- return function(...args) {
15
- if (timeout) clearTimeout(timeout);
16
- timeout = setTimeout(() => {
17
- timeout = void 0;
18
- fn.apply(this, args);
19
- }, wait);
20
- };
21
- }
22
- function slash(string) {
23
- return string.replaceAll("\\", "/");
24
- }
25
- const noop = (v) => v;
26
-
27
- //#endregion
28
- export { debounce, noop, resolveComma, slash, toArray };
@@ -1,25 +0,0 @@
1
- import { bgRed, bgYellow, blue, green } from "ansis";
2
-
3
- //#region src/utils/logger.ts
4
- var Logger = class {
5
- silent = false;
6
- setSilent(value) {
7
- this.silent = value;
8
- }
9
- info(...args) {
10
- if (!this.silent) console.info(blue`ℹ`, ...args);
11
- }
12
- warn(...args) {
13
- if (!this.silent) console.warn("\n", bgYellow` WARN `, ...args, "\n");
14
- }
15
- error(...args) {
16
- if (!this.silent) console.error("\n", bgRed` ERROR `, ...args, "\n");
17
- }
18
- success(...args) {
19
- if (!this.silent) console.info(green`✔`, ...args);
20
- }
21
- };
22
- const logger = new Logger();
23
-
24
- //#endregion
25
- export { logger };
@@ -1,5 +0,0 @@
1
- //#region package.json
2
- var version = "0.11.7";
3
-
4
- //#endregion
5
- export { version };