@cloudflare/worker-bundler 0.1.0 → 0.1.2

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 CHANGED
@@ -4,6 +4,12 @@
4
4
 
5
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
6
 
7
+ ## Runtime requirement
8
+
9
+ This package only runs **inside the Cloudflare Workers runtime (`workerd`)** — both in production and in `wrangler dev`. It bundles via an `esbuild-wasm` `WebAssembly.Module` import that only the Workers module loader can resolve.
10
+
11
+ It will **not** work under plain Node.js. In particular, importing it from a Vitest/Jest test that uses the default Node pool will surface an error pointing you here. To test code that depends on `@cloudflare/worker-bundler`, run your tests with [`@cloudflare/vitest-pool-workers`](https://developers.cloudflare.com/workers/testing/vitest-integration/) so the test body executes inside `workerd`. See `packages/worker-bundler/src/tests/vitest.config.ts` in this repo for an example setup.
12
+
7
13
  ## Installation
8
14
 
9
15
  ```
@@ -107,16 +113,22 @@ Static assets are served with proper content types, ETags, and caching. Requests
107
113
 
108
114
  Bundles source files into a Worker.
109
115
 
110
- | Option | Type | Default | Description |
111
- | ------------ | -------------------------------------- | ------------------------------ | ----------------------------------------------------------------- |
112
- | `files` | `Record<string, string> \| FileSystem` | _required_ | Input files — plain object or any `FileSystem` implementation |
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 |
116
+ | Option | Type | Default | Description |
117
+ | -------------------------------------------------------- | ------------------------------------------ | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
118
+ | `files` | `Record<string, string> \| FileSystem` | _required_ | Input files — plain object or any `FileSystem` implementation |
119
+ | `entryPoint` | `string` | auto-detected | Entry point file path |
120
+ | `bundle` | `boolean` | `true` | Bundle all dependencies into one file |
121
+ | `externals` | `string[]` | `[]` | Modules to exclude from bundling (`cloudflare:*` always external) |
122
+ | `target` | `string` | `'es2022'` | Target environment |
123
+ | `minify` | `boolean` | `false` | Minify output |
124
+ | `sourcemap` | `boolean` | `false` | Generate inline source maps |
125
+ | `registry` | `string` | `'https://registry.npmjs.org'` | npm registry URL |
126
+ | `jsx` | `"transform" \| "preserve" \| "automatic"` | esbuild default | JSX transform mode |
127
+ | `jsxImportSource` | `string` | esbuild default | JSX runtime import source (e.g. `"react"`, `"preact"`) |
128
+ | `define` | `Record<string, string>` | `{}` | Constant replacements applied at bundle time |
129
+ | `loader` | `Record<string, BundlerLoader>` | `{}` | Per-extension loader overrides (e.g. `{ ".svg": "text", ".wasm": "binary" }`). See [Advanced bundler options](#advanced-bundler-options) for the supported set. |
130
+ | `conditions` | `string[]` | esbuild default | Package export conditions to honour during resolution |
131
+ | `__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired` | `unknown[]` | `[]` | Escape hatch: extra esbuild plugins, run before the internal virtual-fs plugin. Not covered by semver — see [Advanced bundler options](#advanced-bundler-options). |
120
132
 
121
133
  Returns:
122
134
 
@@ -133,19 +145,25 @@ Returns:
133
145
 
134
146
  Builds a full-stack app: server Worker + client bundle + static assets.
135
147
 
136
- | Option | Type | Default | Description |
137
- | ------------- | --------------------------------------- | ------------- | --------------------------------------------------- |
138
- | `files` | `Record<string, string> \| FileSystem` | _required_ | All source files — plain object or any `FileSystem` |
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 |
148
+ | Option | Type | Default | Description |
149
+ | -------------------------------------------------------- | ------------------------------------------ | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
150
+ | `files` | `Record<string, string> \| FileSystem` | _required_ | All source files — plain object or any `FileSystem` |
151
+ | `server` | `string` | auto-detected | Server entry point (Worker fetch handler) |
152
+ | `client` | `string \| string[]` | — | Client entry point(s) to bundle for the browser |
153
+ | `assets` | `Record<string, string \| ArrayBuffer>` | — | Static assets (pathname → content) |
154
+ | `assetConfig` | `AssetConfig` | — | Asset serving configuration |
155
+ | `bundle` | `boolean` | `true` | Bundle server dependencies |
156
+ | `externals` | `string[]` | `[]` | Modules to exclude from bundling |
157
+ | `target` | `string` | `'es2022'` | Server target environment |
158
+ | `minify` | `boolean` | `false` | Minify output |
159
+ | `sourcemap` | `boolean` | `false` | Generate source maps |
160
+ | `registry` | `string` | npm default | npm registry URL |
161
+ | `jsx` | `"transform" \| "preserve" \| "automatic"` | esbuild default | JSX transform mode (applied to both server and client bundles) |
162
+ | `jsxImportSource` | `string` | esbuild default | JSX runtime import source (e.g. `"react"`, `"preact"`) |
163
+ | `define` | `Record<string, string>` | `{}` | Constant replacements applied at bundle time (both server and client) |
164
+ | `loader` | `Record<string, BundlerLoader>` | `{}` | Per-extension loader overrides (e.g. `{ ".svg": "text" }`). See [Advanced bundler options](#advanced-bundler-options) for the supported set. |
165
+ | `conditions` | `string[]` | esbuild default | Package export conditions to honour during resolution |
166
+ | `__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired` | `unknown[]` | `[]` | Escape hatch: extra esbuild plugins. See [Advanced bundler options](#advanced-bundler-options). |
149
167
 
150
168
  Returns everything from `createWorker` plus:
151
169
 
@@ -345,7 +363,9 @@ Priority order for `createWorker` (and `createApp` server entry):
345
363
 
346
364
  ## Mounting as a Durable Object
347
365
 
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:
366
+ `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.
367
+
368
+ `getDurableObjectClass(name)` resolves a **named** class export — so export the class with `export class App`, not `export default class App`. The default entrypoint slot cannot hold an actor class, and a default-exported `DurableObject` will surface as an opaque internal error when the facet is invoked.
349
369
 
350
370
  ```ts
351
371
  const result = await createApp({
@@ -353,7 +373,7 @@ const result = await createApp({
353
373
  "src/server.ts": `
354
374
  import { DurableObject } from 'cloudflare:workers';
355
375
 
356
- export default class App extends DurableObject {
376
+ export class App extends DurableObject {
357
377
  async fetch(request: Request) {
358
378
  const url = new URL(request.url);
359
379
  if (url.pathname === '/api/count') {
@@ -474,6 +494,117 @@ const { mainModule, modules } = await createWorker({
474
494
  });
475
495
  ```
476
496
 
497
+ ## Advanced bundler options
498
+
499
+ `createWorker` and `createApp` cover the common cases (target, minify, sourcemap, externals). The options below are escape hatches for advanced consumers — RSC-style transforms, custom asset pipelines, library bundling.
500
+
501
+ > **All options in this section require `bundle: true`** (the default). Transform-only mode (`bundle: false`) skips esbuild entirely and uses sucrase + naïve module resolution instead, so `define`, `loader`, `conditions`, plugins, and the JSX options have no effect there. Setting any of them with `bundle: false` adds a warning to `result.warnings` rather than failing silently.
502
+
503
+ ### `jsx`, `jsxImportSource`
504
+
505
+ Pick a JSX runtime explicitly. With `jsx: "automatic"` you don't need to import React (or whatever runtime) in every file.
506
+
507
+ ```ts
508
+ await createApp({
509
+ files,
510
+ client: "src/client.tsx",
511
+ jsx: "automatic",
512
+ jsxImportSource: "react"
513
+ });
514
+ ```
515
+
516
+ ### `define`
517
+
518
+ Compile-time constant replacement. Each value must be a valid JavaScript expression as a string (so wrap string values in extra quotes).
519
+
520
+ ```ts
521
+ await createWorker({
522
+ files,
523
+ define: {
524
+ "process.env.NODE_ENV": '"production"',
525
+ __DEV__: "false",
526
+ __VERSION__: JSON.stringify(pkg.version)
527
+ }
528
+ });
529
+ ```
530
+
531
+ ### `loader`
532
+
533
+ Tell the bundler how to interpret arbitrary file extensions. The built-in handling for `.ts` / `.tsx` / `.js` / `.jsx` / `.json` / `.css` is preserved unless you override it. Longer extensions match first, so `".d.ts"` wins over `".ts"`.
534
+
535
+ ```ts
536
+ await createWorker({
537
+ files,
538
+ loader: {
539
+ ".svg": "text",
540
+ ".wasm": "binary",
541
+ ".sql": "text"
542
+ }
543
+ });
544
+ ```
545
+
546
+ The supported `BundlerLoader` values are deliberately narrowed to the portable subset that every modern bundler can express:
547
+
548
+ | Loader | Meaning |
549
+ | --------- | ---------------------------------------------------------- |
550
+ | `js` | Plain JavaScript |
551
+ | `jsx` | JSX (transformed per the `jsx` option) |
552
+ | `ts` | TypeScript |
553
+ | `tsx` | TypeScript + JSX |
554
+ | `json` | Parse as JSON, expose as the default export |
555
+ | `css` | Parse as CSS |
556
+ | `text` | Embed file contents as a UTF-8 string default export |
557
+ | `binary` | Embed file contents as a `Uint8Array` default export |
558
+ | `base64` | Embed file contents as a base64 string default export |
559
+ | `dataurl` | Embed file contents as a `data:` URL string default export |
560
+
561
+ esbuild's `file` / `copy` loaders are intentionally not exposed: they emit secondary output files that this bundler currently discards (only the first output is read). If you need that — or anything else esbuild-specific — reach for `__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired` instead.
562
+
563
+ ### `conditions`
564
+
565
+ Package export conditions, in priority order. Useful when bundling libraries that ship multiple builds via `package.json#exports`.
566
+
567
+ ```ts
568
+ await createWorker({
569
+ files,
570
+ conditions: ["workerd", "worker", "browser"]
571
+ });
572
+ ```
573
+
574
+ ### `__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired`
575
+
576
+ > **Read this before using.** This option is **not** covered by semver. The name is the API contract: it can change shape, be renamed, or be removed in any release. The runtime ties you to esbuild — if this package switches bundlers (e.g. to rolldown), plugins authored against this API will break.
577
+
578
+ Pass extra esbuild plugins. They run **before** the bundler's internal virtual-filesystem plugin, so a plugin's `onResolve` / `onLoad` claims fire first (e.g. an RSC plugin claiming `"server-function:*"` before virtual-fs tries to read it from disk).
579
+
580
+ The option is typed as `unknown[]` at the public boundary so the published `.d.ts` doesn't depend on `esbuild-wasm`'s types. Cast your plugin array when passing it in:
581
+
582
+ ```ts
583
+ import type { Plugin } from "esbuild-wasm";
584
+
585
+ const myRscPlugin: Plugin = {
586
+ name: "rsc",
587
+ setup(build) {
588
+ build.onResolve({ filter: /^server-function:/ }, (args) => ({
589
+ path: args.path,
590
+ namespace: "rsc"
591
+ }));
592
+ build.onLoad({ filter: /.*/, namespace: "rsc" }, (args) => ({
593
+ contents: generateServerFunctionStub(args.path),
594
+ loader: "ts"
595
+ }));
596
+ }
597
+ };
598
+
599
+ await createApp({
600
+ files,
601
+ client: "src/client.tsx",
602
+ __dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired: [
603
+ myRscPlugin
604
+ ] as unknown[]
605
+ });
606
+ ```
607
+
477
608
  ## Worker Loader Setup
478
609
 
479
610
  ```jsonc
package/dist/index.d.ts CHANGED
@@ -26,6 +26,39 @@ interface Module {
26
26
  * Output modules for Worker Loader binding
27
27
  */
28
28
  type Modules = Record<string, string | Module>;
29
+ /**
30
+ * Loader names supported for the `loader` option.
31
+ *
32
+ * Deliberately narrowed to the portable subset that every bundler in the
33
+ * ecosystem (esbuild, rolldown, rspack, vite, webpack) can express:
34
+ *
35
+ * - script flavours: `js`, `jsx`, `ts`, `tsx`, `json`, `css`
36
+ * - file content embedding: `text`, `binary`, `base64`, `dataurl`
37
+ *
38
+ * esbuild's `file` and `copy` loaders are intentionally NOT exposed: they
39
+ * emit secondary output files that the bundler currently discards (only the
40
+ * first output file is read). esbuild's `default` / `empty` / `local-css` /
41
+ * `global-css` are also omitted because they are esbuild-internal control
42
+ * flow, not portable concepts.
43
+ *
44
+ * Anything outside this set should go through
45
+ * `__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired` instead.
46
+ */
47
+ type BundlerLoader =
48
+ | "js"
49
+ | "jsx"
50
+ | "ts"
51
+ | "tsx"
52
+ | "json"
53
+ | "css"
54
+ | "text"
55
+ | "binary"
56
+ | "base64"
57
+ | "dataurl";
58
+ /**
59
+ * JSX transform mode passed to esbuild.
60
+ */
61
+ type JsxMode = "transform" | "preserve" | "automatic";
29
62
  /**
30
63
  * Options for createWorker
31
64
  */
@@ -72,6 +105,66 @@ interface CreateWorkerOptions {
72
105
  * @default 'https://registry.npmjs.org'
73
106
  */
74
107
  registry?: string;
108
+ /**
109
+ * JSX transform mode passed to esbuild.
110
+ * `"automatic"` enables the new JSX runtime (no need to import React).
111
+ *
112
+ * Only applies when `bundle: true` (the default). In transform-only mode this
113
+ * option is ignored and a warning is added to the result's `warnings` array.
114
+ */
115
+ jsx?: JsxMode;
116
+ /**
117
+ * Module to import the JSX runtime from when `jsx: "automatic"`.
118
+ * @example "react", "preact", "@emotion/react"
119
+ *
120
+ * Only applies when `bundle: true`.
121
+ */
122
+ jsxImportSource?: string;
123
+ /**
124
+ * Constant replacements applied at bundle time. Each key is replaced with the
125
+ * corresponding value (which must be a JSON-serialisable JavaScript expression).
126
+ * @example { "process.env.NODE_ENV": '"production"', "__DEV__": "false" }
127
+ *
128
+ * Only applies when `bundle: true`. In transform-only mode this option is
129
+ * ignored and a warning is added to the result's `warnings` array.
130
+ */
131
+ define?: Record<string, string>;
132
+ /**
133
+ * Per-extension loader overrides. Extensions are matched on file paths
134
+ * (including the leading dot, e.g. `".svg"`). Built-in handling for
135
+ * `.ts`/`.tsx`/`.js`/`.jsx`/`.json`/`.css` is preserved unless overridden here.
136
+ *
137
+ * Only applies when `bundle: true`.
138
+ */
139
+ loader?: Record<string, BundlerLoader>;
140
+ /**
141
+ * Package export conditions to honour during resolution
142
+ * (e.g. `["workerd", "worker", "browser"]`).
143
+ * Order matters — earlier conditions take precedence.
144
+ *
145
+ * Only applies when `bundle: true`.
146
+ */
147
+ conditions?: string[];
148
+ /**
149
+ * Escape hatch for advanced users: extra esbuild plugins to run **before**
150
+ * the bundler's internal virtual-filesystem plugin.
151
+ *
152
+ * The deliberately unwieldy name is the API contract:
153
+ *
154
+ * - This option is **not** covered by semver. It can change shape, be
155
+ * renamed, or be removed in any release.
156
+ * - The runtime ties you to esbuild. If this package switches bundlers
157
+ * (e.g. to rolldown), plugins authored against this API will break.
158
+ *
159
+ * Typed as `unknown[]` at the public boundary to keep `esbuild-wasm` types
160
+ * out of the published `.d.ts`. Cast your plugin array to `unknown[]` when
161
+ * passing it in. Each element is validated at runtime: it must be an object
162
+ * with `name: string` and `setup: (build) => void`.
163
+ *
164
+ * Only applies when `bundle: true`. In transform-only mode this option is
165
+ * ignored and a warning is added to the result's `warnings` array.
166
+ */
167
+ __dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired?: unknown[];
75
168
  }
76
169
  /**
77
170
  * Parsed wrangler configuration relevant to Worker Loader
@@ -283,6 +376,52 @@ interface CreateAppOptions {
283
376
  * npm registry URL for fetching packages.
284
377
  */
285
378
  registry?: string;
379
+ /**
380
+ * JSX transform mode passed to esbuild. Applied to both server and client
381
+ * bundles.
382
+ */
383
+ jsx?: JsxMode;
384
+ /**
385
+ * Module to import the JSX runtime from when `jsx: "automatic"`.
386
+ */
387
+ jsxImportSource?: string;
388
+ /**
389
+ * Constant replacements applied at bundle time. Applied to both server and
390
+ * client bundles.
391
+ */
392
+ define?: Record<string, string>;
393
+ /**
394
+ * Per-extension loader overrides. Applied to both server and client bundles.
395
+ */
396
+ loader?: Record<string, BundlerLoader>;
397
+ /**
398
+ * Package export conditions to honour during resolution.
399
+ * Applied to both server and client bundles (the host can pass e.g.
400
+ * `["worker", "browser"]` for the client, but most users want a single
401
+ * shared set).
402
+ */
403
+ conditions?: string[];
404
+ /**
405
+ * Escape hatch for advanced users: extra esbuild plugins to run **before**
406
+ * the bundler's internal virtual-filesystem plugin. Applied to both server
407
+ * and client bundles.
408
+ *
409
+ * The deliberately unwieldy name is the API contract:
410
+ *
411
+ * - This option is **not** covered by semver. It can change shape, be
412
+ * renamed, or be removed in any release.
413
+ * - The runtime ties you to esbuild. If this package switches bundlers
414
+ * (e.g. to rolldown), plugins authored against this API will break.
415
+ *
416
+ * Typed as `unknown[]` at the public boundary to keep `esbuild-wasm` types
417
+ * out of the published `.d.ts`. Cast your plugin array to `unknown[]` when
418
+ * passing it in. Each element is validated at runtime: it must be an object
419
+ * with `name: string` and `setup: (build) => void`.
420
+ *
421
+ * On the server side, only applies when `bundle: true`; transform-only mode
422
+ * surfaces a warning instead. Always applies to client bundles.
423
+ */
424
+ __dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired?: unknown[];
286
425
  }
287
426
  /**
288
427
  * Result from createApp
@@ -400,6 +539,7 @@ export {
400
539
  type AssetManifest,
401
540
  type AssetMetadata,
402
541
  type AssetStorage,
542
+ type BundlerLoader,
403
543
  type CreateAppOptions,
404
544
  type CreateAppResult,
405
545
  type CreateWorkerOptions,
@@ -410,6 +550,7 @@ export {
410
550
  type Files,
411
551
  InMemoryFileSystem,
412
552
  type InstallResult,
553
+ type JsxMode,
413
554
  type Modules,
414
555
  type WranglerConfig,
415
556
  buildAssetManifest,