wrangler 4.98.0 → 4.100.0

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.
@@ -1,14 +1,15 @@
1
- import { Rule as Rule$1, CfModule, Environment as Environment$1, Entry, CfModuleType, ApiCredentials, Config as Config$1, Binding, DurableObjectMigration as DurableObjectMigration$1, ContainerApp as ContainerApp$1, Trigger, CfTailConsumer, ServiceFetch, ContainerEngine as ContainerEngine$1, CfUnsafe, CfScriptFormat, AssetsOptions as AssetsOptions$1, ConfigBindingFieldName, NormalizeAndValidateConfigArgs, ResolveConfigPathOptions, RawConfig as RawConfig$1, PackageJSON, ParseError, ComplianceConfig, UserError, FatalError } from '@cloudflare/workers-utils';
1
+ import { Rule as Rule$1, CfModule, Environment as Environment$1, Entry, CfModuleType, StartDevWorkerInput, NodeJSCompatMode, CfScriptFormat, Config as Config$1, AsyncHook, CfAccount as CfAccount$1, AssetsOptions as AssetsOptions$1, Binding, ConfigBindingFieldName, RawConfig as RawConfig$1, NormalizeAndValidateConfigArgs, ResolveConfigPathOptions, PackageJSON, ApiCredentials, ParseError, LoggerLevel, ComplianceConfig, UserError, FatalError } from '@cloudflare/workers-utils';
2
2
  export { Binding, experimental_patchConfig, experimental_readRawConfig, defaultWranglerConfig as unstable_defaultWranglerConfig } from '@cloudflare/workers-utils';
3
- import { Json as Json$1, WorkerRegistry, Miniflare, MiniflareOptions, Mutex, Response as Response$1, NodeJSCompatMode, DispatchFetch, RemoteProxyConnectionString, WorkerOptions, ModuleRule, Request } from 'miniflare';
3
+ import { Json as Json$1, WorkerdStructuredLog, DispatchFetch, Miniflare, WorkerRegistry, MiniflareOptions, Mutex, Response as Response$1, RemoteProxyConnectionString, WorkerOptions, ModuleRule, Request } from 'miniflare';
4
4
  import * as undici from 'undici';
5
5
  import { RequestInfo, RequestInit, Response, FormData } from 'undici';
6
6
  import { Metafile } from 'esbuild';
7
7
  import Protocol from 'devtools-protocol/types/protocol-mapping';
8
8
  import { EventEmitter } from 'node:events';
9
9
  import { ContainerNormalizedConfig } from '@cloudflare/containers-shared';
10
+ import { FetcherScheduledOptions, FetcherScheduledResult, IncomingRequestCfProperties } from '@cloudflare/workers-types/experimental';
10
11
  import { RouterConfig, AssetConfig } from '@cloudflare/workers-shared';
11
- import { IncomingRequestCfProperties } from '@cloudflare/workers-types/experimental';
12
+ export { printBindings as unstable_printBindings } from '@cloudflare/deploy-helpers';
12
13
  import { URLSearchParams } from 'node:url';
13
14
  import { Argv, PositionalOptions, Options, ArgumentsCamelCase, InferredOptionTypes, InferredOptionType } from 'yargs';
14
15
  import Cloudflare from 'cloudflare';
@@ -168,8 +169,8 @@ interface PagesDeployOptions {
168
169
  */
169
170
  declare function deploy({ directory, accountId, projectName, branch, skipCaching, commitMessage, commitHash, commitDirty, functionsDirectory: customFunctionsDirectory, bundle, sourceMaps, args, }: PagesDeployOptions): Promise<{
170
171
  deploymentResponse: {
171
- url: string;
172
172
  id: string;
173
+ url: string;
173
174
  environment: "production" | "preview";
174
175
  build_config: {
175
176
  build_command: string;
@@ -192,14 +193,14 @@ declare function deploy({ directory, accountId, projectName, branch, skipCaching
192
193
  };
193
194
  };
194
195
  latest_stage: {
195
- status: "skipped" | "active" | "canceled" | "idle" | "success" | "failure";
196
- name: "build" | "queued" | "deploy" | "initialize" | "clone_repo";
196
+ status: "skipped" | "active" | "canceled" | "success" | "idle" | "failure";
197
+ name: "queued" | "build" | "deploy" | "initialize" | "clone_repo";
197
198
  started_on: string | null;
198
199
  ended_on: string | null;
199
200
  };
200
201
  stages: {
201
- status: "skipped" | "active" | "canceled" | "idle" | "success" | "failure";
202
- name: "build" | "queued" | "deploy" | "initialize" | "clone_repo";
202
+ status: "skipped" | "active" | "canceled" | "success" | "idle" | "failure";
203
+ name: "queued" | "build" | "deploy" | "initialize" | "clone_repo";
203
204
  started_on: string | null;
204
205
  ended_on: string | null;
205
206
  }[];
@@ -303,6 +304,13 @@ type Experimental_GenerateTypesResult = GenerateTypesResult;
303
304
  */
304
305
  declare function generateTypes(options: Experimental_GenerateTypesOptions): Promise<Experimental_GenerateTypesResult>;
305
306
 
307
+ type _Params<ParamsArray extends [unknown?]> = ParamsArray extends [infer P] ? P : undefined;
308
+ type _EventMethods = keyof Protocol.Events;
309
+ type DevToolsEvent<Method extends _EventMethods> = Method extends unknown ? {
310
+ method: Method;
311
+ params: _Params<Protocol.Events[Method]>;
312
+ } : never;
313
+
306
314
  /**
307
315
  * Information about Wrangler's bundling process that needs passed through
308
316
  * for DevTools sourcemap transformation
@@ -324,28 +332,64 @@ type EsbuildBundle = {
324
332
  sourceMapMetadata: SourceMapMetadata | undefined;
325
333
  };
326
334
 
327
- /**
328
- * A Cloudflare account.
329
- */
330
- interface CfAccount {
331
- /**
332
- * An API token.
333
- *
334
- * @link https://api.cloudflare.com/#user-api-tokens-properties
335
- */
336
- apiToken: ApiCredentials;
337
- /**
338
- * An account ID.
339
- */
340
- accountId: string;
335
+ declare class ConfigController extends Controller {
336
+ #private;
337
+ latestInput?: StartDevWorkerInput;
338
+ latestConfig?: StartDevWorkerOptions;
339
+ set(input: StartDevWorkerInput, throwErrors?: boolean): Promise<StartDevWorkerOptions | undefined>;
340
+ patch(input: Partial<StartDevWorkerInput>): Promise<StartDevWorkerOptions | undefined>;
341
+ onDevRegistryUpdate(event: DevRegistryUpdateEvent): void;
342
+ teardown(): Promise<void>;
343
+ emitConfigUpdateEvent(config: StartDevWorkerOptions): void;
341
344
  }
342
345
 
343
- type _Params<ParamsArray extends [unknown?]> = ParamsArray extends [infer P] ? P : undefined;
344
- type _EventMethods = keyof Protocol.Events;
345
- type DevToolsEvent<Method extends _EventMethods> = Method extends unknown ? {
346
- method: Method;
347
- params: _Params<Protocol.Events[Method]>;
348
- } : never;
346
+ type MiniflareWorker = Awaited<ReturnType<Miniflare["getWorker"]>>;
347
+ interface Worker {
348
+ ready: Promise<void>;
349
+ url: Promise<URL>;
350
+ inspectorUrl: Promise<URL | undefined>;
351
+ config: StartDevWorkerOptions;
352
+ setConfig: ConfigController["set"];
353
+ patchConfig: ConfigController["patch"];
354
+ fetch: DispatchFetch;
355
+ scheduled: MiniflareWorker["scheduled"];
356
+ queue: MiniflareWorker["queue"];
357
+ dispose(): Promise<void>;
358
+ raw: DevEnv;
359
+ }
360
+ type StartDevWorkerOptions = Omit<StartDevWorkerInput, "assets" | "config" | "containers" | "dev"> & {
361
+ /** The configuration path of the worker */
362
+ config?: string;
363
+ /** A worker's directory. Usually where the Wrangler configuration file is located */
364
+ projectRoot: string;
365
+ build: StartDevWorkerInput["build"] & {
366
+ nodejsCompatMode: NodeJSCompatMode;
367
+ format: CfScriptFormat;
368
+ moduleRoot: string;
369
+ moduleRules: Rule$1[];
370
+ define: Record<string, string>;
371
+ additionalModules: CfModule[];
372
+ exports: string[];
373
+ processEntrypoint: boolean;
374
+ };
375
+ legacy: StartDevWorkerInput["legacy"] & {
376
+ site?: Config$1["site"];
377
+ };
378
+ dev: StartDevWorkerInput["dev"] & {
379
+ persist: string | false;
380
+ auth?: AsyncHook<CfAccount$1>;
381
+ /** Handles structured runtime logs. */
382
+ structuredLogsHandler?: (log: WorkerdStructuredLog) => void;
383
+ /** An undici MockAgent to declaratively mock fetch calls to particular resources. */
384
+ mockFetch?: undici.MockAgent;
385
+ };
386
+ entrypoint: string;
387
+ assets?: AssetsOptions$1;
388
+ containers?: ContainerNormalizedConfig[];
389
+ name: string;
390
+ complianceRegion: Config$1["compliance_region"];
391
+ };
392
+ type Bundle = EsbuildBundle;
349
393
 
350
394
  type ErrorEvent = BaseErrorEvent<"ConfigController" | "BundlerController" | "LocalRuntimeController" | "RemoteRuntimeController" | "ProxyWorker" | "InspectorProxyWorker" | "MultiworkerRuntimeController"> | BaseErrorEvent<"ProxyController", {
351
395
  config?: StartDevWorkerOptions;
@@ -470,22 +514,12 @@ declare abstract class RuntimeController extends Controller {
470
514
  abstract onBundleStart(_: BundleStartEvent): void;
471
515
  abstract onBundleComplete(_: BundleCompleteEvent): void;
472
516
  abstract onPreviewTokenExpired(_: PreviewTokenExpiredEvent): void;
517
+ abstract get mf(): Miniflare | undefined;
473
518
  protected emitReloadStartEvent(data: ReloadStartEvent): void;
474
519
  protected emitReloadCompleteEvent(data: ReloadCompleteEvent): void;
475
520
  protected emitDevRegistryUpdateEvent(data: DevRegistryUpdateEvent): void;
476
521
  }
477
522
 
478
- declare class ConfigController extends Controller {
479
- #private;
480
- latestInput?: StartDevWorkerInput;
481
- latestConfig?: StartDevWorkerOptions;
482
- set(input: StartDevWorkerInput, throwErrors?: boolean): Promise<StartDevWorkerOptions | undefined>;
483
- patch(input: Partial<StartDevWorkerInput>): Promise<StartDevWorkerOptions | undefined>;
484
- onDevRegistryUpdate(event: DevRegistryUpdateEvent): void;
485
- teardown(): Promise<void>;
486
- emitConfigUpdateEvent(config: StartDevWorkerOptions): void;
487
- }
488
-
489
523
  declare class BundlerController extends Controller {
490
524
  #private;
491
525
  onConfigUpdate(event: ConfigUpdateEvent): void;
@@ -494,6 +528,13 @@ declare class BundlerController extends Controller {
494
528
  emitBundleCompleteEvent(config: StartDevWorkerOptions, bundle: EsbuildBundle): void;
495
529
  }
496
530
 
531
+ type MaybePromise<T> = T | Promise<T>;
532
+ type DeferredPromise<T> = {
533
+ promise: Promise<T>;
534
+ resolve: (_: MaybePromise<T>) => void;
535
+ reject: (_: Error) => void;
536
+ };
537
+
497
538
  declare class ProxyController extends Controller {
498
539
  ready: DeferredPromise<ReadyEvent>;
499
540
  localServerReady: DeferredPromise<void>;
@@ -560,213 +601,294 @@ declare class DevEnv extends EventEmitter implements ControllerBus {
560
601
  teardown(): Promise<void>;
561
602
  }
562
603
 
563
- type MiniflareWorker = Awaited<ReturnType<Miniflare["getWorker"]>>;
564
- interface Worker {
565
- ready: Promise<void>;
566
- url: Promise<URL>;
567
- inspectorUrl: Promise<URL | undefined>;
568
- config: StartDevWorkerOptions;
569
- setConfig: ConfigController["set"];
570
- patchConfig: ConfigController["patch"];
571
- fetch: DispatchFetch;
572
- scheduled: MiniflareWorker["scheduled"];
573
- queue: MiniflareWorker["queue"];
574
- dispose(): Promise<void>;
575
- raw: DevEnv;
576
- }
577
- interface StartDevWorkerInput {
578
- /** The name of the worker. */
579
- name?: string;
580
- /**
581
- * The javascript or typescript entry-point of the worker.
582
- * This is the `main` property of a Wrangler configuration file.
583
- */
584
- entrypoint?: string;
585
- /** The configuration path of the worker. */
586
- config?: string;
587
- /** The compatibility date for the workerd runtime. */
588
- compatibilityDate?: string;
589
- /** The compatibility flags for the workerd runtime. */
590
- compatibilityFlags?: string[];
591
- /** Specify the compliance region mode of the Worker. */
592
- complianceRegion?: Config$1["compliance_region"];
593
- /** Configuration for Python modules. */
594
- pythonModules?: {
595
- /** A list of glob patterns to exclude files from the python_modules directory when bundling. */
596
- exclude?: string[];
604
+ declare function startWorker(options: StartDevWorkerInput): Promise<Worker>;
605
+
606
+ declare const dev: {
607
+ args: {
608
+ v: boolean | undefined;
609
+ cwd: string | undefined;
610
+ config: string | undefined;
611
+ env: string | undefined;
612
+ envFile: string[] | undefined;
613
+ experimentalProvision: boolean | undefined;
614
+ experimentalAutoCreate: boolean;
615
+ installSkills: boolean;
616
+ script: string | undefined;
617
+ name: string | undefined;
618
+ compatibilityDate: string | undefined;
619
+ compatibilityFlags: string[] | undefined;
620
+ latest: boolean;
621
+ assets: string | undefined;
622
+ bundle: boolean | undefined;
623
+ noBundle: boolean;
624
+ ip: string | undefined;
625
+ port: number | undefined;
626
+ inspectorPort: number | undefined;
627
+ inspectorIp: string | undefined;
628
+ routes: string[] | undefined;
629
+ host: string | undefined;
630
+ localProtocol: "http" | "https" | undefined;
631
+ httpsKeyPath: string | undefined;
632
+ httpsCertPath: string | undefined;
633
+ localUpstream: string | undefined;
634
+ enableContainers: boolean | undefined;
635
+ site: string | undefined;
636
+ siteInclude: string[] | undefined;
637
+ siteExclude: string[] | undefined;
638
+ upstreamProtocol: "http" | "https" | undefined;
639
+ var: string[] | undefined;
640
+ define: string[] | undefined;
641
+ alias: string[] | undefined;
642
+ jsxFactory: string | undefined;
643
+ jsxFragment: string | undefined;
644
+ tsconfig: string | undefined;
645
+ remote: boolean;
646
+ local: boolean | undefined;
647
+ minify: boolean | undefined;
648
+ nodeCompat: boolean | undefined;
649
+ persistTo: string | undefined;
650
+ liveReload: boolean | undefined;
651
+ legacyEnv: boolean | undefined;
652
+ testScheduled: boolean;
653
+ logLevel: "debug" | "none" | "error" | "log" | "info" | "warn" | undefined;
654
+ showInteractiveDevSession: boolean | undefined;
655
+ types: boolean | undefined;
656
+ tunnel: boolean | undefined;
657
+ tunnelName: string | undefined;
658
+ experimentalNewConfig: boolean;
659
+ _: (string | number)[];
660
+ $0: string;
597
661
  };
598
- env?: string;
599
- /**
600
- * An array of paths to the .env files to load for this worker, relative to the project directory.
601
- *
602
- * If not specified, defaults to the standard `.env` files as given by `getDefaultEnvFiles()`.
603
- * The project directory is where the Wrangler configuration file is located or the current working directory otherwise.
604
- */
605
- envFiles?: string[];
606
- /** The bindings available to the worker. The specified bindind type will be exposed to the worker on the `env` object under the same key. */
607
- bindings?: Record<string, Binding>;
662
+ };
663
+ type AdditionalDevProps = {
608
664
  /**
609
- * Default bindings that can be overridden by config bindings.
665
+ * Default vars that can be overridden by config vars.
610
666
  * Useful for injecting environment-specific defaults like CF_PAGES variables.
611
667
  */
612
668
  defaultBindings?: Record<string, Extract<Binding, {
613
669
  type: "plain_text";
614
670
  }>>;
615
- migrations?: DurableObjectMigration$1[];
616
- containers?: ContainerApp$1[];
617
- /** The triggers which will cause the worker's exported default handlers to be called. */
618
- triggers?: Trigger[];
619
- tailConsumers?: CfTailConsumer[];
620
- streamingTailConsumers?: CfTailConsumer[];
621
- /**
622
- * Whether Wrangler should send usage metrics to Cloudflare for this project.
623
- *
624
- * When defined this will override any user settings.
625
- * Otherwise, Wrangler will use the user's preference.
626
- */
627
- sendMetrics?: boolean;
628
- /** Options applying to the worker's build step. Applies to deploy and dev. */
629
- build?: {
630
- /** Whether the worker and its dependencies are bundled. Defaults to true. */
631
- bundle?: boolean;
632
- additionalModules?: CfModule[];
633
- findAdditionalModules?: boolean;
634
- processEntrypoint?: boolean;
635
- /** Specifies types of modules matched by globs. */
636
- moduleRules?: Rule$1[];
637
- /** Replace global identifiers with constant expressions, e.g. { debug: 'true', version: '"1.0.0"' }. Only takes effect if bundle: true. */
638
- define?: Record<string, string>;
639
- /** Alias modules */
640
- alias?: Record<string, string>;
641
- /** Whether the bundled worker is minified. Only takes effect if bundle: true. */
642
- minify?: boolean;
643
- /** Whether to keep function names after JavaScript transpilations. */
644
- keepNames?: boolean;
645
- /** Options controlling a custom build step. */
646
- custom?: {
647
- /** Custom shell command to run before bundling. Runs even if bundle. */
648
- command?: string;
649
- /** The cwd to run the command in. */
650
- workingDirectory?: string;
651
- /** Filepath(s) to watch for changes. Upon changes, the command will be rerun. */
652
- watch?: string | string[];
653
- };
654
- jsxFactory?: string;
655
- jsxFragment?: string;
656
- tsconfig?: string;
657
- nodejsCompatMode?: Hook<NodeJSCompatMode, [Config$1]>;
658
- moduleRoot?: string;
659
- };
660
- /** Options applying to the worker's development preview environment. */
661
- dev?: {
662
- /** Options applying to the worker's inspector server. False disables the inspector server. */
663
- inspector?: {
664
- hostname?: string;
665
- port?: number;
666
- secure?: boolean;
667
- } | false;
668
- /** Whether the worker runs on the edge or locally. This has several options:
669
- * - true | "minimal": Run your Worker's code & bindings in a remote preview session, optionally using minimal mode as an internal detail
670
- * - false: Run your Worker's code & bindings in a local simulator
671
- * - undefined (default): Run your Worker's code locally, and any configured remote bindings remotely
672
- */
673
- remote?: boolean | "minimal";
674
- /** Cloudflare Account credentials. Can be provided upfront or as a function which will be called only when required. */
675
- auth?: AsyncHook<CfAccount, [Pick<Config$1, "account_id">]>;
676
- /** Whether local storage (KV, Durable Objects, R2, D1, etc) is persisted. You can also specify the directory to persist data to. Set to `false` to disable persistence. */
677
- persist?: string | false;
678
- /** Controls which logs are logged 🤙. */
679
- logLevel?: LogLevel;
680
- /** Whether the worker server restarts upon source/config file changes. */
681
- watch?: boolean;
682
- /** Whether a script tag is inserted on text/html responses which will reload the page upon file changes. Defaults to false. */
683
- liveReload?: boolean;
684
- /** The local address to reach your worker. Applies to remote: true (remote mode) and remote: false (local mode). */
685
- server?: {
686
- hostname?: string;
687
- port?: number;
688
- secure?: boolean;
689
- httpsKeyPath?: string;
690
- httpsCertPath?: string;
691
- };
692
- /** Controls what request.url looks like inside the worker. */
693
- origin?: {
694
- hostname?: string;
695
- secure?: boolean;
696
- };
697
- /** A hook for outbound fetch calls from within the worker. */
698
- outboundService?: ServiceFetch;
699
- /** An undici MockAgent to declaratively mock fetch calls to particular resources. */
700
- mockFetch?: undici.MockAgent;
701
- testScheduled?: boolean;
702
- /** Treat this as the primary worker in a multiworker setup (i.e. the first Worker in Miniflare's options) */
703
- multiworkerPrimary?: boolean;
704
- containerBuildId?: string;
705
- /** Whether to build and connect to containers during local dev. Requires Docker daemon to be running. Defaults to true. */
706
- enableContainers?: boolean;
707
- /** Path to the dev registry directory */
708
- registry?: string;
709
- /** Path to the docker executable. Defaults to 'docker' */
710
- dockerPath?: string;
711
- /** Options for the container engine */
712
- containerEngine?: ContainerEngine$1;
713
- /** Re-generate your worker types when your Wrangler configuration file changes */
714
- generateTypes?: boolean;
715
- /** Tunnel configuration for this dev session. */
716
- tunnel?: {
717
- enabled: boolean;
718
- name?: string;
719
- };
720
- };
721
- legacy?: {
722
- site?: Hook<Config$1["site"], [Config$1]>;
723
- useServiceEnvironments?: boolean;
724
- };
725
- unsafe?: Omit<CfUnsafe, "bindings">;
726
- assets?: string;
727
- experimental?: Record<string, never>;
728
- }
729
- type StartDevWorkerOptions = Omit<StartDevWorkerInput, "assets" | "containers" | "dev"> & {
730
- /** A worker's directory. Usually where the Wrangler configuration file is located */
731
- projectRoot: string;
732
- build: StartDevWorkerInput["build"] & {
733
- nodejsCompatMode: NodeJSCompatMode;
734
- format: CfScriptFormat;
735
- moduleRoot: string;
736
- moduleRules: Rule$1[];
737
- define: Record<string, string>;
738
- additionalModules: CfModule[];
739
- exports: string[];
740
- processEntrypoint: boolean;
671
+ vars?: Record<string, string | Json$1>;
672
+ kv?: {
673
+ binding: string;
674
+ id?: string;
675
+ preview_id?: string;
676
+ }[];
677
+ durableObjects?: {
678
+ name: string;
679
+ class_name: string;
680
+ script_name?: string | undefined;
681
+ environment?: string | undefined;
682
+ }[];
683
+ services?: {
684
+ binding: string;
685
+ service: string;
686
+ environment?: string;
687
+ entrypoint?: string;
688
+ }[];
689
+ r2?: {
690
+ binding: string;
691
+ bucket_name?: string;
692
+ preview_bucket_name?: string;
693
+ jurisdiction?: string;
694
+ }[];
695
+ ai?: {
696
+ binding: string;
741
697
  };
742
- legacy: StartDevWorkerInput["legacy"] & {
743
- site?: Config$1["site"];
698
+ stream?: {
699
+ binding: string;
700
+ remote?: boolean;
744
701
  };
745
- dev: StartDevWorkerInput["dev"] & {
746
- persist: string | false;
747
- auth?: AsyncHook<CfAccount>;
702
+ version_metadata?: {
703
+ binding: string;
748
704
  };
749
- entrypoint: string;
750
- assets?: AssetsOptions$1;
751
- containers?: ContainerNormalizedConfig[];
752
- name: string;
753
- complianceRegion: Config$1["compliance_region"];
705
+ d1Databases?: Array<Omit<Environment$1["d1_databases"][number], "database_id"> & {
706
+ database_id?: string;
707
+ }>;
708
+ processEntrypoint?: boolean;
709
+ additionalModules?: CfModule[];
710
+ moduleRoot?: string;
711
+ rules?: Rule$1[];
712
+ showInteractiveDevSession?: boolean;
754
713
  };
755
- type HookValues = string | number | boolean | object | undefined | null;
756
- type Hook<T extends HookValues, Args extends unknown[] = []> = T | ((...args: Args) => T);
757
- type AsyncHook<T extends HookValues, Args extends unknown[] = []> = Hook<T, Args> | Hook<Promise<T>, Args>;
758
- type Bundle = EsbuildBundle;
759
- type LogLevel = "debug" | "info" | "log" | "warn" | "error" | "none";
760
-
761
- type MaybePromise<T> = T | Promise<T>;
762
- type DeferredPromise<T> = {
763
- promise: Promise<T>;
764
- resolve: (_: MaybePromise<T>) => void;
765
- reject: (_: Error) => void;
714
+ type DevArguments = Omit<(typeof dev)["args"], "installSkills">;
715
+ type StartDevOptions = DevArguments & AdditionalDevProps & {
716
+ forceLocal?: boolean;
717
+ accountId?: string;
718
+ disableDevRegistry?: boolean;
719
+ enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
720
+ onReady?: (ip: string, port: number) => void;
721
+ enableIpc?: boolean;
722
+ dockerPath?: string;
723
+ containerEngine?: string;
724
+ /** Set to `false` to disable persistence. When `true` or `undefined`, uses default persistence path. */
725
+ persist?: boolean;
766
726
  };
727
+
767
728
  declare function convertConfigBindingsToStartWorkerBindings(configBindings: Partial<Pick<Config$1, ConfigBindingFieldName>>): StartDevWorkerOptions["bindings"];
768
729
 
769
- declare function startWorker(options: StartDevWorkerInput): Promise<Worker>;
730
+ type TestHarnessOptions = {
731
+ /**
732
+ * Base directory used to resolve relative worker config paths.
733
+ * Defaults to `process.cwd()`.
734
+ */
735
+ root?: string | undefined;
736
+ /**
737
+ * Workers to run in this server. The first worker is the primary worker.
738
+ */
739
+ workers: WorkerInput[];
740
+ };
741
+ type WorkerHandle = {
742
+ /**
743
+ * Dispatches a fetch event directly to this worker.
744
+ * Relative URL inputs are resolved against the URL returned by `listen()`.
745
+ *
746
+ * @example
747
+ * ```ts
748
+ * const response = await worker.fetch("/", {
749
+ * method: "POST",
750
+ * body: "Hello, world!"
751
+ * });
752
+ * ```
753
+ */
754
+ fetch: DispatchFetch;
755
+ /**
756
+ * Dispatches a scheduled event directly to this Worker.
757
+ *
758
+ * @example
759
+ * ```ts
760
+ * const result = await worker.scheduled({
761
+ * cron: "0 * * * *",
762
+ * scheduledTime: new Date(),
763
+ * });
764
+ * ```
765
+ */
766
+ scheduled(options: FetcherScheduledOptions): Promise<FetcherScheduledResult>;
767
+ };
768
+ type TestHarness = {
769
+ /**
770
+ * Starts the server and returns its current URL.
771
+ * Calling this more than once returns the same running server session until
772
+ * the server is closed or reset.
773
+ *
774
+ * If no options were passed to `createTestHarness()`, call `update(options)`
775
+ * before starting the server.
776
+ */
777
+ listen(): Promise<{
778
+ url: URL;
779
+ }>;
780
+ /**
781
+ * Dispatches a fetch request through the server.
782
+ *
783
+ * - Relative URLs are resolved against the current server URL. Absolute URLs
784
+ * are also accepted, and can be used to control the hostname seen by the Worker.
785
+ * - Requests are matched against each Worker's configured routes and dispatched to
786
+ * the first matching Worker, or to the primary Worker if no routes match.
787
+ * - To dispatch directly to a specific Worker, use `server.getWorker(name).fetch()`.
788
+ *
789
+ * @example
790
+ * ```ts
791
+ * const server = createTestHarness({
792
+ * workers: [
793
+ * { configPath: "./wrangler.dashboard.jsonc" }, // No route pattern
794
+ * { configPath: "./wrangler.api.jsonc" }, // Route pattern: "example.com/api/*"
795
+ * { configPath: "./wrangler.admin.jsonc" }, // Route pattern: "admin.example.com/*"
796
+ * ]
797
+ * });
798
+ *
799
+ * await server.fetch("/users");
800
+ * // Dispatches a request to the dashboard Worker (the first Worker) with URL "http://localhost:{port}/users"
801
+ *
802
+ * await server.fetch("http://admin.example.com/accounts");
803
+ * // Dispatches a request to the admin Worker with URL "http://admin.example.com/accounts"
804
+ *
805
+ * await server.fetch("http://example.com/api/data");
806
+ * // Dispatches a request to the API Worker with URL "http://example.com/api/data"
807
+ * ```
808
+ */
809
+ fetch: DispatchFetch;
810
+ /**
811
+ * Returns a handle for dispatching events directly to a Worker.
812
+ * When no name is provided, this returns the primary Worker, which is the first
813
+ * Worker in the server's `workers` options.
814
+ */
815
+ getWorker(name?: string): WorkerHandle;
816
+ /**
817
+ * Returns captured Workers runtime logs since the current server session
818
+ * started or `clearLogs()` was last called.
819
+ */
820
+ getLogs(): WorkerdStructuredLog[];
821
+ /**
822
+ * Clears captured Workers runtime logs.
823
+ */
824
+ clearLogs(): void;
825
+ /**
826
+ * Prints a diagnostic timeline for this test server.
827
+ *
828
+ * Use this to trace the sequence of server events and Workers runtime logs
829
+ * leading up to a test failure. Call `server.debug()` from your test runner's
830
+ * failure or cleanup hook when the current test has failed.
831
+ */
832
+ debug(): void;
833
+ /**
834
+ * Updates the server configuration and reloads the running Workers.
835
+ *
836
+ * If the server has not started yet, this configures the options that will be
837
+ * used by `listen()`.
838
+ */
839
+ update(options: TestHarnessOptions | ((currentOptions: TestHarnessOptions) => TestHarnessOptions)): Promise<void>;
840
+ /**
841
+ * Restores the server to the options used when the current session first
842
+ * started. Storage is recreated, and the server URL may change after reset.
843
+ */
844
+ reset(): Promise<void>;
845
+ /**
846
+ * Stops the server and releases all runtime resources.
847
+ */
848
+ close(): Promise<void>;
849
+ };
850
+ type InlineConfig = Omit<RawConfig$1, "env">;
851
+ type WorkerInput = {
852
+ /**
853
+ * Path to a Wrangler config file for this Worker.
854
+ * Relative paths resolve from server `root`.
855
+ */
856
+ configPath: string | URL;
857
+ /**
858
+ * Wrangler environment to load from the config file.
859
+ */
860
+ env?: string;
861
+ /**
862
+ * Test-only vars that override vars from the Wrangler config.
863
+ */
864
+ vars?: Record<string, Json$1>;
865
+ /**
866
+ * Test-only secrets that override values loaded from `.dev.vars` and `.env` files.
867
+ */
868
+ secrets?: Record<string, string>;
869
+ } | {
870
+ /**
871
+ * Inline Wrangler config for this Worker.
872
+ */
873
+ config: InlineConfig;
874
+ };
875
+ /**
876
+ * Creates a local test server for running Workers.
877
+ *
878
+ * The server can run one or more Workers from Wrangler config files, including
879
+ * generated configs from Vite, or from inline configuration objects.
880
+ *
881
+ * @example
882
+ * ```ts
883
+ * const server = createTestHarness({
884
+ * workers: [{ configPath: "./wrangler.jsonc" }],
885
+ * });
886
+ * await server.listen();
887
+ * const response = await server.fetch("/api/users");
888
+ * await server.close();
889
+ * ```
890
+ */
891
+ declare function createTestHarness(options?: TestHarnessOptions): TestHarness;
770
892
 
771
893
  type ReadConfigCommandArgs = NormalizeAndValidateConfigArgs & {
772
894
  config?: string;
@@ -2955,6 +3077,22 @@ declare function unstable_getMiniflareWorkerOptions(config: Config, env?: string
2955
3077
  containerBuildId?: string;
2956
3078
  }): Unstable_MiniflareWorkerOptions;
2957
3079
 
3080
+ /**
3081
+ * A Cloudflare account.
3082
+ */
3083
+ interface CfAccount {
3084
+ /**
3085
+ * An API token.
3086
+ *
3087
+ * @link https://api.cloudflare.com/#user-api-tokens-properties
3088
+ */
3089
+ apiToken: ApiCredentials;
3090
+ /**
3091
+ * An account ID.
3092
+ */
3093
+ accountId: string;
3094
+ }
3095
+
2958
3096
  type StartRemoteProxySessionOptions = {
2959
3097
  workerName?: string;
2960
3098
  auth?: NonNullable<StartDevWorkerInput["dev"]>["auth"];
@@ -3004,23 +3142,14 @@ declare function maybeStartOrUpdateRemoteProxySession(wranglerOrWorkerConfigObje
3004
3142
  auth?: AsyncHook<CfAccount> | undefined;
3005
3143
  } | null>;
3006
3144
 
3007
- declare const LOGGER_LEVELS: {
3008
- readonly none: -1;
3009
- readonly error: 0;
3010
- readonly warn: 1;
3011
- readonly info: 2;
3012
- readonly log: 3;
3013
- readonly debug: 4;
3014
- };
3015
- type LoggerLevel = keyof typeof LOGGER_LEVELS;
3016
3145
  type TableRow<Keys extends string> = Record<Keys, string>;
3017
3146
  declare class Logger {
3018
3147
  #private;
3019
3148
  constructor();
3020
3149
  private overrideLoggerLevel?;
3021
3150
  private onceHistory;
3022
- get loggerLevel(): "debug" | "none" | "error" | "info" | "log" | "warn";
3023
- set loggerLevel(val: "debug" | "none" | "error" | "info" | "log" | "warn");
3151
+ get loggerLevel(): "debug" | "none" | "error" | "log" | "info" | "warn";
3152
+ set loggerLevel(val: "debug" | "none" | "error" | "log" | "info" | "warn");
3024
3153
  resetLoggerLevel(): void;
3025
3154
  columns: number;
3026
3155
  json: (data: unknown) => void;
@@ -3050,23 +3179,6 @@ declare class Logger {
3050
3179
  private formatMessage;
3051
3180
  }
3052
3181
 
3053
- type PrintContext = {
3054
- log?: (message: string) => void;
3055
- registry?: WorkerRegistry | null;
3056
- local?: boolean;
3057
- isMultiWorker?: boolean;
3058
- remoteBindingsDisabled?: boolean;
3059
- name?: string;
3060
- provisioning?: boolean;
3061
- warnIfNoBindings?: boolean;
3062
- unsafeMetadata?: Record<string, unknown>;
3063
- };
3064
- /**
3065
- * Print all the bindings a worker would have access to.
3066
- * Accepts StartDevWorkerInput["bindings"] format
3067
- */
3068
- declare function printBindings(bindings: StartDevWorkerInput["bindings"], tailConsumers?: CfTailConsumer[], streamingTailConsumers?: CfTailConsumer[], containers?: ContainerApp$1[], context?: PrintContext): void;
3069
-
3070
3182
  /**
3071
3183
  * Resolves the named tunnel to hostnames whose ingress rules
3072
3184
  * target the current local dev origin and the token needed
@@ -3080,6 +3192,28 @@ declare function resolveNamedTunnel(name: string, origin: URL, options: {
3080
3192
  token: string;
3081
3193
  }>;
3082
3194
 
3195
+ /**
3196
+ * Run the dev server until it tears down (a hotkey quit in a TTY, or a
3197
+ * signal from a non-interactive parent). Mirrors `wrangler dev`'s command
3198
+ * handler and installs no signal handlers of its own, so signal handling
3199
+ * and exit codes match `wrangler dev` exactly.
3200
+ *
3201
+ * @param options Fully-built `StartDevOptions` (built in `bin/cf-wrangler.js`).
3202
+ * @returns `0` on a clean teardown.
3203
+ */
3204
+ declare function runCfWranglerDev(options: StartDevOptions): Promise<number>;
3205
+
3206
+ interface DevArgs {
3207
+ mode?: string;
3208
+ port?: number;
3209
+ host?: string;
3210
+ local?: boolean;
3211
+ }
3212
+ declare class ArgParseError extends Error {
3213
+ constructor(message: string);
3214
+ }
3215
+ declare function parseArgs(argv: string[]): DevArgs;
3216
+
3083
3217
  /**
3084
3218
  * Split an SQLQuery into an array of statements
3085
3219
  */
@@ -3087,6 +3221,18 @@ declare function splitSqlQuery(sql: string): string[];
3087
3221
 
3088
3222
  declare function runAutoConfig(autoConfigDetails: AutoConfigDetails, autoConfigOptions?: AutoConfigOptions): Promise<AutoConfigSummary>;
3089
3223
 
3224
+ /**
3225
+ * The implementation for fetching a kv value from the cloudflare API.
3226
+ * We special-case this one call, because it's the only API call that
3227
+ * doesn't return json. We inline the implementation and try not to share
3228
+ * any code with the other calls. We should push back on any new APIs that
3229
+ * try to introduce non-"standard" response structures.
3230
+ *
3231
+ * Note: any calls to fetchKVGetValue must call encodeURIComponent on key
3232
+ * before passing it
3233
+ */
3234
+ declare function fetchKVGetValue(complianceConfig: ComplianceConfig, accountId: string, namespaceId: string, key: string): Promise<ArrayBuffer>;
3235
+
3090
3236
  /**
3091
3237
  * Make a fetch request, and extract the `result` from the JSON response.
3092
3238
  */
@@ -3097,6 +3243,14 @@ declare function fetchResult<ResponseType>(complianceConfig: ComplianceConfig, r
3097
3243
  * and repeating the request if the results are paginated.
3098
3244
  */
3099
3245
  declare function fetchListResult<ResponseType>(complianceConfig: ComplianceConfig, resource: string, init?: RequestInit, queryParams?: URLSearchParams): Promise<ResponseType[]>;
3246
+ /**
3247
+ * Make a fetch request for a list of values,
3248
+ * extracting the `result` from the JSON response,
3249
+ * and repeating the request if the results are paginated.
3250
+ *
3251
+ * This is similar to fetchListResult, but it uses the `page` query parameter instead of `cursor`.
3252
+ */
3253
+ declare function fetchPagedListResult<ResponseType>(complianceConfig: ComplianceConfig, resource: string, init?: RequestInit, queryParams?: URLSearchParams): Promise<ResponseType[]>;
3100
3254
 
3101
3255
  interface ConfirmOptions {
3102
3256
  defaultValue?: boolean;
@@ -3225,6 +3379,8 @@ type HandlerContext = {
3225
3379
  */
3226
3380
  fetchResult: typeof fetchResult;
3227
3381
  fetchListResult: typeof fetchListResult;
3382
+ fetchPagedListResult: typeof fetchPagedListResult;
3383
+ fetchKVGetValue: typeof fetchKVGetValue;
3228
3384
  /**
3229
3385
  * Interactive prompts
3230
3386
  */
@@ -3506,4 +3662,4 @@ interface Unstable_ASSETSBindingsOptions {
3506
3662
  }
3507
3663
  declare const unstable_generateASSETSBinding: (opts: Unstable_ASSETSBindingsOptions) => (request: Request) => Promise<Response$1>;
3508
3664
 
3509
- export { type Experimental_GenerateTypesOptions, type Experimental_GenerateTypesResult, type GetPlatformProxyOptions, type PlatformProxy, type RemoteProxySession, type SourcelessWorkerOptions, type StartRemoteProxySessionOptions, type Unstable_ASSETSBindingsOptions, type Config as Unstable_Config, type Unstable_DevOptions, type Unstable_DevWorker, type Unstable_MiniflareWorkerOptions, type RawConfig as Unstable_RawConfig, type RawEnvironment as Unstable_RawEnvironment, Framework as experimental_AutoConfigFramework, generateTypes as experimental_generateTypes, getDetailsForAutoConfig as experimental_getDetailsForAutoConfig, experimental_getWranglerCommands, runAutoConfig as experimental_runAutoConfig, getPlatformProxy, maybeStartOrUpdateRemoteProxySession, startRemoteProxySession, DevEnv as unstable_DevEnv, convertConfigBindingsToStartWorkerBindings as unstable_convertConfigBindingsToStartWorkerBindings, unstable_dev, unstable_generateASSETSBinding, unstable_getDevCompatibilityDate, getDurableObjectClassNameToUseSQLiteMap as unstable_getDurableObjectClassNameToUseSQLiteMap, unstable_getMiniflareWorkerOptions, getVarsForDev as unstable_getVarsForDev, getWorkerNameFromProject as unstable_getWorkerNameFromProject, unstable_pages, printBindings as unstable_printBindings, readConfig as unstable_readConfig, resolveNamedTunnel as unstable_resolveNamedTunnel, splitSqlQuery as unstable_splitSqlQuery, startWorker as unstable_startWorker };
3665
+ export { ArgParseError, type Experimental_GenerateTypesOptions, type Experimental_GenerateTypesResult, type GetPlatformProxyOptions, type PlatformProxy, type RemoteProxySession, type SourcelessWorkerOptions, type StartRemoteProxySessionOptions, type TestHarness, type TestHarnessOptions, type Unstable_ASSETSBindingsOptions, type Config as Unstable_Config, type Unstable_DevOptions, type Unstable_DevWorker, type Unstable_MiniflareWorkerOptions, type RawConfig as Unstable_RawConfig, type RawEnvironment as Unstable_RawEnvironment, type WorkerHandle, createTestHarness, Framework as experimental_AutoConfigFramework, generateTypes as experimental_generateTypes, getDetailsForAutoConfig as experimental_getDetailsForAutoConfig, experimental_getWranglerCommands, runAutoConfig as experimental_runAutoConfig, getPlatformProxy, maybeStartOrUpdateRemoteProxySession, parseArgs as parseCfWranglerArgs, runCfWranglerDev, startRemoteProxySession, DevEnv as unstable_DevEnv, convertConfigBindingsToStartWorkerBindings as unstable_convertConfigBindingsToStartWorkerBindings, unstable_dev, unstable_generateASSETSBinding, unstable_getDevCompatibilityDate, getDurableObjectClassNameToUseSQLiteMap as unstable_getDurableObjectClassNameToUseSQLiteMap, unstable_getMiniflareWorkerOptions, getVarsForDev as unstable_getVarsForDev, getWorkerNameFromProject as unstable_getWorkerNameFromProject, unstable_pages, readConfig as unstable_readConfig, resolveNamedTunnel as unstable_resolveNamedTunnel, splitSqlQuery as unstable_splitSqlQuery, startWorker as unstable_startWorker };