@cloudflare/worker-bundler 0.0.0 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,501 @@
1
+ # worker-bundler
2
+
3
+ > **Experimental**: This package is under active development and its API may change without notice. Not recommended for production use.
4
+
5
+ Bundle and serve full-stack applications on Cloudflare's [Worker Loader binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/worker-loader/) (closed beta). Dynamically generate Workers with real npm dependencies, or build complete apps with client-side bundles and static asset serving.
6
+
7
+ ## Installation
8
+
9
+ ```
10
+ npm install @cloudflare/worker-bundler
11
+ ```
12
+
13
+ ## Quick Start
14
+
15
+ ### Bundle a Worker
16
+
17
+ Provide source code and dependencies — the bundler handles the rest:
18
+
19
+ ```ts
20
+ import { createWorker } from "@cloudflare/worker-bundler";
21
+
22
+ const worker = env.LOADER.get("my-worker", async () => {
23
+ const { mainModule, modules } = await createWorker({
24
+ files: {
25
+ "src/index.ts": `
26
+ import { Hono } from 'hono';
27
+ import { cors } from 'hono/cors';
28
+
29
+ const app = new Hono();
30
+ app.use('*', cors());
31
+ app.get('/', (c) => c.text('Hello from Hono!'));
32
+ app.get('/json', (c) => c.json({ message: 'It works!' }));
33
+
34
+ export default app;
35
+ `,
36
+ "package.json": JSON.stringify({
37
+ dependencies: { hono: "^4.0.0" }
38
+ })
39
+ }
40
+ });
41
+
42
+ return { mainModule, modules, compatibilityDate: "2026-01-01" };
43
+ });
44
+
45
+ await worker.getEntrypoint().fetch(request);
46
+ ```
47
+
48
+ ### Build a Full-Stack App
49
+
50
+ Use `createApp` to bundle a server Worker, client-side JavaScript, and static assets together. Assets are returned separately for host-side serving — they are not embedded in the isolate:
51
+
52
+ ```ts
53
+ import {
54
+ createApp,
55
+ handleAssetRequest,
56
+ createMemoryStorage
57
+ } from "@cloudflare/worker-bundler";
58
+
59
+ const result = await createApp({
60
+ files: {
61
+ "src/server.ts": `
62
+ export default {
63
+ fetch(request) {
64
+ return new Response("API response");
65
+ }
66
+ }
67
+ `,
68
+ "src/client.ts": `
69
+ document.getElementById("app").textContent = "Hello from the client!";
70
+ `
71
+ },
72
+ server: "src/server.ts",
73
+ client: "src/client.ts",
74
+ assets: {
75
+ "/index.html":
76
+ "<!DOCTYPE html><div id='app'></div><script src='/client.js'></script>",
77
+ "/favicon.ico": favicon
78
+ },
79
+ assetConfig: {
80
+ not_found_handling: "single-page-application"
81
+ }
82
+ });
83
+
84
+ const worker = env.LOADER.get("my-app", () => ({
85
+ mainModule: result.mainModule,
86
+ modules: result.modules,
87
+ compatibilityDate: "2026-01-01"
88
+ }));
89
+
90
+ // Serve assets on the host, forward the rest to the isolate
91
+ const storage = createMemoryStorage(result.assets);
92
+ const assetResponse = await handleAssetRequest(
93
+ request,
94
+ result.assetManifest,
95
+ storage,
96
+ result.assetConfig
97
+ );
98
+ if (assetResponse) return assetResponse;
99
+ return worker.getEntrypoint().fetch(request);
100
+ ```
101
+
102
+ Static assets are served with proper content types, ETags, and caching. Requests that don't match an asset fall through to your server code.
103
+
104
+ ## API
105
+
106
+ ### `createWorker(options)`
107
+
108
+ Bundles source files into a Worker.
109
+
110
+ | Option | Type | Default | Description |
111
+ | ------------ | ------------------------ | ------------------------------ | ----------------------------------------------------------------- |
112
+ | `files` | `Record<string, string>` | _required_ | Input files (path → content) |
113
+ | `entryPoint` | `string` | auto-detected | Entry point file path |
114
+ | `bundle` | `boolean` | `true` | Bundle all dependencies into one file |
115
+ | `externals` | `string[]` | `[]` | Modules to exclude from bundling (`cloudflare:*` always external) |
116
+ | `target` | `string` | `'es2022'` | Target environment |
117
+ | `minify` | `boolean` | `false` | Minify output |
118
+ | `sourcemap` | `boolean` | `false` | Generate inline source maps |
119
+ | `registry` | `string` | `'https://registry.npmjs.org'` | npm registry URL |
120
+
121
+ Returns:
122
+
123
+ ```ts
124
+ {
125
+ mainModule: string;
126
+ modules: Record<string, string | Module>;
127
+ wranglerConfig?: WranglerConfig;
128
+ warnings?: string[];
129
+ }
130
+ ```
131
+
132
+ ### `createApp(options)`
133
+
134
+ Builds a full-stack app: server Worker + client bundle + static assets.
135
+
136
+ | Option | Type | Default | Description |
137
+ | ------------- | --------------------------------------- | ------------- | ----------------------------------------------- |
138
+ | `files` | `Record<string, string>` | _required_ | All source files (server + client) |
139
+ | `server` | `string` | auto-detected | Server entry point (Worker fetch handler) |
140
+ | `client` | `string \| string[]` | — | Client entry point(s) to bundle for the browser |
141
+ | `assets` | `Record<string, string \| ArrayBuffer>` | — | Static assets (pathname → content) |
142
+ | `assetConfig` | `AssetConfig` | — | Asset serving configuration |
143
+ | `bundle` | `boolean` | `true` | Bundle server dependencies |
144
+ | `externals` | `string[]` | `[]` | Modules to exclude from bundling |
145
+ | `target` | `string` | `'es2022'` | Server target environment |
146
+ | `minify` | `boolean` | `false` | Minify output |
147
+ | `sourcemap` | `boolean` | `false` | Generate source maps |
148
+ | `registry` | `string` | npm default | npm registry URL |
149
+
150
+ Returns everything from `createWorker` plus:
151
+
152
+ ```ts
153
+ {
154
+ assets: Record<string, string | ArrayBuffer>; // Combined assets for host-side serving
155
+ assetManifest: AssetManifest; // Metadata (content types, ETags) per asset
156
+ assetConfig?: AssetConfig; // The asset config used
157
+ clientBundles?: string[]; // Output paths of client bundles
158
+ }
159
+ ```
160
+
161
+ ### `handleAssetRequest(request, manifest, storage, config?)`
162
+
163
+ Standalone async asset request handler. The manifest holds routing metadata (content types, ETags) while the storage backend provides content on demand:
164
+
165
+ ```ts
166
+ import { handleAssetRequest, buildAssets } from "@cloudflare/worker-bundler";
167
+
168
+ const { manifest, storage } = await buildAssets({
169
+ "/index.html": "<h1>Hello</h1>",
170
+ "/app.js": "console.log('hi')"
171
+ });
172
+
173
+ export default {
174
+ async fetch(request) {
175
+ const assetResponse = await handleAssetRequest(request, manifest, storage, {
176
+ not_found_handling: "single-page-application"
177
+ });
178
+ if (assetResponse) return assetResponse;
179
+
180
+ // Fall through to your API logic
181
+ return new Response("API");
182
+ }
183
+ };
184
+ ```
185
+
186
+ Returns a `Promise<Response | null>` — a `Response` if an asset matches, or `null` to fall through.
187
+
188
+ ## Storage Hooks
189
+
190
+ The asset handler separates **manifest** (routing metadata) from **storage** (content retrieval). This lets you plug in any backend.
191
+
192
+ ### `AssetStorage` Interface
193
+
194
+ ```ts
195
+ interface AssetStorage {
196
+ get(pathname: string): Promise<ReadableStream | ArrayBuffer | string | null>;
197
+ }
198
+ ```
199
+
200
+ ### Built-in: In-Memory Storage
201
+
202
+ The simplest option — stores everything in memory:
203
+
204
+ ```ts
205
+ import {
206
+ buildAssetManifest,
207
+ createMemoryStorage
208
+ } from "@cloudflare/worker-bundler";
209
+
210
+ const assets = { "/index.html": "<h1>Hi</h1>" };
211
+ const manifest = await buildAssetManifest(assets);
212
+ const storage = createMemoryStorage(assets);
213
+ ```
214
+
215
+ Or use the convenience function that returns both:
216
+
217
+ ```ts
218
+ import { buildAssets } from "@cloudflare/worker-bundler";
219
+
220
+ const { manifest, storage } = await buildAssets({
221
+ "/index.html": "<h1>Hi</h1>"
222
+ });
223
+ ```
224
+
225
+ ### Custom: KV Storage
226
+
227
+ ```ts
228
+ import type { AssetStorage } from "@cloudflare/worker-bundler";
229
+
230
+ function createKVStorage(kv: KVNamespace): AssetStorage {
231
+ return {
232
+ async get(pathname) {
233
+ return kv.get(pathname, "arrayBuffer");
234
+ }
235
+ };
236
+ }
237
+ ```
238
+
239
+ ### Custom: R2 Storage
240
+
241
+ ```ts
242
+ function createR2Storage(bucket: R2Bucket, prefix = "assets"): AssetStorage {
243
+ return {
244
+ async get(pathname) {
245
+ const obj = await bucket.get(`${prefix}${pathname}`);
246
+ return obj?.body ?? null;
247
+ }
248
+ };
249
+ }
250
+ ```
251
+
252
+ ### Custom: Workspace Storage
253
+
254
+ ```ts
255
+ import type { Workspace } from "@cloudflare/shell";
256
+
257
+ function createWorkspaceStorage(workspace: Workspace): AssetStorage {
258
+ return {
259
+ async get(pathname) {
260
+ return workspace.readFile(pathname);
261
+ }
262
+ };
263
+ }
264
+ ```
265
+
266
+ All storage backends work with the same `handleAssetRequest` — just pass a different `storage` argument.
267
+
268
+ ## Asset Configuration
269
+
270
+ ### HTML Handling
271
+
272
+ Controls how HTML files are resolved and how trailing slashes are handled:
273
+
274
+ | Mode | Behavior |
275
+ | ---------------------- | --------------------------------------------------------------- |
276
+ | `auto-trailing-slash` | `/about` serves `about.html`; `/blog/` serves `blog/index.html` |
277
+ | `force-trailing-slash` | Redirects `/about` → `/about/`, serves from `index.html` |
278
+ | `drop-trailing-slash` | Redirects `/about/` → `/about`, serves from `.html` |
279
+ | `none` | Exact path matching only |
280
+
281
+ Default: `auto-trailing-slash`
282
+
283
+ ### Not-Found Handling
284
+
285
+ | Mode | Behavior |
286
+ | ------------------------- | -------------------------------------------------- |
287
+ | `single-page-application` | Serves `/index.html` for all unmatched routes |
288
+ | `404-page` | Serves nearest `404.html` walking up the directory |
289
+ | `none` | Returns `null` (fall through to your Worker) |
290
+
291
+ Default: `none`
292
+
293
+ ### Redirects
294
+
295
+ ```ts
296
+ {
297
+ redirects: {
298
+ static: {
299
+ "/old-page": { status: 301, to: "/new-page" }
300
+ },
301
+ dynamic: {
302
+ "/blog/:slug": { status: 302, to: "/posts/:slug" },
303
+ "/docs/*": { status: 301, to: "/wiki/*" }
304
+ }
305
+ }
306
+ }
307
+ ```
308
+
309
+ Dynamic redirects support `:placeholder` tokens and `*` splat patterns.
310
+
311
+ ### Custom Headers
312
+
313
+ ```ts
314
+ {
315
+ headers: {
316
+ "/*": {
317
+ set: { "X-Frame-Options": "DENY" }
318
+ },
319
+ "/api/*": {
320
+ set: { "Access-Control-Allow-Origin": "*" },
321
+ unset: ["X-Frame-Options"]
322
+ }
323
+ }
324
+ }
325
+ ```
326
+
327
+ Patterns use glob syntax. Rules are applied in order — later rules can override earlier ones.
328
+
329
+ ### Caching
330
+
331
+ The asset handler sets cache headers automatically:
332
+
333
+ - **HTML and non-hashed files**: `public, max-age=0, must-revalidate`
334
+ - **Hashed files** (e.g. `app.a1b2c3d4.js`): `public, max-age=31536000, immutable`
335
+ - **ETag support**: Conditional requests with `If-None-Match` return `304 Not Modified`
336
+
337
+ ## Entry Point Detection
338
+
339
+ Priority order for `createWorker` (and `createApp` server entry):
340
+
341
+ 1. Explicit `entryPoint` / `server` option
342
+ 2. `main` field in wrangler config
343
+ 3. `exports`, `module`, or `main` field in `package.json`
344
+ 4. Default paths: `src/index.ts`, `src/index.js`, `index.ts`, `index.js`
345
+
346
+ ## Mounting as a Durable Object
347
+
348
+ `createApp` bundles code and collects assets — how the output is mounted is the caller's concern. If the user's code exports a `DurableObject` subclass, load it with `getDurableObjectClass` and mount it as a facet for persistent storage:
349
+
350
+ ```ts
351
+ const result = await createApp({
352
+ files: {
353
+ "src/server.ts": `
354
+ import { DurableObject } from 'cloudflare:workers';
355
+
356
+ export default class App extends DurableObject {
357
+ async fetch(request: Request) {
358
+ const url = new URL(request.url);
359
+ if (url.pathname === '/api/count') {
360
+ const count = ((await this.ctx.storage.get('count')) as number) ?? 0;
361
+ await this.ctx.storage.put('count', count + 1);
362
+ return Response.json({ count });
363
+ }
364
+ return new Response('Not found', { status: 404 });
365
+ }
366
+ }
367
+ `
368
+ },
369
+ assets: {
370
+ "/index.html": "<!DOCTYPE html><h1>Counter</h1>"
371
+ }
372
+ });
373
+
374
+ // Load the bundle and get the DO class
375
+ const worker = env.LOADER.get(loaderId, () => ({
376
+ mainModule: result.mainModule,
377
+ modules: result.modules,
378
+ compatibilityDate: "2026-01-28"
379
+ }));
380
+
381
+ // Mount as a facet for persistent storage
382
+ const facet = this.ctx.facets.get("app", () => ({
383
+ class: worker.getDurableObjectClass("App"),
384
+ id: "app"
385
+ }));
386
+
387
+ // Serve assets on the host, forward the rest to the facet
388
+ const storage = createMemoryStorage(result.assets);
389
+ const assetResponse = await handleAssetRequest(
390
+ request,
391
+ result.assetManifest,
392
+ storage,
393
+ result.assetConfig
394
+ );
395
+ if (assetResponse) return assetResponse;
396
+ return facet.fetch(request);
397
+ ```
398
+
399
+ The facet gets its own isolated SQLite storage that persists independently of the host DO's storage. Abort the facet on code changes to pick up new code while preserving storage:
400
+
401
+ ```ts
402
+ this.ctx.facets.abort("app", new Error("Rebuilding"));
403
+ ```
404
+
405
+ ## More Examples
406
+
407
+ ### Multiple Dependencies
408
+
409
+ ```ts
410
+ const { mainModule, modules } = await createWorker({
411
+ files: {
412
+ "src/index.ts": `
413
+ import { Hono } from 'hono';
414
+ import { zValidator } from '@hono/zod-validator';
415
+ import { z } from 'zod';
416
+
417
+ const app = new Hono();
418
+ const schema = z.object({ name: z.string() });
419
+
420
+ app.post('/greet', zValidator('json', schema), (c) => {
421
+ const { name } = c.req.valid('json');
422
+ return c.json({ message: \`Hello, \${name}!\` });
423
+ });
424
+
425
+ export default app;
426
+ `,
427
+ "package.json": JSON.stringify({
428
+ dependencies: {
429
+ hono: "^4.0.0",
430
+ "@hono/zod-validator": "^0.4.0",
431
+ zod: "^3.23.0"
432
+ }
433
+ })
434
+ }
435
+ });
436
+ ```
437
+
438
+ ### With Wrangler Config
439
+
440
+ ```ts
441
+ const { mainModule, modules, wranglerConfig } = await createWorker({
442
+ files: {
443
+ "src/index.ts": `
444
+ export default {
445
+ fetch: () => new Response('Hello!')
446
+ }
447
+ `,
448
+ "wrangler.toml": `
449
+ main = "src/index.ts"
450
+ compatibility_date = "2026-01-01"
451
+ compatibility_flags = ["nodejs_compat"]
452
+ `
453
+ }
454
+ });
455
+
456
+ const worker = env.LOADER.get("my-worker", () => ({
457
+ mainModule,
458
+ modules,
459
+ compatibilityDate: wranglerConfig?.compatibilityDate ?? "2026-01-01",
460
+ compatibilityFlags: wranglerConfig?.compatibilityFlags
461
+ }));
462
+ ```
463
+
464
+ ### Transform-only Mode
465
+
466
+ Skip bundling to preserve the module structure:
467
+
468
+ ```ts
469
+ const { mainModule, modules } = await createWorker({
470
+ files: {
471
+ /* ... */
472
+ },
473
+ bundle: false
474
+ });
475
+ ```
476
+
477
+ ## Worker Loader Setup
478
+
479
+ ```jsonc
480
+ // wrangler.jsonc (host worker)
481
+ {
482
+ "worker_loaders": [{ "binding": "LOADER" }]
483
+ }
484
+ ```
485
+
486
+ ```ts
487
+ interface Env {
488
+ LOADER: WorkerLoader;
489
+ }
490
+ ```
491
+
492
+ ## Known Limitations
493
+
494
+ - **Flat node_modules** — All packages are installed into a single flat directory. If two packages need different incompatible versions of the same transitive dependency, only one version is installed.
495
+ - **Long file paths in tarballs** — The tar parser handles classic headers but not POSIX extended (PAX) headers. Packages with paths longer than 100 characters may have those files silently truncated.
496
+ - **Text files only from npm** — Only text files (`.js`, `.json`, `.css`, etc.) are extracted from tarballs. Binary files like `.wasm` or `.node` are skipped.
497
+ - **No recursion depth limit** — Transitive dependency resolution has no depth limit. A pathological dependency tree could cause excessive network requests.
498
+
499
+ ## License
500
+
501
+ MIT
Binary file