Skip to content
Merged
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
5 changes: 2 additions & 3 deletions package-lock.json

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

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@
"eslint-plugin-self": "^1.2.1",
"eslint-plugin-testing-library": "^7.16.2",
"globals": "^17.6.0",
"typescript-eslint": "^8.59.4"
"typescript-eslint": "^8.59.4",
"unrs-resolver": "^1.12.2"
},
"devDependencies": {
"@types/jest": "^30.0.0",
Expand Down
60 changes: 60 additions & 0 deletions src/bundle.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import fs from 'node:fs';
import {createRequire} from 'node:module';
import path from 'node:path';
import {execFileSync} from 'node:child_process';

const requireFromTest = createRequire(__filename);

function buildBundle(): string {
execFileSync('npm', ['run', 'build'], {
cwd: path.resolve(__dirname, '..'),
stdio: 'pipe',
});

return path.resolve(__dirname, '../dist/index.cjs');
}

describe('published bundle', () => {
it('inlines metadata for bundled plugins that read their own package.json', () => {
const bundlePath = buildBundle();
const bundle = fs.readFileSync(bundlePath, 'utf8');

expect(bundle).not.toContain('cjsRequire("../package.json")');

const sandboxRoot = path.resolve(__dirname, '../.tmp');

fs.mkdirSync(sandboxRoot, {recursive: true});

const sandbox = fs.mkdtempSync(path.join(sandboxRoot, 'croct-eslint-plugin-'));
const packageDir = path.join(sandbox, 'node_modules/@croct/eslint-plugin');
const distDir = path.join(packageDir, 'dist');

fs.mkdirSync(distDir, {recursive: true});
fs.copyFileSync(bundlePath, path.join(distDir, 'index.cjs'));
fs.writeFileSync(
path.join(packageDir, 'package.json'),
JSON.stringify({name: '@croct/eslint-plugin', version: '0.0.0-dev', main: 'dist/index.cjs'}),
);

const script = [
`const plugin = require(${JSON.stringify(packageDir)});`,
'const javascriptConfig = plugin.configs.javascript.at(-1);',
'process.stdout.write(JSON.stringify(javascriptConfig.plugins[\'import-x\'].meta));',
].join('\n');

const meta = execFileSync(
'node',
['-e', script],
{cwd: path.resolve(__dirname, '..'), encoding: 'utf8'},
);

const importXPackageJson = JSON.parse(
fs.readFileSync(requireFromTest.resolve('eslint-plugin-import-x/package.json'), 'utf8'),
) as {name: string, version: string};

expect(JSON.parse(meta)).toEqual({
name: importXPackageJson.name,
version: importXPackageJson.version,
});
});
});
104 changes: 104 additions & 0 deletions tsdown.config.mts
Original file line number Diff line number Diff line change
@@ -1,11 +1,115 @@
import { defineConfig } from 'tsdown';
import fs from 'node:fs';
import path from 'node:path';
import {parseAst} from 'rolldown/parseAst';

type AstNode = {
type?: string;
start?: number;
end?: number;
name?: string;
value?: unknown;
callee?: AstNode;
arguments?: AstNode[];
[key: string]: unknown;
};

type Replacement = {
start: number;
end: number;
value: string;
};

function isNode(value: unknown): value is AstNode {
return typeof value === 'object' && value !== null && typeof (value as AstNode).type === 'string';
}

function isNodeArray(value: unknown): value is AstNode[] {
return Array.isArray(value) && value.every(isNode);
}

function isBundledDependency(id: string): boolean {
return id.includes('/node_modules/') || id.includes('\\node_modules\\');
}

function isPackageJsonSpecifier(value: unknown): value is string {
return typeof value === 'string' && value.startsWith('.') && path.basename(value) === 'package.json';
}

function findPackageJsonRequires(node: AstNode, visitor: (node: AstNode, specifier: string) => void): void {
if (
node.type === 'CallExpression'
&& node.callee?.type === 'Identifier'
&& (node.callee.name === 'cjsRequire' || node.callee.name === 'require')
&& node.arguments?.length === 1
&& node.arguments[0]?.type === 'Literal'
&& isPackageJsonSpecifier(node.arguments[0].value)
) {
visitor(node, node.arguments[0].value);
}

for (const value of Object.values(node)) {
if (isNode(value)) {
findPackageJsonRequires(value, visitor);
} else if (isNodeArray(value)) {
for (const child of value) {
findPackageJsonRequires(child, visitor);
}
}
}
}

function applyReplacements(code: string, replacements: Replacement[]): string {
return replacements
.sort((first, second) => second.start - first.start)
.reduce(
(result, replacement) => (
result.slice(0, replacement.start) + replacement.value + result.slice(replacement.end)
),
code,
);
}

function inlineBundledPackageJson() {
return {
name: 'inline-bundled-package-json',
transform(code: string, id: string, meta: {ast?: AstNode} = {}) {
if (!isBundledDependency(id) || !code.includes('package.json')) {
return null;
}

const ast = meta.ast ?? parseAst(code, null, id) as AstNode;
const replacements: Replacement[] = [];

findPackageJsonRequires(ast, (node, specifier) => {
if (node.start === undefined || node.end === undefined) {
return;
}

const packageJsonPath = path.resolve(path.dirname(id), specifier);

if (!fs.existsSync(packageJsonPath)) {
return;
}

replacements.push({
start: node.start,
end: node.end,
value: JSON.stringify(JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))),
});
});

return replacements.length > 0 ? applyReplacements(code, replacements) : null;
},
};
}

export default defineConfig({
entry: ['src/index.ts'],
format: 'cjs',
dts: true,
platform: 'node',
plugins: [inlineBundledPackageJson()],
alias: {
// Redirect to a shim that statically resolves rules
// (the original uses `requireindex` which breaks in bundles)
Expand Down
Loading