Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 0 additions & 10 deletions build.config.ts

This file was deleted.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
"oxc-minify": "^0.72.2",
"oxc-parser": "^0.72.2",
"oxc-transform": "^0.72.2",
"pathe": "^2.0.3",
"pkg-types": "^2.1.0",
"pretty-bytes": "^7.0.0",
"rolldown": "1.0.0-beta.10",
"rolldown-plugin-dts": "^0.13.7",
Expand Down
9 changes: 9 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

117 changes: 117 additions & 0 deletions src/auto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { existsSync } from "node:fs";
import type { PackageJson } from "pkg-types";
import type { BuildEntry } from "./types.ts";
import { normalize, resolve } from "pathe";
import { extractExportFilenames } from "./utils.ts";

type InferEntriesResult = {
entries: BuildEntry[];
dts?: boolean;
warnings: string[];
};

/**
* @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";
}
}

let dts = false;

// Infer entries from package files
const entries: BuildEntry[] = [];
for (const output of outputs) {
// Supported output file extensions are `.d.ts`, and `.mjs`
// But we support any file extension here in case user has extended rolldown options
const outputSlug = output.file.replace(
/(\*[^/\\]*|\.d\.(m)?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 ? "" : String.raw`\.\w+`}$`,
);
return sourceFiles
.find((i) => SOURCE_RE.test(i))
?.replace(/(\.d\.(m)?ts|\.\w+)$/, "");
}, undefined as any);

if (!input) {
if (!existsSync(resolve(rootDir || ".", output.file))) {
warnings.push(`Could not find entrypoint for \`${output.file}\``);
}
continue;
}

const entry =
entries.find((i) => i.input === input) ||
entries[entries.push({ input, type: 'bundle' }) - 1];

if (/\.d\.(m)?ts$/.test(output.file)) {
dts = true;
}

if (isDir) {
entry.outDir = outputSlug;
}
}

return { entries, dts, warnings };
}

export const getEntrypointPaths = (path: string): string[] => {
const segments = normalize(path).split("/");
return segments
.map((_, index) => segments.slice(index).join("/"))
.filter(Boolean);
};
6 changes: 4 additions & 2 deletions src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,16 @@ import type {
} from "./types.ts";

import { fileURLToPath } from "node:url";
import { isAbsolute, join, resolve } from "node:path";
import { isAbsolute, resolve } from "pathe";
import { rm } from "node:fs/promises";
import { consola } from "consola";
import { colors as c } from "consola/utils";
import { rolldownBuild } from "./builders/bundle.ts";
import { transformDir } from "./builders/transform.ts";
import { fmtPath, analyzeDir } from "./utils.ts";
import prettyBytes from "pretty-bytes";
import { readPackageJSON } from "pkg-types";
import type { PackageJson } from "pkg-types";

/**
* Build dist/ from src/
Expand All @@ -22,7 +24,7 @@ export async function build(config: BuildConfig): Promise<void> {
const start = Date.now();

const pkgDir = normalizePath(config.cwd);
const pkg = await readJSON(join(pkgDir, "package.json")).catch(() => ({}));
const pkg = (await readPackageJSON(pkgDir)) || {} as PackageJson;
const ctx: BuildContext = { pkg, pkgDir };

consola.log(
Expand Down
2 changes: 1 addition & 1 deletion src/builders/bundle.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { builtinModules } from "node:module";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname, relative, join, basename, extname, resolve } from "node:path";
import { dirname, relative, join, basename, extname, resolve } from "pathe";
import { consola } from "consola";
import { colors as c } from "consola/utils";
import { rolldown } from "rolldown";
Expand Down
2 changes: 1 addition & 1 deletion src/builders/plugins/shebang.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Ported from https://github.com/unjs/unbuild/blob/main/src/builders/rollup/plugins/shebang.ts

import { promises as fsp } from "node:fs";
import { resolve } from "node:path";
import { resolve } from "pathe";
import type { Plugin } from "rolldown";

export const SHEBANG_RE: RegExp = /^#![^\n]*/;
Expand Down
2 changes: 1 addition & 1 deletion src/builders/transform.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { BuildContext, TransformEntry } from "../types.ts";

import { pathToFileURL } from "node:url";
import { dirname, extname, join, relative } from "node:path";
import { dirname, extname, join, relative } from "pathe";
import { mkdir, readFile, symlink, writeFile } from "node:fs/promises";
import { consola } from "consola";
import { colors as c } from "consola/utils";
Expand Down
43 changes: 40 additions & 3 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,15 @@

import { parseArgs } from "node:util";
import { consola } from "consola";
import { build } from "./build.ts";
import { loadConfig } from "c12";
import { readPackageJSON } from 'pkg-types'
import { join, resolve } from "pathe";
import { colors } from "consola/utils";

import type { BuildConfig, BuildEntry } from "./types.ts";
import { build } from "./build.ts";
import { inferEntries } from "./auto.ts";
import { listRecursively } from "./utils.ts";

// https://nodejs.org/api/util.html#utilparseargsconfig
const args = parseArgs({
Expand Down Expand Up @@ -51,8 +56,40 @@ if (args.values.stub) {
}

if (rawEntries.length === 0) {
consola.error("No build entries specified.");
process.exit(1);
// If no entries are specified, infer them from the package.json
const pkgDir = resolve(process.cwd())
const pkg = await readPackageJSON(pkgDir)
const sourceFiles = listRecursively(join(pkgDir, "src"));
const res = inferEntries(pkg, sourceFiles, process.cwd())
entries.push({
type: 'bundle',
input: res.entries.map((entry) => entry.input as string),
dts: res.dts,
})
if (entries.length === 0) {
consola.error("No build entries specified.");
process.exit(1);
}
consola.log(
"🔍️Automatically detected entries ",
colors.cyan(
res.entries
.map((e) =>
colors.bold(
(e.input as string)
.replace(resolve(process.cwd()) + "/", "")
.replace(/\/$/, "/*"),
),
)
.join(", "),
),
colors.gray(
["esm", res.dts && "dts"]
.filter(Boolean)
.map((tag) => `[${tag}]`)
.join(" "),
),
);
}

await build({
Expand Down
10 changes: 9 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ import type { Options as DtsOptions } from "rolldown-plugin-dts";
import type { TransformOptions } from "oxc-transform";
import type { MinifyOptions as OXCMinifyOptions } from "oxc-minify";
import type { ResolveOptions } from "exsolve";
import type { PackageJson } from "pkg-types";

export interface BuildContext {
pkgDir: string;
pkg: { name: string } & Record<string, unknown>;
pkg: PackageJson;
}

export type _BuildEntry = {
Expand Down Expand Up @@ -62,6 +63,13 @@ export type BundleEntry = _BuildEntry & {
* Set to `false` to disable.
*/
dts?: boolean | DtsOptions;

/**
* Generate a CommonJS bundle.
*
* Defaults to `false` if not provided.
*/
cjs?: boolean;
};

export type TransformEntry = _BuildEntry & {
Expand Down
84 changes: 82 additions & 2 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { readdirSync, statSync } from "node:fs";
import { join, resolve } from "node:path";
import { gzipSync } from "node:zlib";

import { join, resolve } from "pathe";
import { type Plugin, rolldown } from "rolldown";
import { minify } from "oxc-minify";
import { gzipSync } from "node:zlib";
import type { PackageJson } from "pkg-types";

export function fmtPath(path: string): string {
return resolve(path).replace(process.cwd(), ".");
Expand Down Expand Up @@ -112,3 +113,82 @@ export async function sideEffectSize(

return Buffer.byteLength(output[0].code.trim());
}

export function listRecursively(path: string): string[] {
const filenames = new Set<string>();
const walk = (path: string): void => {
const files = readdirSync(path);
for (const file of files) {
const fullPath = resolve(path, file);
if (statSync(fullPath).isDirectory()) {
filenames.add(fullPath + "/");
walk(fullPath);
} else {
filenames.add(fullPath);
}
}
};
walk(path);
return [...filenames];
}

export function inferExportType(
condition: string,
previousConditions: string[] = [],
filename = "",
): "esm" | "cjs" {
if (filename) {
if (filename.endsWith(".d.ts")) {
return "esm";
}
if (filename.endsWith(".mjs")) {
return "esm";
}
if (filename.endsWith(".cjs")) {
return "cjs";
}
}
switch (condition) {
case "import": {
return "esm";
}
case "require": {
return "cjs";
}
default: {
if (previousConditions.length === 0) {
// TODO: Check against type:module for default
return "esm";
}
const [newCondition, ...rest] = previousConditions;
return inferExportType(newCondition, rest, filename);
}
}
}

export type OutputDescriptor = { file: string; type?: "esm" | "cjs" };

export function extractExportFilenames(
exports: PackageJson["exports"],
conditions: string[] = [],
): OutputDescriptor[] {
if (!exports) {
return [];
}
if (typeof exports === "string") {
return [{ file: exports, type: "esm" }];
}
return (
Object.entries(exports)
// Filter out .json subpaths such as package.json
.filter(([subpath]) => !subpath.endsWith(".json"))
.flatMap(([condition, exports]) =>
typeof exports === "string"
? {
file: exports,
type: inferExportType(condition, conditions, exports),
}
: extractExportFilenames(exports, [...conditions, condition]),
)
);
}
Loading