From 13ea7c192e6eadd664853d73bedceb6d498c14c2 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 18 Jan 2026 03:22:07 -0600 Subject: [PATCH] Support file: URIs in package.json --- src/lib/build/esmPlugin.ts | 13 +++++ src/lib/build/fsPlugin.ts | 104 ++++++++++++++++++++++++++++++++---- src/lib/build/index.test.ts | 59 ++++++++++++++++++++ src/lib/build/index.ts | 2 +- 4 files changed, 168 insertions(+), 10 deletions(-) diff --git a/src/lib/build/esmPlugin.ts b/src/lib/build/esmPlugin.ts index fa2c9700..47db9992 100644 --- a/src/lib/build/esmPlugin.ts +++ b/src/lib/build/esmPlugin.ts @@ -260,6 +260,19 @@ export function esmPlugin(options: EsmPluginOptions): Plugin { // not a URL; continue } + // Check if this is a file: dependency + const allDeps = { + ...packageJson.dependencies, + ...packageJson.devDependencies, + ...packageJson.peerDependencies, + }; + const depVersion = allDeps[packageName]; + + if (depVersion && depVersion.startsWith("file:")) { + // Let fsPlugin handle file: dependencies + return; + } + // Determine importer lock path (breadcrumb) const importerLockPath = getImporterLockPath(args.importer); diff --git a/src/lib/build/fsPlugin.ts b/src/lib/build/fsPlugin.ts index 553a2aa2..b7bea340 100644 --- a/src/lib/build/fsPlugin.ts +++ b/src/lib/build/fsPlugin.ts @@ -10,14 +10,21 @@ interface TsConfig { }; } +interface PackageJson { + dependencies?: { [key: string]: string }; + devDependencies?: { [key: string]: string }; + peerDependencies?: { [key: string]: string }; +} + interface FsPluginOptions { fs: JSRuntimeFS; cwd: string; tsconfig?: TsConfig; + packageJson?: PackageJson; } export function fsPlugin(options: FsPluginOptions): Plugin { - const { fs, cwd, tsconfig } = options; + const { fs, cwd, tsconfig, packageJson } = options; return { name: "fs", @@ -30,21 +37,65 @@ export function fsPlugin(options: FsPluginOptions): Plugin { }); build.onResolve({ filter: /.*/ }, async (args) => { - // Skip resolving paths from external URLs + // Skip resolving paths from external URLs (but not fs: namespace) if (/^https?:\/\//.test(args.importer)) { return; } - let resolved: string; + let resolved: string | undefined; + + // Handle absolute paths if (args.path.startsWith("/")) { resolved = args.path; - } else if (args.path.startsWith("@/")) { + } + // Handle @/ alias + else if (args.path.startsWith("@/")) { resolved = join(cwd, "src", args.path.slice(2)); - } else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) { - resolved = join(dirname(args.importer), args.path); - } else if (args.importer && tsconfig?.compilerOptions?.baseUrl) { + } + // Handle relative paths + else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) { + // Remove fs: prefix from importer if present + const importerPath = args.importer.replace(/^fs:/, ''); + resolved = join(dirname(importerPath), args.path); + } + // Handle bare imports (e.g., "react", "@scope/package") + else if (args.path.match(/^[^./]/)) { + // Check if this is a file: dependency + const packageName = args.path.startsWith("@") + ? args.path.split("/").slice(0, 2).join("/") + : args.path.split("/")[0]; + + const allDeps = { + ...packageJson?.dependencies, + ...packageJson?.devDependencies, + ...packageJson?.peerDependencies, + }; + + const depVersion = allDeps[packageName]; + + if (depVersion && depVersion.startsWith("file:")) { + // Extract the file path (e.g., "file:./path" -> "./path") + const filePath = depVersion.slice(5); // Remove "file:" prefix + const packagePath = join(cwd, filePath); + + // Get the subpath within the package (e.g., "package/subdir/file" -> "/subdir/file") + const subpath = args.path.slice(packageName.length); + + resolved = join(packagePath, subpath); + } else { + return; // Let esmPlugin handle this + } + } + // Handle tsconfig baseUrl + else if (args.importer && tsconfig?.compilerOptions?.baseUrl) { resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path); - } else { + } + // Nothing matched, let other plugins handle it + else { + return; + } + + if (!resolved) { return; } @@ -114,8 +165,43 @@ async function tryFileVariants( return basePath; } - // If it's a directory, try index files + // If it's a directory, try package.json first, then index files if (stat.isDirectory()) { + // Try to read package.json for entry point + try { + const packageJsonPath = join(basePath, "package.json"); + const packageJsonText = await fs.readFile(packageJsonPath, "utf8"); + const packageJson = JSON.parse(packageJsonText); + + // Check for various entry point fields + const entryPoint = packageJson.exports?.['.'] + || packageJson.module + || packageJson.main + || 'index.js'; + + // Resolve the entry point + const entryPath = typeof entryPoint === 'string' + ? join(basePath, entryPoint) + : join(basePath, 'index.js'); + + const entryStat = await statSafe(fs, entryPath); + if (entryStat.isFile()) { + return entryPath; + } + + // Try with different extensions if the entry point doesn't exist + for (const ext of extensions) { + const entryWithExt = entryPath.replace(/\.[^.]+$/, '') + ext; + const entryExtStat = await statSafe(fs, entryWithExt); + if (entryExtStat.isFile()) { + return entryWithExt; + } + } + } catch { + // package.json doesn't exist or is invalid, fall through to index files + } + + // Fall back to trying index files for (const ext of extensions) { const indexFile = join(basePath, "index" + ext); const indexStat = await statSafe(fs, indexFile); diff --git a/src/lib/build/index.test.ts b/src/lib/build/index.test.ts index f56a05ca..134f7d5f 100644 --- a/src/lib/build/index.test.ts +++ b/src/lib/build/index.test.ts @@ -535,4 +535,63 @@ react@^18.0.0: // Verify tsconfig.json was attempted to be read expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/tsconfig.json', 'utf8'); }); + + it('should support file: dependencies in package.json', async () => { + const packageJsonWithFileDeps = JSON.stringify({ + name: "test-project", + dependencies: { + "@bitchat/capacitor-ble-mesh": "file:./capacitor-bitchat-mesh", + "react": "^18.2.0" + } + }); + + // Mock required files + vi.mocked(mockFS.readFile) + .mockImplementation(async (path: string) => { + if (path.endsWith('package.json')) { + return packageJsonWithFileDeps; + } + if (path.endsWith('index.html')) { + return ''; + } + if (path.endsWith('package-lock.json')) { + return '{"dependencies": {}}'; + } + 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, + esmUrl: 'https://esm.shakespeare.diy', + }); + + // Should successfully build with file: 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'); + }); }); \ No newline at end of file diff --git a/src/lib/build/index.ts b/src/lib/build/index.ts index de24958c..2ebf9d54 100644 --- a/src/lib/build/index.ts +++ b/src/lib/build/index.ts @@ -130,7 +130,7 @@ async function bundle( assetNames: "[name]-[hash]", plugins: [ shakespearePlugin({ esmUrl }), - fsPlugin({ fs, cwd: projectPath, tsconfig }), + fsPlugin({ fs, cwd: projectPath, tsconfig, packageJson }), esmPlugin({ packageJson, packageLock, target, esmUrl }), ], define: {