miniflare 0.0.0-0737e0f78

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.
Files changed (38) hide show
  1. package/README.md +847 -0
  2. package/bootstrap.js +11 -0
  3. package/dist/src/index.d.ts +4230 -0
  4. package/dist/src/index.js +10253 -0
  5. package/dist/src/index.js.map +6 -0
  6. package/dist/src/workers/assets/assets-kv.worker.js +24 -0
  7. package/dist/src/workers/assets/assets-kv.worker.js.map +6 -0
  8. package/dist/src/workers/assets/assets.worker.js +9220 -0
  9. package/dist/src/workers/assets/assets.worker.js.map +6 -0
  10. package/dist/src/workers/assets/router.worker.js +8690 -0
  11. package/dist/src/workers/assets/router.worker.js.map +6 -0
  12. package/dist/src/workers/cache/cache-entry-noop.worker.js +19 -0
  13. package/dist/src/workers/cache/cache-entry-noop.worker.js.map +6 -0
  14. package/dist/src/workers/cache/cache-entry.worker.js +28 -0
  15. package/dist/src/workers/cache/cache-entry.worker.js.map +6 -0
  16. package/dist/src/workers/cache/cache.worker.js +655 -0
  17. package/dist/src/workers/cache/cache.worker.js.map +6 -0
  18. package/dist/src/workers/core/entry.worker.js +1037 -0
  19. package/dist/src/workers/core/entry.worker.js.map +6 -0
  20. package/dist/src/workers/d1/database.worker.js +350 -0
  21. package/dist/src/workers/d1/database.worker.js.map +6 -0
  22. package/dist/src/workers/kv/namespace.worker.js +258 -0
  23. package/dist/src/workers/kv/namespace.worker.js.map +6 -0
  24. package/dist/src/workers/kv/sites.worker.js +147 -0
  25. package/dist/src/workers/kv/sites.worker.js.map +6 -0
  26. package/dist/src/workers/queues/broker.worker.js +286 -0
  27. package/dist/src/workers/queues/broker.worker.js.map +6 -0
  28. package/dist/src/workers/r2/bucket.worker.js +1157 -0
  29. package/dist/src/workers/r2/bucket.worker.js.map +6 -0
  30. package/dist/src/workers/ratelimit/ratelimit.worker.js +54 -0
  31. package/dist/src/workers/ratelimit/ratelimit.worker.js.map +6 -0
  32. package/dist/src/workers/shared/index.worker.js +706 -0
  33. package/dist/src/workers/shared/index.worker.js.map +6 -0
  34. package/dist/src/workers/shared/object-entry.worker.js +21 -0
  35. package/dist/src/workers/shared/object-entry.worker.js.map +6 -0
  36. package/dist/src/workers/shared/zod.worker.js +2719 -0
  37. package/dist/src/workers/shared/zod.worker.js.map +6 -0
  38. package/package.json +108 -0
package/README.md ADDED
@@ -0,0 +1,847 @@
1
+ # 🔥 Miniflare
2
+
3
+ **Miniflare 3** is a simulator for developing and testing
4
+ [**Cloudflare Workers**](https://workers.cloudflare.com/), powered by
5
+ [`workerd`](https://github.com/cloudflare/workerd).
6
+
7
+ > :warning: Miniflare 3 is API-only, and does not expose a CLI. Use Wrangler
8
+ > with `wrangler dev` to develop your Workers locally with Miniflare 3.
9
+
10
+ ## Quick Start
11
+
12
+ ```shell
13
+ $ npm install miniflare --save-dev
14
+ ```
15
+
16
+ ```js
17
+ import { Miniflare } from "miniflare";
18
+
19
+ // Create a new Miniflare instance, starting a workerd server
20
+ const mf = new Miniflare({
21
+ script: `addEventListener("fetch", (event) => {
22
+ event.respondWith(new Response("Hello Miniflare!"));
23
+ })`,
24
+ });
25
+
26
+ // Send a request to the workerd server, the host is ignored
27
+ const response = await mf.dispatchFetch("http://localhost:8787/");
28
+ console.log(await response.text()); // Hello Miniflare!
29
+
30
+ // Cleanup Miniflare, shutting down the workerd server
31
+ await mf.dispose();
32
+ ```
33
+
34
+ ## API
35
+
36
+ ### `type Awaitable<T>`
37
+
38
+ `T | Promise<T>`
39
+
40
+ Represents a value that can be `await`ed. Used in callback types to allow
41
+ `Promise`s to be returned if necessary.
42
+
43
+ ### `type Json`
44
+
45
+ `string | number | boolean | null | Record<string, Json> | Json[]`
46
+
47
+ Represents a JSON-serialisable value.
48
+
49
+ ### `type ModuleRuleType`
50
+
51
+ `"ESModule" | "CommonJS" | "Text" | "Data" | "CompiledWasm"`
52
+
53
+ Represents how a module's contents should be interpreted.
54
+
55
+ - `"ESModule"`: interpret as
56
+ [ECMAScript module](https://tc39.es/ecma262/#sec-modules)
57
+ - `"CommonJS"`: interpret as
58
+ [CommonJS module](https://nodejs.org/api/modules.html#modules-commonjs-modules)
59
+ - `"Text"`: interpret as UTF8-encoded data, expose in runtime with
60
+ `string`-typed `default` export
61
+ - `"Data"`: interpret as arbitrary binary data, expose in runtime with
62
+ `ArrayBuffer`-typed `default` export
63
+ - `"CompiledWasm"`: interpret as binary WebAssembly module data, expose in
64
+ runtime with `WebAssembly.Module`-typed `default` export
65
+
66
+ ### `interface ModuleDefinition`
67
+
68
+ Represents a manually defined module.
69
+
70
+ - `type: ModuleRuleType`
71
+
72
+ How this module's contents should be interpreted.
73
+
74
+ - `path: string`
75
+
76
+ Path of this module. The module's "name" will be obtained by converting this
77
+ to a relative path. The original path will be used to read `contents` if it's
78
+ omitted.
79
+
80
+ - `contents?: string | Uint8Array`
81
+
82
+ Contents override for this module. Binary data should be passed as
83
+ `Uint8Array`s. If omitted, will be read from `path`.
84
+
85
+ ### `interface ModuleRule`
86
+
87
+ Represents a rule for identifying the `ModuleRuleType` of automatically located
88
+ modules.
89
+
90
+ - `type: ModuleRuleType`
91
+
92
+ How to interpret modules that match the `include` patterns.
93
+
94
+ - `include: string[]`
95
+
96
+ Glob patterns to match located module paths against (e.g. `["**/*.txt"]`).
97
+
98
+ - `fallthrough?: boolean`
99
+
100
+ If `true`, ignore any further rules of this `type`. This is useful for
101
+ disabling the built-in `ESModule` and `CommonJS` rules that match `*.mjs` and
102
+ `*.js`/`*.cjs` files respectively.
103
+
104
+ ### `type Persistence`
105
+
106
+ `boolean | string | undefined`
107
+
108
+ Represents where data should be persisted, if anywhere.
109
+
110
+ - If this is `undefined` or `false`, data will be stored in-memory and only
111
+ persist between `Miniflare#setOptions()` calls, not restarts nor
112
+ `new Miniflare` instances.
113
+ - If this is `true`, data will be stored on the file-system, in the `$PWD/.mf`
114
+ directory.
115
+ - If this looks like a URL, then:
116
+ - If the protocol is `memory:`, data will be stored in-memory as above.
117
+ - If the protocol is `file:`, data will be stored on the file-system, in the
118
+ specified directory (e.g. `file:///path/to/directory`).
119
+ - Otherwise, if this is just a regular `string`, data will be stored on the
120
+ file-system, using the value as the directory path.
121
+
122
+ ### `enum LogLevel`
123
+
124
+ `NONE, ERROR, WARN, INFO, DEBUG, VERBOSE`
125
+
126
+ Controls which messages Miniflare logs. All messages at or below the selected
127
+ level will be logged.
128
+
129
+ ### `interface LogOptions`
130
+
131
+ - `prefix?: string`
132
+
133
+ String to add before the level prefix when logging messages. Defaults to `mf`.
134
+
135
+ - `suffix?: string`
136
+
137
+ String to add after the level prefix when logging messages.
138
+
139
+ ### `class Log`
140
+
141
+ - `constructor(level?: LogLevel, opts?: LogOptions)`
142
+
143
+ Creates a new logger that logs all messages at or below the specified level to
144
+ the `console`.
145
+
146
+ - `error(message: Error)`
147
+
148
+ Logs a message at the `ERROR` level. If the constructed log `level` is less
149
+ than `ERROR`, `throw`s the `message` instead.
150
+
151
+ - `warn(message: string)`
152
+
153
+ Logs a message at the `WARN` level.
154
+
155
+ - `info(message: string)`
156
+
157
+ Logs a message at the `INFO` level.
158
+
159
+ - `debug(message: string)`
160
+
161
+ Logs a message at the `DEBUG` level.
162
+
163
+ - `verbose(message: string)`
164
+
165
+ Logs a message at the `VERBOSE` level.
166
+
167
+ ### `class NoOpLog extends Log`
168
+
169
+ - `constructor()`
170
+
171
+ Creates a new logger that logs nothing to the `console`, and always `throw`s
172
+ `message`s logged at the `ERROR` level.
173
+
174
+ ### `interface QueueProducerOptions`
175
+
176
+ - `queueName: string`
177
+
178
+ The name of the queue where messages will be sent by the producer.
179
+
180
+ - `deliveryDelay?: number`
181
+
182
+ Default number of seconds to delay the delivery of messages to consumers.
183
+ Value between `0` (no delay) and `42300` (12 hours).
184
+
185
+ ### `interface QueueConsumerOptions`
186
+
187
+ - `maxBatchSize?: number`
188
+
189
+ Maximum number of messages allowed in each batch. Defaults to `5`.
190
+
191
+ - `maxBatchTimeout?: number`
192
+
193
+ Maximum number of seconds to wait for a full batch. If a message is sent, and
194
+ this timeout elapses, a partial batch will be dispatched. Defaults to `1`.
195
+
196
+ - `maxRetries?: number`
197
+
198
+ Maximum number of times to retry dispatching a message, if handling it throws,
199
+ or it is explicitly retried. Defaults to `2`.
200
+
201
+ - `deadLetterQueue?: string`
202
+
203
+ Name of another Queue to send a message on if it fails processing after
204
+ `maxRetries`. If this isn't specified, failed messages will be discarded.
205
+
206
+ - `retryDelay?: number`
207
+
208
+ Number of seconds to delay the (re-)delivery of messages by default. Value
209
+ between `0` (no delay) and `42300` (12 hours).
210
+
211
+ ### `interface WorkerOptions`
212
+
213
+ Options for an individual Worker/"nanoservice". All bindings are accessible on
214
+ the global scope in service-worker format Workers, or via the 2nd `env`
215
+ parameter in module format Workers.
216
+
217
+ #### Core
218
+
219
+ - `name?: string`
220
+
221
+ Unique name for this worker. Only required if multiple `workers` are
222
+ specified.
223
+
224
+ - `rootPath?: string`
225
+
226
+ Path against which all other path options for this Worker are resolved
227
+ relative to. This path is itself resolved relative to the `rootPath` from
228
+ `SharedOptions` if multiple workers are specified. Defaults to the current
229
+ working directory.
230
+
231
+ - `script?: string`
232
+
233
+ JavaScript code for this worker. If this is a service worker format Worker, it
234
+ must not have any imports. If this is a modules format Worker, it must not
235
+ have any _npm_ imports, and `modules: true` must be set. If it does have
236
+ imports, `scriptPath` must also be set so Miniflare knows where to resolve
237
+ them relative to.
238
+
239
+ - `scriptPath?: string`
240
+
241
+ Path of JavaScript entrypoint. If this is a service worker format Worker, it
242
+ must not have any imports. If this is a modules format Worker, it must not
243
+ have any _npm_ imports, and `modules: true` must be set.
244
+
245
+ - `modules?: boolean | ModuleDefinition[]`
246
+
247
+ - If `true`, Miniflare will treat `script`/`scriptPath` as an ES Module and
248
+ automatically locate transitive module dependencies according to
249
+ `modulesRules`. Note that automatic location is not perfect: if the
250
+ specifier to a dynamic `import()` or `require()` is not a string literal, an
251
+ exception will be thrown.
252
+
253
+ - If set to an array, modules can be defined manually. Transitive dependencies
254
+ must also be defined. Note the first module must be the entrypoint and have
255
+ type `"ESModule"`.
256
+
257
+ - `modulesRoot?: string`
258
+
259
+ If `modules` is set to `true` or an array, modules' "name"s will be their
260
+ `path`s relative to this value. This ensures file paths in stack traces are
261
+ correct.
262
+
263
+ <!-- prettier-ignore-start -->
264
+ <!-- (for disabling `;` insertion in `js` code block) -->
265
+
266
+ - `modulesRules?: ModuleRule[]`
267
+
268
+ Rules for identifying the `ModuleRuleType` of automatically located modules
269
+ when `modules: true` is set. Note the following default rules are always
270
+ included at the end:
271
+
272
+ ```js
273
+ [
274
+ { type: "ESModule", include: ["**/*.mjs"] },
275
+ { type: "CommonJS", include: ["**/*.js", "**/*.cjs"] },
276
+ ]
277
+ ```
278
+
279
+ > If `script` and `scriptPath` are set, and `modules` is set to an array,
280
+ > `modules` takes priority for a Worker's code, followed by `script`, then
281
+ > `scriptPath`.
282
+
283
+ <!-- prettier-ignore-end -->
284
+
285
+ - `compatibilityDate?: string`
286
+
287
+ [Compatibility date](https://developers.cloudflare.com/workers/platform/compatibility-dates/)
288
+ to use for this Worker. Defaults to a date far in the past.
289
+
290
+ - `compatibilityFlags?: string[]`
291
+
292
+ [Compatibility flags](https://developers.cloudflare.com/workers/platform/compatibility-dates/)
293
+ to use for this Worker.
294
+
295
+ - `bindings?: Record<string, Json>`
296
+
297
+ Record mapping binding name to arbitrary JSON-serialisable values to inject as
298
+ bindings into this Worker.
299
+
300
+ - `wasmBindings?: Record<string, string>`
301
+
302
+ Record mapping binding name to paths containing binary WebAssembly module data
303
+ to inject as `WebAssembly.Module` bindings into this Worker.
304
+
305
+ - `textBlobBindings?: Record<string, string>`
306
+
307
+ Record mapping binding name to paths containing UTF8-encoded data to inject as
308
+ `string` bindings into this Worker.
309
+
310
+ - `dataBlobBindings?: Record<string, string>`
311
+
312
+ Record mapping binding name to paths containing arbitrary binary data to
313
+ inject as `ArrayBuffer` bindings into this Worker.
314
+
315
+ - `serviceBindings?: Record<string, string | typeof kCurrentWorker | { name: string | typeof kCurrentWorker, entrypoint?: string } | { network: Network } | { external: ExternalServer } | { disk: DiskDirectory } | (request: Request, instance: Miniflare) => Awaitable<Response>>`
316
+
317
+ Record mapping binding name to service designators to inject as
318
+ `{ fetch: typeof fetch }`
319
+ [service bindings](https://developers.cloudflare.com/workers/platform/bindings/about-service-bindings/)
320
+ into this Worker.
321
+
322
+ - If the designator is a `string`, requests will be dispatched to the Worker
323
+ with that `name`.
324
+ - If the designator is `(await import("miniflare")).kCurrentWorker`, requests
325
+ will be dispatched to the Worker defining the binding.
326
+ - If the designator is an object of the form `{ name: ..., entrypoint: ... }`,
327
+ requests will be dispatched to the entrypoint named `entrypoint` in the
328
+ Worker named `name`. The `entrypoint` defaults to `default`, meaning
329
+ `{ name: "a" }` is the same as `"a"`. If `name` is
330
+ `(await import("miniflare")).kCurrentWorker`, requests will be dispatched to
331
+ the Worker defining the binding.
332
+ - If the designator is an object of the form `{ network: { ... } }`, where
333
+ `network` is a
334
+ [`workerd` `Network` struct](https://github.com/cloudflare/workerd/blob/bdbd6075c7c53948050c52d22f2dfa37bf376253/src/workerd/server/workerd.capnp#L555-L598),
335
+ requests will be dispatched according to the `fetch`ed URL.
336
+ - If the designator is an object of the form `{ external: { ... } }` where
337
+ `external` is a
338
+ [`workerd` `ExternalServer` struct](https://github.com/cloudflare/workerd/blob/bdbd6075c7c53948050c52d22f2dfa37bf376253/src/workerd/server/workerd.capnp#L504-L553),
339
+ requests will be dispatched to the specified remote server.
340
+ - If the designator is an object of the form `{ disk: { ... } }` where `disk`
341
+ is a
342
+ [`workerd` `DiskDirectory` struct](https://github.com/cloudflare/workerd/blob/bdbd6075c7c53948050c52d22f2dfa37bf376253/src/workerd/server/workerd.capnp#L600-L643),
343
+ requests will be dispatched to an HTTP service backed by an on-disk
344
+ directory.
345
+ - If the designator is a function, requests will be dispatched to your custom
346
+ handler. This allows you to access data and functions defined in Node.js
347
+ from your Worker. Note `instance` will be the `Miniflare` instance
348
+ dispatching the request.
349
+
350
+ <!--prettier-ignore-start-->
351
+
352
+ - `wrappedBindings?: Record<string, string | { scriptName: string, entrypoint?: string, bindings?: Record<string, Json> }>`
353
+
354
+ Record mapping binding name to designators to inject as
355
+ [wrapped bindings](https://github.com/cloudflare/workerd/blob/bfcef2d850514c569c039cb84c43bc046af4ffb9/src/workerd/server/workerd.capnp#L469-L487) into this Worker.
356
+ Wrapped bindings allow custom bindings to be written as JavaScript functions
357
+ accepting an `env` parameter of "inner bindings" and returning the value to
358
+ bind. A `string` designator is equivalent to `{ scriptName: <string> }`.
359
+ `scriptName`'s bindings will be used as "inner bindings". JSON `bindings` in
360
+ the `designator` also become "inner bindings" and will override any of
361
+ `scriptName` bindings with the same name. The Worker named `scriptName`...
362
+
363
+ - Must define a single `ESModule` as its source, using
364
+ `{ modules: true, script: "..." }`, `{ modules: true, scriptPath: "..." }`,
365
+ or `{ modules: [...] }`
366
+ - Must provide the function to use for the wrapped binding as an `entrypoint`
367
+ named export or a default export if `entrypoint` is omitted
368
+ - Must not be the first/entrypoint worker
369
+ - Must not be bound to with service or Durable Object bindings
370
+ - Must not define `compatibilityDate` or `compatibilityFlags`
371
+ - Must not define `outboundService`
372
+ - Must not directly or indirectly have a wrapped binding to itself
373
+ - Must not be used as an argument to `Miniflare#getWorker()`
374
+
375
+ <details>
376
+ <summary><b>Wrapped Bindings Example</b></summary>
377
+
378
+ ```ts
379
+ import { Miniflare } from "miniflare";
380
+ const store = new Map<string, string>();
381
+ const mf = new Miniflare({
382
+ workers: [
383
+ {
384
+ wrappedBindings: {
385
+ MINI_KV: {
386
+ scriptName: "mini-kv", // Use Worker named `mini-kv` for implementation
387
+ bindings: { NAMESPACE: "ns" }, // Override `NAMESPACE` inner binding
388
+ },
389
+ },
390
+ modules: true,
391
+ script: `export default {
392
+ async fetch(request, env, ctx) {
393
+ // Example usage of wrapped binding
394
+ await env.MINI_KV.set("key", "value");
395
+ return new Response(await env.MINI_KV.get("key"));
396
+ }
397
+ }`,
398
+ },
399
+ {
400
+ name: "mini-kv",
401
+ serviceBindings: {
402
+ // Function-valued service binding for accessing Node.js state
403
+ async STORE(request) {
404
+ const { pathname } = new URL(request.url);
405
+ const key = pathname.substring(1);
406
+ if (request.method === "GET") {
407
+ const value = store.get(key);
408
+ const status = value === undefined ? 404 : 200;
409
+ return new Response(value ?? null, { status });
410
+ } else if (request.method === "PUT") {
411
+ const value = await request.text();
412
+ store.set(key, value);
413
+ return new Response(null, { status: 204 });
414
+ } else if (request.method === "DELETE") {
415
+ store.delete(key);
416
+ return new Response(null, { status: 204 });
417
+ } else {
418
+ return new Response(null, { status: 405 });
419
+ }
420
+ },
421
+ },
422
+ modules: true,
423
+ script: `
424
+ // Implementation of binding
425
+ class MiniKV {
426
+ constructor(env) {
427
+ this.STORE = env.STORE;
428
+ this.baseURL = "http://x/" + (env.NAMESPACE ?? "") + ":";
429
+ }
430
+ async get(key) {
431
+ const res = await this.STORE.fetch(this.baseURL + key);
432
+ return res.status === 404 ? null : await res.text();
433
+ }
434
+ async set(key, body) {
435
+ await this.STORE.fetch(this.baseURL + key, { method: "PUT", body });
436
+ }
437
+ async delete(key) {
438
+ await this.STORE.fetch(this.baseURL + key, { method: "DELETE" });
439
+ }
440
+ }
441
+
442
+ // env has the type { STORE: Fetcher, NAMESPACE?: string }
443
+ export default function (env) {
444
+ return new MiniKV(env);
445
+ }
446
+ `,
447
+ },
448
+ ],
449
+ });
450
+ ```
451
+
452
+ </details>
453
+
454
+ > :warning: `wrappedBindings` are only supported in modules format Workers.
455
+
456
+ <!--prettier-ignore-end-->
457
+
458
+ - `outboundService?: string | { network: Network } | { external: ExternalServer } | { disk: DiskDirectory } | (request: Request) => Awaitable<Response>`
459
+
460
+ Dispatch this Worker's global `fetch()` and `connect()` requests to the
461
+ configured service. Service designators follow the same rules above for
462
+ `serviceBindings`.
463
+
464
+ - `fetchMock?: import("undici").MockAgent`
465
+
466
+ An [`undici` `MockAgent`](https://undici.nodejs.org/#/docs/api/MockAgent) to
467
+ dispatch this Worker's global `fetch()` requests through.
468
+
469
+ > :warning: `outboundService` and `fetchMock` are mutually exclusive options.
470
+ > At most one of them may be specified per Worker.
471
+
472
+ - `routes?: string[]`
473
+
474
+ Array of route patterns for this Worker. These follow the same
475
+ [routing rules](https://developers.cloudflare.com/workers/platform/triggers/routes/#matching-behavior)
476
+ as deployed Workers. If no routes match, Miniflare will fallback to the Worker
477
+ defined first.
478
+
479
+ #### Cache
480
+
481
+ - `cache?: boolean`
482
+
483
+ If `false`, default and named caches will be disabled. The Cache API will
484
+ still be available, it just won't cache anything.
485
+
486
+ - `cacheWarnUsage?: boolean`
487
+
488
+ If `true`, the first use of the Cache API will log a warning stating that the
489
+ Cache API is unsupported on `workers.dev` subdomains.
490
+
491
+ #### Durable Objects
492
+
493
+ - `durableObjects?: Record<string, string | { className: string, scriptName?: string }>`
494
+
495
+ Record mapping binding name to Durable Object class designators to inject as
496
+ `DurableObjectNamespace` bindings into this Worker.
497
+
498
+ - If the designator is a `string`, it should be the name of a `class` exported
499
+ by this Worker.
500
+ - If the designator is an object, and `scriptName` is `undefined`, `className`
501
+ should be the name of a `class` exported by this Worker.
502
+ - Otherwise, `className` should be the name of a `class` exported by the
503
+ Worker with a `name` of `scriptName`.
504
+
505
+ #### KV
506
+
507
+ - `kvNamespaces?: Record<string, string> | string[]`
508
+
509
+ Record mapping binding name to KV namespace IDs to inject as `KVNamespace`
510
+ bindings into this Worker. Different Workers may bind to the same namespace ID
511
+ with different binding names. If a `string[]` of binding names is specified,
512
+ the binding name and KV namespace ID are assumed to be the same.
513
+
514
+ - `sitePath?: string`
515
+
516
+ Path to serve Workers Sites files from. If set, `__STATIC_CONTENT` and
517
+ `__STATIC_CONTENT_MANIFEST` bindings will be injected into this Worker. In
518
+ modules mode, `__STATIC_CONTENT_MANIFEST` will also be exposed as a module
519
+ with a `string`-typed `default` export, containing the JSON-stringified
520
+ manifest. Note Workers Sites files are never cached in Miniflare.
521
+
522
+ - `siteInclude?: string[]`
523
+
524
+ If set, only files with paths matching these glob patterns will be served.
525
+
526
+ - `siteExclude?: string[]`
527
+
528
+ If set, only files with paths _not_ matching these glob patterns will be
529
+ served.
530
+
531
+ - `assetsPath?: string`
532
+
533
+ Path to serve Workers assets from.
534
+
535
+ - `assetsKVBindingName?: string`
536
+ Name of the binding to the KV namespace that the assets are in. If `assetsPath` is set, this binding will be injected into this Worker.
537
+
538
+ - `assetsManifestBindingName?: string`
539
+ Name of the binding to an `ArrayBuffer` containing the binary-encoded assets manifest. If `assetsPath` is set, this binding will be injected into this Worker.
540
+
541
+ #### R2
542
+
543
+ - `r2Buckets?: Record<string, string> | string[]`
544
+
545
+ Record mapping binding name to R2 bucket names to inject as `R2Bucket`
546
+ bindings into this Worker. Different Workers may bind to the same bucket name
547
+ with different binding names. If a `string[]` of binding names is specified,
548
+ the binding name and bucket name are assumed to be the same.
549
+
550
+ #### D1
551
+
552
+ - `d1Databases?: Record<string, string> | string[]`
553
+
554
+ Record mapping binding name to D1 database IDs to inject as `D1Database`
555
+ bindings into this Worker. Note binding names starting with `__D1_BETA__` are
556
+ injected as `Fetcher` bindings instead, and must be wrapped with a facade to
557
+ provide the expected `D1Database` API. Different Workers may bind to the same
558
+ database ID with different binding names. If a `string[]` of binding names is
559
+ specified, the binding name and database ID are assumed to be the same.
560
+
561
+ #### Queues
562
+
563
+ - `queueProducers?: Record<string, QueueProducerOptions> | string[]`
564
+
565
+ Record mapping binding name to queue options to inject as `WorkerQueue` bindings
566
+ into this Worker. Different Workers may bind to the same queue name with
567
+ different binding names. If a `string[]` of binding names is specified, the
568
+ binding name and queue name (part of the queue options) are assumed to be the same.
569
+
570
+ - `queueConsumers?: Record<string, QueueConsumerOptions> | string[]`
571
+
572
+ Record mapping queue name to consumer options. Messages enqueued on the
573
+ corresponding queues will be dispatched to this Worker. Note each queue can
574
+ have at most one consumer. If a `string[]` of queue names is specified,
575
+ default consumer options will be used.
576
+
577
+ #### Analytics Engine, Sending Email, Vectorize and Workers for Platforms
578
+
579
+ _Not yet supported_
580
+
581
+ If you need support for these locally, consider using the `wrappedBindings`
582
+ option to mock them out.
583
+
584
+ #### Browser Rendering and Workers AI
585
+
586
+ _Not yet supported_
587
+
588
+ If you need support for these locally, consider using the `serviceBindings`
589
+ option to mock them out.
590
+
591
+ ### `interface SharedOptions`
592
+
593
+ Options shared between all Workers/"nanoservices".
594
+
595
+ #### Core
596
+
597
+ - `rootPath?: string`
598
+
599
+ Path against which all other path options for this instance are resolved
600
+ relative to. Defaults to the current working directory.
601
+
602
+ - `host?: string`
603
+
604
+ Hostname that the `workerd` server should listen on. Defaults to `127.0.0.1`.
605
+
606
+ - `port?: number`
607
+
608
+ Port that the `workerd` server should listen on. Tries to default to `8787`,
609
+ but falls back to a random free port if this is in use. Note if a manually
610
+ specified port is in use, Miniflare throws an error, rather than attempting to
611
+ find a free port.
612
+
613
+ - `https?: boolean`
614
+
615
+ If `true`, start an HTTPS server using a pre-generated self-signed certificate
616
+ for `localhost`. Note this certificate is not valid for any other hostnames or
617
+ IP addresses. If you need to access the HTTPS server from another device,
618
+ you'll need to generate your own certificate and use the other `https*`
619
+ options below.
620
+
621
+ ```shell
622
+ $ openssl req -newkey rsa:2048 -nodes -keyout key.pem -x509 -days 365 -out cert.pem
623
+ ```
624
+
625
+ ```js
626
+ new Miniflare({
627
+ httpsKeyPath: "key.pem",
628
+ httpsCertPath: "cert.pem",
629
+ });
630
+ ```
631
+
632
+ - `httpsKey?: string`
633
+
634
+ When one of `httpsCert` or `httpCertPath` is also specified, starts an HTTPS
635
+ server using the value of this option as the PEM encoded private key.
636
+
637
+ - `httpsKeyPath?: string`
638
+
639
+ When one of `httpsCert` or `httpCertPath` is also specified, starts an HTTPS
640
+ server using the PEM encoded private key stored at this file path.
641
+
642
+ - `httpsCert?: string`
643
+
644
+ When one of `httpsKey` or `httpsKeyPath` is also specified, starts an HTTPS
645
+ server using the value of this option as the PEM encoded certificate chain.
646
+
647
+ - `httpsCertPath?: string`
648
+
649
+ When one of `httpsKey` or `httpsKeyPath` is also specified, starts an HTTPS
650
+ server using the PEM encoded certificate chain stored at this file path.
651
+
652
+ - `inspectorPort?: number`
653
+
654
+ Port that `workerd` should start a DevTools inspector server on. Visit
655
+ `chrome://inspect` in a Chromium-based browser to connect to this. This can be
656
+ used to see detailed `console.log`s, profile CPU usage, and will eventually
657
+ allow step-through debugging.
658
+
659
+ - `verbose?: boolean`
660
+
661
+ Enable `workerd`'s `--verbose` flag for verbose logging. This can be used to
662
+ see simplified `console.log`s.
663
+
664
+ - `log?: Log`
665
+
666
+ Logger implementation for Miniflare's errors, warnings and informative
667
+ messages.
668
+
669
+ - `upstream?: string`
670
+
671
+ URL to use as the origin for incoming requests. If specified, all incoming
672
+ `request.url`s will be rewritten to start with this string. This is especially
673
+ useful when testing Workers that act as a proxy, and not as origins
674
+ themselves.
675
+
676
+ - `cf?: boolean | string | Record<string, any>`
677
+
678
+ Controls the object returned from incoming `Request`'s `cf` property.
679
+
680
+ - If set to a falsy value, an object with default placeholder values will be
681
+ used
682
+ - If set to an object, that object will be used
683
+ - If set to `true`, a real `cf` object will be fetched from a trusted
684
+ Cloudflare endpoint and cached in `node_modules/.mf` for 30 days
685
+ - If set to a `string`, a real `cf` object will be fetched and cached at the
686
+ provided path for 30 days
687
+
688
+ - `liveReload?: boolean`
689
+
690
+ If `true`, Miniflare will inject a script into HTML responses that
691
+ automatically reloads the page in-browser whenever the Miniflare instance's
692
+ options are updated.
693
+
694
+ #### Cache, Durable Objects, KV, R2 and D1
695
+
696
+ - `cachePersist?: Persistence`
697
+
698
+ Where to persist data cached in default or named caches. See docs for
699
+ `Persistence`.
700
+
701
+ - `durableObjectsPersist?: Persistence`
702
+
703
+ Where to persist data stored in Durable Objects. See docs for `Persistence`.
704
+
705
+ - `kvPersist?: Persistence`
706
+
707
+ Where to persist data stored in KV namespaces. See docs for `Persistence`.
708
+
709
+ - `r2Persist?: Persistence`
710
+
711
+ Where to persist data stored in R2 buckets. See docs for `Persistence`.
712
+
713
+ - `d1Persist?: Persistence`
714
+
715
+ Where to persist data stored in D1 databases. See docs for `Persistence`.
716
+
717
+ #### Analytics Engine, Browser Rendering, Sending Email, Vectorize, Workers AI and Workers for Platforms
718
+
719
+ _Not yet supported_
720
+
721
+ ### `type MiniflareOptions`
722
+
723
+ `SharedOptions & (WorkerOptions | { workers: WorkerOptions[] })`
724
+
725
+ Miniflare accepts either a single Worker configuration or multiple Worker
726
+ configurations in the `workers` array. When specifying an array of Workers, the
727
+ first Worker is designated the entrypoint and will receive all incoming HTTP
728
+ requests. Some options are shared between all workers and should always be
729
+ defined at the top-level.
730
+
731
+ ### `class Miniflare`
732
+
733
+ - `constructor(opts: MiniflareOptions)`
734
+
735
+ Creates a Miniflare instance and starts a new `workerd` server. Note unlike
736
+ Miniflare 2, Miniflare 3 _always_ starts a HTTP server listening on the
737
+ configured `host` and `port`: there are no `createServer`/`startServer`
738
+ functions.
739
+
740
+ - `setOptions(opts: MiniflareOptions)`
741
+
742
+ Updates the configuration for this Miniflare instance and restarts the
743
+ `workerd` server. Note unlike Miniflare 2, this does _not_ merge the new
744
+ configuration with the old configuration. Note that calling this function will
745
+ invalidate any existing values returned by the `Miniflare#get*()` methods,
746
+ preventing them from being used.
747
+
748
+ - `ready: Promise<URL>`
749
+
750
+ Returns a `Promise` that resolves with a `http` `URL` to the `workerd` server
751
+ once it has started and is able to accept requests.
752
+
753
+ - `dispatchFetch(input: RequestInfo, init?: RequestInit): Promise<Response>`
754
+
755
+ Sends a HTTP request to the `workerd` server, dispatching a `fetch` event in
756
+ the entrypoint Worker. Returns a `Promise` that resolves with the response.
757
+ Note that this implicitly waits for the `ready` `Promise` to resolve, there's
758
+ no need to do that yourself first. Additionally, the host of the request's URL
759
+ is always ignored and replaced with the `workerd` server's.
760
+
761
+ - `getBindings<Env extends Record<string, unknown> = Record<string, unknown>>(workerName?: string): Promise<Env>`
762
+
763
+ Returns a `Promise` that resolves with a record mapping binding names to
764
+ bindings, for all bindings in the Worker with the specified `workerName`. If
765
+ `workerName` is not specified, defaults to the entrypoint Worker.
766
+
767
+ - `getWorker(workerName?: string): Promise<Fetcher>`
768
+
769
+ Returns a `Promise` that resolves with a
770
+ [`Fetcher`](https://workers-types.pages.dev/experimental/#Fetcher) pointing to
771
+ the specified `workerName`. If `workerName` is not specified, defaults to the
772
+ entrypoint Worker. Note this `Fetcher` uses the experimental
773
+ [`service_binding_extra_handlers`](https://github.com/cloudflare/workerd/blob/1d9158af7ca1389474982c76ace9e248320bec77/src/workerd/io/compatibility-date.capnp#L290-L297)
774
+ compatibility flag to expose
775
+ [`scheduled()`](https://workers-types.pages.dev/experimental/#Fetcher.scheduled)
776
+ and [`queue()`](https://workers-types.pages.dev/experimental/#Fetcher.queue)
777
+ methods for dispatching `scheduled` and `queue` events.
778
+
779
+ - `getCaches(): Promise<CacheStorage>`
780
+
781
+ Returns a `Promise` that resolves with the
782
+ [`CacheStorage`](https://developers.cloudflare.com/workers/runtime-apis/cache/)
783
+ instance of the entrypoint Worker. This means if `cache: false` is set on the
784
+ entrypoint, calling methods on the resolved value won't do anything.
785
+
786
+ - `getD1Database(bindingName: string, workerName?: string): Promise<D1Database>`
787
+
788
+ Returns a `Promise` that resolves with the
789
+ [`D1Database`](https://developers.cloudflare.com/d1/platform/client-api/)
790
+ instance corresponding to the specified `bindingName` of `workerName`. Note
791
+ `bindingName` must not begin with `__D1_BETA__`. If `workerName` is not
792
+ specified, defaults to the entrypoint Worker.
793
+
794
+ - `getDurableObjectNamespace(bindingName: string, workerName?: string): Promise<DurableObjectNamespace>`
795
+
796
+ Returns a `Promise` that resolves with the
797
+ [`DurableObjectNamespace`](https://developers.cloudflare.com/workers/runtime-apis/durable-objects/#access-a-durable-object-from-a-worker)
798
+ instance corresponding to the specified `bindingName` of `workerName`. If
799
+ `workerName` is not specified, defaults to the entrypoint Worker.
800
+
801
+ - `getKVNamespace(bindingName: string, workerName?: string): Promise<KVNamespace>`
802
+
803
+ Returns a `Promise` that resolves with the
804
+ [`KVNamespace`](https://developers.cloudflare.com/workers/runtime-apis/kv/)
805
+ instance corresponding to the specified `bindingName` of `workerName`. If
806
+ `workerName` is not specified, defaults to the entrypoint Worker.
807
+
808
+ - `getQueueProducer<Body>(bindingName: string, workerName?: string): Promise<Queue<Body>>`
809
+
810
+ Returns a `Promise` that resolves with the
811
+ [`Queue`](https://developers.cloudflare.com/queues/platform/javascript-apis/)
812
+ producer instance corresponding to the specified `bindingName` of
813
+ `workerName`. If `workerName` is not specified, defaults to the entrypoint
814
+ Worker.
815
+
816
+ - `getR2Bucket(bindingName: string, workerName?: string): Promise<R2Bucket>`
817
+
818
+ Returns a `Promise` that resolves with the
819
+ [`R2Bucket`](https://developers.cloudflare.com/r2/api/workers/workers-api-reference/)
820
+ producer instance corresponding to the specified `bindingName` of
821
+ `workerName`. If `workerName` is not specified, defaults to the entrypoint
822
+ Worker.
823
+
824
+ - `dispose(): Promise<void>`
825
+
826
+ Cleans up the Miniflare instance, and shuts down the `workerd` server. Note
827
+ that after this is called, `Miniflare#setOptions()` and
828
+ `Miniflare#dispatchFetch()` cannot be called. Additionally, calling this
829
+ function will invalidate any values returned by the `Miniflare#get*()`
830
+ methods, preventing them from being used.
831
+
832
+ - `getCf(): Promise<Record<string, any>>`
833
+
834
+ Returns the same object returned from incoming `Request`'s `cf` property. This
835
+ object depends on the `cf` property from `SharedOptions`.
836
+
837
+ ## Configuration
838
+
839
+ ### Local `workerd`
840
+
841
+ You can override the `workerd` binary being used by miniflare with a your own local build by setting the `MINIFLARE_WORKERD_PATH` environment variable.
842
+
843
+ For example:
844
+
845
+ ```shell
846
+ $ export MINIFLARE_WORKERD_PATH="<WORKERD_REPO_DIR>/bazel-bin/src/workerd/server/workerd"
847
+ ```