From c72170f19cdb7daf35f0628d6abb54f06065f9b1 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 2 Oct 2025 15:05:09 -0500 Subject: [PATCH] Build by actually mimicking Vite's handling of index.html --- src/lib/build/fsPlugin.ts | 16 ++++- src/lib/build/index.ts | 96 +++++++++++++++++++----------- src/lib/build/shakespearePlugin.ts | 20 +++++++ 3 files changed, 96 insertions(+), 36 deletions(-) diff --git a/src/lib/build/fsPlugin.ts b/src/lib/build/fsPlugin.ts index cb53dd4e..1352e274 100644 --- a/src/lib/build/fsPlugin.ts +++ b/src/lib/build/fsPlugin.ts @@ -16,9 +16,15 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin { }); build.onResolve({ filter: /.*/ }, async (args) => { - let resolved: string; + // Skip resolving paths from external URLs + if (/^https?:\/\//.test(args.importer)) { + return; + } - if (args.path.startsWith("@/")) { + let resolved: string; + if (args.path.startsWith("/")) { + resolved = args.path; + } else if (args.path.startsWith("@/")) { resolved = join(cwd, args.path.slice(2)); } else if (args.kind === "entry-point") { resolved = join(cwd, args.path); @@ -28,6 +34,12 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin { return; } + // Security: prevent accessing files outside the project directory + const projectDir = join(cwd, ".."); + if (resolved.startsWith("/") && !resolved.startsWith(projectDir)) { + throw new Error(`Access to files outside the project directory is not allowed: ${resolved}`); + } + // Vite query parameters https://vite.dev/guide/assets const [cleaned, query] = resolved.split("?"); diff --git a/src/lib/build/index.ts b/src/lib/build/index.ts index 6817bcb2..9d6a0d1a 100644 --- a/src/lib/build/index.ts +++ b/src/lib/build/index.ts @@ -1,3 +1,4 @@ +import { join } from "path-browserify"; import { getEsbuild } from "@/lib/esbuild"; import { copyFiles } from "@/lib/copyFiles"; @@ -32,25 +33,47 @@ async function bundle( ); const doc = domParser.parseFromString(indexHtmlText, "text/html"); + const entryPoints: string[] = []; + const entryScripts: Record = {}; + + // Find all module scripts with relative paths in index.html + for (const script of doc.scripts) { + const scriptSrc = script.getAttribute("src"); + + if (scriptSrc && script.type === "module" && /^[./]/.test(scriptSrc)) { + const path = join(projectPath, scriptSrc); + + // Files in the public directory take precedence over source files + if (scriptSrc.startsWith("/")) { + if (await fileExists(fs, join(projectPath, "public", scriptSrc))) { + continue; + } + } + + entryPoints.push(path); + entryScripts[path] = script; + } + } + + // Enable Tailwind CSS if a config file is present + for (const path of ["tailwind.config.ts", "tailwind.config.js"]) { + if (await fileExists(fs, join(projectPath, path))) { + entryPoints.push(`shakespeare:${path}`); + break; + } + } const results = await esbuild.build({ - stdin: { - contents: ` - import "@/main.tsx"; - import tailwindConfig from "@/../tailwind.config.ts"; - import "https://esm.sh/tailwindcss-cdn@3"; - tailwind.config = tailwindConfig; - `, - loader: "tsx", - }, + entryPoints, bundle: true, write: false, format: "esm", target, outdir: "/", jsx: "automatic", + metafile: true, plugins: [ - shakespearePlugin(), // Takes precedence over esmPlugin + shakespearePlugin(), fsPlugin(fs, `${projectPath}/src`), esmPlugin(JSON.parse(packageLockText), target), ], @@ -62,18 +85,32 @@ async function bundle( const dist: Record = {}; for (const file of results.outputFiles) { - const relativePath = file.path.replace(/^\//, ""); - if (relativePath === "stdin.js") { - dist["main.js"] = file.contents; - } else if (relativePath === "stdin.css") { - dist["main.css"] = file.contents; - } else { - dist[relativePath] = file.contents; + const ext = file.path.split('.').pop(); + const filename = `${file.path.split('/').pop()?.split('.')?.[0] || "chunk"}-${file.hash}.${ext}`; + const entryPoint = results.metafile.outputs[file.path.slice(1)]?.entryPoint?.replace(/^fs:/, ''); + const script = entryPoint ? entryScripts[entryPoint] : null; + + if (script) { + script.setAttribute("src", "/" + filename); + dist[filename] = file.contents; + } else if (ext === "js") { + const script = document.createElement("script"); + script.type = "module"; + script.src = "/" + filename; + doc.head.appendChild(script); + dist[filename] = file.contents; + } else if (ext === "css") { + // Embed stylesheets as Tailwind CSS styles + const style = doc.createElement("style"); + style.setAttribute("type", "text/tailwindcss"); + style.textContent = file.text; + doc.head.appendChild(style); } } - // Update index.html with proper script and link tags - updateIndexHtml(doc, dist); + // HACK: Remove existing CSP header for now. + // TODO: Parse CSP and ensure esm.sh is allowed. + doc.querySelector("meta[http-equiv=\"content-security-policy\"]")?.remove(); const updatedHtml = "\n" + doc.documentElement.outerHTML; dist["index.html"] = new TextEncoder().encode(updatedHtml); @@ -156,20 +193,11 @@ export async function buildProject(options: BuildProjectOptions): Promise<{ }; } -function updateIndexHtml(doc: Document, dist: Record): void { - const entrypoint = doc.querySelector('script[src="/src/main.tsx"]'); - - if (!entrypoint) { - throw new Error("No entrypoint script found in index.html"); - } - - entrypoint.setAttribute("src", "/main.js"); - - const css = dist["main.css"]; - if (css) { - const style = doc.createElement("style"); - style.setAttribute("type", "text/tailwindcss"); - style.textContent = new TextDecoder().decode(css); - doc.head.appendChild(style); +async function fileExists(fs: JSRuntimeFS, path: string): Promise { + try { + const stat = await fs.stat(path); + return stat.isFile(); + } catch { + return false; } } \ No newline at end of file diff --git a/src/lib/build/shakespearePlugin.ts b/src/lib/build/shakespearePlugin.ts index c315be66..ec272afc 100644 --- a/src/lib/build/shakespearePlugin.ts +++ b/src/lib/build/shakespearePlugin.ts @@ -10,6 +10,26 @@ export function shakespearePlugin(): Plugin { name: "shakespeare", setup(build) { + // Handle Tailwind CSS configuration files + build.onResolve({ filter: /^shakespeare:tailwind\.config\.(js|ts)$/ }, (args) => { + return { + path: args.path, + namespace: "shakespeare-tailwind", + }; + }); + + build.onLoad({ filter: /.*/, namespace: "shakespeare-tailwind" }, async (args) => { + const { pathname } = new URL(args.path); + return { + contents: ` + import tailwindConfig from "@/../${pathname}"; + import "https://esm.sh/tailwindcss-cdn@3"; + tailwind.config = tailwindConfig; + `, + loader: "js", + }; + }); + // Handle "sonner" imports with a dummy API build.onResolve({ filter: /^sonner$/ }, (args) => { return {