Let esmPlugin accept a package.json, make packageLock optional

This commit is contained in:
Alex Gleason committed 2025-10-06 09:02:41 -05:00
1 parent 5cf0c60b88
commit d0c039b37b
3 files changed
+104 -11

No files matched your search

+32 -10
View File
@@ -13,7 +13,20 @@ interface PackageLock {
};
}
export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
interface PackageJson {
dependencies?: { [key: string]: string };
devDependencies?: { [key: string]: string };
peerDependencies?: { [key: string]: string };
}
interface EsmPluginOptions {
packageJson: PackageJson;
packageLock?: PackageLock;
target?: string;
}
export function esmPlugin(options: EsmPluginOptions): Plugin {
const { packageJson, packageLock, target } = options;
/** Cache of URL redirects */
const redirectedURLs = new Map<string, string>();
@@ -21,9 +34,11 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
const urlLockPath = new Map<string, string>();
/** Build quick indexes from the lockfile */
const packagesEntries = Object.entries(packageLock.packages || {}).filter(
(e): e is [string, NonNullable<PackageLock["packages"][string]>] => Boolean(e[1])
);
const packagesEntries = packageLock
? Object.entries(packageLock.packages || {}).filter(
(e): e is [string, NonNullable<PackageLock["packages"][string]>] => Boolean(e[1])
)
: [];
// Map of `${name}@${version}` -> array of lock paths where that exact install exists
const nameVersionToPaths = new Map<string, string[]>();
@@ -101,10 +116,10 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
const resolveFrom = (lockPath: string | undefined, depName: string): string | undefined => {
const dep = normalizeNameForLock(depName);
const has = (p: string): boolean => Boolean(packageLock.packages?.[p]);
const has = (p: string): boolean => Boolean(packageLock?.packages?.[p]);
// Self-import: if the importer package name matches the requested dep, return the same lock path
if (lockPath) {
if (lockPath && packageLock) {
const importerInfo = packageLock.packages?.[lockPath];
const importerNameFromInfo = importerInfo?.name ? normalizeNameForLock(importerInfo.name) : undefined;
const importerNameFromPath = lockPath.replace(/^.*\bnode_modules\//, "");
@@ -161,7 +176,7 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
if (m) {
const jsrAlias = `@jsr/${m[1]}__${m[2]}`;
// Read importer deps from lockPath
const importerDeps = lockPath ? packageLock.packages?.[lockPath]?.dependencies : undefined;
const importerDeps = lockPath && packageLock ? packageLock.packages?.[lockPath]?.dependencies : undefined;
if (importerDeps && Object.prototype.hasOwnProperty.call(importerDeps, jsrAlias)) {
searchOrder = [jsrAlias, dep];
} else {
@@ -253,11 +268,18 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
const childLockPath = resolveFrom(importerLockPath, packageName);
// Determine CDN name and version
const childInfo = childLockPath ? packageLock.packages?.[childLockPath] : undefined;
const version = childInfo?.version; // exact installed version from lock
const childInfo = childLockPath && packageLock ? packageLock.packages?.[childLockPath] : undefined;
let version = childInfo?.version; // exact installed version from lock
// If no version found in lock file, fall back to package.json
if (!version) {
version = packageJson.dependencies?.[packageName]
?? packageJson.devDependencies?.[packageName]
?? packageJson.peerDependencies?.[packageName];
}
// Decide CDN package name. Prefer explicit @jsr alias, then installed name, then canonical normalized name.
const importerInfo = importerLockPath ? packageLock.packages?.[importerLockPath] : undefined;
const importerInfo = importerLockPath && packageLock ? packageLock.packages?.[importerLockPath] : undefined;
const importerDeps = importerInfo?.dependencies ?? undefined;
// Determine CDN package name
+58
View File
@@ -408,4 +408,62 @@ react@^18.0.0:
expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/package-lock.json', 'utf8');
expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/yarn.lock', 'utf8');
});
it('should use package.json dependencies as fallback when no lock file exists', async () => {
const packageJsonWithDeps = JSON.stringify({
name: "test-project",
dependencies: {
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
});
// Mock required files
vi.mocked(mockFS.readFile)
.mockImplementation(async (path: string) => {
if (path.endsWith('package.json')) {
return packageJsonWithDeps;
}
if (path.endsWith('index.html')) {
return '<html><head></head><body><script src="/src/main.tsx"></script></body></html>';
}
if (path.endsWith('package-lock.json') || path.endsWith('yarn.lock')) {
throw new Error('File not found');
}
throw new Error(`File not found: ${path}`);
});
// Mock stat to indicate no public directory
vi.mocked(mockFS.stat)
.mockImplementation(async (path: string) => {
if (path === '/test/project/public') {
throw new Error('Directory not found');
}
return { isDirectory: () => false, isFile: () => true };
});
// Mock additional filesystem operations for buildProject
vi.mocked(mockFS.readdir).mockImplementation(async (path: string) => {
if (path === '/test/project/dist') {
return [];
}
return [];
});
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
const result = await buildProject({
fs: mockFS,
projectPath: '/test/project',
domParser: mockDOMParser,
});
// Should successfully build using package.json dependencies
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3]));
expect(result.files['index.html']).toBeDefined();
// Verify package.json was read
expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/package.json', 'utf8');
});
});
+14 -1
View File
@@ -30,14 +30,23 @@ async function bundle(
"utf8",
);
// Read package.json
const packageJsonText = await fs.readFile(
`${projectPath}/package.json`,
"utf8",
);
const packageJson = JSON.parse(packageJsonText);
// Try to read package-lock.json first, fall back to yarn.lock
let packageLock;
let buildMode: string;
try {
const packageLockText = await fs.readFile(
`${projectPath}/package-lock.json`,
"utf8",
);
packageLock = JSON.parse(packageLockText);
buildMode = "npm (package-lock.json)";
} catch {
// If package-lock.json doesn't exist, try yarn.lock
try {
@@ -46,12 +55,16 @@ async function bundle(
"utf8",
);
packageLock = convertYarnLockToPackageLock(yarnLockText);
buildMode = "yarn (yarn.lock)";
} catch {
// If neither exists, use empty packages object
packageLock = { packages: {} };
buildMode = "package.json only (no lock file)";
}
}
console.log(`Building with ${buildMode}`);
const doc = domParser.parseFromString(indexHtmlText, "text/html");
const entryPoints: string[] = [];
const entryScripts: Record<string, HTMLScriptElement> = {};
@@ -99,7 +112,7 @@ async function bundle(
plugins: [
shakespearePlugin(),
fsPlugin(fs, `${projectPath}/src`),
esmPlugin(packageLock, target),
esmPlugin({ packageJson, packageLock, target }),
],
define: {
"import.meta.env": JSON.stringify({}),