mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
mkstack builds with esbuild
This commit is contained in:
1 parent
1447c8f748
commit
50f60e59a1
6 files changed
+229
-237
No files matched your search
@@ -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);
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<string, string>();
|
||||
|
||||
/** Retrieve redirected URL from cache */
|
||||
const getRedirectedURL = async (url: string): Promise<string> => {
|
||||
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/[email protected]` redirects to `https://esm.sh/@fontsource/[email protected]/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,
|
||||
};
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
import type { Loader, Plugin } from 'esbuild-wasm';
|
||||
|
||||
export function esmShPlugin(dependencies: Record<string, string>): 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: [email protected], package@^1.0.0, @scope/[email protected]
|
||||
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,
|
||||
};
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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<string> {
|
||||
const extensions = ['.ts', '.tsx', '.js', '.jsx', '.css'];
|
||||
async function tryFileVariants(
|
||||
fs: JSRuntimeFS,
|
||||
basePath: string,
|
||||
): Promise<string> {
|
||||
const extensions = [".ts", ".tsx", ".js", ".jsx", ".css"];
|
||||
|
||||
try {
|
||||
await fs.stat(basePath);
|
||||
@@ -71,7 +78,7 @@ async function tryFileVariants(fs: JSRuntimeFS, basePath: string): Promise<strin
|
||||
|
||||
// Try directory index files
|
||||
for (const ext of extensions) {
|
||||
const indexFile = path.join(basePath, 'index' + ext);
|
||||
const indexFile = path.join(basePath, "index" + ext);
|
||||
try {
|
||||
await fs.stat(indexFile);
|
||||
return indexFile;
|
||||
@@ -80,5 +87,5 @@ async function tryFileVariants(fs: JSRuntimeFS, basePath: string): Promise<strin
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('File not found');
|
||||
throw new Error("File not found");
|
||||
}
|
||||
+68
-83
@@ -1,115 +1,100 @@
|
||||
import * as esbuild from 'esbuild-wasm';
|
||||
import * as esbuild from "esbuild-wasm";
|
||||
|
||||
import { esmShPlugin } from './esmShPlugin';
|
||||
import { lightningFsPlugin } from './lightningFsPlugin';
|
||||
import { esmPlugin } from "./esmPlugin";
|
||||
import { fsPlugin } from "./fsPlugin";
|
||||
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
|
||||
await esbuild.initialize({
|
||||
const esbuildInitPromise = esbuild.initialize({
|
||||
worker: false,
|
||||
wasmURL: 'https://unpkg.com/esbuild-wasm/esbuild.wasm',
|
||||
wasmURL: "https://esm.sh/esbuild-wasm@0.25.8/esbuild.wasm",
|
||||
});
|
||||
|
||||
export async function buildProject(fs: JSRuntimeFS, projectId: string): Promise<Record<string, Uint8Array>> {
|
||||
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<Record<string, Uint8Array>> {
|
||||
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<string, Uint8Array> = {};
|
||||
|
||||
// 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 = "<!DOCTYPE html>\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 '<!DOCTYPE html>\n' + doc.documentElement.outerHTML;
|
||||
}
|
||||
Reference in new issue
Block a user