-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathauto.ts
171 lines (153 loc) · 4.91 KB
/
auto.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import { existsSync } from "node:fs";
import { normalize, join, resolve } from "pathe";
import { consola } from "consola";
import chalk from "chalk";
import type { PackageJson } from "pkg-types";
import { extractExportFilenames, listRecursively, warn } from "./utils";
import { BuildEntry, definePreset, MkdistBuildEntry } from "./types";
type InferEntriesResult = {
entries: BuildEntry[];
cjs?: boolean;
dts?: boolean;
warnings: string[];
};
export const autoPreset = definePreset(() => {
return {
hooks: {
"build:prepare"(ctx) {
// Disable auto if entries already provided of pkg not available
if (!ctx.pkg || ctx.options.entries.length > 0) {
return;
}
const sourceFiles = listRecursively(join(ctx.options.rootDir, "src"));
const res = inferEntries(ctx.pkg, sourceFiles, ctx.options.rootDir);
for (const message of res.warnings) {
warn(ctx, message);
}
ctx.options.entries.push(...res.entries);
if (res.cjs) {
ctx.options.rollup.emitCJS = true;
}
if (res.dts) {
ctx.options.declaration = res.dts;
}
consola.info(
"Automatically detected entries:",
chalk.cyan(
ctx.options.entries
.map((e) =>
chalk.bold(
e.input
.replace(ctx.options.rootDir + "/", "")
.replace(/\/$/, "/*"),
),
)
.join(", "),
),
chalk.gray(
["esm", res.cjs && "cjs", res.dts && "dts"]
.filter(Boolean)
.map((tag) => `[${tag}]`)
.join(" "),
),
);
},
},
};
});
/**
* @param {PackageJson} pkg The contents of a package.json file to serve as the source for inferred entries.
* @param {string[]} sourceFiles A list of source files to use for inferring entries.
* @param {string | undefined} rootDir The root directory of the project.
*/
export function inferEntries(
pkg: PackageJson,
sourceFiles: string[],
rootDir?: string,
): InferEntriesResult {
const warnings = [];
// Sort files so least-nested files are first
sourceFiles.sort((a, b) => a.split("/").length - b.split("/").length);
// Come up with a list of all output files & their formats
const outputs = extractExportFilenames(pkg.exports);
if (pkg.bin) {
const binaries =
typeof pkg.bin === "string" ? [pkg.bin] : Object.values(pkg.bin);
for (const file of binaries) {
outputs.push({ file });
}
}
if (pkg.main) {
outputs.push({ file: pkg.main });
}
if (pkg.module) {
outputs.push({ type: "esm", file: pkg.module });
}
if (pkg.types || pkg.typings) {
outputs.push({ file: pkg.types || pkg.typings! });
}
// Try to detect output types
const isESMPkg = pkg.type === "module";
for (const output of outputs.filter((o) => !o.type)) {
const isJS = output.file.endsWith(".js");
if ((isESMPkg && isJS) || output.file.endsWith(".mjs")) {
output.type = "esm";
} else if ((!isESMPkg && isJS) || output.file.endsWith(".cjs")) {
output.type = "cjs";
}
}
let cjs = false;
let dts = false;
// Infer entries from package files
const entries: BuildEntry[] = [];
for (const output of outputs) {
// Supported output file extensions are `.d.ts`, `.cjs` and `.mjs`
// But we support any file extension here in case user has extended rollup options
const outputSlug = output.file.replace(
/(\*[^/\\]*|\.d\.(m|c)?ts|\.\w+)$/,
"",
);
const isDir = outputSlug.endsWith("/");
// Skip top level directory
if (isDir && ["./", "/"].includes(outputSlug)) {
continue;
}
const possiblePaths = getEntrypointPaths(outputSlug);
// eslint-disable-next-line unicorn/no-array-reduce
const input = possiblePaths.reduce<string | undefined>((source, d) => {
if (source) {
return source;
}
const SOURCE_RE = new RegExp(`(?<=/|$)${d}${isDir ? "" : "\\.\\w+"}$`);
return sourceFiles
.find((i) => SOURCE_RE.test(i))
?.replace(/(\.d\.(m|c)?ts|\.\w+)$/, "");
}, undefined as any);
if (!input) {
if (!existsSync(resolve(rootDir || ".", output.file))) {
warnings.push(`Could not find entrypoint for \`${output.file}\``);
}
continue;
}
if (output.type === "cjs") {
cjs = true;
}
const entry =
entries.find((i) => i.input === input) ||
entries[entries.push({ input }) - 1];
if (/\.d\.(m|c)?ts$/.test(output.file)) {
dts = true;
}
if (isDir) {
entry.outDir = outputSlug;
(entry as MkdistBuildEntry).format = output.type;
}
}
return { entries, cjs, dts, warnings };
}
export const getEntrypointPaths = (path: string) => {
const segments = normalize(path).split("/");
return segments
.map((_, index) => segments.slice(index).join("/"))
.filter(Boolean);
};