From 82daf4044b14578c04fe072fbb5b9f490247ee56 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 11 Aug 2025 13:15:08 -0800 Subject: [PATCH] mkstack builds with esbuild --- src/components/Shakespeare/ChatPane.tsx | 7 +- src/lib/ProjectsManager.ts | 4 +- src/lib/build/esmPlugin.ts | 125 +++++++++++++++ src/lib/build/esmShPlugin.ts | 130 --------------- .../{lightningFsPlugin.ts => fsPlugin.ts} | 49 +++--- src/lib/build/index.ts | 151 ++++++++---------- 6 files changed, 229 insertions(+), 237 deletions(-) create mode 100644 src/lib/build/esmPlugin.ts delete mode 100644 src/lib/build/esmShPlugin.ts rename src/lib/build/{lightningFsPlugin.ts => fsPlugin.ts} (55%) diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 63c0b0d3..0ff3dbf1 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -73,7 +73,12 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) { setIsBuildLoading(true); updateMetadata('Shakespeare', `Building ${projectName}...`); - const dist = await buildProject(browserFS, projectId); + const dist = await buildProject({ + fs: browserFS, + projectPath: `/projects/${projectId}`, + domParser: new DOMParser(), + target: "esnext", + }); console.log(dist); diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index 6499cc1e..2e529f80 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -8,8 +8,8 @@ if (typeof window !== 'undefined') { (window as { Buffer?: typeof Buffer }).Buffer = Buffer; } -// const GIT_TEMPLATE_URL = 'https://relay.ngit.dev/npub1q3sle0kvfsehgsuexttt3ugjd8xdklxfwwkh559wxckmzddywnws6cd26p/mkstack.git'; -const GIT_TEMPLATE_URL = 'https://relay.ngit.dev/npub1q3sle0kvfsehgsuexttt3ugjd8xdklxfwwkh559wxckmzddywnws6cd26p/lovable-blank.git'; +const GIT_TEMPLATE_URL = 'https://relay.ngit.dev/npub1q3sle0kvfsehgsuexttt3ugjd8xdklxfwwkh559wxckmzddywnws6cd26p/mkstack.git'; +// const GIT_TEMPLATE_URL = 'https://relay.ngit.dev/npub1q3sle0kvfsehgsuexttt3ugjd8xdklxfwwkh559wxckmzddywnws6cd26p/lovable-blank.git'; export interface Project { id: string; diff --git a/src/lib/build/esmPlugin.ts b/src/lib/build/esmPlugin.ts new file mode 100644 index 00000000..0242291e --- /dev/null +++ b/src/lib/build/esmPlugin.ts @@ -0,0 +1,125 @@ +import type { Loader, Plugin } from "esbuild-wasm"; + +interface PackageLock { + packages: { + [key: string]: { + name?: string; + version: string; + } | undefined; + }; +} + +export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { + /** Cache of URL redirects */ + const redirectedURLs = new Map(); + + /** Retrieve redirected URL from cache */ + const getRedirectedURL = async (url: string): Promise => { + const existing = redirectedURLs.get(url); + if (existing) return existing; + + const response = await fetch(url, { method: "HEAD", redirect: "manual" }); + + if (response.status === 301 || response.status === 302) { + const location = response.headers.get("Location"); + if (location) { + redirectedURLs.set(url, location); + return location; + } + } + + redirectedURLs.set(url, url); + return url; + }; + + return { + name: "esm", + + setup(build) { + // Handle bare imports like "react" + build.onResolve({ filter: /^[^./].*/ }, (args) => { + const packageName = args.path.startsWith("@") + ? args.path.split("/").slice(0, 2).join("/") + : args.path.split("/")[0]; + + const packageInfo = packageLock.packages["node_modules/" + packageName]; + const packagePath = args.path.slice(packageName.length); + const version = packageInfo?.version; + + if (!version) return; + + const name = packageInfo.name ?? packageName; + const specifier = `${name}@${version}${packagePath}`; + + const url = new URL(`https://esm.sh/*${specifier}`); + + if (target) { + url.searchParams.set("target", target); + } + + return { + path: url.toString(), + namespace: "esm", + }; + }); + + // Handle relative or absolute imports inside esm.sh modules + build.onResolve({ filter: /.*/, namespace: "esm" }, async (args) => { + let fullURL: URL; + + try { + fullURL = new URL(args.path); + } catch { + try { + // When resolving relative paths, it's important the baseURL is *after* any redirects. + // For example, `https://esm.sh/@fontsource/inter@5.2.6` redirects to `https://esm.sh/@fontsource/inter@5.2.6/index.css` + // and this changes the outcome of resolving paths like `./font.woff2` and `../font.woff2` + const baseURL = args.path.startsWith("./") + ? await getRedirectedURL(args.importer) + : args.importer; + + fullURL = new URL(args.path, baseURL); + } catch { + return { + errors: [{ text: `Could not resolve ${args.path}` }], + }; + } + } + + return { + path: fullURL.toString(), + namespace: "esm", + }; + }); + + // Load ESM modules + build.onLoad({ filter: /.*/, namespace: "esm" }, async (args) => { + const res = await fetch(args.path); + + if (!res.ok) { + throw new Error(`Failed to fetch ${args.path}`); + } + + let loader: Loader | undefined; + const contentType = res.headers.get("Content-Type")?.split(";")[0]; + + if (contentType) { + if (contentType === "application/javascript") { + loader = "js"; + } else if (contentType === "text/css") { + loader = "css"; + } else { + loader = "text"; + } + } + + const contents = await res.text(); + + return { + contents, + loader, + }; + }); + }, + }; +} diff --git a/src/lib/build/esmShPlugin.ts b/src/lib/build/esmShPlugin.ts deleted file mode 100644 index fc117220..00000000 --- a/src/lib/build/esmShPlugin.ts +++ /dev/null @@ -1,130 +0,0 @@ -import type { Loader, Plugin } from 'esbuild-wasm'; - -export function esmShPlugin(dependencies: Record): Plugin { - return { - name: 'esm-sh', - setup(build) { - // Handle bare imports like "react" - build.onResolve({ filter: /^[^./].*/ }, async (args) => { - const jsrPrefix = "npm:@jsr/"; - - const packageName = args.path.startsWith('@') - ? args.path.split('/').slice(0, 2).join('/') - : args.path.split('/')[0]; - - const version = dependencies[packageName]; - const packagePath = args.path.slice(packageName.length); - - if (version.startsWith(jsrPrefix)) { - const baseSpecifier = "@" + version.slice(jsrPrefix.length).replace('__', '/'); - - const specifier = packagePath - ? `${baseSpecifier}${packagePath}` - : baseSpecifier; - - return { - path: `https://esm.sh/jsr/${specifier}?external=react,react-dom`, - namespace: 'http', - }; - } - - if (version) { - const specifier = packagePath - ? `${packageName}@${version}${packagePath}` - : `${packageName}@${version}`; - - return { - path: `https://esm.sh/${specifier}?external=react,react-dom`, - namespace: 'http', - }; - } - }); - - // Handle relative or absolute imports inside esm.sh modules - build.onResolve({ filter: /.*/, namespace: 'http' }, (args) => { - let fullURL: URL; - - if (args.path.startsWith('http://') || args.path.startsWith('https://')) { - // Already a full URL - fullURL = new URL(args.path); - } else if (args.path.startsWith('/')) { - // Absolute path - resolve from origin - const baseURL = new URL(args.importer); - fullURL = new URL(args.path, baseURL.origin); - } else { - // Relative path (including ./ and ../) - const baseURL = new URL(args.importer); - - // For esm.sh package URLs, we need to ensure the package path ends with '/' - // to treat it as a directory rather than a file - let pathname = baseURL.pathname; - - // Decode the pathname to check for version patterns - const decodedPathname = decodeURIComponent(pathname); - - // Check if this looks like a package URL and doesn't already end with '/' - if (!pathname.endsWith('/')) { - const lastSegment = decodedPathname.substring(decodedPathname.lastIndexOf('/') + 1); - - // If the last segment contains @ (version), it's likely a package reference - // Common patterns: package@1.0.0, package@^1.0.0, @scope/package@1.0.0 - if (lastSegment.includes('@')) { - // Check if there's a file extension after the version (like .js, .css) - const versionPart = lastSegment.substring(lastSegment.lastIndexOf('@')); - // Look for file extensions (.js, .css, etc) but not version dots (1.0.0) - const hasFileExtension = /\.[a-zA-Z]+$/.test(versionPart); - - if (!hasFileExtension) { - pathname += '/'; - } - } - } - - // Create new URL with modified pathname - const baseURLWithSlash = new URL(baseURL); - baseURLWithSlash.pathname = pathname; - - // Now resolve the relative path - fullURL = new URL(args.path, baseURLWithSlash); - } - - // Preserve/add external params - fullURL.searchParams.set('external', 'react,react-dom'); - - return { - path: fullURL.toString(), - namespace: 'http', - }; - }); - - // Load HTTP modules - build.onLoad({ filter: /.*/, namespace: 'http' }, async (args) => { - const res = await fetch(args.path); - - if (!res.ok) { - throw new Error(`Failed to fetch ${args.path}`); - } - - let loader: Loader | undefined; - const contentType = res.headers.get('Content-Type')?.split(';')[0]; - - if (contentType) { - if (contentType === 'application/javascript') { - loader = 'js'; - } else if (contentType === 'text/css') { - loader = 'css'; - } else { - loader = 'text'; - } - } - - const contents = await res.text(); - - return { - contents, - loader, - }; - }); - }, - }; -} diff --git a/src/lib/build/lightningFsPlugin.ts b/src/lib/build/fsPlugin.ts similarity index 55% rename from src/lib/build/lightningFsPlugin.ts rename to src/lib/build/fsPlugin.ts index d0714b48..4b23fd9a 100644 --- a/src/lib/build/lightningFsPlugin.ts +++ b/src/lib/build/fsPlugin.ts @@ -1,18 +1,19 @@ -import path from 'path-browserify'; +import path from "path-browserify"; -import type { Loader, Plugin } from 'esbuild-wasm'; +import type { Loader, Plugin } from "esbuild-wasm"; import type { JSRuntimeFS } from '@/lib/JSRuntime'; -export function lightningFsPlugin(fs: JSRuntimeFS, cwd: string): Plugin { +export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin { return { - name: 'lightning-fs', + name: "fs", + setup(build) { build.onResolve({ filter: /.*/ }, async (args) => { let resolved: string; - if (args.path.startsWith('@/')) { + if (args.path.startsWith("@/")) { resolved = path.join(cwd, args.path.slice(2)); - } else if (args.resolveDir === '/') { + } else if (args.kind === "entry-point") { resolved = path.join(cwd, args.path); } else if (args.importer) { resolved = path.join(path.dirname(args.importer), args.path); @@ -28,28 +29,34 @@ export function lightningFsPlugin(fs: JSRuntimeFS, cwd: string): Plugin { return { path: resolved, - namespace: 'lightning-fs', + namespace: "fs", }; }); - build.onLoad({ filter: /.*/, namespace: 'lightning-fs' }, async (args) => { - const ext = path.extname(args.path).slice(1); + build.onLoad( + { filter: /.*/, namespace: "fs" }, + async (args) => { + const ext = path.extname(args.path).slice(1); - if (!['ts', 'tsx', 'js', 'jsx', 'css'].includes(ext)) { - return; - } + if (!["ts", "tsx", "js", "jsx", "css"].includes(ext)) { + return; + } - return { - contents: await fs.readFile(args.path, 'utf8'), - loader: ext as Loader, - }; - }); + return { + contents: await fs.readFile(args.path, "utf8"), + loader: ext as Loader, + }; + }, + ); }, }; } -async function tryFileVariants(fs: JSRuntimeFS, basePath: string): Promise { - const extensions = ['.ts', '.tsx', '.js', '.jsx', '.css']; +async function tryFileVariants( + fs: JSRuntimeFS, + basePath: string, +): Promise { + const extensions = [".ts", ".tsx", ".js", ".jsx", ".css"]; try { await fs.stat(basePath); @@ -71,7 +78,7 @@ async function tryFileVariants(fs: JSRuntimeFS, basePath: string): Promise> { - const indexHtml = await fs.readFile(`/projects/${projectId}/index.html`, 'utf8'); - const packageJson = await fs.readFile(`/projects/${projectId}/package.json`, 'utf8'); +export interface BuildProjectOptions { + fs: JSRuntimeFS; + projectPath: string; + domParser: DOMParser; + target?: string; +} - // Parse index.html to find the main script entry point - const entryPoints = parseEntryPoints(indexHtml); - if (!entryPoints.length) { - throw new Error('No entry point script found in index.html'); - } +export async function buildProject( + options: BuildProjectOptions, +): Promise> { + await esbuildInitPromise; + + const { fs, projectPath, domParser, target } = options; + + const indexHtmlText = await fs.readFile( + `${projectPath}/index.html`, + "utf8", + ); + const packageLockText = await fs.readFile( + `${projectPath}/package-lock.json`, + "utf8", + ); + + const doc = domParser.parseFromString(indexHtmlText, "text/html"); const results = await esbuild.build({ - entryPoints, + entryPoints: ["./main.tsx"], bundle: true, write: false, - format: 'esm', - target: 'esnext', - outdir: 'dist', - jsx: 'automatic', + format: "esm", + target: target ?? "esnext", + outdir: "/", + jsx: "automatic", plugins: [ - lightningFsPlugin(fs, `/projects/${projectId}/src`), - esmShPlugin(JSON.parse(packageJson).dependencies || {}), + fsPlugin(fs, `${projectPath}/src`), + esmPlugin(JSON.parse(packageLockText), target), ], }); const dist: Record = {}; - // Process output files - const jsFiles: string[] = []; - const cssFiles: string[] = []; - for (const file of results.outputFiles) { - const relativePath = file.path.replace(/^\/dist\//, ''); + const relativePath = file.path.replace(/^\//, ""); dist[relativePath] = file.contents; - - // Track JS and CSS files for HTML injection - if (relativePath.endsWith('.js')) { - jsFiles.push(relativePath); - } else if (relativePath.endsWith('.css')) { - cssFiles.push(relativePath); - } } // Update index.html with proper script and link tags - const updatedHtml = updateIndexHtml(indexHtml, jsFiles, cssFiles); - dist['index.html'] = new TextEncoder().encode(updatedHtml); + updateIndexHtml(doc); + + const updatedHtml = "\n" + doc.documentElement.outerHTML; + dist["index.html"] = new TextEncoder().encode(updatedHtml); return dist; } -function parseEntryPoints(html: string): string[] { - const parser = new DOMParser(); - const doc = parser.parseFromString(html, 'text/html'); +function updateIndexHtml(doc: Document): void { + const entrypoint = doc.querySelector('script[src="/src/main.tsx"]'); - // Look for script tags with type="module" and src attribute - const scripts = doc.getElementsByTagName('script'); - - return Array.from(scripts) - .filter((script) => new URL(script.src).origin === location.origin) // Only include same-origin scripts - .map((script) => new URL(script.src).pathname.replace(/^\/src\//, '')); -} - -function updateIndexHtml(originalHtml: string, jsFiles: string[], cssFiles: string[]): string { - const parser = new DOMParser(); - const doc = parser.parseFromString(originalHtml, 'text/html'); - - // Remove existing script tags that reference our built files - for (const elem of doc.getElementsByTagName('script')) { - if (new URL(elem.src).origin === location.origin) { - elem.remove(); - } + if (!entrypoint) { + throw new Error("No entrypoint script found in index.html"); } - // Remove existing link tags that reference our built CSS files - for (const elem of doc.getElementsByTagName('link')) { - if (elem.rel === 'stylesheet' && new URL(elem.href).origin === location.origin) { - elem.remove(); - } + entrypoint.setAttribute("src", "/main.js"); + + const style = doc.createElement("link"); + style.setAttribute("rel", "stylesheet"); + style.setAttribute("href", "/main.css"); + doc.head.appendChild(style); + + const tailwindScript = doc.createElement("script"); + tailwindScript.setAttribute( + "src", + "https://esm.sh/@tailwindcss/browser@4", + ); + tailwindScript.setAttribute("type", "module"); + doc.head.appendChild(tailwindScript); + + const csp = doc.querySelector('meta[http-equiv="content-security-policy"]'); + if (csp) { + csp.setAttribute( + "content", + csp.getAttribute("content")?.replace( + "script-src 'self'", + "script-src 'self' https://esm.sh" + ) ?? "" + ); } - - // Add CSS files to the head - const head = doc.head; - cssFiles.forEach((file) => { - const link = doc.createElement('link'); - link.rel = 'stylesheet'; - link.href = `/${file}`; - head.appendChild(link); - }); - - // Add JS files before the closing body tag - const body = doc.body; - jsFiles.forEach((file) => { - const script = doc.createElement('script'); - script.type = 'module'; - script.src = `/${file}`; - body.appendChild(script); - }); - - const tailwindScript = doc.createElement('script'); - tailwindScript.src = 'https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4'; - head.appendChild(tailwindScript); - - return '\n' + doc.documentElement.outerHTML; } \ No newline at end of file