tsdown 0.18.3 → 0.18.4

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,25 +1,21 @@
1
1
  import { createRequire as __cjs_createRequire } from "node:module";
2
2
  const __cjs_require = __cjs_createRequire(import.meta.url);
3
- import { a as getNameLabel, c as importWithError, d as pkgExists, f as promiseWithResolvers, g as toArray, h as slash, i as generateColor, l as matchPattern, m as resolveRegex, n as LogLevels, o as globalLogger, p as resolveComma, r as createLogger, s as prettyFormat, t as version, u as noop } from "./package-deaowsxO.mjs";
3
+ import { a as globalLogger, c as matchPattern, d as promiseWithResolvers, f as resolveComma, h as toArray, l as noop, m as slash, o as prettyFormat, s as importWithError, t as LogLevels } from "./logger-s1ImI5j1.mjs";
4
+ import { a as loadConfigFile, c as formatBytes, d as cleanOutDir, f as fsCopy, h as lowestCommonAncestor, i as resolveUserConfig, l as CssCodeSplitPlugin, m as fsRemove, o as getPackageType, p as fsExists, r as mergeUserOptions, s as writeExports, u as cleanChunks } from "./config-DlCfPR2i.mjs";
5
+ import { t as version } from "./package-BZkqghxy.mjs";
4
6
  import { builtinModules, isBuiltin } from "node:module";
5
- import path, { dirname, extname, join, normalize, sep } from "node:path";
6
- import { fileURLToPath, pathToFileURL } from "node:url";
7
+ import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";
8
+ import path, { join } from "node:path";
9
+ import process from "node:process";
10
+ import util, { formatWithOptions, promisify } from "node:util";
7
11
  import { blue, bold, dim, green, underline } from "ansis";
8
- import { clearRequireCache, init, isSupported } from "import-without-cache";
9
- import * as Rolldown from "rolldown";
10
- import { VERSION, build, watch } from "rolldown";
11
12
  import { createDebug } from "obug";
12
- import { access, chmod, cp, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
13
- import process, { env } from "node:process";
14
- import { createConfigCoreLoader } from "unconfig-core";
15
- const picomatch = __cjs_require("picomatch");
16
- import util, { formatWithOptions, parseEnv, promisify } from "node:util";
17
- import { createDefu } from "defu";
18
13
  import { glob, isDynamicPattern } from "tinyglobby";
19
14
  import { RE_CSS, RE_DTS, RE_JS, RE_NODE_MODULES } from "rolldown-plugin-dts/filename";
20
- const minVersion = __cjs_require("semver/ranges/min-version.js");
21
- import { up } from "empathic/find";
22
- import { up as up$1 } from "empathic/package";
15
+ import { fileURLToPath } from "node:url";
16
+ import { clearRequireCache } from "import-without-cache";
17
+ import * as Rolldown from "rolldown";
18
+ import { VERSION, build, watch } from "rolldown";
23
19
  const coerce = __cjs_require("semver/functions/coerce.js");
24
20
  const satisfies = __cjs_require("semver/functions/satisfies.js");
25
21
  import { Hookable } from "hookable";
@@ -31,664 +27,6 @@ import { Buffer } from "node:buffer";
31
27
  import { brotliCompress, gzip } from "node:zlib";
32
28
  import readline from "node:readline";
33
29
 
34
- //#region node_modules/.pnpm/is-in-ci@2.0.0/node_modules/is-in-ci/index.js
35
- const check = (key) => key in env && env[key] !== "0" && env[key] !== "false";
36
- const isInCi = check("CI") || check("CONTINUOUS_INTEGRATION");
37
- var is_in_ci_default = isInCi;
38
-
39
- //#endregion
40
- //#region src/utils/fs.ts
41
- function fsExists(path$1) {
42
- return access(path$1).then(() => true, () => false);
43
- }
44
- function fsStat(path$1) {
45
- return stat(path$1).catch(() => null);
46
- }
47
- function fsRemove(path$1) {
48
- return rm(path$1, {
49
- force: true,
50
- recursive: true
51
- }).catch(() => {});
52
- }
53
- function fsCopy(from, to) {
54
- return cp(from, to, {
55
- recursive: true,
56
- force: true
57
- });
58
- }
59
- function lowestCommonAncestor(...filepaths) {
60
- if (filepaths.length === 0) return "";
61
- if (filepaths.length === 1) return dirname(filepaths[0]);
62
- filepaths = filepaths.map(normalize);
63
- const [first, ...rest] = filepaths;
64
- let ancestor = first.split(sep);
65
- for (const filepath of rest) {
66
- const directories = filepath.split(sep, ancestor.length);
67
- let index = 0;
68
- for (const directory of directories) if (directory === ancestor[index]) index += 1;
69
- else {
70
- ancestor = ancestor.slice(0, index);
71
- break;
72
- }
73
- ancestor = ancestor.slice(0, index);
74
- }
75
- return ancestor.length <= 1 && ancestor[0] === "" ? sep + ancestor[0] : ancestor.join(sep);
76
- }
77
- function stripExtname(filePath) {
78
- const ext = extname(filePath);
79
- if (!ext.length) return filePath;
80
- return filePath.slice(0, -ext.length);
81
- }
82
-
83
- //#endregion
84
- //#region src/config/file.ts
85
- const debug$9 = createDebug("tsdown:config:file");
86
- async function loadViteConfig(prefix, cwd, configLoader) {
87
- const loader = resolveConfigLoader(configLoader);
88
- debug$9("Loading Vite config via loader: ", loader);
89
- const parser = createParser(loader);
90
- const [result] = await createConfigCoreLoader({
91
- sources: [{
92
- files: [`${prefix}.config`],
93
- extensions: [
94
- "js",
95
- "mjs",
96
- "ts",
97
- "cjs",
98
- "mts",
99
- "mts"
100
- ],
101
- parser
102
- }],
103
- cwd
104
- }).load(true);
105
- if (!result) return;
106
- const { config, source } = result;
107
- globalLogger.info(`Using Vite config: ${underline(source)}`);
108
- const resolved = await config;
109
- if (typeof resolved === "function") return resolved({
110
- command: "build",
111
- mode: "production"
112
- });
113
- return resolved;
114
- }
115
- const configPrefix = "tsdown.config";
116
- async function loadConfigFile(inlineConfig, workspace) {
117
- let cwd = inlineConfig.cwd || process.cwd();
118
- let overrideConfig = false;
119
- let { config: filePath } = inlineConfig;
120
- if (filePath === false) return { configs: [{}] };
121
- if (typeof filePath === "string") {
122
- const stats = await fsStat(filePath);
123
- if (stats) {
124
- const resolved = path.resolve(filePath);
125
- if (stats.isFile()) {
126
- overrideConfig = true;
127
- filePath = resolved;
128
- cwd = path.dirname(filePath);
129
- } else if (stats.isDirectory()) cwd = resolved;
130
- }
131
- }
132
- const loader = resolveConfigLoader(inlineConfig.configLoader);
133
- debug$9("Using config loader:", loader);
134
- const parser = createParser(loader);
135
- const [result] = await createConfigCoreLoader({
136
- sources: overrideConfig ? [{
137
- files: [filePath],
138
- extensions: [],
139
- parser
140
- }] : [{
141
- files: [configPrefix],
142
- extensions: [
143
- "ts",
144
- "mts",
145
- "cts",
146
- "js",
147
- "mjs",
148
- "cjs",
149
- "json"
150
- ],
151
- parser
152
- }, {
153
- files: ["package.json"],
154
- parser
155
- }],
156
- cwd,
157
- stopAt: workspace && path.dirname(workspace)
158
- }).load(true);
159
- let exported = [];
160
- let file;
161
- if (result) {
162
- ({config: exported, source: file} = result);
163
- globalLogger.info(`config file: ${underline(file)}`, loader === "native" ? "" : `(${loader})`);
164
- exported = await exported;
165
- if (typeof exported === "function") exported = await exported(inlineConfig, { ci: is_in_ci_default });
166
- }
167
- exported = toArray(exported);
168
- if (exported.length === 0) exported.push({});
169
- if (exported.some((config) => typeof config === "function")) throw new Error("Function should not be nested within multiple tsdown configurations. It must be at the top level.\nExample: export default defineConfig(() => [...])");
170
- return {
171
- configs: exported.map((config) => ({
172
- ...config,
173
- cwd: config.cwd ? path.resolve(cwd, config.cwd) : cwd
174
- })),
175
- file
176
- };
177
- }
178
- const isBun = !!process.versions.bun;
179
- const nativeTS = process.features.typescript || process.versions.deno;
180
- const autoLoader = isBun || nativeTS && isSupported ? "native" : "unrun";
181
- function resolveConfigLoader(configLoader = "auto") {
182
- if (configLoader === "auto") return autoLoader;
183
- else return configLoader === "native" ? "native" : "unrun";
184
- }
185
- function createParser(loader) {
186
- return async (filepath) => {
187
- const basename = path.basename(filepath);
188
- const isPkgJson = basename === "package.json";
189
- if (basename === configPrefix || isPkgJson || basename.endsWith(".json")) {
190
- const contents = await readFile(filepath, "utf8");
191
- const parsed = JSON.parse(contents);
192
- if (isPkgJson) return parsed?.tsdown;
193
- return parsed;
194
- }
195
- if (loader === "native") return nativeImport(filepath);
196
- return unrunImport(filepath);
197
- };
198
- }
199
- async function nativeImport(id) {
200
- const url = pathToFileURL(id);
201
- const importAttributes = Object.create(null);
202
- if (isSupported) {
203
- importAttributes.cache = "no";
204
- init({ skipNodeModules: true });
205
- } else if (!isBun) url.searchParams.set("no-cache", crypto.randomUUID());
206
- const mod = await import(url.href, { with: importAttributes }).catch((error) => {
207
- if (error?.message?.includes?.("Cannot find module")) throw new Error(`Failed to load the config file. Try setting the --config-loader CLI flag to \`unrun\`.\n\n${error.message}`, { cause: error });
208
- else throw error;
209
- });
210
- return mod.default || mod;
211
- }
212
- async function unrunImport(id) {
213
- const { unrun } = await import("unrun");
214
- const { module: module$1 } = await unrun({ path: pathToFileURL(id).href });
215
- return module$1;
216
- }
217
-
218
- //#endregion
219
- //#region src/features/clean.ts
220
- const debug$8 = createDebug("tsdown:clean");
221
- const RE_LAST_SLASH = /[/\\]$/;
222
- async function cleanOutDir(configs) {
223
- const removes = /* @__PURE__ */ new Set();
224
- for (const config of configs) {
225
- if (config.debug && (config.debug.clean ?? true)) config.clean.push(".rolldown");
226
- if (!config.clean.length) continue;
227
- const files = await glob(config.clean, {
228
- cwd: config.cwd,
229
- absolute: true,
230
- onlyFiles: false,
231
- dot: true
232
- });
233
- const normalizedOutDir = config.outDir.replace(RE_LAST_SLASH, "");
234
- for (const file of files) if (file.replace(RE_LAST_SLASH, "") !== normalizedOutDir) removes.add(file);
235
- }
236
- if (!removes.size) return;
237
- globalLogger.info(`Cleaning ${removes.size} files`);
238
- await Promise.all([...removes].map(async (file) => {
239
- debug$8("Removing", file);
240
- await fsRemove(file);
241
- }));
242
- debug$8("Removed %d files", removes.size);
243
- }
244
- function resolveClean(clean, outDir, cwd) {
245
- if (clean === true) clean = [slash(outDir)];
246
- else if (!clean) clean = [];
247
- if (clean.some((item) => path.resolve(item) === cwd)) throw new Error("Cannot clean the current working directory. Please specify a different path to clean option.");
248
- return clean;
249
- }
250
- async function cleanChunks(outDir, chunks) {
251
- await Promise.all(chunks.map(async (chunk) => {
252
- const filePath = path.resolve(outDir, chunk.fileName);
253
- debug$8("Removing chunk file", filePath);
254
- await fsRemove(filePath);
255
- }));
256
- }
257
-
258
- //#endregion
259
- //#region src/features/entry.ts
260
- async function resolveEntry(logger, entry, cwd, color, nameLabel) {
261
- if (!entry || Object.keys(entry).length === 0) {
262
- const defaultEntry = path.resolve(cwd, "src/index.ts");
263
- if (await fsExists(defaultEntry)) entry = { index: defaultEntry };
264
- else throw new Error(`${nameLabel} No input files, try "tsdown <your-file>" or create src/index.ts`);
265
- }
266
- const entryMap = await toObjectEntry(entry, cwd);
267
- const entries = Object.values(entryMap);
268
- if (entries.length === 0) throw new Error(`${nameLabel} Cannot find entry: ${JSON.stringify(entry)}`);
269
- logger.info(nameLabel, `entry: ${color(entries.map((entry$1) => path.relative(cwd, entry$1)).join(", "))}`);
270
- return entryMap;
271
- }
272
- async function toObjectEntry(entry, cwd) {
273
- if (typeof entry === "string") entry = [entry];
274
- if (!Array.isArray(entry)) return Object.fromEntries((await Promise.all(Object.entries(entry).map(async ([key, value]) => {
275
- if (!key.includes("*")) {
276
- if (Array.isArray(value)) throw new TypeError(`Object entry "${key}" cannot have an array value when the key is not a glob pattern.`);
277
- return [[key, value]];
278
- }
279
- const patterns = toArray(value);
280
- const positivePatterns = patterns.filter((p) => !p.startsWith("!"));
281
- if (positivePatterns.length === 0) throw new TypeError(`Object entry "${key}" has no positive pattern. At least one positive pattern is required.`);
282
- if (positivePatterns.length > 1) throw new TypeError(`Object entry "${key}" has multiple positive patterns: ${positivePatterns.join(", ")}. Only one positive pattern is allowed. Use negation patterns (prefixed with "!") to exclude files.`);
283
- const valueGlob = picomatch.scan(positivePatterns[0]);
284
- return (await glob(patterns, {
285
- cwd,
286
- expandDirectories: false
287
- })).map((file) => [slash(key.replaceAll("*", stripExtname(path.relative(valueGlob.base, file)))), path.resolve(cwd, file)]);
288
- }))).flat());
289
- const isGlob = entry.some((e) => isDynamicPattern(e));
290
- let resolvedEntry;
291
- if (isGlob) resolvedEntry = (await glob(entry, {
292
- cwd,
293
- expandDirectories: false,
294
- absolute: true
295
- })).map((file) => path.resolve(file));
296
- else resolvedEntry = entry;
297
- const base = lowestCommonAncestor(...resolvedEntry);
298
- return Object.fromEntries(resolvedEntry.map((file) => {
299
- return [slash(stripExtname(path.relative(base, file))), file];
300
- }));
301
- }
302
-
303
- //#endregion
304
- //#region src/utils/format.ts
305
- function formatBytes(bytes) {
306
- if (bytes === Infinity) return void 0;
307
- return `${(bytes / 1e3).toFixed(2)} kB`;
308
- }
309
- function detectIndentation(jsonText) {
310
- const lines = jsonText.split(/\r?\n/);
311
- for (const line of lines) {
312
- const match = line.match(/^(\s+)\S/);
313
- if (!match) continue;
314
- if (match[1].includes(" ")) return " ";
315
- return match[1].length;
316
- }
317
- return 2;
318
- }
319
-
320
- //#endregion
321
- //#region src/features/pkg/exports.ts
322
- async function writeExports(options, chunks) {
323
- const pkg = options.pkg;
324
- const exports = options.exports;
325
- const { publishExports, ...generated } = await generateExports(pkg, chunks, exports);
326
- const updatedPkg = {
327
- ...pkg,
328
- ...generated,
329
- packageJsonPath: void 0
330
- };
331
- if (publishExports) {
332
- updatedPkg.publishConfig ||= {};
333
- updatedPkg.publishConfig.exports = publishExports;
334
- }
335
- const original = await readFile(pkg.packageJsonPath, "utf8");
336
- let contents = JSON.stringify(updatedPkg, null, detectIndentation(original));
337
- if (original.endsWith("\n")) contents += "\n";
338
- if (contents !== original) await writeFile(pkg.packageJsonPath, contents, "utf8");
339
- }
340
- function shouldExclude(fileName, exclude) {
341
- if (!exclude?.length) return false;
342
- return matchPattern(fileName, exclude);
343
- }
344
- async function generateExports(pkg, chunks, { devExports, all, exclude, customExports }) {
345
- const pkgRoot$1 = path.dirname(pkg.packageJsonPath);
346
- let main, module$1, cjsTypes, esmTypes;
347
- const exportsMap = /* @__PURE__ */ new Map();
348
- for (const [format, chunksByFormat] of Object.entries(chunks)) {
349
- if (format !== "es" && format !== "cjs") continue;
350
- const filteredChunks = chunksByFormat.filter((chunk) => chunk.type === "chunk" && chunk.isEntry && !shouldExclude(chunk.fileName, exclude));
351
- const onlyOneEntry = filteredChunks.filter((chunk) => !RE_DTS.test(chunk.fileName)).length === 1;
352
- for (const chunk of filteredChunks) {
353
- const normalizedName = slash(chunk.fileName);
354
- let name = stripExtname(normalizedName);
355
- const isDts = name.endsWith(".d");
356
- if (isDts) name = name.slice(0, -2);
357
- const isIndex = onlyOneEntry || name === "index";
358
- const outDirRelative = slash(path.relative(pkgRoot$1, chunk.outDir));
359
- const distFile = `${outDirRelative ? `./${outDirRelative}` : "."}/${normalizedName}`;
360
- if (isIndex) {
361
- name = ".";
362
- if (format === "cjs") if (isDts) cjsTypes = distFile;
363
- else main = distFile;
364
- else if (format === "es") if (isDts) esmTypes = distFile;
365
- else module$1 = distFile;
366
- } else if (name.endsWith("/index")) name = `./${name.slice(0, -6)}`;
367
- else name = `./${name}`;
368
- let subExport = exportsMap.get(name);
369
- if (!subExport) {
370
- subExport = {};
371
- exportsMap.set(name, subExport);
372
- }
373
- if (!isDts) {
374
- subExport[format] = distFile;
375
- if (chunk.facadeModuleId && !subExport.src) subExport.src = `./${slash(path.relative(pkgRoot$1, chunk.facadeModuleId))}`;
376
- }
377
- }
378
- }
379
- const sortedExportsMap = Array.from(exportsMap.entries()).toSorted(([a], [b]) => {
380
- if (a === "index") return -1;
381
- return a.localeCompare(b);
382
- });
383
- let exports = Object.fromEntries(sortedExportsMap.map(([name, subExport]) => [name, genSubExport(devExports, subExport)]));
384
- exportMeta(exports, all);
385
- if (customExports) exports = await customExports(exports, {
386
- pkg,
387
- chunks,
388
- isPublish: false
389
- });
390
- let publishExports;
391
- if (devExports) {
392
- publishExports = Object.fromEntries(sortedExportsMap.map(([name, subExport]) => [name, genSubExport(false, subExport)]));
393
- exportMeta(publishExports, all);
394
- if (customExports) publishExports = await customExports(publishExports, {
395
- pkg,
396
- chunks,
397
- isPublish: true
398
- });
399
- }
400
- return {
401
- main: main || module$1 || pkg.main,
402
- module: module$1 || pkg.module,
403
- types: cjsTypes || esmTypes || pkg.types,
404
- exports,
405
- publishExports
406
- };
407
- }
408
- function genSubExport(devExports, { src, es, cjs }) {
409
- if (devExports === true) return src;
410
- let value;
411
- const dualFormat = es && cjs;
412
- if (!dualFormat && !devExports) value = cjs || es;
413
- else {
414
- value = {};
415
- if (typeof devExports === "string") value[devExports] = src;
416
- if (cjs) value[dualFormat ? "require" : "default"] = cjs;
417
- if (es) value[dualFormat ? "import" : "default"] = es;
418
- }
419
- return value;
420
- }
421
- function exportMeta(exports, all) {
422
- if (all) exports["./*"] = "./*";
423
- else exports["./package.json"] = "./package.json";
424
- }
425
- function hasExportsTypes(pkg) {
426
- const exports = pkg?.exports;
427
- if (!exports) return false;
428
- if (typeof exports === "object" && exports !== null && !Array.isArray(exports)) {
429
- if ("types" in exports) return true;
430
- if ("." in exports) {
431
- const mainExport = exports["."];
432
- if (typeof mainExport === "object" && mainExport !== null && "types" in mainExport) return true;
433
- }
434
- }
435
- return false;
436
- }
437
-
438
- //#endregion
439
- //#region src/features/target.ts
440
- function resolveTarget(logger, target, color, pkg, nameLabel) {
441
- if (target === false) return;
442
- if (target == null) {
443
- const pkgTarget = resolvePackageTarget(pkg);
444
- if (pkgTarget) target = pkgTarget;
445
- else return;
446
- }
447
- if (typeof target === "number") throw new TypeError(`Invalid target: ${target}`);
448
- const targets = resolveComma(toArray(target));
449
- if (targets.length) logger.info(nameLabel, `target${targets.length > 1 ? "s" : ""}: ${color(targets.join(", "))}`);
450
- return targets;
451
- }
452
- function resolvePackageTarget(pkg) {
453
- const nodeVersion = pkg?.engines?.node;
454
- if (!nodeVersion) return;
455
- const nodeMinVersion = minVersion(nodeVersion);
456
- if (!nodeMinVersion) return;
457
- if (nodeMinVersion.version === "0.0.0") return;
458
- return `node${nodeMinVersion.version}`;
459
- }
460
-
461
- //#endregion
462
- //#region src/features/tsconfig.ts
463
- function findTsconfig(cwd, name = "tsconfig.json") {
464
- return up(name, { cwd }) || false;
465
- }
466
- async function resolveTsconfig(logger, tsconfig, cwd, color, nameLabel) {
467
- const original = tsconfig;
468
- if (tsconfig !== false) {
469
- if (tsconfig === true || tsconfig == null) {
470
- tsconfig = findTsconfig(cwd);
471
- if (original && !tsconfig) logger.warn(`No tsconfig found in ${blue(cwd)}`);
472
- } else {
473
- const tsconfigPath = path.resolve(cwd, tsconfig);
474
- const stat$1 = await fsStat(tsconfigPath);
475
- if (stat$1?.isFile()) tsconfig = tsconfigPath;
476
- else if (stat$1?.isDirectory()) {
477
- tsconfig = findTsconfig(tsconfigPath);
478
- if (!tsconfig) logger.warn(`No tsconfig found in ${blue(tsconfigPath)}`);
479
- } else {
480
- tsconfig = findTsconfig(cwd, tsconfig);
481
- if (!tsconfig) logger.warn(`tsconfig ${blue(original)} doesn't exist`);
482
- }
483
- }
484
- if (tsconfig) logger.info(nameLabel, `tsconfig: ${color(path.relative(cwd, tsconfig))}`);
485
- }
486
- return tsconfig;
487
- }
488
-
489
- //#endregion
490
- //#region src/utils/package.ts
491
- const debug$7 = createDebug("tsdown:package");
492
- async function readPackageJson(dir) {
493
- const packageJsonPath = up$1({ cwd: dir });
494
- if (!packageJsonPath) return;
495
- debug$7("Reading package.json:", packageJsonPath);
496
- const contents = await readFile(packageJsonPath, "utf8");
497
- return {
498
- ...JSON.parse(contents),
499
- packageJsonPath
500
- };
501
- }
502
- function getPackageType(pkg) {
503
- if (pkg?.type) {
504
- if (!["module", "commonjs"].includes(pkg.type)) throw new Error(`Invalid package.json type: ${pkg.type}`);
505
- return pkg.type;
506
- }
507
- }
508
- function normalizeFormat(format) {
509
- switch (format) {
510
- case "es":
511
- case "esm":
512
- case "module": return "es";
513
- case "cjs":
514
- case "commonjs": return "cjs";
515
- default: return format;
516
- }
517
- }
518
-
519
- //#endregion
520
- //#region src/config/options.ts
521
- const debugLog = createDebug("tsdown:config:options");
522
- async function resolveUserConfig(userConfig, inlineConfig) {
523
- let { entry, format = ["es"], plugins = [], clean = true, silent = false, logLevel = silent ? "silent" : "info", failOnWarn = "ci-only", customLogger, treeshake = true, platform = "node", outDir = "dist", sourcemap = false, dts, unused = false, watch: watch$1 = false, ignoreWatch, shims = false, skipNodeModulesBundle = false, publint: publint$1 = false, attw: attw$1 = false, fromVite, alias, tsconfig, report = true, target, env: env$1 = {}, envFile, envPrefix = "TSDOWN_", copy: copy$1, publicDir, hash = true, cwd = process.cwd(), name, workspace, external, noExternal, exports = false, bundle, unbundle = typeof bundle === "boolean" ? !bundle : false, removeNodeProtocol, nodeProtocol, cjsDefault = true, globImport = true, inlineOnly, fixedExtension = platform === "node", debug: debug$10 = false, write = true } = userConfig;
524
- const pkg = await readPackageJson(cwd);
525
- if (workspace) name ||= pkg?.name;
526
- const color = generateColor(name);
527
- const nameLabel = getNameLabel(color, name);
528
- if (!filterConfig(inlineConfig.filter, cwd, name)) {
529
- debugLog("[filter] skipping config %s", cwd);
530
- return [];
531
- }
532
- const logger = createLogger(logLevel, {
533
- customLogger,
534
- failOnWarn: resolveFeatureOption(failOnWarn, true)
535
- });
536
- if (typeof bundle === "boolean") logger.warn("`bundle` option is deprecated. Use `unbundle` instead.");
537
- if (removeNodeProtocol && nodeProtocol) throw new TypeError("`removeNodeProtocol` is deprecated. Please only use `nodeProtocol` instead.");
538
- nodeProtocol = nodeProtocol ?? (removeNodeProtocol ? "strip" : false);
539
- outDir = path.resolve(cwd, outDir);
540
- clean = resolveClean(clean, outDir, cwd);
541
- const resolvedEntry = await resolveEntry(logger, entry, cwd, color, nameLabel);
542
- if (dts == null) dts = !!(pkg?.types || pkg?.typings || hasExportsTypes(pkg));
543
- target = resolveTarget(logger, target, color, pkg, nameLabel);
544
- tsconfig = await resolveTsconfig(logger, tsconfig, cwd, color, nameLabel);
545
- if (typeof external === "string") external = resolveRegex(external);
546
- if (typeof noExternal === "string") noExternal = resolveRegex(noExternal);
547
- publint$1 = resolveFeatureOption(publint$1, {});
548
- attw$1 = resolveFeatureOption(attw$1, {});
549
- exports = resolveFeatureOption(exports, {});
550
- unused = resolveFeatureOption(unused, {});
551
- report = resolveFeatureOption(report, {});
552
- dts = resolveFeatureOption(dts, {});
553
- if (!pkg) {
554
- if (exports) throw new Error("`package.json` not found, cannot write exports");
555
- if (publint$1) logger.warn(nameLabel, "publint is enabled but package.json is not found");
556
- if (attw$1) logger.warn(nameLabel, "attw is enabled but package.json is not found");
557
- }
558
- if (publicDir) if (copy$1) throw new TypeError("`publicDir` is deprecated. Cannot be used with `copy`");
559
- else logger.warn(`${blue`publicDir`} is deprecated. Use ${blue`copy`} instead.`);
560
- envPrefix = toArray(envPrefix);
561
- if (envPrefix.includes("")) logger.warn("`envPrefix` includes an empty string; filtering is disabled. All environment variables from the env file and process.env will be injected into the build. Ensure this is intended to avoid accidental leakage of sensitive information.");
562
- const envFromProcess = filterEnv(process.env, envPrefix);
563
- if (envFile) {
564
- const resolvedPath = path.resolve(cwd, envFile);
565
- logger.info(nameLabel, `env file: ${color(resolvedPath)}`);
566
- env$1 = {
567
- ...filterEnv(parseEnv(await readFile(resolvedPath, "utf8")), envPrefix),
568
- ...envFromProcess,
569
- ...env$1
570
- };
571
- } else env$1 = {
572
- ...envFromProcess,
573
- ...env$1
574
- };
575
- debugLog(`Environment variables: %O`, env$1);
576
- if (fromVite) {
577
- const viteUserConfig = await loadViteConfig(fromVite === true ? "vite" : fromVite, cwd, inlineConfig.configLoader);
578
- if (viteUserConfig) {
579
- const viteAlias = viteUserConfig.resolve?.alias;
580
- if (Array.isArray(viteAlias)) throw new TypeError("Unsupported resolve.alias in Vite config. Use object instead of array");
581
- if (viteAlias) alias = {
582
- ...alias,
583
- ...viteAlias
584
- };
585
- if (viteUserConfig.plugins) plugins = [viteUserConfig.plugins, plugins];
586
- }
587
- }
588
- ignoreWatch = toArray(ignoreWatch).map((ignore) => {
589
- ignore = resolveRegex(ignore);
590
- if (typeof ignore === "string") return path.resolve(cwd, ignore);
591
- return ignore;
592
- });
593
- if (noExternal != null && typeof noExternal !== "function") {
594
- const noExternalPatterns = toArray(noExternal);
595
- noExternal = (id) => matchPattern(id, noExternalPatterns);
596
- }
597
- if (inlineOnly != null) inlineOnly = toArray(inlineOnly);
598
- debug$10 = resolveFeatureOption(debug$10, {});
599
- if (debug$10) if (watch$1) {
600
- if (debug$10.devtools) logger.warn("Devtools is not supported in watch mode, disabling it.");
601
- debug$10.devtools = false;
602
- } else debug$10.devtools ??= !!pkgExists("@vitejs/devtools/cli");
603
- const config = {
604
- ...userConfig,
605
- alias,
606
- attw: attw$1,
607
- cjsDefault,
608
- clean,
609
- copy: publicDir || copy$1,
610
- cwd,
611
- debug: debug$10,
612
- dts,
613
- entry: resolvedEntry,
614
- env: env$1,
615
- exports,
616
- external,
617
- fixedExtension,
618
- globImport,
619
- hash,
620
- ignoreWatch,
621
- inlineOnly,
622
- logger,
623
- name,
624
- nameLabel,
625
- nodeProtocol,
626
- noExternal,
627
- outDir,
628
- pkg,
629
- platform,
630
- plugins,
631
- publint: publint$1,
632
- report,
633
- shims,
634
- skipNodeModulesBundle,
635
- sourcemap,
636
- target,
637
- treeshake,
638
- tsconfig,
639
- unbundle,
640
- unused,
641
- watch: watch$1,
642
- write
643
- };
644
- const objectFormat = typeof format === "object" && !Array.isArray(format);
645
- return (objectFormat ? Object.keys(format) : resolveComma(toArray(format, "es"))).map((fmt, idx) => {
646
- const once = idx === 0;
647
- const overrides = objectFormat ? format[fmt] : void 0;
648
- return {
649
- ...config,
650
- copy: once ? config.copy : void 0,
651
- onSuccess: once ? config.onSuccess : void 0,
652
- format: normalizeFormat(fmt),
653
- ...overrides
654
- };
655
- });
656
- }
657
- /** filter env variables by prefixes */
658
- function filterEnv(envDict, envPrefixes) {
659
- const env$1 = {};
660
- for (const [key, value] of Object.entries(envDict)) if (envPrefixes.some((prefix) => key.startsWith(prefix)) && value !== void 0) env$1[key] = value;
661
- return env$1;
662
- }
663
- const defu = createDefu((obj, key, value) => {
664
- if (Array.isArray(obj[key]) && Array.isArray(value)) {
665
- obj[key] = value;
666
- return true;
667
- }
668
- });
669
- async function mergeUserOptions(defaults, user, args) {
670
- const userOutputOptions = typeof user === "function" ? await user(defaults, ...args) : user;
671
- if (!userOutputOptions) return defaults;
672
- return defu(userOutputOptions, defaults);
673
- }
674
- function resolveFeatureOption(value, defaults) {
675
- if (typeof value === "object" && value !== null) return resolveCIOption(value.enabled ?? true) ? value : false;
676
- return resolveCIOption(value) ? defaults : false;
677
- }
678
- function resolveCIOption(value) {
679
- if (value === "ci-only") return is_in_ci_default ? true : false;
680
- if (value === "local-only") return is_in_ci_default ? false : true;
681
- return value;
682
- }
683
- function filterConfig(filter, configCwd, name) {
684
- if (!filter) return true;
685
- let cwd = path.relative(process.cwd(), configCwd);
686
- if (cwd === "") cwd = ".";
687
- if (filter instanceof RegExp) return name && filter.test(name) || filter.test(cwd);
688
- return toArray(filter).some((value) => name && name === value || cwd === value);
689
- }
690
-
691
- //#endregion
692
30
  //#region src/config/workspace.ts
693
31
  const debug$6 = createDebug("tsdown:config:workspace");
694
32
  const DEFAULT_EXCLUDE_WORKSPACE = [
@@ -906,7 +244,7 @@ async function attw(options) {
906
244
  const t = performance.now();
907
245
  debug$4("Running attw check");
908
246
  const tempDir = await mkdtemp(path.join(tmpdir(), "tsdown-attw-"));
909
- const attwCore = await importWithError("@arethetypeswrong/core");
247
+ const attwCore = await importWithError("@arethetypeswrong/core", options.attw.resolvePaths);
910
248
  let checkResult;
911
249
  try {
912
250
  const { stdout: tarballInfo } = await exec("npm", [
@@ -976,8 +314,8 @@ async function publint(options) {
976
314
  }
977
315
  const t = performance.now();
978
316
  debug$3("Running publint");
979
- const { publint: publint$1 } = await importWithError("publint");
980
- const { formatMessage } = await import("publint/utils");
317
+ const { publint: publint$1 } = await importWithError("publint", options.publint.resolvePaths);
318
+ const { formatMessage } = await importWithError("publint/utils", options.publint.resolvePaths);
981
319
  const { messages } = await publint$1({
982
320
  ...options.publint,
983
321
  pkgDir: path.dirname(options.pkg.packageJsonPath)
@@ -1404,7 +742,7 @@ async function getBuildOptions(config, format, configFiles, bundle, cjsDts = fal
1404
742
  return rolldownConfig;
1405
743
  }
1406
744
  async function resolveInputOptions(config, format, configFiles, bundle, cjsDts, isDualFormat) {
1407
- const { alias, cjsDefault, cwd, debug: debug$10, dts, entry, env: env$1, external, globImport, loader, logger, nameLabel, nodeProtocol, platform, plugins: userPlugins, report, shims, target, treeshake, tsconfig, unused, watch: watch$1 } = config;
745
+ const { alias, cjsDefault, cwd, debug: debug$7, dts, entry, env: env$1, external, globImport, loader, logger, nameLabel, nodeProtocol, platform, plugins: userPlugins, report, shims, target, treeshake, tsconfig, unused, watch: watch$1 } = config;
1408
746
  const plugins = [];
1409
747
  if (nodeProtocol) plugins.push(NodeProtocolPlugin(nodeProtocol));
1410
748
  if (config.pkg || config.skipNodeModulesBundle) plugins.push(ExternalPlugin(config));
@@ -1430,6 +768,8 @@ async function resolveInputOptions(config, format, configFiles, bundle, cjsDts,
1430
768
  }));
1431
769
  }
1432
770
  if (target) plugins.push(await LightningCSSPlugin({ target }));
771
+ const cssPlugin = CssCodeSplitPlugin(config);
772
+ if (cssPlugin) plugins.push(cssPlugin);
1433
773
  plugins.push(ShebangPlugin(logger, cwd, nameLabel, isDualFormat));
1434
774
  if (globImport) plugins.push(importGlobPlugin({ root: cwd }));
1435
775
  }
@@ -1466,7 +806,7 @@ async function resolveInputOptions(config, format, configFiles, bundle, cjsDts,
1466
806
  if (log.code === "MIXED_EXPORT") return;
1467
807
  defaultHandler(level, log);
1468
808
  } : void 0,
1469
- debug: debug$10 || void 0,
809
+ debug: debug$7 || void 0,
1470
810
  checks: { pluginTimings: false }
1471
811
  }, config.inputOptions, [format, { cjsDts }]);
1472
812
  }