Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
privatenumber committed Dec 20, 2023
1 parent 48e0fdc commit a120c2f
Show file tree
Hide file tree
Showing 24 changed files with 284 additions and 119 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@
"files": [
"dist"
],
"bin": "./dist/cli.js",
"imports": {
"typescript": "./src/local-typescript-loader.ts"
},
"bin": "./dist/cli.js",
"scripts": {
"build": "tsx src/cli.ts --minify --target node18",
"test": "pnpm build && tsx tests/index.ts",
Expand Down
16 changes: 10 additions & 6 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,19 +48,22 @@ const argv = cli({
default: false,
},
env: {
type: [function Env(flagValue: string) {
const [key, value] = flagValue.split('=');
return { key, value };
}],
type: [
(flagValue: string) => {
const [key, value] = flagValue.split('=');
return { key, value };
},
],
description: 'Compile-time environment variables (eg. --env.NODE_ENV=production)',
},

// TODO: rename to conditions and -C flag like Node.js
exportCondition: {
type: [String],
description: 'Export conditions for resolving dependency export and import maps (eg. --export-condition=node)',
},
sourcemap: {
type(flagValue: string) {
type: (flagValue: string) => {
if (flagValue === '') {
return true;
}
Expand All @@ -76,7 +79,7 @@ const argv = cli({

help: {
description: 'Minimalistic package bundler',
render(nodes, renderers) {
render: (nodes, renderers) => {
renderers.flagOperator = flagData => (
(flagData.name === 'env')
? '.key='
Expand Down Expand Up @@ -128,6 +131,7 @@ if (tsconfigTarget) {
})));

const rollupConfigs = await getRollupConfigs(

/**
* Resolve symlink in source path.
*
Expand Down
4 changes: 2 additions & 2 deletions src/local-typescript-loader.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
function getLocalTypescriptPath() {
const getLocalTypescriptPath = () => {
const cwd = process.cwd();
try {
return require.resolve('typescript', {
Expand All @@ -7,7 +7,7 @@ function getLocalTypescriptPath() {
} catch {
throw new Error(`Could not find \`typescript\` in ${cwd}`);
}
}
};

// eslint-disable-next-line n/global-require
export default require(getLocalTypescriptPath());
14 changes: 7 additions & 7 deletions src/utils/get-rollup-configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ const stripQuery = (url: string) => url.split('?')[0];
type Output = OutputOptions[] & Record<string, OutputOptions>;

const getConfig = {
async type(
type: async (
options: Options,
) {
) => {
const dts = await import('rollup-plugin-dts');

return {
Expand All @@ -56,12 +56,12 @@ const getConfig = {
} satisfies RollupOptions;
},

app(
app: (
options: Options,
aliases: AliasMap,
env: EnvObject,
executablePaths: string[],
) {
) => {
const esbuildConfig = {
target: options.target,
};
Expand Down Expand Up @@ -117,7 +117,7 @@ type RollupConfigs = {
[T in keyof GetConfig]?: Awaited<ReturnType<GetConfig[T]>>;
};

export async function getRollupConfigs(
export const getRollupConfigs = async (
sourceDirectoryPath: string,
distributionDirectoryPath: string,
inputs: {
Expand All @@ -129,7 +129,7 @@ export async function getRollupConfigs(
flags: Options,
aliases: AliasMap,
packageJson: PackageJson,
) {
) => {
const executablePaths = inputs
.filter(({ exportEntry }) => exportEntry.isExecutable)
.map(({ exportEntry }) => exportEntry.outputPath);
Expand Down Expand Up @@ -233,4 +233,4 @@ export async function getRollupConfigs(
}

return configs satisfies Record<string, RollupOptions>;
}
};
12 changes: 6 additions & 6 deletions src/utils/get-source-path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import { fsExists } from './fs-exists.js';

const { stringify } = JSON;

async function tryExtensions(
const tryExtensions = async (
pathWithoutExtension: string,
extensions: readonly string[],
) {
) => {
for (const extension of extensions) {
const pathWithExtension = pathWithoutExtension + extension;
if (await fsExists(pathWithExtension)) {
Expand All @@ -16,7 +16,7 @@ async function tryExtensions(
};
}
}
}
};

const extensionMap = {
'.d.ts': ['.d.ts', '.d.mts', '.d.cts', '.ts', '.mts', '.cts'],
Expand All @@ -29,11 +29,11 @@ const extensionMap = {

const distExtensions = Object.keys(extensionMap) as (keyof typeof extensionMap)[];

export async function getSourcePath(
export const getSourcePath = async (
exportEntry: ExportEntry,
source: string,
dist: string,
) {
) => {
const sourcePathUnresolved = source + exportEntry.outputPath.slice(dist.length);

for (const distExtension of distExtensions) {
Expand All @@ -54,4 +54,4 @@ export async function getSourcePath(
}

throw new Error(`Could not find matching source file for export path ${stringify(exportEntry.outputPath)}`);
}
};
16 changes: 9 additions & 7 deletions src/utils/parse-package-json/get-export-entries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import type { PackageJson } from 'type-fest';
import type { PackageType, ExportEntry } from '../../types.js';
import { normalizePath } from '../normalize-path.js';

const getFileType = (filePath: string): PackageType | undefined => {
const getFileType = (
filePath: string,
): PackageType | undefined => {
if (filePath.endsWith('.mjs')) {
return 'module';
}
Expand All @@ -13,11 +15,11 @@ const getFileType = (filePath: string): PackageType | undefined => {

const isPath = (filePath: string) => filePath.startsWith('.');

function parseExportsMap(
const parseExportsMap = (
exportMap: PackageJson['exports'],
packageType: PackageType,
packagePath = 'exports',
): ExportEntry[] {
): ExportEntry[] => {
if (exportMap) {
if (typeof exportMap === 'string') {
if (isPath(exportMap)) {
Expand Down Expand Up @@ -104,12 +106,12 @@ function parseExportsMap(
}

return [];
}
};

function addExportPath(
const addExportPath = (
exportPathsMap: Record<string, ExportEntry>,
exportEntry: ExportEntry,
) {
) => {
exportEntry.outputPath = normalizePath(exportEntry.outputPath);

const { outputPath: exportPath, type, platform } = exportEntry;
Expand All @@ -128,7 +130,7 @@ function addExportPath(
} else {
exportPathsMap[exportPath] = exportEntry;
}
}
};

export const getExportEntries = (packageJson: PackageJson) => {
const exportEntriesMap: Record<string, ExportEntry> = {};
Expand Down
2 changes: 1 addition & 1 deletion src/utils/rollup-plugins/create-require.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const createRequire = (): Plugin => ({
: null
),

load(id) {
load: (id) => {
if (id !== virtualModuleName) {
return null;
}
Expand Down
58 changes: 29 additions & 29 deletions src/utils/rollup-plugins/esbuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ import { createFilter } from '@rollup/pluginutils';
import { transform, type TransformOptions, type Format } from 'esbuild';
import { tsconfig } from '../tsconfig.js';

export function esbuildTransform(
export const esbuildTransform = (
options?: TransformOptions,
): Plugin {
): Plugin => {
const filter = createFilter(
/\.([cm]?ts|[jt]sx)$/,
);

return {
name: 'esbuild-transform',
async transform(code, id) {
transform: async (code, id) => {
if (!filter(id)) {
return null;
}
Expand All @@ -34,9 +34,11 @@ export function esbuildTransform(
};
},
};
}
};

const getEsbuildFormat = (rollupFormat: InternalModuleFormat): Format | undefined => {
const getEsbuildFormat = (
rollupFormat: InternalModuleFormat,
): Format | undefined => {
if (rollupFormat === 'es') {
return 'esm';
}
Expand All @@ -46,31 +48,29 @@ const getEsbuildFormat = (rollupFormat: InternalModuleFormat): Format | undefine
}
};

export function esbuildMinify(
export const esbuildMinify = (
options?: TransformOptions,
): Plugin {
return {
name: 'esbuild-minify',
async renderChunk(code, _, rollupOptions) {
const result = await transform(code, {
/**
* `target` is used to prevent new minification syntax
* from being used.
*
* https://github.com/evanw/esbuild/releases/tag/v0.14.25#:~:text=Minification%20now%20takes%20advantage%20of%20the%20%3F.%20operator
*/
...options,
): Plugin => ({
name: 'esbuild-minify',
renderChunk: async (code, _, rollupOptions) => {
const result = await transform(code, {
/**
* `target` is used to prevent new minification syntax
* from being used.
*
* https://github.com/evanw/esbuild/releases/tag/v0.14.25#:~:text=Minification%20now%20takes%20advantage%20of%20the%20%3F.%20operator
*/
...options,

// https://github.com/egoist/rollup-plugin-esbuild/issues/317
format: getEsbuildFormat(rollupOptions.format),
// https://github.com/egoist/rollup-plugin-esbuild/issues/317
format: getEsbuildFormat(rollupOptions.format),

minify: true,
});
minify: true,
});

return {
code: result.code,
map: result.map || null,
};
},
};
}
return {
code: result.code,
map: result.map || null,
};
},
});
1 change: 1 addition & 0 deletions src/utils/rollup-plugins/externalize-node-builtins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export const externalizeNodeBuiltins = ({ target }: {
];

return !(

// 12.20.0 <= x < 13.0.0
(
compareSemver(semver, [12, 20, 0]) >= 0
Expand Down
8 changes: 2 additions & 6 deletions src/utils/rollup-plugins/patch-binary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,7 @@ export const patchBinary = (
): Plugin => ({
name: 'patch-binary',

renderChunk(
code,
chunk,
outputOptions,
) {
renderChunk: (code, chunk, outputOptions) => {
if (!chunk.isEntry || !chunk.facadeModuleId) {
return;
}
Expand All @@ -37,7 +33,7 @@ export const patchBinary = (
}
},

async writeBundle(outputOptions, bundle) {
writeBundle: async (outputOptions, bundle) => {
const entryFileNames = outputOptions.entryFileNames as (chunk: OutputChunk) => string;

const chmodFiles = Object.values(bundle).map(async (chunk) => {
Expand Down
10 changes: 8 additions & 2 deletions tests/specs/builds/bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ export default testSuite(({ describe }, nodePath: string) => {
exports: './dist/index.mjs',
});

const pkgrollProcess = await pkgroll([], { cwd: fixture.path, nodePath });
const pkgrollProcess = await pkgroll([], {
cwd: fixture.path,
nodePath,
});

expect(pkgrollProcess.exitCode).toBe(0);
expect(pkgrollProcess.stderr).toBe('');
Expand Down Expand Up @@ -44,7 +47,10 @@ export default testSuite(({ describe }, nodePath: string) => {
},
});

const pkgrollProcess = await pkgroll([], { cwd: fixture.path, nodePath });
const pkgrollProcess = await pkgroll([], {
cwd: fixture.path,
nodePath,
});

expect(pkgrollProcess.exitCode).toBe(0);
expect(pkgrollProcess.stderr).toBe('');
Expand Down
Loading

0 comments on commit a120c2f

Please sign in to comment.