wrangler
Version:
Command-line interface for all things Cloudflare Workers
1,432 lines (1,313 loc) • 899 kB
TypeScript
/// <reference types="node" />
import { Blob as Blob_2 } from 'buffer';
import { ConnectionOptions } from 'tls';
import type { DispatchFetch } from 'miniflare';
import { Duplex } from 'stream';
import { EventEmitter } from 'events';
import { EventEmitter as EventEmitter_2 } from 'node:events';
import type { IncomingRequestCfProperties } from '@cloudflare/workers-types/experimental';
import { IpcNetConnectOpts } from 'net';
import type { Json } from 'miniflare';
import type { MessagePort as MessagePort_2 } from 'worker_threads';
import type { Metafile } from 'esbuild';
import { Miniflare } from 'miniflare';
import type { MiniflareOptions } from 'miniflare';
import type { ModuleRule } from 'miniflare';
import { Mutex } from 'miniflare';
import type { NodeJSCompatMode } from 'miniflare';
import { Readable } from 'stream';
import { ReadableStream as ReadableStream_2 } from 'stream/web';
import type { Request as Request_3 } from 'miniflare';
import { Response as Response_3 } from 'miniflare';
import { Socket } from 'net';
import { TcpNetConnectOpts } from 'net';
import { TLSSocket } from 'tls';
import { URL as URL_2 } from 'url';
import { UrlObject } from 'url';
import { URLSearchParams as URLSearchParams_2 } from 'url';
import type { WorkerOptions } from 'miniflare';
import { Writable } from 'stream';
import { z } from 'zod';
declare type AbortSignal_2 = unknown;
declare interface AddEventListenerOptions extends EventListenerOptions {
once?: boolean
passive?: boolean
signal?: AbortSignal
}
declare class Agent extends Dispatcher{
constructor(opts?: Agent.Options)
/** `true` after `dispatcher.close()` has been called. */
closed: boolean;
/** `true` after `dispatcher.destroyed()` has been called or `dispatcher.close()` has been called and the dispatcher shutdown has completed. */
destroyed: boolean;
/** Dispatches a request. */
dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean;
}
declare namespace Agent {
interface Options extends Pool.Options {
/** Default: `(origin, opts) => new Pool(origin, opts)`. */
factory?(origin: string | URL_2, opts: Object): Dispatcher;
/** Integer. Default: `0` */
maxRedirections?: number;
interceptors?: { Agent?: readonly Dispatcher.DispatchInterceptor[] } & Pool.Options["interceptors"]
}
interface DispatchOptions extends Dispatcher.DispatchOptions {
/** Integer. */
maxRedirections?: number;
}
}
declare type ApiCredentials = {
apiToken: string;
} | {
authKey: string;
authEmail: string;
};
declare type AssetConfig = z.infer<typeof AssetConfigSchema>;
declare const AssetConfigSchema: z.ZodObject<{
account_id: z.ZodOptional<z.ZodNumber>;
script_id: z.ZodOptional<z.ZodNumber>;
compatibility_date: z.ZodOptional<z.ZodString>;
compatibility_flags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
html_handling: z.ZodOptional<z.ZodEnum<["auto-trailing-slash", "force-trailing-slash", "drop-trailing-slash", "none"]>>;
not_found_handling: z.ZodOptional<z.ZodEnum<["single-page-application", "404-page", "none"]>>;
redirects: z.ZodOptional<z.ZodObject<{
version: z.ZodLiteral<1>;
staticRules: z.ZodRecord<z.ZodString, z.ZodObject<{
status: z.ZodNumber;
to: z.ZodString;
lineNumber: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
status?: number;
to?: string;
lineNumber?: number;
}, {
status?: number;
to?: string;
lineNumber?: number;
}>>;
rules: z.ZodRecord<z.ZodString, z.ZodObject<{
status: z.ZodNumber;
to: z.ZodString;
}, "strip", z.ZodTypeAny, {
status?: number;
to?: string;
}, {
status?: number;
to?: string;
}>>;
}, "strip", z.ZodTypeAny, {
version?: 1;
staticRules?: Record<string, {
status?: number;
to?: string;
lineNumber?: number;
}>;
rules?: Record<string, {
status?: number;
to?: string;
}>;
}, {
version?: 1;
staticRules?: Record<string, {
status?: number;
to?: string;
lineNumber?: number;
}>;
rules?: Record<string, {
status?: number;
to?: string;
}>;
}>>;
headers: z.ZodOptional<z.ZodObject<{
version: z.ZodLiteral<2>;
rules: z.ZodRecord<z.ZodString, z.ZodObject<{
set: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
unset: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
}, "strip", z.ZodTypeAny, {
set?: Record<string, string>;
unset?: string[];
}, {
set?: Record<string, string>;
unset?: string[];
}>>;
}, "strip", z.ZodTypeAny, {
version?: 2;
rules?: Record<string, {
set?: Record<string, string>;
unset?: string[];
}>;
}, {
version?: 2;
rules?: Record<string, {
set?: Record<string, string>;
unset?: string[];
}>;
}>>;
}, "strip", z.ZodTypeAny, {
account_id?: number;
script_id?: number;
compatibility_date?: string;
compatibility_flags?: string[];
html_handling?: "none" | "auto-trailing-slash" | "force-trailing-slash" | "drop-trailing-slash";
not_found_handling?: "none" | "single-page-application" | "404-page";
redirects?: {
version?: 1;
staticRules?: Record<string, {
status?: number;
to?: string;
lineNumber?: number;
}>;
rules?: Record<string, {
status?: number;
to?: string;
}>;
};
headers?: {
version?: 2;
rules?: Record<string, {
set?: Record<string, string>;
unset?: string[];
}>;
};
}, {
account_id?: number;
script_id?: number;
compatibility_date?: string;
compatibility_flags?: string[];
html_handling?: "none" | "auto-trailing-slash" | "force-trailing-slash" | "drop-trailing-slash";
not_found_handling?: "none" | "single-page-application" | "404-page";
redirects?: {
version?: 1;
staticRules?: Record<string, {
status?: number;
to?: string;
lineNumber?: number;
}>;
rules?: Record<string, {
status?: number;
to?: string;
}>;
};
headers?: {
version?: 2;
rules?: Record<string, {
set?: Record<string, string>;
unset?: string[];
}>;
};
}>;
declare type Assets = {
/** Absolute path to assets directory */
directory?: string;
/** Name of `env` binding property in the User Worker. */
binding?: string;
/** How to handle HTML requests. */
html_handling?: "auto-trailing-slash" | "force-trailing-slash" | "drop-trailing-slash" | "none";
/** How to handle requests that do not match an asset. */
not_found_handling?: "single-page-application" | "404-page" | "none";
/**
* If true, route every request to the User Worker, whether or not it matches an asset.
* If false, then respond to requests that match an asset with that asset directly.
* */
run_worker_first?: boolean;
};
declare type AssetsOptions = {
directory: string;
binding?: string;
routerConfig: RouterConfig;
assetConfig: AssetConfig;
_redirects?: string;
_headers?: string;
};
declare type AsyncHook<T extends HookValues, Args extends unknown[] = []> = Hook<T, Args> | Hook<Promise<T>, Args>;
declare class BalancedPool extends Dispatcher {
constructor(url: string | string[] | URL_2 | URL_2[], options?: Pool.Options);
addUpstream(upstream: string | URL_2): BalancedPool;
removeUpstream(upstream: string | URL_2): BalancedPool;
upstreams: Array<string>;
/** `true` after `pool.close()` has been called. */
closed: boolean;
/** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */
destroyed: boolean;
}
declare type BaseErrorEvent<Source = string, Data = undefined> = {
type: "error";
reason: string;
cause: Error | SerializedError;
source: Source;
data: Data;
};
declare type BinaryFile = File_2<Uint8Array>;
declare type BinaryType = 'blob' | 'arraybuffer'
declare type Binding = {
type: "plain_text";
value: string;
} | {
type: "json";
value: Json;
} | ({
type: "kv_namespace";
} & BindingOmit<CfKvNamespace>) | ({
type: "send_email";
} & NameOmit<CfSendEmailBindings>) | {
type: "wasm_module";
source: BinaryFile;
} | {
type: "text_blob";
source: File_2;
} | {
type: "browser";
} | {
type: "ai";
} | {
type: "images";
} | {
type: "version_metadata";
} | {
type: "data_blob";
source: BinaryFile;
} | ({
type: "durable_object_namespace";
} & NameOmit<CfDurableObject>) | ({
type: "workflow";
} & BindingOmit<CfWorkflow>) | ({
type: "queue";
} & BindingOmit<CfQueue>) | ({
type: "r2_bucket";
} & BindingOmit<CfR2Bucket>) | ({
type: "d1";
} & BindingOmit<CfD1Database>) | ({
type: "vectorize";
} & BindingOmit<CfVectorize>) | ({
type: "hyperdrive";
} & BindingOmit<CfHyperdrive>) | ({
type: "service";
} & BindingOmit<CfService>) | {
type: "fetcher";
fetcher: ServiceFetch;
} | ({
type: "analytics_engine";
} & BindingOmit<CfAnalyticsEngineDataset>) | ({
type: "dispatch_namespace";
} & BindingOmit<CfDispatchNamespace>) | ({
type: "mtls_certificate";
} & BindingOmit<CfMTlsCertificate>) | ({
type: "pipeline";
} & BindingOmit<CfPipeline>) | ({
type: "logfwdr";
} & NameOmit<CfLogfwdrBinding>) | {
type: `unsafe_${string}`;
} | {
type: "assets";
};
declare type BindingOmit<T> = Omit<T, "binding">;
declare interface BlobPropertyBag {
type?: string
endings?: 'native' | 'transparent'
}
declare type BodyInit =
| ArrayBuffer
| AsyncIterable<Uint8Array>
| Blob_2
| FormData_2
| Iterable<Uint8Array>
| NodeJS.ArrayBufferView
| URLSearchParams_2
| null
| string
declare interface BodyMixin {
readonly body: ReadableStream_2 | null
readonly bodyUsed: boolean
readonly arrayBuffer: () => Promise<ArrayBuffer>
readonly blob: () => Promise<Blob_2>
readonly formData: () => Promise<FormData_2>
readonly json: () => Promise<unknown>
readonly text: () => Promise<string>
}
declare class BodyReadable extends Readable {
constructor(
resume?: (this: Readable, size: number) => void | null,
abort?: () => void | null,
contentType?: string
)
/** Consumes and returns the body as a string
* https://fetch.spec.whatwg.org/#dom-body-text
*/
text(): Promise<string>
/** Consumes and returns the body as a JavaScript Object
* https://fetch.spec.whatwg.org/#dom-body-json
*/
json(): Promise<unknown>
/** Consumes and returns the body as a Blob
* https://fetch.spec.whatwg.org/#dom-body-blob
*/
blob(): Promise<Blob_2>
/** Consumes and returns the body as an ArrayBuffer
* https://fetch.spec.whatwg.org/#dom-body-arraybuffer
*/
arrayBuffer(): Promise<ArrayBuffer>
/** Not implemented
*
* https://fetch.spec.whatwg.org/#dom-body-formdata
*/
formData(): Promise<never>
/** Returns true if the body is not null and the body has been consumed
*
* Otherwise, returns false
*
* https://fetch.spec.whatwg.org/#dom-body-bodyused
*/
readonly bodyUsed: boolean
/** Throws on node 16.6.0
*
* If body is null, it should return null as the body
*
* If body is not null, should return the body as a ReadableStream
*
* https://fetch.spec.whatwg.org/#dom-body-body
*/
readonly body: never | undefined
/** Dumps the response body by reading `limit` number of bytes.
* @param opts.limit Number of bytes to read (optional) - Default: 262144
*/
dump(opts?: { limit: number }): Promise<void>
}
declare function buildConnector (options?: buildConnector.BuildOptions): buildConnector.connector
declare namespace buildConnector {
type BuildOptions = (ConnectionOptions | TcpNetConnectOpts | IpcNetConnectOpts) & {
allowH2?: boolean;
maxCachedSessions?: number | null;
socketPath?: string | null;
timeout?: number | null;
port?: number;
keepAlive?: boolean | null;
keepAliveInitialDelay?: number | null;
}
interface Options {
hostname: string
host?: string
protocol: string
port: string
servername?: string
localAddress?: string | null
httpSocket?: Socket
}
type Callback = (...args: CallbackArgs) => void
type CallbackArgs = [null, Socket | TLSSocket] | [Error, null]
interface connector {
(options: buildConnector.Options, callback: buildConnector.Callback): void
}
}
declare type Bundle = EsbuildBundle;
declare type BundleCompleteEvent = {
type: "bundleComplete";
config: StartDevWorkerOptions;
bundle: Bundle;
};
declare class BundlerController extends Controller<BundlerControllerEventMap> {
#private;
onConfigUpdate(event: ConfigUpdateEvent): void;
teardown(): Promise<void>;
emitBundleStartEvent(config: StartDevWorkerOptions): void;
emitBundleCompleteEvent(config: StartDevWorkerOptions, bundle: EsbuildBundle): void;
}
declare type BundlerControllerEventMap = ControllerEventMap & {
bundleStart: [BundleStartEvent];
bundleComplete: [BundleCompleteEvent];
};
declare type BundleStartEvent = {
type: "bundleStart";
config: StartDevWorkerOptions;
};
declare interface Cache {
match (request: RequestInfo, options?: CacheQueryOptions): Promise<Response_2 | undefined>,
matchAll (request?: RequestInfo, options?: CacheQueryOptions): Promise<readonly Response_2[]>,
add (request: RequestInfo): Promise<undefined>,
addAll (requests: RequestInfo[]): Promise<undefined>,
put (request: RequestInfo, response: Response_2): Promise<undefined>,
delete (request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>,
keys (request?: RequestInfo, options?: CacheQueryOptions): Promise<readonly Request_2[]>
}
/**
* No-op implementation of Cache
*/
declare class Cache_2 {
delete(request: CacheRequest, options?: CacheQueryOptions_2): Promise<boolean>;
match(request: CacheRequest, options?: CacheQueryOptions_2): Promise<CacheResponse | undefined>;
put(request: CacheRequest, response: CacheResponse): Promise<void>;
}
declare interface CacheQueryOptions {
ignoreSearch?: boolean,
ignoreMethod?: boolean,
ignoreVary?: boolean
}
declare type CacheQueryOptions_2 = {
ignoreMethod?: boolean;
};
declare type CacheRequest = any;
declare type CacheResponse = any;
declare const caches: CacheStorage;
declare interface CacheStorage {
match (request: RequestInfo, options?: MultiCacheQueryOptions): Promise<Response_2 | undefined>,
has (cacheName: string): Promise<boolean>,
open (cacheName: string): Promise<Cache>,
delete (cacheName: string): Promise<boolean>,
keys (): Promise<string[]>
}
declare const CacheStorage: {
prototype: CacheStorage
new(): CacheStorage
};
/**
* 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_2 {
constructor();
open(cacheName: string): Promise<Cache_2>;
get default(): Cache_2;
}
/**
* A Cloudflare account.
*/
declare interface CfAccount {
/**
* An API token.
*
* @link https://api.cloudflare.com/#user-api-tokens-properties
*/
apiToken: ApiCredentials;
/**
* An account ID.
*/
accountId: string;
}
declare interface CfAnalyticsEngineDataset {
binding: string;
dataset?: string;
}
declare type CfCapnp = {
base_path?: never;
source_schemas?: never;
compiled_schema: string;
} | {
base_path: string;
source_schemas: string[];
compiled_schema?: never;
};
declare interface CfD1Database {
binding: string;
database_id?: string | typeof INHERIT_SYMBOL;
database_name?: string;
preview_database_id?: string;
database_internal_env?: string;
migrations_table?: string;
migrations_dir?: string;
}
declare interface CfDispatchNamespace {
binding: string;
namespace: string;
outbound?: {
service: string;
environment?: string;
parameters?: string[];
};
}
/**
* A Durable Object.
*/
declare interface CfDurableObject {
name: string;
class_name: string;
script_name?: string;
environment?: string;
}
declare interface CfHyperdrive {
binding: string;
id: string;
localConnectionString?: string;
}
/**
* A KV namespace.
*/
declare interface CfKvNamespace {
binding: string;
id?: string | typeof INHERIT_SYMBOL;
}
declare interface CfLogfwdrBinding {
name: string;
destination: string;
}
/**
* An imported module.
*/
declare interface CfModule {
/**
* The module name.
*
* @example
* './src/index.js'
*/
name: string;
/**
* The absolute path of the module on disk, or `undefined` if this is a
* virtual module. Used as the source URL for this module, so source maps are
* correctly resolved.
*
* @example
* '/path/to/src/index.js'
*/
filePath: string | undefined;
/**
* The module content, usually JavaScript or WASM code.
*
* @example
* export default {
* async fetch(request) {
* return new Response('Ok')
* }
* }
*/
content: string | Buffer<ArrayBuffer>;
/**
* An optional sourcemap for this module if it's of a ESM or CJS type, this will only be present
* if we're deploying with sourcemaps enabled. Since we copy extra modules that aren't bundled
* we need to also copy the relevant sourcemaps into the final out directory.
*/
sourceMap?: CfWorkerSourceMap;
/**
* The module type.
*
* If absent, will default to the main module's type.
*/
type?: CfModuleType;
}
/**
* A module type.
*/
declare type CfModuleType = "esm" | "commonjs" | "compiled-wasm" | "text" | "buffer" | "python" | "python-requirement";
declare interface CfMTlsCertificate {
binding: string;
certificate_id: string;
}
declare interface CfPipeline {
binding: string;
pipeline: string;
}
declare interface CfQueue {
binding: string;
queue_name: string;
delivery_delay?: number;
}
declare interface CfR2Bucket {
binding: string;
bucket_name?: string | typeof INHERIT_SYMBOL;
jurisdiction?: string;
}
/**
* The type of Worker
*/
declare type CfScriptFormat = "modules" | "service-worker";
/**
* A binding to send email.
*/
declare interface CfSendEmailBindings {
name: string;
destination_address?: string;
allowed_destination_addresses?: string[];
}
declare interface CfService {
binding: string;
service: string;
environment?: string;
entrypoint?: string;
}
declare interface CfUnsafe {
bindings: CfUnsafeBinding[] | undefined;
metadata: CfUnsafeMetadata | undefined;
capnp: CfCapnp | undefined;
}
declare interface CfUnsafeBinding {
name: string;
type: string;
}
declare type CfUnsafeMetadata = Record<string, unknown>;
declare interface CfVectorize {
binding: string;
index_name: string;
}
declare interface CfWorkerSourceMap {
/**
* The name of the source map.
*
* @example
* 'out.js.map'
*/
name: string;
/**
* The content of the source map, which is a JSON object described by the v3
* spec.
*
* @example
* {
* "version" : 3,
* "file": "out.js",
* "sourceRoot": "",
* "sources": ["foo.js", "bar.js"],
* "sourcesContent": [null, null],
* "names": ["src", "maps", "are", "fun"],
* "mappings": "A,AAAB;;ABCDE;"
* }
*/
content: string | Buffer;
}
declare interface CfWorkflow {
name: string;
class_name: string;
binding: string;
script_name?: string;
}
/**
* A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default.
*/
declare class Client extends Dispatcher {
constructor(url: string | URL_2, options?: Client.Options);
/** Property to get and set the pipelining factor. */
pipelining: number;
/** `true` after `client.close()` has been called. */
closed: boolean;
/** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */
destroyed: boolean;
}
declare namespace Client {
interface OptionsInterceptors {
Client: readonly Dispatcher.DispatchInterceptor[];
}
interface Options {
/** TODO */
interceptors?: OptionsInterceptors;
/** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */
maxHeaderSize?: number;
/** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */
headersTimeout?: number;
/** @deprecated unsupported socketTimeout, use headersTimeout & bodyTimeout instead */
socketTimeout?: never;
/** @deprecated unsupported requestTimeout, use headersTimeout & bodyTimeout instead */
requestTimeout?: never;
/** TODO */
connectTimeout?: number;
/** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */
bodyTimeout?: number;
/** @deprecated unsupported idleTimeout, use keepAliveTimeout instead */
idleTimeout?: never;
/** @deprecated unsupported keepAlive, use pipelining=0 instead */
keepAlive?: never;
/** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */
keepAliveTimeout?: number;
/** @deprecated unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead */
maxKeepAliveTimeout?: never;
/** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */
keepAliveMaxTimeout?: number;
/** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */
keepAliveTimeoutThreshold?: number;
/** TODO */
socketPath?: string;
/** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */
pipelining?: number;
/** @deprecated use the connect option instead */
tls?: never;
/** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */
strictContentLength?: boolean;
/** TODO */
maxCachedSessions?: number;
/** TODO */
maxRedirections?: number;
/** TODO */
connect?: buildConnector.BuildOptions | buildConnector.connector;
/** TODO */
maxRequestsPerClient?: number;
/** TODO */
localAddress?: string;
/** Max response body size in bytes, -1 is disabled */
maxResponseSize?: number;
/** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */
autoSelectFamily?: boolean;
/** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */
autoSelectFamilyAttemptTimeout?: number;
/**
* @description Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation.
* @default false
*/
allowH2?: boolean;
/**
* @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame.
* @default 100
*/
maxConcurrentStreams?: number
}
interface SocketInfo {
localAddress?: string
localPort?: number
remoteAddress?: string
remotePort?: number
remoteFamily?: string
timeout?: number
bytesWritten?: number
bytesRead?: number
}
}
declare interface CloseEvent extends Event_2 {
readonly code: number
readonly reason: string
readonly wasClean: boolean
}
declare const CloseEvent: {
prototype: CloseEvent
new (type: string, eventInitDict?: CloseEventInit): CloseEvent
};
declare interface CloseEventInit extends EventInit {
code?: number
reason?: string
wasClean?: boolean
}
/**
* Configuration in wrangler for Cloudchamber
*/
declare type CloudchamberConfig = {
image?: string;
location?: string;
vcpu?: number;
memory?: string;
ipv4?: boolean;
};
declare interface ComputedFields {
/** The path to the Wrangler configuration file (if any, and possibly redirected from the user Wrangler configuration) used to create this configuration. */
configPath: string | undefined;
/** The path to the user's Wrangler configuration file (if any), which may have been redirected to another file that used to create this configuration. */
userConfigPath: string | undefined;
/**
* The original top level name for the Worker in the raw configuration.
*
* When a raw configuration has been flattened to a single environment the worker name may have been replaced or transformed.
* It can be useful to know what the top-level name was before the flattening.
*/
topLevelName: string | undefined;
}
declare class ConfigController extends Controller<ConfigControllerEventMap> {
#private;
latestInput?: StartDevWorkerInput;
latestConfig?: StartDevWorkerOptions;
set(input: StartDevWorkerInput, throwErrors?: boolean): Promise<StartDevWorkerOptions | undefined>;
patch(input: Partial<StartDevWorkerInput>): Promise<StartDevWorkerOptions | undefined>;
teardown(): Promise<void>;
emitConfigUpdateEvent(config: StartDevWorkerOptions): void;
}
declare type ConfigControllerEventMap = ControllerEventMap & {
configUpdate: [ConfigUpdateEvent];
};
declare interface ConfigFields<Dev extends RawDevConfig> {
/**
* A boolean to enable "legacy" style wrangler environments (from Wrangler v1).
* These have been superseded by Services, but there may be projects that won't
* (or can't) use them. If you're using a legacy environment, you can set this
* to `true` to enable it.
*/
legacy_env: boolean;
/**
* 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.
*/
send_metrics: boolean | undefined;
/**
* Options to configure the development server that your worker will use.
*/
dev: Dev;
/**
* The definition of a Worker Site, a feature that lets you upload
* static assets with your Worker.
*
* More details at https://developers.cloudflare.com/workers/platform/sites
*/
site: {
/**
* The directory containing your static assets.
*
* It must be a path relative to your Wrangler configuration file.
* Example: bucket = "./public"
*
* If there is a `site` field then it must contain this `bucket` field.
*/
bucket: string;
/**
* The location of your Worker script.
*
* @deprecated DO NOT use this (it's a holdover from Wrangler v1.x). Either use the top level `main` field, or pass the path to your entry file as a command line argument.
* @breaking
*/
"entry-point"?: string;
/**
* An exclusive list of .gitignore-style patterns that match file
* or directory names from your bucket location. Only matched
* items will be uploaded. Example: include = ["upload_dir"]
*
* @optional
* @default []
*/
include?: string[];
/**
* A list of .gitignore-style patterns that match files or
* directories in your bucket that should be excluded from
* uploads. Example: exclude = ["ignore_dir"]
*
* @optional
* @default []
*/
exclude?: string[];
} | undefined;
/**
* A list of wasm modules that your worker should be bound to. This is
* the "legacy" way of binding to a wasm module. ES module workers should
* do proper module imports.
*/
wasm_modules: {
[key: string]: string;
} | undefined;
/**
* A list of text files that your worker should be bound to. This is
* the "legacy" way of binding to a text file. ES module workers should
* do proper module imports.
*/
text_blobs: {
[key: string]: string;
} | undefined;
/**
* A list of data files that your worker should be bound to. This is
* the "legacy" way of binding to a data file. ES module workers should
* do proper module imports.
*/
data_blobs: {
[key: string]: string;
} | undefined;
/**
* A map of module aliases. Lets you swap out a module for any others.
* Corresponds with esbuild's `alias` config
*/
alias: {
[key: string]: string;
} | undefined;
/**
* By default, the Wrangler configuration file is the source of truth for your environment configuration, like a terraform file.
*
* If you change your vars in the dashboard, wrangler *will* override/delete them on its next deploy.
*
* If you want to keep your dashboard vars when wrangler deploys, set this field to true.
*
* @default false
* @nonInheritable
*/
keep_vars?: boolean;
}
/**
* The possible types for a `Rule`.
*/
declare type ConfigModuleRuleType = "ESModule" | "CommonJS" | "CompiledWasm" | "Text" | "Data" | "PythonModule" | "PythonRequirement";
declare type ConfigUpdateEvent = {
type: "configUpdate";
config: StartDevWorkerOptions;
};
/** Starts two-way communications with the requested resource. */
declare function connect(
url: string | URL_2 | UrlObject,
options?: { dispatcher?: Dispatcher } & Omit<Dispatcher.ConnectOptions, 'origin' | 'path'>
): Promise<Dispatcher.ConnectData>;
/**
* Configuration for a container application
*/
declare type ContainerApp = {
name: string;
instances: number;
image?: string;
class_name: string;
scheduling_policy?: "regional" | "moon";
configuration: {
image: string;
labels?: {
name: string;
value: string;
}[];
secrets?: {
name: string;
type: "env";
secret: string;
}[];
};
constraints?: {
regions?: string[];
cities?: string[];
tier?: number;
};
};
declare abstract class Controller<EventMap extends ControllerEventMap = ControllerEventMap> extends TypedEventEmitterImpl<EventMap> {
emitErrorEvent(data: ErrorEvent): void;
}
declare type ControllerEventMap = {
error: [ErrorEvent];
};
declare interface Cookie {
name: string
value: string
expires?: Date | number
maxAge?: number
domain?: string
path?: string
secure?: boolean
httpOnly?: boolean
sameSite?: 'Strict' | 'Lax' | 'None'
unparsed?: string[]
}
declare function createRedirectInterceptor (opts: RedirectInterceptorOpts): Dispatcher.DispatchInterceptor
declare type CustomDomainRoute = {
pattern: string;
custom_domain: boolean;
};
declare class DecoratorHandler implements Dispatcher.DispatchHandlers{
constructor (handler: Dispatcher.DispatchHandlers)
}
declare type DeferredPromise<T> = {
promise: Promise<T>;
resolve: (_: MaybePromise<T>) => void;
reject: (_: Error) => void;
};
declare function deleteCookie (
headers: Headers_2,
name: string,
attributes?: { name?: string, domain?: string }
): void
/**
* 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: {
url: string;
id: 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: {
metadata: {
branch: string;
commit_hash: string;
commit_message: string;
};
type: string;
};
latest_stage: {
status: "canceled" | "active" | "idle" | "success" | "failure" | "skipped";
name: "queued" | "build" | "deploy" | "initialize" | "clone_repo";
started_on: string | null;
ended_on: string | null;
};
stages: {
status: "canceled" | "active" | "idle" | "success" | "failure" | "skipped";
name: "queued" | "build" | "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;
kv_namespaces?: any;
source?: {
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?: "none" | "custom" | "all" | undefined;
preview_branch_includes?: string[] | undefined;
preview_branch_excludes?: string[] | undefined;
};
type: "github" | "gitlab";
} | undefined;
env_vars?: any;
durable_object_namespaces?: any;
is_skipped?: boolean | undefined;
files?: {
[x: string]: string | undefined;
} | undefined;
};
formData: FormData_2;
}>;
declare interface DevConfig {
/**
* IP address for the local dev server to listen on,
*
* @default localhost
*/
ip: string;
/**
* Port for the local dev server to listen on
*
* @default 8787
*/
port: number | undefined;
/**
* Port for the local dev server's inspector to listen on
*
* @default 9229
*/
inspector_port: number | undefined;
/**
* Protocol that local wrangler dev server listens to requests on.
*
* @default http
*/
local_protocol: "http" | "https";
/**
* Protocol that wrangler dev forwards requests on
*
* Setting this to `http` is not currently implemented for remote mode.
* See https://github.com/cloudflare/workers-sdk/issues/583
*
* @default https
*/
upstream_protocol: "https" | "http";
/**
* Host to forward requests to, defaults to the host of the first route of project
*/
host: string | undefined;
}
declare type DevToolsEvent<Method extends _EventMethods> = Method extends unknown ? {
method: Method;
params: _Params<ProtocolMapping.Events[Method]>;
} : never;
declare namespace DiagnosticsChannel {
interface Request {
origin?: string | URL_2;
completed: boolean;
method?: Dispatcher.HttpMethod;
path: string;
headers: string;
addHeader(key: string, value: string): Request;
}
interface Response {
statusCode: number;
statusText: string;
headers: Array<Buffer>;
}
type Error = unknown;
interface ConnectParams {
host: URL_2["host"];
hostname: URL_2["hostname"];
protocol: URL_2["protocol"];
port: URL_2["port"];
servername: string | null;
}
type Connector = buildConnector.connector;
interface RequestCreateMessage {
request: Request;
}
interface RequestBodySentMessage {
request: Request;
}
interface RequestHeadersMessage {
request: Request;
response: Response;
}
interface RequestTrailersMessage {
request: Request;
trailers: Array<Buffer>;
}
interface RequestErrorMessage {
request: Request;
error: Error;
}
interface ClientSendHeadersMessage {
request: Request;
headers: string;
socket: Socket;
}
interface ClientBeforeConnectMessage {
connectParams: ConnectParams;
connector: Connector;
}
interface ClientConnectedMessage {
socket: Socket;
connectParams: ConnectParams;
connector: Connector;
}
interface ClientConnectErrorMessage {
error: Error;
socket: Socket;
connectParams: ConnectParams;
connector: Connector;
}
}
/** Dispatcher is the core API used to dispatch requests. */
declare class Dispatcher extends EventEmitter {
/** Dispatches a request. This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. It is primarily intended for library developers who implement higher level APIs on top of this. */
dispatch(options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean;
/** Starts two-way communications with the requested resource. */
connect(options: Dispatcher.ConnectOptions): Promise<Dispatcher.ConnectData>;
connect(options: Dispatcher.ConnectOptions, callback: (err: Error | null, data: Dispatcher.ConnectData) => void): void;
/** Performs an HTTP request. */
request(options: Dispatcher.RequestOptions): Promise<Dispatcher.ResponseData>;
request(options: Dispatcher.RequestOptions, callback: (err: Error | null, data: Dispatcher.ResponseData) => void): void;
/** For easy use with `stream.pipeline`. */
pipeline(options: Dispatcher.PipelineOptions, handler: Dispatcher.PipelineHandler): Duplex;
/** A faster version of `Dispatcher.request`. */
stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory): Promise<Dispatcher.StreamData>;
stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory, callback: (err: Error | null, data: Dispatcher.StreamData) => void): void;
/** Upgrade to a different protocol. */
upgrade(options: Dispatcher.UpgradeOptions): Promise<Dispatcher.UpgradeData>;
upgrade(options: Dispatcher.UpgradeOptions, callback: (err: Error | null, data: Dispatcher.UpgradeData) => void): void;
/** Closes the client and gracefully waits for enqueued requests to complete before invoking the callback (or returning a promise if no callback is provided). */
close(): Promise<void>;
close(callback: () => void): void;
/** Destroy the client abruptly with the given err. All the pending and running requests will be asynchronously aborted and error. Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. */
destroy(): Promise<void>;
destroy(err: Error | null): Promise<void>;
destroy(callback: () => void): void;
destroy(err: Error | null, callback: () => void): void;
on(eventName: 'connect', callback: (origin: URL_2, targets: readonly Dispatcher[]) => void): this;
on(eventName: 'disconnect', callback: (origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
on(eventName: 'connectionError', callback: (origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
on(eventName: 'drain', callback: (origin: URL_2) => void): this;
once(eventName: 'connect', callback: (origin: URL_2, targets: readonly Dispatcher[]) => void): this;
once(eventName: 'disconnect', callback: (origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
once(eventName: 'connectionError', callback: (origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
once(eventName: 'drain', callback: (origin: URL_2) => void): this;
off(eventName: 'connect', callback: (origin: URL_2, targets: readonly Dispatcher[]) => void): this;
off(eventName: 'disconnect', callback: (origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
off(eventName: 'connectionError', callback: (origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
off(eventName: 'drain', callback: (origin: URL_2) => void): this;
addListener(eventName: 'connect', callback: (origin: URL_2, targets: readonly Dispatcher[]) => void): this;
addListener(eventName: 'disconnect', callback: (origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
addListener(eventName: 'connectionError', callback: (origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
addListener(eventName: 'drain', callback: (origin: URL_2) => void): this;
removeListener(eventName: 'connect', callback: (origin: URL_2, targets: readonly Dispatcher[]) => void): this;
removeListener(eventName: 'disconnect', callback: (origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
removeListener(eventName: 'connectionError', callback: (origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
removeListener(eventName: 'drain', callback: (origin: URL_2) => void): this;
prependListener(eventName: 'connect', callback: (origin: URL_2, targets: readonly Dispatcher[]) => void): this;
prependListener(eventName: 'disconnect', callback: (origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
prependListener(eventName: 'connectionError', callback: (origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
prependListener(eventName: 'drain', callback: (origin: URL_2) => void): this;
prependOnceListener(eventName: 'connect', callback: (origin: URL_2, targets: readonly Dispatcher[]) => void): this;
prependOnceListener(eventName: 'disconnect', callback: (origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
prependOnceListener(eventName: 'connectionError', callback: (origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this;
prependOnceListener(eventName: 'drain', callback: (origin: URL_2) => void): this;
listeners(eventName: 'connect'): ((origin: URL_2, targets: readonly Dispatcher[]) => void)[]
listeners(eventName: 'disconnect'): ((origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[];
listeners(eventName: 'connectionError'): ((origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[];
listeners(eventName: 'drain'): ((origin: URL_2) => void)[];
rawListeners(eventName: 'connect'): ((origin: URL_2, targets: readonly Dispatcher[]) => void)[]
rawListeners(eventName: 'disconnect'): ((origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[];
rawListeners(eventName: 'connectionError'): ((origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[];
rawListeners(eventName: 'drain'): ((origin: URL_2) => void)[];
emit(eventName: 'connect', origin: URL_2, targets: readonly Dispatcher[]): boolean;
emit(eventName: 'disconnect', origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean;
emit(eventName: 'connectionError', origin: URL_2, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean;
emit(eventName: 'drain', origin: URL_2): boolean;
}
declare namespace Dispatcher {
interface DispatchOptions {
origin?: string | URL_2;
path: string;
method: HttpMethod;
/** Default: `null` */
body?: string | Buffer | Uint8Array | Readable | null | FormData_2;
/** Default: `null` */
headers?: IncomingHttpHeaders | string[] | null;
/** Query string params to be embedded in the request URL. Default: `null` */
query?: Record<string, any>;
/** Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline have completed. Default: `true` if `method` is `HEAD` or `GET`. */
idempotent?: boolean;
/** Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. */
blocking?: boolean;
/** Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. Default: `method === 'CONNECT' || null`. */
upgrade?: boolean | string | null;
/** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers. Defaults to 300 seconds. */
headersTimeout?: number | null;
/** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use 0 to disable it entirely. Defaults to 300 seconds. */
bodyTimeout?: number | null;
/** Whether the request should stablish a keep-alive or not. Default `false` */
reset?: boolean;
/** Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. Defaults to false */
throwOnError?: boolean;
/** For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server*/
expectContinue?: boolean;
}
interface ConnectOptions {
path: string;
/** Default: `null` */
headers?: IncomingHttpHeaders | string[] | null;
/** Default: `null` */
signal?: AbortSignal_2 | EventEmitter | null;
/** This argument parameter is passed through to `ConnectData` */
opaque?: unknown;
/** Default: 0 */
maxRedirections?: number;
/** Default: `null` */
responseHeader?: 'raw' | null;
}
interface RequestOptions extends DispatchOptions {
/** Default: `null` */
opaque?: unknown;
/** Default: `null` */
signal?: AbortSignal_2 | EventEmitter | null;
/** Default: 0 */
maxRedirections?: number;
/** Default: `null` */
onInfo?: (info: { statusCode: number, headers: Record<string, string | string[]> }) => void;
/** Default: `null` */
responseHeader?: 'raw' | null;
/** Default: `64 KiB` */
highWaterMark?: number;
}
interface PipelineOptions extends RequestOptions {
/** `true` if the `handler` will return an object stream. Default: `false` */
objectMode?: boolean;
}
interface UpgradeOptions {
path: string;
/** Default: `'GET'` */
method?: string;
/** Default: `null` */
headers?: IncomingHttpHeaders | string[] | null;
/** A string of comma separated protocols, in descending pre