mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Bundle Cloudflare Worker before deploying
This commit is contained in:
5 files changed
+193
-72
No files matched your search
@@ -259,6 +259,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
baseDomain: cloudflareProvider.baseDomain,
|
||||
projectName: cloudflareForm.projectName || undefined,
|
||||
corsProxy: cloudflareProvider.proxy ? config.corsProxy : undefined,
|
||||
esmUrl: config.esmUrl,
|
||||
});
|
||||
} else if (selectedProvider.type === 'deno') {
|
||||
const denoProvider = selectedProvider;
|
||||
|
||||
+113
-57
@@ -10,6 +10,7 @@ import { fsPlugin } from "./fsPlugin";
|
||||
import { convertYarnLockToPackageLock } from "./yarnLockConverter";
|
||||
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import type { Plugin } from 'esbuild-wasm';
|
||||
|
||||
export interface BuildProjectOptions {
|
||||
fs: JSRuntimeFS;
|
||||
@@ -20,6 +21,115 @@ export interface BuildProjectOptions {
|
||||
esmUrl: string;
|
||||
}
|
||||
|
||||
export interface PackageJson {
|
||||
dependencies?: { [key: string]: string };
|
||||
devDependencies?: { [key: string]: string };
|
||||
peerDependencies?: { [key: string]: string };
|
||||
}
|
||||
|
||||
export interface PackageLock {
|
||||
packages: {
|
||||
[key: string]: {
|
||||
name?: string;
|
||||
version: string;
|
||||
dependencies?: { [key: string]: string };
|
||||
peerDependencies?: { [key: string]: string };
|
||||
} | undefined;
|
||||
};
|
||||
}
|
||||
|
||||
export interface TsConfig {
|
||||
compilerOptions?: {
|
||||
baseUrl?: string;
|
||||
paths?: Record<string, string[]>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface BuildContext {
|
||||
packageJson: PackageJson;
|
||||
packageLock: PackageLock;
|
||||
tsconfig?: TsConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read package.json, package-lock.json/yarn.lock, and tsconfig.json from project
|
||||
* Exported for use by deployment adapters that need to bundle workers
|
||||
*/
|
||||
export async function readBuildContext(
|
||||
fs: JSRuntimeFS,
|
||||
projectPath: string,
|
||||
): Promise<BuildContext> {
|
||||
// Read package.json
|
||||
let packageJson: PackageJson;
|
||||
try {
|
||||
const packageJsonText = await fs.readFile(
|
||||
`${projectPath}/package.json`,
|
||||
"utf8",
|
||||
);
|
||||
packageJson = JSON.parse(packageJsonText);
|
||||
} catch {
|
||||
packageJson = {};
|
||||
}
|
||||
|
||||
// Try to read tsconfig.json
|
||||
let tsconfig: TsConfig | undefined;
|
||||
try {
|
||||
const tsconfigText = await fs.readFile(
|
||||
`${projectPath}/tsconfig.json`,
|
||||
"utf8",
|
||||
);
|
||||
tsconfig = JSONC.parse(tsconfigText);
|
||||
} catch {
|
||||
// tsconfig.json is optional
|
||||
tsconfig = undefined;
|
||||
}
|
||||
|
||||
// Try to read package-lock.json first, fall back to yarn.lock
|
||||
let packageLock: PackageLock;
|
||||
try {
|
||||
const packageLockText = await fs.readFile(
|
||||
`${projectPath}/package-lock.json`,
|
||||
"utf8",
|
||||
);
|
||||
packageLock = JSON.parse(packageLockText);
|
||||
console.log(`Building with npm (package-lock.json)`);
|
||||
} catch {
|
||||
// If package-lock.json doesn't exist, try yarn.lock
|
||||
try {
|
||||
const yarnLockText = await fs.readFile(
|
||||
`${projectPath}/yarn.lock`,
|
||||
"utf8",
|
||||
);
|
||||
packageLock = convertYarnLockToPackageLock(yarnLockText);
|
||||
console.log(`Building with yarn (yarn.lock)`);
|
||||
} catch {
|
||||
// If neither exists, use empty packages object
|
||||
packageLock = { packages: {} };
|
||||
console.log(`Building with package.json only (no lock file)`);
|
||||
}
|
||||
}
|
||||
|
||||
return { packageJson, packageLock, tsconfig };
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the common esbuild plugins for both project and worker builds
|
||||
* Exported for use by deployment adapters that need to bundle workers
|
||||
*/
|
||||
export function createPlugins(
|
||||
fs: JSRuntimeFS,
|
||||
projectPath: string,
|
||||
context: BuildContext,
|
||||
esmUrl: string,
|
||||
target?: string,
|
||||
): Plugin[] {
|
||||
return [
|
||||
shakespearePlugin({ esmUrl }),
|
||||
fsPlugin({ fs, cwd: projectPath, tsconfig: context.tsconfig, packageJson: context.packageJson }),
|
||||
esmPlugin({ packageJson: context.packageJson, packageLock: context.packageLock, target, esmUrl }),
|
||||
];
|
||||
}
|
||||
|
||||
async function bundle(
|
||||
options: BuildProjectOptions,
|
||||
): Promise<Record<string, Uint8Array>> {
|
||||
@@ -31,58 +141,8 @@ async function bundle(
|
||||
"utf8",
|
||||
);
|
||||
|
||||
// Read package.json
|
||||
let packageJson;
|
||||
try {
|
||||
const packageJsonText = await fs.readFile(
|
||||
`${projectPath}/package.json`,
|
||||
"utf8",
|
||||
);
|
||||
packageJson = JSON.parse(packageJsonText);
|
||||
} catch {
|
||||
packageJson = {};
|
||||
}
|
||||
|
||||
// Try to read tsconfig.json
|
||||
let tsconfig;
|
||||
try {
|
||||
const tsconfigText = await fs.readFile(
|
||||
`${projectPath}/tsconfig.json`,
|
||||
"utf8",
|
||||
);
|
||||
tsconfig = JSONC.parse(tsconfigText);
|
||||
} catch {
|
||||
// tsconfig.json is optional
|
||||
tsconfig = undefined;
|
||||
}
|
||||
|
||||
// Try to read package-lock.json first, fall back to yarn.lock
|
||||
let packageLock;
|
||||
let buildMode: string;
|
||||
try {
|
||||
const packageLockText = await fs.readFile(
|
||||
`${projectPath}/package-lock.json`,
|
||||
"utf8",
|
||||
);
|
||||
packageLock = JSON.parse(packageLockText);
|
||||
buildMode = "npm (package-lock.json)";
|
||||
} catch {
|
||||
// If package-lock.json doesn't exist, try yarn.lock
|
||||
try {
|
||||
const yarnLockText = await fs.readFile(
|
||||
`${projectPath}/yarn.lock`,
|
||||
"utf8",
|
||||
);
|
||||
packageLock = convertYarnLockToPackageLock(yarnLockText);
|
||||
buildMode = "yarn (yarn.lock)";
|
||||
} catch {
|
||||
// If neither exists, use empty packages object
|
||||
packageLock = { packages: {} };
|
||||
buildMode = "package.json only (no lock file)";
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Building with ${buildMode}`);
|
||||
// Read build context (package.json, package-lock.json, tsconfig.json)
|
||||
const context = await readBuildContext(fs, projectPath);
|
||||
|
||||
const doc = domParser.parseFromString(indexHtmlText, "text/html");
|
||||
const entryPoints: string[] = [];
|
||||
@@ -128,11 +188,7 @@ async function bundle(
|
||||
entryNames: "[name]-[hash]",
|
||||
chunkNames: "[name]-[hash]",
|
||||
assetNames: "[name]-[hash]",
|
||||
plugins: [
|
||||
shakespearePlugin({ esmUrl }),
|
||||
fsPlugin({ fs, cwd: projectPath, tsconfig, packageJson }),
|
||||
esmPlugin({ packageJson, packageLock, target, esmUrl }),
|
||||
],
|
||||
plugins: createPlugins(fs, projectPath, context, esmUrl, target),
|
||||
define: {
|
||||
"import.meta.env": JSON.stringify({}),
|
||||
},
|
||||
|
||||
@@ -3,6 +3,8 @@ import type { DeployAdapter, DeployOptions, DeployResult, CloudflareDeployConfig
|
||||
import { proxyUrl } from '../proxyUrl';
|
||||
import { parse as parseJsonc } from 'jsonc-parser';
|
||||
import { join } from 'path-browserify';
|
||||
import { readBuildContext, createPlugins } from '../build';
|
||||
import { getEsbuild } from '../esbuild';
|
||||
|
||||
interface AssetManifest {
|
||||
[path: string]: { hash: string; size: number };
|
||||
@@ -61,6 +63,7 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
private baseDomain: string;
|
||||
private projectName?: string;
|
||||
private corsProxy?: string;
|
||||
private esmUrl: string;
|
||||
|
||||
constructor(config: CloudflareDeployConfig) {
|
||||
this.fs = config.fs;
|
||||
@@ -70,6 +73,7 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
this.baseDomain = config.baseDomain || 'workers.dev';
|
||||
this.projectName = config.projectName;
|
||||
this.corsProxy = config.corsProxy;
|
||||
this.esmUrl = config.esmUrl;
|
||||
}
|
||||
|
||||
async deploy(options: DeployOptions): Promise<DeployResult> {
|
||||
@@ -264,6 +268,41 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
return data.result || {};
|
||||
}
|
||||
|
||||
private async bundleWorker(entryPoint: string, projectPath: string): Promise<string> {
|
||||
const esbuild = await getEsbuild();
|
||||
|
||||
// Read build context (package.json, package-lock.json, tsconfig.json)
|
||||
const context = await readBuildContext(this.fs, projectPath);
|
||||
|
||||
// Resolve the entry point path
|
||||
const entryPointPath = entryPoint.startsWith('/')
|
||||
? entryPoint
|
||||
: join(projectPath, entryPoint);
|
||||
|
||||
// Build the worker with dependencies bundled
|
||||
const results = await esbuild.build({
|
||||
entryPoints: [entryPointPath],
|
||||
bundle: true,
|
||||
write: false,
|
||||
format: "esm",
|
||||
target: "esnext",
|
||||
outdir: "/",
|
||||
metafile: true,
|
||||
sourcemap: false, // Workers typically don't need sourcemaps
|
||||
plugins: createPlugins(this.fs, projectPath, context, this.esmUrl),
|
||||
define: {
|
||||
"import.meta.env": JSON.stringify({}),
|
||||
},
|
||||
});
|
||||
|
||||
if (results.outputFiles.length === 0) {
|
||||
throw new Error(`Failed to bundle worker: no output files generated`);
|
||||
}
|
||||
|
||||
// Return the bundled worker code as a string
|
||||
return results.outputFiles[0].text;
|
||||
}
|
||||
|
||||
private async deployWorker(
|
||||
scriptName: string,
|
||||
assetsJwt: string,
|
||||
@@ -276,19 +315,23 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
// Determine the main module name from wrangler.jsonc or defaults
|
||||
const mainModuleName = wranglerConfig?.main || '_worker.js';
|
||||
|
||||
// Try to read custom worker script from project, fall back to default
|
||||
// Try to bundle custom worker script from project (supports .js and .ts), fall back to default
|
||||
let workerScript: string;
|
||||
try {
|
||||
workerScript = await this.fs.readFile(join(projectPath, mainModuleName), 'utf8');
|
||||
} catch {
|
||||
// Fallback to default worker script if custom script not found
|
||||
workerScript = `export default {
|
||||
async fetch(request) {
|
||||
// This worker only serves static assets
|
||||
// The assets are automatically served by Cloudflare's asset handler
|
||||
return new Response('Not Found', { status: 404 });
|
||||
}
|
||||
};`;
|
||||
// Check if a custom worker file exists (try both .js and .ts)
|
||||
const workerExists = await this.fileExists(join(projectPath, mainModuleName));
|
||||
|
||||
if (workerExists) {
|
||||
// Bundle the worker with its dependencies
|
||||
workerScript = await this.bundleWorker(mainModuleName, projectPath);
|
||||
} else {
|
||||
// Fallback to default worker script if custom script not found
|
||||
workerScript = this.getDefaultWorkerScript();
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to bundle custom worker script, using default:`, error);
|
||||
// Fallback to default worker script on any error
|
||||
workerScript = this.getDefaultWorkerScript();
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
@@ -450,4 +493,23 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
};
|
||||
return mimeTypes[ext] || 'application/octet-stream';
|
||||
}
|
||||
|
||||
private async fileExists(path: string): Promise<boolean> {
|
||||
try {
|
||||
const stat = await this.fs.stat(path);
|
||||
return stat.isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private getDefaultWorkerScript(): string {
|
||||
return `export default {
|
||||
async fetch(request) {
|
||||
// This worker only serves static assets
|
||||
// The assets are automatically served by Cloudflare's asset handler
|
||||
return new Response('Not Found', { status: 404 });
|
||||
}
|
||||
};`;
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,7 @@ export interface CloudflareDeployConfig {
|
||||
baseDomain?: string;
|
||||
projectName?: string;
|
||||
corsProxy?: string;
|
||||
esmUrl: string;
|
||||
}
|
||||
|
||||
export interface DenoDeployConfig {
|
||||
|
||||
+5
-4
@@ -244,10 +244,11 @@ When deploying, all components (frontend, backend, APIs) must go to a **single p
|
||||
#### Cloudflare Workers
|
||||
|
||||
- **wrangler.jsonc** (optional): Configuration file in project root
|
||||
- **_worker.js** (optional): Custom worker script in project root
|
||||
- Only \`.js\` supported, NOT \`.ts\`
|
||||
- Static assets are handled automatically
|
||||
- Add this only if you need server-side logic (APIs, edge functions, etc.)
|
||||
- **worker.ts** (optional): Custom worker script in project root
|
||||
- Supports \`.ts\`, \`.mjs\`, and \`.js\` extensions (defaults to \`worker.ts\`)
|
||||
- Worker scripts are automatically bundled with their dependencies before deployment
|
||||
- Static assets are handled automatically by Cloudflare's asset handler
|
||||
- Add this only if you need server-side logic (APIs, edge functions, middleware, etc.)
|
||||
|
||||
#### Netlify Functions
|
||||
|
||||
|
||||
Reference in new issue
Block a user