UNPKG

wrangler

Version:

Command-line interface for all things Cloudflare Workers

1,426 lines (1,399 loc) 116 kB
import { Rule as Rule$1, CfModule, Environment as Environment$1, CfScriptFormat, CfModuleType, Config as Config$1, Binding, DurableObjectMigration as DurableObjectMigration$1, ContainerApp as ContainerApp$1, Trigger, CfTailConsumer, ServiceFetch, ContainerEngine as ContainerEngine$1, CfUnsafe, ConfigBindingFieldName, NormalizeAndValidateConfigArgs, ResolveConfigPathOptions, RawConfig as RawConfig$1, PackageJSON, ParseError, ComplianceConfig, UserError, FatalError } from '@cloudflare/workers-utils'; export { Binding, experimental_patchConfig, experimental_readRawConfig, defaultWranglerConfig as unstable_defaultWranglerConfig } from '@cloudflare/workers-utils'; import { Json as Json$1, WorkerRegistry, Miniflare, MiniflareOptions, Mutex, Response as Response$1, NodeJSCompatMode, DispatchFetch, RemoteProxyConnectionString, WorkerOptions, ModuleRule, Request } from 'miniflare'; import * as undici from 'undici'; import { RequestInfo, RequestInit, Response, FormData } from 'undici'; import { RouterConfig, AssetConfig } from '@cloudflare/workers-shared'; import { Metafile } from 'esbuild'; import Protocol from 'devtools-protocol/types/protocol-mapping'; import { EventEmitter } from 'node:events'; import { ContainerNormalizedConfig } from '@cloudflare/containers-shared'; import { IncomingRequestCfProperties } from '@cloudflare/workers-types/experimental'; import { URLSearchParams } from 'node:url'; import { Argv, PositionalOptions, Options, ArgumentsCamelCase, InferredOptionTypes, InferredOptionType } from 'yargs'; import Cloudflare from 'cloudflare'; interface EnablePagesAssetsServiceBindingOptions { proxyPort?: number; directory?: string; } interface Unstable_DevOptions { config?: string; env?: string; envFiles?: string[]; ip?: string; port?: number; bundle?: boolean; inspectorPort?: number; localProtocol?: "http" | "https"; httpsKeyPath?: string; httpsCertPath?: string; assets?: string; site?: string; siteInclude?: string[]; siteExclude?: string[]; compatibilityDate?: string; compatibilityFlags?: string[]; persist?: boolean; persistTo?: string; vars?: Record<string, string | Json$1>; kv?: { binding: string; id?: string; preview_id?: string; remote?: boolean; }[]; durableObjects?: { name: string; class_name: string; script_name?: string | undefined; environment?: string | undefined; }[]; services?: { binding: string; service: string; environment?: string | undefined; entrypoint?: string | undefined; remote?: boolean; }[]; r2?: { binding: string; bucket_name?: string; preview_bucket_name?: string; remote?: boolean; }[]; ai?: { binding: string; }; version_metadata?: { binding: string; }; moduleRoot?: string; rules?: Rule$1[]; logLevel?: "none" | "info" | "error" | "log" | "warn" | "debug"; inspect?: boolean; local?: boolean; accountId?: string; experimental?: { processEntrypoint?: boolean; additionalModules?: CfModule[]; d1Databases?: Environment$1["d1_databases"]; disableExperimentalWarning?: boolean; disableDevRegistry?: boolean; enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions; forceLocal?: boolean; liveReload?: boolean; showInteractiveDevSession?: boolean; testMode?: boolean; testScheduled?: boolean; watch?: boolean; fileBasedRegistry?: boolean; enableIpc?: boolean; enableContainers?: boolean; dockerPath?: string; containerEngine?: string; }; } interface Unstable_DevWorker { port: number; address: string; stop: () => Promise<void>; fetch: (input?: RequestInfo, init?: RequestInit) => Promise<Response>; waitUntilExit: () => Promise<void>; } /** * unstable_dev starts a wrangler dev server, and returns a promise that resolves with utility functions to interact with it. */ declare function unstable_dev(script: string, options?: Unstable_DevOptions, apiOptions?: unknown): Promise<Unstable_DevWorker>; interface PagesDeployOptions { /** * Path to static assets to deploy to Pages */ directory: string; /** * The Cloudflare Account ID that owns the project that's * being published */ accountId: string; /** * The name of the project to be published */ projectName: string; /** * Branch name to use. Defaults to production branch */ branch?: string; /** * Whether or not to skip local file upload result caching */ skipCaching?: boolean; /** * Commit message associated to deployment */ commitMessage?: string; /** * Commit hash associated to deployment */ commitHash?: string; /** * Whether or not the deployment should be considered to be * in a dirty commit state */ commitDirty?: boolean; /** * Path to the project's functions directory. Default uses * the current working directory + /functions since this is * typically called in a CLI */ functionsDirectory?: string; /** * Whether to run bundling on `_worker.js` before deploying. * Default: true */ bundle?: boolean; /** * Whether to upload any server-side sourcemaps with this deployment */ sourceMaps: boolean; /** * Command line args passed to the `pages deploy` cmd */ args?: Record<string, unknown>; } /** * Publish a directory to an account/project. * NOTE: You will need the `CLOUDFLARE_API_KEY` environment * variable set */ declare function deploy({ directory, accountId, projectName, branch, skipCaching, commitMessage, commitHash, commitDirty, functionsDirectory: customFunctionsDirectory, bundle, sourceMaps, args, }: PagesDeployOptions): Promise<{ deploymentResponse: { id: string; url: string; environment: "production" | "preview"; build_config: { build_command: string; destination_dir: string; root_dir: string; web_analytics_tag?: string | undefined; web_analytics_token?: string | undefined; fast_builds?: boolean | undefined; }; created_on: string; production_branch: string; project_id: string; project_name: string; deployment_trigger: { type: string; metadata: { branch: string; commit_hash: string; commit_message: string; }; }; latest_stage: { status: "canceled" | "active" | "success" | "idle" | "failure" | "skipped"; name: "build" | "queued" | "deploy" | "initialize" | "clone_repo"; started_on: string | null; ended_on: string | null; }; stages: { status: "canceled" | "active" | "success" | "idle" | "failure" | "skipped"; name: "build" | "queued" | "deploy" | "initialize" | "clone_repo"; started_on: string | null; ended_on: string | null; }[]; aliases: string[]; modified_on: string; short_id: string; build_image_major_version: number; source?: { type: "github" | "gitlab"; config: { owner: string; repo_name: string; production_branch?: string | undefined; pr_comments_enabled?: boolean | undefined; deployments_enabled?: boolean | undefined; production_deployments_enabled?: boolean | undefined; preview_deployment_setting?: "custom" | "none" | "all" | undefined; preview_branch_includes?: string[] | undefined; preview_branch_excludes?: string[] | undefined; }; } | undefined; kv_namespaces?: any; env_vars?: any; durable_object_namespaces?: any; is_skipped?: boolean | undefined; files?: { [x: string]: string | undefined; } | undefined; }; formData: FormData; }>; declare const unstable_pages: { deploy: typeof deploy; }; type AssetsOptions = { directory: string; binding?: string; routerConfig: RouterConfig; assetConfig: AssetConfig; _redirects?: string; _headers?: string; run_worker_first?: boolean | string[]; }; type ApiCredentials = { apiToken: string; } | { authKey: string; authEmail: string; }; /** * An entry point for the Worker. * * It consists not just of a `file`, but also of a `directory` that is used to resolve relative paths. */ type Entry = { /** A worker's entrypoint */ file: string; /** A worker's directory. Usually where the Wrangler configuration file is located */ projectRoot: string; /** The path to the config file, if it exists. */ configPath: string | undefined; /** Is this a module worker or a service worker? */ format: CfScriptFormat; /** The directory that contains all of a `--no-bundle` worker's modules. Usually `${directory}/src`. Defaults to path.dirname(file) */ moduleRoot: string; /** * A worker's name */ name?: string | undefined; /** Export from a Worker's entrypoint */ exports: string[]; }; /** * Information about Wrangler's bundling process that needs passed through * for DevTools sourcemap transformation */ interface SourceMapMetadata { tmpDir: string; entryDirectory: string; } type EsbuildBundle = { id: number; path: string; entrypointSource: string; entry: Entry; type: CfModuleType; modules: CfModule[]; dependencies: Metafile["outputs"][string]["inputs"]; sourceMapPath: string | undefined; sourceMapMetadata: SourceMapMetadata | undefined; }; /** * A Cloudflare account. */ interface CfAccount { /** * An API token. * * @link https://api.cloudflare.com/#user-api-tokens-properties */ apiToken: ApiCredentials; /** * An account ID. */ accountId: string; } type _Params<ParamsArray extends [unknown?]> = ParamsArray extends [infer P] ? P : undefined; type _EventMethods = keyof Protocol.Events; type DevToolsEvent<Method extends _EventMethods> = Method extends unknown ? { method: Method; params: _Params<Protocol.Events[Method]>; } : never; type ErrorEvent = BaseErrorEvent<"ConfigController" | "BundlerController" | "LocalRuntimeController" | "RemoteRuntimeController" | "ProxyWorker" | "InspectorProxyWorker" | "MultiworkerRuntimeController"> | BaseErrorEvent<"ProxyController", { config?: StartDevWorkerOptions; bundle?: Bundle; }> | BaseErrorEvent<"BundlerController", { config?: StartDevWorkerOptions; filePath?: string; }>; type BaseErrorEvent<Source = string, Data = undefined> = { type: "error"; reason: string; cause: Error | SerializedError; source: Source; data: Data; }; type ConfigUpdateEvent = { type: "configUpdate"; config: StartDevWorkerOptions; }; type BundleStartEvent = { type: "bundleStart"; config: StartDevWorkerOptions; }; type BundleCompleteEvent = { type: "bundleComplete"; config: StartDevWorkerOptions; bundle: Bundle; }; type ReloadStartEvent = { type: "reloadStart"; config: StartDevWorkerOptions; bundle: Bundle; }; type ReloadCompleteEvent = { type: "reloadComplete"; config: StartDevWorkerOptions; bundle: Bundle; proxyData: ProxyData; }; type DevRegistryUpdateEvent = { type: "devRegistryUpdate"; registry: WorkerRegistry; }; type PreviewTokenExpiredEvent = { type: "previewTokenExpired"; proxyData: ProxyData; }; type ReadyEvent = { type: "ready"; proxyWorker: Miniflare; url: URL; inspectorUrl: URL | undefined; }; type ProxyWorkerIncomingRequestBody = { type: "play"; proxyData: ProxyData; } | { type: "pause"; }; type ProxyWorkerOutgoingRequestBody = { type: "error"; error: SerializedError; } | { type: "previewTokenExpired"; proxyData: ProxyData; } | { type: "debug-log"; args: Parameters<typeof console.debug>; }; type InspectorProxyWorkerIncomingWebSocketMessage = { type: ReloadStartEvent["type"]; } | { type: ReloadCompleteEvent["type"]; proxyData: ProxyData; }; type InspectorProxyWorkerOutgoingWebsocketMessage = DevToolsEvent<"Runtime.consoleAPICalled"> | DevToolsEvent<"Runtime.exceptionThrown">; type InspectorProxyWorkerOutgoingRequestBody = { type: "error"; error: SerializedError; } | { type: "runtime-websocket-error"; error: SerializedError; } | { type: "debug-log"; args: Parameters<typeof console.debug>; } | { type: "load-network-resource"; url: string; }; type SerializedError = { message: string; name?: string; stack?: string | undefined; cause?: unknown; }; type UrlOriginParts = Pick<URL, "protocol" | "hostname" | "port">; type UrlOriginAndPathnameParts = Pick<URL, "protocol" | "hostname" | "port" | "pathname">; type ProxyData = { userWorkerUrl: UrlOriginParts; userWorkerInspectorUrl?: UrlOriginAndPathnameParts; userWorkerInnerUrlOverrides?: Partial<UrlOriginParts>; headers: Record<string, string>; liveReload?: boolean; proxyLogsToController?: boolean; }; type ControllerEvent = ErrorEvent | ConfigUpdateEvent | BundleStartEvent | BundleCompleteEvent | ReloadStartEvent | ReloadCompleteEvent | DevRegistryUpdateEvent | PreviewTokenExpiredEvent; interface ControllerBus { dispatch(event: ControllerEvent): void; } declare abstract class Controller { #private; protected bus: ControllerBus; constructor(bus: ControllerBus); teardown(): Promise<void>; protected emitErrorEvent(event: ErrorEvent): void; } declare abstract class RuntimeController extends Controller { abstract onBundleStart(_: BundleStartEvent): void; abstract onBundleComplete(_: BundleCompleteEvent): void; abstract onPreviewTokenExpired(_: PreviewTokenExpiredEvent): void; protected emitReloadStartEvent(data: ReloadStartEvent): void; protected emitReloadCompleteEvent(data: ReloadCompleteEvent): void; protected emitDevRegistryUpdateEvent(data: DevRegistryUpdateEvent): void; } declare class ConfigController extends Controller { #private; latestInput?: StartDevWorkerInput; latestConfig?: StartDevWorkerOptions; set(input: StartDevWorkerInput, throwErrors?: boolean): Promise<StartDevWorkerOptions | undefined>; patch(input: Partial<StartDevWorkerInput>): Promise<StartDevWorkerOptions | undefined>; onDevRegistryUpdate(event: DevRegistryUpdateEvent): void; teardown(): Promise<void>; emitConfigUpdateEvent(config: StartDevWorkerOptions): void; } declare class BundlerController extends Controller { #private; onConfigUpdate(event: ConfigUpdateEvent): void; teardown(): Promise<void>; emitBundleStartEvent(config: StartDevWorkerOptions): void; emitBundleCompleteEvent(config: StartDevWorkerOptions, bundle: EsbuildBundle): void; } declare class ProxyController extends Controller { ready: DeferredPromise<ReadyEvent>; localServerReady: DeferredPromise<void>; proxyWorker?: Miniflare; proxyWorkerOptions?: MiniflareOptions; private inspectorProxyWorkerWebSocket?; protected latestConfig?: StartDevWorkerOptions; protected latestBundle?: EsbuildBundle; secret: `${string}-${string}-${string}-${string}-${string}`; protected createProxyWorker(): void; private reconnectInspectorProxyWorker; runtimeMessageMutex: Mutex; sendMessageToProxyWorker(message: ProxyWorkerIncomingRequestBody, retries?: number): Promise<void>; sendMessageToInspectorProxyWorker(message: InspectorProxyWorkerIncomingWebSocketMessage, retries?: number): Promise<void>; get inspectorEnabled(): boolean; onConfigUpdate(data: ConfigUpdateEvent): void; onBundleStart(data: BundleStartEvent): void; onReloadStart(data: ReloadStartEvent): void; onReloadComplete(data: ReloadCompleteEvent): void; onProxyWorkerMessage(message: ProxyWorkerOutgoingRequestBody): void; onInspectorProxyWorkerMessage(message: InspectorProxyWorkerOutgoingWebsocketMessage): void; onInspectorProxyWorkerRequest(message: InspectorProxyWorkerOutgoingRequestBody): Promise<Response$1>; _torndown: boolean; teardown(): Promise<void>; emitReadyEvent(proxyWorker: Miniflare, url: URL, inspectorUrl: URL | undefined): void; emitPreviewTokenExpiredEvent(proxyData: ProxyData): void; emitErrorEvent(data: ErrorEvent): void; emitErrorEvent(reason: string, cause?: Error | SerializedError): void; } type ControllerFactory<C extends Controller> = (devEnv: DevEnv) => C; declare class DevEnv extends EventEmitter implements ControllerBus { config: ConfigController; bundler: BundlerController; runtimes: RuntimeController[]; proxy: ProxyController; startWorker(options: StartDevWorkerInput): Promise<Worker>; constructor({ configFactory, bundlerFactory, runtimeFactories, proxyFactory, }?: { configFactory?: ControllerFactory<ConfigController>; bundlerFactory?: ControllerFactory<BundlerController>; runtimeFactories?: ControllerFactory<RuntimeController>[]; proxyFactory?: ControllerFactory<ProxyController>; }); /** * Central message bus dispatch method. * All events from controllers flow through here, making the event routing explicit and traceable. * * Event flow: * - ConfigController emits configUpdate → BundlerController, ProxyController * - BundlerController emits bundleStart → ProxyController, RuntimeControllers * - BundlerController emits bundleComplete → RuntimeControllers * - RuntimeController emits reloadStart → ProxyController * - RuntimeController emits reloadComplete → ProxyController * - RuntimeController emits devRegistryUpdate → ConfigController * - ProxyController emits previewTokenExpired → RuntimeControllers * - Any controller emits error → DevEnv error handler */ dispatch(event: ControllerEvent): void; private handleErrorEvent; teardown(): Promise<void>; } type MiniflareWorker = Awaited<ReturnType<Miniflare["getWorker"]>>; interface Worker { ready: Promise<void>; url: Promise<URL>; inspectorUrl: Promise<URL | undefined>; config: StartDevWorkerOptions; setConfig: ConfigController["set"]; patchConfig: ConfigController["patch"]; fetch: DispatchFetch; scheduled: MiniflareWorker["scheduled"]; queue: MiniflareWorker["queue"]; dispose(): Promise<void>; raw: DevEnv; } interface StartDevWorkerInput { /** The name of the worker. */ name?: string; /** * The javascript or typescript entry-point of the worker. * This is the `main` property of a Wrangler configuration file. */ entrypoint?: string; /** The configuration path of the worker. */ config?: string; /** The compatibility date for the workerd runtime. */ compatibilityDate?: string; /** The compatibility flags for the workerd runtime. */ compatibilityFlags?: string[]; /** Specify the compliance region mode of the Worker. */ complianceRegion?: Config$1["compliance_region"]; /** Configuration for Python modules. */ pythonModules?: { /** A list of glob patterns to exclude files from the python_modules directory when bundling. */ exclude?: string[]; }; env?: string; /** * An array of paths to the .env files to load for this worker, relative to the project directory. * * If not specified, defaults to the standard `.env` files as given by `getDefaultEnvFiles()`. * The project directory is where the Wrangler configuration file is located or the current working directory otherwise. */ envFiles?: string[]; /** The bindings available to the worker. The specified bindind type will be exposed to the worker on the `env` object under the same key. */ bindings?: Record<string, Binding>; /** * Default bindings that can be overridden by config bindings. * Useful for injecting environment-specific defaults like CF_PAGES variables. */ defaultBindings?: Record<string, Extract<Binding, { type: "plain_text"; }>>; migrations?: DurableObjectMigration$1[]; containers?: ContainerApp$1[]; /** The triggers which will cause the worker's exported default handlers to be called. */ triggers?: Trigger[]; tailConsumers?: CfTailConsumer[]; streamingTailConsumers?: CfTailConsumer[]; /** * Whether Wrangler should send usage metrics to Cloudflare for this project. * * When defined this will override any user settings. * Otherwise, Wrangler will use the user's preference. */ sendMetrics?: boolean; /** Options applying to the worker's build step. Applies to deploy and dev. */ build?: { /** Whether the worker and its dependencies are bundled. Defaults to true. */ bundle?: boolean; additionalModules?: CfModule[]; findAdditionalModules?: boolean; processEntrypoint?: boolean; /** Specifies types of modules matched by globs. */ moduleRules?: Rule$1[]; /** Replace global identifiers with constant expressions, e.g. { debug: 'true', version: '"1.0.0"' }. Only takes effect if bundle: true. */ define?: Record<string, string>; /** Alias modules */ alias?: Record<string, string>; /** Whether the bundled worker is minified. Only takes effect if bundle: true. */ minify?: boolean; /** Whether to keep function names after JavaScript transpilations. */ keepNames?: boolean; /** Options controlling a custom build step. */ custom?: { /** Custom shell command to run before bundling. Runs even if bundle. */ command?: string; /** The cwd to run the command in. */ workingDirectory?: string; /** Filepath(s) to watch for changes. Upon changes, the command will be rerun. */ watch?: string | string[]; }; jsxFactory?: string; jsxFragment?: string; tsconfig?: string; nodejsCompatMode?: Hook<NodeJSCompatMode, [Config$1]>; moduleRoot?: string; }; /** Options applying to the worker's development preview environment. */ dev?: { /** Options applying to the worker's inspector server. False disables the inspector server. */ inspector?: { hostname?: string; port?: number; secure?: boolean; } | false; /** Whether the worker runs on the edge or locally. This has several options: * - true | "minimal": Run your Worker's code & bindings in a remote preview session, optionally using minimal mode as an internal detail * - false: Run your Worker's code & bindings in a local simulator * - undefined (default): Run your Worker's code locally, and any configured remote bindings remotely */ remote?: boolean | "minimal"; /** Cloudflare Account credentials. Can be provided upfront or as a function which will be called only when required. */ auth?: AsyncHook<CfAccount, [Pick<Config$1, "account_id">]>; /** Whether local storage (KV, Durable Objects, R2, D1, etc) is persisted. You can also specify the directory to persist data to. */ persist?: string; /** Controls which logs are logged 🤙. */ logLevel?: LogLevel; /** Whether the worker server restarts upon source/config file changes. */ watch?: boolean; /** Whether a script tag is inserted on text/html responses which will reload the page upon file changes. Defaults to false. */ liveReload?: boolean; /** The local address to reach your worker. Applies to remote: true (remote mode) and remote: false (local mode). */ server?: { hostname?: string; port?: number; secure?: boolean; httpsKeyPath?: string; httpsCertPath?: string; }; /** Controls what request.url looks like inside the worker. */ origin?: { hostname?: string; secure?: boolean; }; /** A hook for outbound fetch calls from within the worker. */ outboundService?: ServiceFetch; /** An undici MockAgent to declaratively mock fetch calls to particular resources. */ mockFetch?: undici.MockAgent; testScheduled?: boolean; /** Treat this as the primary worker in a multiworker setup (i.e. the first Worker in Miniflare's options) */ multiworkerPrimary?: boolean; containerBuildId?: string; /** Whether to build and connect to containers during local dev. Requires Docker daemon to be running. Defaults to true. */ enableContainers?: boolean; /** Path to the dev registry directory */ registry?: string; /** Path to the docker executable. Defaults to 'docker' */ dockerPath?: string; /** Options for the container engine */ containerEngine?: ContainerEngine$1; /** Re-generate your worker types when your Wrangler configuration file changes */ generateTypes?: boolean; }; legacy?: { site?: Hook<Config$1["site"], [Config$1]>; useServiceEnvironments?: boolean; }; unsafe?: Omit<CfUnsafe, "bindings">; assets?: string; experimental?: { tailLogs: boolean; }; } type StartDevWorkerOptions = Omit<StartDevWorkerInput, "assets" | "containers"> & { /** A worker's directory. Usually where the Wrangler configuration file is located */ projectRoot: string; build: StartDevWorkerInput["build"] & { nodejsCompatMode: NodeJSCompatMode; format: CfScriptFormat; moduleRoot: string; moduleRules: Rule$1[]; define: Record<string, string>; additionalModules: CfModule[]; exports: string[]; processEntrypoint: boolean; }; legacy: StartDevWorkerInput["legacy"] & { site?: Config$1["site"]; }; dev: StartDevWorkerInput["dev"] & { persist: string; auth?: AsyncHook<CfAccount>; }; entrypoint: string; assets?: AssetsOptions; containers?: ContainerNormalizedConfig[]; name: string; complianceRegion: Config$1["compliance_region"]; }; type HookValues = string | number | boolean | object | undefined | null; type Hook<T extends HookValues, Args extends unknown[] = []> = T | ((...args: Args) => T); type AsyncHook<T extends HookValues, Args extends unknown[] = []> = Hook<T, Args> | Hook<Promise<T>, Args>; type Bundle = EsbuildBundle; type LogLevel = "debug" | "info" | "log" | "warn" | "error" | "none"; type MaybePromise<T> = T | Promise<T>; type DeferredPromise<T> = { promise: Promise<T>; resolve: (_: MaybePromise<T>) => void; reject: (_: Error) => void; }; declare function convertConfigBindingsToStartWorkerBindings(configBindings: Partial<Pick<Config$1, ConfigBindingFieldName>>): StartDevWorkerOptions["bindings"]; declare function startWorker(options: StartDevWorkerInput): Promise<Worker>; type ReadConfigCommandArgs = NormalizeAndValidateConfigArgs & { config?: string; script?: string; }; type ReadConfigOptions = ResolveConfigPathOptions & { hideWarnings?: boolean; preserveOriginalMain?: boolean; }; /** * Get the Wrangler configuration; read it from the give `configPath` if available. */ declare function readConfig(args: ReadConfigCommandArgs, options?: ReadConfigOptions): Config$1; /** * Based on the migrations, infer what the current Durable Object class names are. * This includes unbound (ctx.exports) and bound DOs. * Returns class name mapped to whether it uses SQLite storage. * This is imperfect because you can delete a migration after it has been applied. */ declare function getDurableObjectClassNameToUseSQLiteMap(migrations: Config$1["migrations"] | undefined): Map<string, boolean>; /** * Note about this file: * * Here we are providing a no-op implementation of the runtime Cache API instead of using * the miniflare implementation (via `mf.getCaches()`). * * We are not using miniflare's implementation because that would require the user to provide * miniflare-specific Request objects and they would receive back miniflare-specific Response * objects, this (in particular the Request part) is not really suitable for `getPlatformProxy` * as people would ideally interact with their bindings in a very production-like manner and * requiring them to deal with miniflare-specific classes defeats a bit the purpose of the utility. * * Similarly the Request and Response types here are set to `undefined` as not to use specific ones * that would require us to make a choice right now or the user to adapt their code in order to work * with the api. * * We need to find a better/generic manner in which we can reuse the miniflare cache implementation, * but until then the no-op implementation below will have to do. */ /** * No-op implementation of CacheStorage */ declare class CacheStorage { constructor(); open(cacheName: string): Promise<Cache>; get default(): Cache; } type CacheRequest = any; type CacheResponse = any; /** * No-op implementation of Cache */ declare class Cache { delete(request: CacheRequest, options?: CacheQueryOptions): Promise<boolean>; match(request: CacheRequest, options?: CacheQueryOptions): Promise<CacheResponse | undefined>; put(request: CacheRequest, response: CacheResponse): Promise<void>; } type CacheQueryOptions = { ignoreMethod?: boolean; }; declare class ExecutionContext { waitUntil(promise: Promise<any>): void; passThroughOnException(): void; props: any; } type Json = string | number | boolean | null | Json[] | { [id: string]: Json; }; /** * The `Environment` interface declares all the configuration fields that * can be specified for an environment. * * This could be the top-level default environment, or a specific named environment. */ interface Environment extends EnvironmentInheritable, EnvironmentNonInheritable { } type SimpleRoute = string; type ZoneIdRoute = { pattern: string; zone_id: string; custom_domain?: boolean; }; type ZoneNameRoute = { pattern: string; zone_name: string; custom_domain?: boolean; }; type CustomDomainRoute = { pattern: string; custom_domain: boolean; }; type Route = SimpleRoute | ZoneIdRoute | ZoneNameRoute | CustomDomainRoute; /** * Configuration in wrangler for Cloudchamber */ type CloudchamberConfig = { image?: string; location?: string; instance_type?: "dev" | "basic" | "standard" | "lite" | "standard-1" | "standard-2" | "standard-3" | "standard-4"; vcpu?: number; memory?: string; ipv4?: boolean; }; type UnsafeBinding = { /** * The name of the binding provided to the Worker */ name: string; /** * The 'type' of the unsafe binding. */ type: string; dev?: { plugin: { /** * Package is the bare specifier of the package that exposes plugins to integrate into Miniflare via a named `plugins` export. * @example "@cloudflare/my-external-miniflare-plugin" */ package: string; /** * Plugin is the name of the plugin exposed by the package. * @example "MY_UNSAFE_PLUGIN" */ name: string; }; /** * Optional mapping of unsafe bindings names to options provided for the plugin. */ options?: Record<string, unknown>; }; [key: string]: unknown; }; /** * Configuration for a container application */ type ContainerApp = { /** * Name of the application * @optional Defaults to `worker_name-class_name` if not specified. */ name?: string; /** * Number of application instances * @deprecated * @hidden */ instances?: number; /** * Number of maximum application instances. * @optional */ max_instances?: number; /** * The path to a Dockerfile, or an image URI for the Cloudflare registry. */ image: string; /** * Build context of the application. * @optional - defaults to the directory of `image`. */ image_build_context?: string; /** * Image variables available to the image at build-time only. * For runtime env vars, refer to https://developers.cloudflare.com/containers/examples/env-vars-and-secrets/ * @optional */ image_vars?: Record<string, string>; /** * The class name of the Durable Object the container is connected to. */ class_name: string; /** * The scheduling policy of the application * @optional * @default "default" */ scheduling_policy?: "default" | "moon" | "regional"; /** * The instance type to be used for the container. * Select from one of the following named instance types: * - lite: 1/16 vCPU, 256 MiB memory, and 2 GB disk * - basic: 1/4 vCPU, 1 GiB memory, and 4 GB disk * - standard-1: 1/2 vCPU, 4 GiB memory, and 8 GB disk * - standard-2: 1 vCPU, 6 GiB memory, and 12 GB disk * - standard-3: 2 vCPU, 8 GiB memory, and 16 GB disk * - standard-4: 4 vCPU, 12 GiB memory, and 20 GB disk * - dev: 1/16 vCPU, 256 MiB memory, and 2 GB disk (deprecated, use "lite" instead) * - standard: 1 vCPU, 4 GiB memory, and 4 GB disk (deprecated, use "standard-1" instead) * * Customers on an enterprise plan have the additional option to set custom limits. * * @optional * @default "dev" */ instance_type?: "dev" | "basic" | "standard" | "lite" | "standard-1" | "standard-2" | "standard-3" | "standard-4" | { /** @defaults to 0.0625 (1/16 vCPU) */ vcpu?: number; /** @defaults to 256 MiB */ memory_mib?: number; /** @defaults to 2 GB */ disk_mb?: number; }; wrangler_ssh?: { /** * If enabled, those with write access to a container will be able to SSH into it through Wrangler. * @default false */ enabled: boolean; /** * Port that the SSH service is running on * @defaults to 22 */ port?: number; }; /** * SSH public keys to put in the container's authorized_keys file. */ authorized_keys?: { name: string; public_key: string; }[]; /** * Trusted user CA keys to put in the container's trusted_user_ca_keys file. */ trusted_user_ca_keys?: { name?: string; public_key: string; }[]; /** * @deprecated Use top level `containers` fields instead. * `configuration.image` should be `image` * limits should be set via `instance_type` * @hidden */ configuration?: { image?: string; labels?: { name: string; value: string; }[]; secrets?: { name: string; type: "env"; secret: string; }[]; disk?: { size_mb: number; }; vcpu?: number; memory_mib?: number; }; /** * Scheduling constraints * @hidden */ constraints?: { regions?: string[]; cities?: string[]; /** * @deprecated Use `tiers` instead */ tier?: number; tiers?: number[]; }; /** * Scheduling affinities * @hidden */ affinities?: { colocation?: "datacenter"; hardware_generation?: "highest-overall-performance"; }; /** * @deprecated use the `class_name` field instead. * @hidden */ durable_objects?: { namespace_id: string; }; /** * Configures what percentage of instances should be updated at each step of a rollout. * You can specify this as a single number, or an array of numbers. * * If this is a single number, each step will progress by that percentage. * The options are 5, 10, 20, 25, 50 or 100. * * If this is an array, each step specifies the cumulative rollout progress. * The final step must be 100. * * This can be overridden adhoc by deploying with the `--containers-rollout=immediate` flag, * which will roll out to 100% of instances in one step. * * @optional * @default [10,100] * */ rollout_step_percentage?: number | number[]; /** * How a rollout should be created. It supports the following modes: * - full_auto: The container application will be rolled out fully automatically. * - none: The container application won't have a roll out or update. * - manual: The container application will be rollout fully by manually actioning progress steps. * @optional * @default "full_auto" * @hidden */ rollout_kind?: "full_auto" | "none" | "full_manual"; /** * Configures the grace period (in seconds) for active instances before being shutdown during a rollout. * @optional * @default 0 */ rollout_active_grace_period?: number; /** * Directly passed to the API without wrangler-side validation or transformation. * @hidden */ unsafe?: Record<string, unknown>; }; /** * Configuration in wrangler for Durable Object Migrations */ type DurableObjectMigration = { /** A unique identifier for this migration. */ tag: string; /** The new Durable Objects being defined. */ new_classes?: string[]; /** The new SQLite Durable Objects being defined. */ new_sqlite_classes?: string[]; /** The Durable Objects being renamed. */ renamed_classes?: { from: string; to: string; }[]; /** The Durable Objects being removed. */ deleted_classes?: string[]; }; /** * The `EnvironmentInheritable` interface declares all the configuration fields for an environment * that can be inherited (and overridden) from the top-level environment. */ interface EnvironmentInheritable { /** * The name of your Worker. Alphanumeric + dashes only. * * @inheritable */ name: string | undefined; /** * This is the ID of the account associated with your zone. * You might have more than one account, so make sure to use * the ID of the account associated with the zone/route you * provide, if you provide one. It can also be specified through * the CLOUDFLARE_ACCOUNT_ID environment variable. * * @inheritable */ account_id: string | undefined; /** * A date in the form yyyy-mm-dd, which will be used to determine * which version of the Workers runtime is used. * * More details at https://developers.cloudflare.com/workers/configuration/compatibility-dates * * @inheritable */ compatibility_date: string | undefined; /** * A list of flags that enable features from upcoming features of * the Workers runtime, usually used together with compatibility_date. * * More details at https://developers.cloudflare.com/workers/configuration/compatibility-flags/ * * @default [] * @inheritable */ compatibility_flags: string[]; /** * The entrypoint/path to the JavaScript file that will be executed. * * @inheritable */ main: string | undefined; /** * If true then Wrangler will traverse the file tree below `base_dir`; * Any files that match `rules` will be included in the deployed Worker. * Defaults to true if `no_bundle` is true, otherwise false. * * @inheritable */ find_additional_modules: boolean | undefined; /** * Determines whether Wrangler will preserve bundled file names. * Defaults to false. * If left unset, files will be named using the pattern ${fileHash}-${basename}, * for example, `34de60b44167af5c5a709e62a4e20c4f18c9e3b6-favicon.ico`. * * @inheritable */ preserve_file_names: boolean | undefined; /** * The directory in which module rules should be evaluated when including additional files into a Worker deployment. * This defaults to the directory containing the `main` entry point of the Worker if not specified. * * @inheritable */ base_dir: string | undefined; /** * Whether we use <name>.<subdomain>.workers.dev to * test and deploy your Worker. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#workersdev * * @default true * @breaking * @inheritable */ workers_dev: boolean | undefined; /** * Whether we use <version>-<name>.<subdomain>.workers.dev to * serve Preview URLs for your Worker. * * @default false * @inheritable */ preview_urls: boolean | undefined; /** * A list of routes that your Worker should be published to. * Only one of `routes` or `route` is required. * * Only required when workers_dev is false, and there's no scheduled Worker (see `triggers`) * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#types-of-routes * * @inheritable */ routes: Route[] | undefined; /** * A route that your Worker should be published to. Literally * the same as routes, but only one. * Only one of `routes` or `route` is required. * * Only required when workers_dev is false, and there's no scheduled Worker * * @inheritable */ route: Route | undefined; /** * Path to a custom tsconfig * * @inheritable */ tsconfig: string | undefined; /** * The function to use to replace jsx syntax. * * @default "React.createElement" * @inheritable */ jsx_factory: string; /** * The function to use to replace jsx fragment syntax. * * @default "React.Fragment" * @inheritable */ jsx_fragment: string; /** * A list of migrations that should be uploaded with your Worker. * * These define changes in your Durable Object declarations. * * More details at https://developers.cloudflare.com/workers/learning/using-durable-objects#configuring-durable-object-classes-with-migrations * * @default [] * @inheritable */ migrations: DurableObjectMigration[]; /** * "Cron" definitions to trigger a Worker's "scheduled" function. * * Lets you call Workers periodically, much like a cron job. * * More details here https://developers.cloudflare.com/workers/platform/cron-triggers * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#triggers * * @default {crons:[]} * @inheritable */ triggers: { crons: string[] | undefined; }; /** * Specify limits for runtime behavior. * Only supported for the "standard" Usage Model * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#limits * * @inheritable */ limits: UserLimits | undefined; /** * An ordered list of rules that define which modules to import, * and what type to import them as. You will need to specify rules * to use Text, Data, and CompiledWasm modules, or when you wish to * have a .js file be treated as an ESModule instead of CommonJS. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#bundling * * @inheritable */ rules: Rule[]; /** * Configures a custom build step to be run by Wrangler when building your Worker. * * Refer to the [custom builds documentation](https://developers.cloudflare.com/workers/cli-wrangler/configuration#build) * for more details. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#custom-builds * * @default {watch_dir:"./src"} */ build: { /** The command used to build your Worker. On Linux and macOS, the command is executed in the `sh` shell and the `cmd` shell for Windows. The `&&` and `||` shell operators may be used. */ command?: string; /** The directory in which the command is executed. */ cwd?: string; /** The directory to watch for changes while using wrangler dev, defaults to the current working directory */ watch_dir?: string | string[]; }; /** * Skip internal build steps and directly deploy script * @inheritable */ no_bundle: boolean | undefined; /** * Minify the script before uploading. * @inheritable */ minify: boolean | undefined; /** * Set the `name` property to the original name for functions and classes renamed during minification. * * See https://esbuild.github.io/api/#keep-names * * @default true * @inheritable */ keep_names: boolean | undefined; /** * Designates this Worker as an internal-only "first-party" Worker. * * @inheritable */ first_party_worker: boolean | undefined; /** * List of bindings that you will send to logfwdr * * @default {bindings:[]} * @inheritable */ logfwdr: { bindings: { /** The binding name used to refer to logfwdr */ name: string; /** The destination for this logged message */ destination: string; }[]; }; /** * Send Trace Events from this Worker to Workers Logpush. * * This will not configure a corresponding Logpush job automatically. * * For more information about Workers Logpush, see: * https://blog.cloudflare.com/logpush-for-workers/ * * @inheritable */ logpush: boolean | undefined; /** * Include source maps when uploading this worker. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#source-maps * * @inheritable */ upload_source_maps: boolean | undefined; /** * Specify how the Worker should be located to minimize round-trip time. * * More details: https://developers.cloudflare.com/workers/platform/smart-placement/ * * @inheritable */ placement: { mode: "off" | "smart"; hint?: string; } | { mode?: "targeted"; region: string; } | { mode?: "targeted"; host: string; } | { mode?: "targeted"; hostname: string; } | undefined; /** * Specify the directory of static assets to deploy/serve * * More details at https://developers.cloudflare.com/workers/frameworks/ * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#assets * * @inheritable */ assets: Assets | undefined; /** * Specify the observability behavior of the Worker. * * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#observability * * @inheritable */ observability: Observability | undefined; /** * Specify the compliance region mode of the Worker. * * Although if the user does not specify a compliance region, the default is `public`, * it can be set to `undefined` in configuration to delegate to the CLOUDFLARE_COMPLIANCE_REGION environment variable. */ compliance_region: "public" | "fedramp_high" | undefined; /** * Configuration for Python modules. * * @inheritable */ python_modules: { /** * A list of glob patterns to exclude files from the python_modules directory when bundling. * * Patterns are relative to the python_modules directory and use glob syntax. * * @default ["**\*.pyc"] */ exclude: string[]; }; } type DurableObjectBindings = { /** The name of the binding used to refer to the Durable Object */ name: string; /** The exported class name of the Durable Object */ class_name: string; /** The script where the Durable Object is defined (if it's external to this Worker) */ script_name?: string; /** The service environment of the script_name to bind to */ environment?: string; }[]; type WorkflowBinding = { /** The name of the binding used to refer to the Workflow */ binding: string; /** The name of the Workflow */ name: string; /** The exported class name of the Workflow */ class_name: string; /** The script where the Workflow is defined (if it's external to this Worker) */ script_name?: string; /** Whether the Workflow should be remote or not in local development */ remote?: boolean; }; /** * The `EnvironmentNonInheritable` interface declares all the configuration fields for an environment * that cannot be inherited from the top-level environment, and must be defined specifically. * * If any of these fields are defined at the top-level then they should also be specifically defined * for each named environment. */ interface EnvironmentNonInheritable { /** * A map of values to substitute when deploying your Worker. * * NOTE: This field is not automatically inherited from the top level environment, * and so must be specified in every named environment. * * @