import * as fs from "fs"; import * as path from "path"; import { globSync } from "glob"; import { Volume } from "memfs"; import { rollup } from "rollup"; import { nodeResolve } from "@rollup/plugin-node-resolve"; import commonjs from "@rollup/plugin-commonjs"; import nodePolyfills from "rollup-plugin-polyfill-node"; // --------------------------------------------------------------------------- // Helpers — read real package files and directory trees into a flat map // --------------------------------------------------------------------------- export function readPkgFiles( pkgName: string, patterns: string[], ): Record { const pkgDir = path.dirname(require.resolve(`${pkgName}/package.json`)); const out: Record = {}; const files = globSync(patterns, { cwd: pkgDir, nodir: true }); for (const f of files) { out[`/node_modules/${pkgName}/${f}`] = fs.readFileSync( path.join(pkgDir, f), "utf-8", ); } return out; } export function readTree( dir: string, virtualBase: string, ): Record { const out: Record = {}; for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { const full = path.join(dir, entry.name); const virt = `${virtualBase}/${entry.name}`; if (entry.isDirectory()) { Object.assign(out, readTree(full, virt)); } else if (entry.isFile()) { out[virt] = fs.readFileSync(full, "utf-8"); } } return out; } // --------------------------------------------------------------------------- // Volume builder — assembles a serialized memfs volume from a flat file map // --------------------------------------------------------------------------- export function buildVolume( files: Record, ): Record { const vol = Volume.fromJSON(files); return vol.toJSON() as Record; } // --------------------------------------------------------------------------- // Browser bundle — bundles memfs as ESM for use inside page.evaluate() // --------------------------------------------------------------------------- export async function bundleMemfsForBrowser(): Promise { const bundle = await rollup({ input: require.resolve("memfs"), plugins: [ { name: "strip-node-prefix", async resolveId( source: string, importer: string | undefined, options: any, ) { if (source === "path" || source === "node:path") { return require.resolve("../../src/path-polyfill.js"); } if (source.startsWith("node:")) { return this.resolve(source.slice(5), importer, { ...options, skipSelf: true, }); } return null; }, }, commonjs(), nodeResolve({ browser: true, preferBuiltins: false }), nodePolyfills(), ], }); const { output } = await bundle.generate({ format: "esm" }); await bundle.close(); return output[0].code; }