Add pnpm lockfile support

This commit is contained in:
Alex Gleason committed 2025-10-16 13:41:47 -05:00
1 parent d87700e731
commit cbf55c9117
7 files changed
+753 -19

No files matched your search

+1 -1
View File
@@ -325,7 +325,7 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
? `${cdnName}@${version}${packagePath}`
: `${cdnName}${packagePath}`;
const url = new URL(`${esmUrl}/*${specifier}`);
const url = new URL(`${esmUrl}/${specifier}`);
if (target) url.searchParams.set("target", target);
if (childLockPath) url.searchParams.set("lp", encodeURIComponent(childLockPath));
+61 -17
View File
@@ -9,6 +9,7 @@ import { esmPlugin } from "./esmPlugin";
import { fsPlugin } from "./fsPlugin";
import { sveltePlugin } from "./sveltePlugin";
import { convertYarnLockToPackageLock } from "./yarnLockConverter";
import { convertPnpmLockToPackageLock } from "./pnpmLockConverter";
import type { JSRuntimeFS } from '@/lib/JSRuntime';
@@ -105,7 +106,7 @@ async function bundleSvelteKit(
console.log('Merged Svelte aliases into tsconfig paths:', tsconfig.compilerOptions.paths);
}
// Try to read package-lock.json first, fall back to yarn.lock
// Try to read package-lock.json first, fall back to yarn.lock, then pnpm-lock.yaml
let packageLock;
let buildMode: string;
try {
@@ -124,8 +125,17 @@ async function bundleSvelteKit(
packageLock = convertYarnLockToPackageLock(yarnLockText);
buildMode = "yarn (yarn.lock)";
} catch {
packageLock = { packages: {} };
buildMode = "package.json only (no lock file)";
try {
const pnpmLockText = await fs.readFile(
`${projectPath}/pnpm-lock.yaml`,
"utf8",
);
packageLock = convertPnpmLockToPackageLock(pnpmLockText);
buildMode = "pnpm (pnpm-lock.yaml)";
} catch {
packageLock = { packages: {} };
buildMode = "package.json only (no lock file)";
}
}
}
@@ -191,22 +201,19 @@ async function bundleSvelteKit(
const dist: Record<string, Uint8Array> = {};
const doc = domParser.parseFromString(appHtmlText, "text/html");
// Track the main component file for mounting
let mainComponentPath: string | undefined;
// Process output files
for (const file of results.outputFiles) {
const ext = file.path.split('.').pop();
const filename = `${file.path.slice(1)}`;
const entryPoint = results.metafile.outputs[filename]?.entryPoint?.replace(/^fs:/, '');
if (ext === "js") {
const script = document.createElement("script");
script.type = "module";
script.src = "/" + filename;
// Insert before %sveltekit.head% placeholder or in head
const head = doc.head;
if (head.textContent?.includes("%sveltekit.head%")) {
head.innerHTML = head.innerHTML.replace("%sveltekit.head%", script.outerHTML);
} else {
head.appendChild(script);
// Track the main component for mounting
if (entryPoint && entryPoints.includes(entryPoint)) {
mainComponentPath = "/" + filename;
}
dist[filename] = file.contents;
@@ -227,6 +234,33 @@ async function bundleSvelteKit(
}
}
// Create a mounting script for the Svelte component
if (mainComponentPath) {
// Get svelte version from package.json
const svelteVersion = packageJson.dependencies?.svelte ||
packageJson.devDependencies?.svelte ||
'5';
const mountScript = `
import Component from '${mainComponentPath}';
import { mount } from '${esmUrl}/svelte@${svelteVersion}';
// Mount the component to the target element
const target = document.getElementById('svelte') || document.body;
mount(Component, { target });
`;
const mountScriptHash = Math.random().toString(36).substring(7);
const mountScriptFilename = `mount-${mountScriptHash}.js`;
dist[mountScriptFilename] = new TextEncoder().encode(mountScript);
// Add the mount script to the HTML
const script = document.createElement("script");
script.type = "module";
script.src = "/" + mountScriptFilename;
doc.head.appendChild(script);
}
// Replace SvelteKit placeholders
let htmlContent = doc.documentElement.outerHTML;
@@ -283,7 +317,7 @@ async function bundle(
tsconfig = undefined;
}
// Try to read package-lock.json first, fall back to yarn.lock
// Try to read package-lock.json first, fall back to yarn.lock, then pnpm-lock.yaml
let packageLock;
let buildMode: string;
try {
@@ -303,9 +337,19 @@ async function bundle(
packageLock = convertYarnLockToPackageLock(yarnLockText);
buildMode = "yarn (yarn.lock)";
} catch {
// If neither exists, use empty packages object
packageLock = { packages: {} };
buildMode = "package.json only (no lock file)";
// If yarn.lock doesn't exist, try pnpm-lock.yaml
try {
const pnpmLockText = await fs.readFile(
`${projectPath}/pnpm-lock.yaml`,
"utf8",
);
packageLock = convertPnpmLockToPackageLock(pnpmLockText);
buildMode = "pnpm (pnpm-lock.yaml)";
} catch {
// If no lock file exists, use empty packages object
packageLock = { packages: {} };
buildMode = "package.json only (no lock file)";
}
}
}
+270
View File
@@ -0,0 +1,270 @@
import { describe, it, expect } from 'vitest';
import { convertPnpmLockToPackageLock } from './pnpmLockConverter';
describe('convertPnpmLockToPackageLock', () => {
it('should convert a simple pnpm-lock.yaml entry', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
/[email protected]:
version: 18.2.0
resolution: {integrity: sha512-...}
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
expect(result.packages['node_modules/react']).toEqual({
name: 'react',
version: '18.2.0',
});
});
it('should convert scoped packages', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
/@babel/[email protected]:
version: 7.23.0
resolution: {integrity: sha512-...}
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
expect(result.packages['node_modules/@babel/core']).toEqual({
name: '@babel/core',
version: '7.23.0',
});
});
it('should parse dependencies', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
/[email protected]([email protected]):
version: 18.2.0
resolution: {integrity: sha512-...}
dependencies:
loose-envify: 1.4.0
scheduler: 0.23.0
peerDependencies:
react: ^18.2.0
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
expect(result.packages['node_modules/react-dom']).toEqual({
name: 'react-dom',
version: '18.2.0',
dependencies: {
'loose-envify': '1.4.0',
'scheduler': '0.23.0',
},
peerDependencies: {
'react': '^18.2.0',
},
});
});
it('should parse peer dependencies', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
/@testing-library/[email protected]([email protected])([email protected]):
version: 14.0.0
resolution: {integrity: sha512-...}
peerDependencies:
react: ^18.0.0
react-dom: ^18.0.0
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
expect(result.packages['node_modules/@testing-library/react']).toEqual({
name: '@testing-library/react',
version: '14.0.0',
peerDependencies: {
react: '^18.0.0',
'react-dom': '^18.0.0',
},
});
});
it('should handle multiple packages', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
/[email protected]:
version: 18.2.0
resolution: {integrity: sha512-...}
/[email protected]([email protected]):
version: 18.2.0
resolution: {integrity: sha512-...}
dependencies:
react: 18.2.0
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
expect(result.packages['node_modules/react']).toEqual({
name: 'react',
version: '18.2.0',
});
expect(result.packages['node_modules/react-dom']).toEqual({
name: 'react-dom',
version: '18.2.0',
dependencies: {
react: '18.2.0',
},
});
});
it('should skip entries without version', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
/[email protected]:
resolution: {integrity: sha512-...}
/[email protected]:
version: 1.0.0
resolution: {integrity: sha512-...}
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
expect(result.packages['node_modules/invalid-entry']).toBeUndefined();
expect(result.packages['node_modules/valid-entry']).toEqual({
name: 'valid-entry',
version: '1.0.0',
});
});
it('should handle empty pnpm-lock.yaml', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
expect(result.packages).toEqual({});
});
it('should handle packages with peer dependency specifiers in key', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
/[email protected]([email protected])([email protected]):
version: 6.0.0
resolution: {integrity: sha512-...}
dependencies:
some-dep: 1.0.0
peerDependencies:
react: '>= 16.8.0'
react-dom: '>= 16.8.0'
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
expect(result.packages['node_modules/styled-components']).toEqual({
name: 'styled-components',
version: '6.0.0',
dependencies: {
'some-dep': '1.0.0',
},
peerDependencies: {
react: '>= 16.8.0',
'react-dom': '>= 16.8.0',
},
});
});
it('should stop parsing after packages section ends', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
/[email protected]:
version: 18.2.0
resolution: {integrity: sha512-...}
snapshots:
/[email protected]:
dependencies:
loose-envify: 1.4.0
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
// Should only have the package from packages section, not from snapshots
expect(result.packages['node_modules/react']).toEqual({
name: 'react',
version: '18.2.0',
});
expect(Object.keys(result.packages).length).toBe(1);
});
it('should handle multiple installations of same package@version with different peer deps', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
/[email protected]([email protected])([email protected]):
version: 3.9.3
resolution: {integrity: sha512-...}
peerDependencies:
eslint: ^8.0.0 || ^9.0.0
svelte: ^4.0.0 || ^5.0.0
/[email protected]([email protected])([email protected]):
version: 3.9.3
resolution: {integrity: sha512-...}
peerDependencies:
eslint: ^8.0.0 || ^9.0.0
svelte: ^4.0.0 || ^5.0.0
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
// First installation should use simple path
expect(result.packages['node_modules/eslint-plugin-svelte']).toEqual({
name: 'eslint-plugin-svelte',
version: '3.9.3',
peerDependencies: {
eslint: '^8.0.0 || ^9.0.0',
svelte: '^4.0.0 || ^5.0.0',
},
});
// Second installation should use nested path
expect(result.packages['node_modules/.pnpm/eslint-plugin-svelte_1']).toEqual({
name: 'eslint-plugin-svelte',
version: '3.9.3',
peerDependencies: {
eslint: '^8.0.0 || ^9.0.0',
svelte: '^4.0.0 || ^5.0.0',
},
});
expect(Object.keys(result.packages).length).toBe(2);
});
});
+215
View File
@@ -0,0 +1,215 @@
/**
* Converts pnpm-lock.yaml format to package-lock.json format for use with esmPlugin.
* This is a simplified converter that extracts enough information for dependency resolution.
*/
interface PnpmLockPackage {
version?: string;
dependencies?: Record<string, string>;
peerDependencies?: Record<string, string>;
}
interface PackageLockPackage {
name?: string;
version: string;
dependencies?: Record<string, string>;
peerDependencies?: Record<string, string>;
}
interface PackageLock {
packages: {
[key: string]: PackageLockPackage;
};
}
/**
* Parse a pnpm-lock.yaml file and convert it to package-lock.json format
*/
export function convertPnpmLockToPackageLock(pnpmLockContent: string): PackageLock {
const packages: Record<string, PackageLockPackage> = {};
// Parse pnpm-lock.yaml entries
const entries = parsePnpmLock(pnpmLockContent);
// Track which package@version combinations we've seen to handle duplicates
const seenVersions = new Map<string, number>();
for (const [key, entry] of Object.entries(entries)) {
if (!entry.version) continue;
const packageName = extractPackageName(key);
if (!packageName) continue;
const versionKey = `${packageName}@${entry.version}`;
const count = seenVersions.get(versionKey) || 0;
seenVersions.set(versionKey, count + 1);
// Determine the lock path
let lockPath: string;
if (count === 0) {
// First occurrence - use simple node_modules path
lockPath = `node_modules/${packageName}`;
} else {
// Subsequent occurrences - create unique nested paths
// This handles cases where the same package@version is installed
// multiple times with different peer dependencies
lockPath = `node_modules/.pnpm/${packageName}_${count}`;
}
packages[lockPath] = {
name: packageName,
version: entry.version,
dependencies: entry.dependencies,
peerDependencies: entry.peerDependencies,
};
}
return { packages };
}
/**
* Parse pnpm-lock.yaml content into a map of entries
* This is a simple YAML parser focused on the packages section
*/
function parsePnpmLock(content: string): Record<string, PnpmLockPackage> {
const entries: Record<string, PnpmLockPackage> = {};
const lines = content.split('\n');
let inPackagesSection = false;
let currentKey: string | null = null;
let currentEntry: Partial<PnpmLockPackage> = {};
let inDependencies = false;
let inPeerDependencies = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Skip comments and empty lines
if (line.trim().startsWith('#') || line.trim() === '') {
continue;
}
// Detect the packages section
if (line.match(/^packages:/)) {
inPackagesSection = true;
continue;
}
// Exit packages section when we hit another top-level key
if (inPackagesSection && line.match(/^[a-zA-Z]/)) {
inPackagesSection = false;
// Save last entry before exiting
if (currentKey && currentEntry.version) {
entries[currentKey] = currentEntry as PnpmLockPackage;
}
break;
}
if (!inPackagesSection) continue;
// Get indentation level
const indent = line.search(/\S/);
if (indent === -1) continue;
// Package entry (2-space indent from packages:)
// Example: " /@babel/[email protected]:"
const packageMatch = line.match(/^ {2}(\/[^:]+):\s*$/);
if (packageMatch) {
// Save previous entry
if (currentKey && currentEntry.version) {
entries[currentKey] = currentEntry as PnpmLockPackage;
}
// Start new entry
currentKey = packageMatch[1];
currentEntry = {};
inDependencies = false;
inPeerDependencies = false;
continue;
}
// Skip if we don't have a current package
if (!currentKey) continue;
// Property lines (4-space indent from package key)
const propertyMatch = line.match(/^ {4}([a-zA-Z]+):\s*$/);
const valueMatch = line.match(/^ {4}([a-zA-Z]+):\s*(.+)\s*$/);
const depMatch = line.match(/^ {6}([^:]+):\s*(.+)\s*$/);
if (propertyMatch) {
const [, key] = propertyMatch;
if (key === 'dependencies') {
inDependencies = true;
inPeerDependencies = false;
currentEntry.dependencies = {};
} else if (key === 'peerDependencies') {
inPeerDependencies = true;
inDependencies = false;
currentEntry.peerDependencies = {};
} else {
inDependencies = false;
inPeerDependencies = false;
}
} else if (valueMatch && !inDependencies && !inPeerDependencies) {
const [, key, value] = valueMatch;
if (key === 'version') {
currentEntry.version = value.trim();
}
} else if (depMatch) {
const [, key, value] = depMatch;
const cleanKey = key.trim();
// Remove quotes from value if present
const cleanValue = value.trim().replace(/^['"]|['"]$/g, '');
if (inDependencies && currentEntry.dependencies) {
currentEntry.dependencies[cleanKey] = cleanValue;
} else if (inPeerDependencies && currentEntry.peerDependencies) {
currentEntry.peerDependencies[cleanKey] = cleanValue;
}
}
}
// Save last entry
if (currentKey && currentEntry.version) {
entries[currentKey] = currentEntry as PnpmLockPackage;
}
return entries;
}
/**
* Extract the package name from a pnpm-lock.yaml key
* Examples:
* "/@babel/[email protected]" -> "@babel/core"
* "/[email protected]" -> "react"
* "/[email protected]([email protected])" -> "react-dom"
*/
function extractPackageName(key: string): string | null {
// Remove leading slash
let cleaned = key.startsWith('/') ? key.slice(1) : key;
// Remove peer dependency specifications in parentheses
// Example: "[email protected]([email protected])" -> "[email protected]"
cleaned = cleaned.replace(/\([^)]*\)$/, '');
// Handle scoped packages: "@scope/package@version"
if (cleaned.startsWith('@')) {
const parts = cleaned.split('@');
// parts will be: ['', 'scope/package', 'version']
if (parts.length >= 2) {
return `@${parts[1]}`;
}
}
// Handle regular packages: "package@version"
const atIndex = cleaned.indexOf('@');
if (atIndex > 0) {
return cleaned.substring(0, atIndex);
}
// If no @ found, return the whole string
return cleaned || null;
}