///
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 { IncomingMessage } from 'http';
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 as ModuleRule_2 } from 'miniflare';
import { Mutex } from 'miniflare';
import { Readable } from 'stream';
import { ReadableStream } from 'stream/web';
import type { Request as Request_2 } from 'miniflare';
import { Response as Response_2 } from 'miniflare';
import type { Server } from 'node:http';
import { ServerResponse } from 'http';
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 { WebSocket as WebSocket_2 } from 'miniflare';
import type { WorkerOptions } from 'miniflare';
import { Writable } from 'stream';
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 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;
/** `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 = {
type: "error";
reason: string;
cause: Error | SerializedError;
source: Source;
data: Data;
};
declare type BinaryType = 'blob' | 'arraybuffer'
declare type Binding = {
type: "kv";
id: string;
} | {
type: "r2";
bucket_name: string;
} | {
type: "d1";
/** The binding name used to refer to the D1 database in the worker. */
binding: string;
/** The name of this D1 database. */
database_name: string;
/** The UUID of this D1 database (not required). */
database_id: string;
/** The UUID of this D1 database for Wrangler Dev (if specified). */
preview_database_id?: string;
/** The name of the migrations table for this D1 database (defaults to 'd1_migrations'). */
migrations_table?: string;
/** The path to the directory of migrations for this D1 database (defaults to './migrations'). */
migrations_dir?: string;
/** Internal use only. */
database_internal_env?: string;
} | {
type: "durable-object";
className: string;
service?: ServiceDesignator;
} | {
type: "service";
service: ServiceDesignator | ServiceFetch;
} | {
type: "queue-producer";
name: string;
} | {
type: "constellation";
project_id: string;
} | {
type: "var";
value: string | Json | Uint8Array;
} | {
type: `unsafe-${string}`;
[key: string]: unknown;
};
/**
* Result of the `getBindingsProxy` utility
*/
export declare type BindingsProxy, CfProperties extends Record = IncomingRequestCfProperties> = Omit, "env"> & {
/**
* Object containing the various proxies
*/
bindings: Bindings;
};
declare interface BlobPropertyBag {
type?: string
endings?: 'native' | 'transparent'
}
declare type BodyInit =
| ArrayBuffer
| AsyncIterable
| Blob_2
| FormData
| Iterable
| NodeJS.ArrayBufferView
| URLSearchParams_2
| null
| string
declare interface BodyMixin {
readonly body: ReadableStream | null
readonly bodyUsed: boolean
readonly arrayBuffer: () => Promise
readonly blob: () => Promise
readonly formData: () => Promise
readonly json: () => Promise
readonly text: () => Promise
}
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
/** Consumes and returns the body as a JavaScript Object
* https://fetch.spec.whatwg.org/#dom-body-json
*/
json(): Promise
/** Consumes and returns the body as a Blob
* https://fetch.spec.whatwg.org/#dom-body-blob
*/
blob(): Promise
/** Consumes and returns the body as an ArrayBuffer
* https://fetch.spec.whatwg.org/#dom-body-arraybuffer
*/
arrayBuffer(): Promise
/** Not implemented
*
* https://fetch.spec.whatwg.org/#dom-body-formdata
*/
formData(): Promise
/** 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
}
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 BundleCompleteEvent = {
type: "bundleComplete";
config: StartDevWorkerOptions;
bundle: EsbuildBundle;
};
declare class BundlerController extends Controller {
onConfigUpdate(_: ConfigUpdateEvent): void;
teardown(): Promise;
emitBundleStartEvent(data: BundleStartEvent): void;
emitBundleCompletetEvent(data: BundleCompleteEvent): void;
on(event: "bundleStart", listener: (_: BundleStartEvent) => void): this;
on(event: "bundleComplete", listener: (_: BundleCompleteEvent) => void): this;
on(event: "error", listener: (_: ErrorEvent) => void): this;
once: typeof BundlerController.on;
}
declare type BundleStartEvent = {
type: "bundleStart";
config: StartDevWorkerOptions;
};
declare interface Cache {
match (request: RequestInfo, options?: CacheQueryOptions): Promise,
matchAll (request?: RequestInfo, options?: CacheQueryOptions): Promise,
add (request: RequestInfo): Promise,
addAll (requests: RequestInfo[]): Promise,
put (request: RequestInfo, response: Response): Promise,
delete (request: RequestInfo, options?: CacheQueryOptions): Promise,
keys (request?: RequestInfo, options?: CacheQueryOptions): Promise
}
/**
* No-op implementation of Cache
*/
declare class Cache_2 {
delete(request: CacheRequest, options?: CacheQueryOptions_2): Promise;
match(request: CacheRequest, options?: CacheQueryOptions_2): Promise;
put(request: CacheRequest, response: CacheResponse): Promise;
}
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,
has (cacheName: string): Promise,
open (cacheName: string): Promise,
delete (cacheName: string): Promise,
keys (): Promise
}
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;
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;
}
/**
* A Durable Object.
*/
declare interface CfDurableObject {
name: string;
class_name: string;
script_name?: string;
environment?: 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;
/**
* 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";
/**
* The type of Worker
*/
declare type CfScriptFormat = "modules" | "service-worker";
/**
* 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 = {
vcpu?: number;
memory?: string;
};
declare class ConfigController extends EventEmitter_2 {
config?: StartDevWorkerOptions;
setOptions(_: StartDevWorkerOptions): void;
updateOptions(_: Partial): void;
teardown(): Promise;
emitConfigUpdateEvent(data: ConfigUpdateEvent): void;
on(event: "configUpdate", listener: (_: ConfigUpdateEvent) => void): this;
on(event: "error", listener: (_: ErrorEvent) => void): this;
once: typeof ConfigController.on;
}
declare interface ConfigFields {
configPath: string | undefined;
/**
* 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;
/**
* 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 []
*/
migrations: {
/** A unique identifier for this migration. */
tag: string;
/** The new Durable Objects being defined. */
new_classes?: string[];
/** The Durable Objects being renamed. */
renamed_classes?: {
from: string;
to: string;
}[];
/** The Durable Objects being removed. */
deleted_classes?: string[];
}[];
/**
* 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.toml 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;
/**
* Serve a folder of static assets with your Worker, without any additional code.
* This can either be a string, or an object with additional config fields.
*/
assets: {
bucket: string;
include: string[];
exclude: string[];
browser_TTL: number | undefined;
serve_single_page_app: boolean;
} | 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;
/**
* By default, wrangler.toml 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
): Promise;
declare abstract class Controller extends EventEmitter_2 {
}
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 = {
promise: Promise;
resolve: (_: MaybePromise) => void;
reject: (_: Error) => void;
};
declare function deleteCookie (
headers: Headers,
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, args, }: PagesDeployOptions): Promise<{
url: string;
id: string;
environment: "production" | "preview";
project_id: string;
project_name: string;
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;
deployment_trigger: {
metadata: {
branch: string;
commit_hash: string;
commit_message: string;
};
type: string;
};
latest_stage: {
name: "build" | "deploy" | "queued" | "initialize" | "clone_repo";
status: "active" | "idle" | "canceled" | "success" | "failure" | "skipped";
started_on: string | null;
ended_on: string | null;
};
stages: {
name: "build" | "deploy" | "queued" | "initialize" | "clone_repo";
status: "active" | "idle" | "canceled" | "success" | "failure" | "skipped";
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" | "all" | "custom" | 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;
}>;
declare interface DeprecatedConfigFields {
/**
* The project "type". A holdover from Wrangler v1.x.
* Valid values were "webpack", "javascript", and "rust".
*
* @deprecated DO NOT USE THIS. Most common features now work out of the box with wrangler, including modules, jsx, typescript, etc. If you need anything more, use a custom build.
* @breaking
*/
type?: "webpack" | "javascript" | "rust";
/**
* Path to the webpack config to use when building your worker.
* A holdover from Wrangler v1.x, used with `type: "webpack"`.
*
* @deprecated DO NOT USE THIS. Most common features now work out of the box with wrangler, including modules, jsx, typescript, etc. If you need anything more, use a custom build.
* @breaking
*/
webpack_config?: string;
/**
* Configuration only used by a standalone use of the miniflare binary.
* @deprecated
*/
miniflare?: unknown;
}
/**
* Deprecated upload configuration.
*/
declare interface DeprecatedUpload {
/**
* The format of the Worker script.
*
* @deprecated We infer the format automatically now.
*/
format?: "modules" | "service-worker";
/**
* The directory you wish to upload your Worker from,
* relative to the wrangler.toml file.
*
* Defaults to the directory containing the wrangler.toml file.
*
* @deprecated
*/
dir?: string;
/**
* The path to the Worker script, relative to `upload.dir`.
*
* @deprecated This will be replaced by a command line argument.
*/
main?: string;
/**
* @deprecated This is now defined at the top level `rules` field.
*/
rules?: Environment["rules"];
}
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 unknown ? {
method: Method;
params: _Params;
} : never;
declare interface DevWorker {
ready: Promise;
config?: StartDevWorkerOptions;
setOptions(options: StartDevWorkerOptions): void;
updateOptions(options: Partial): void;
fetch: DispatchFetch;
scheduled(cron?: string): Promise;
queue(queueName: string, ...messages: unknown[]): Promise;
dispose(): Promise;
}
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;
}
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;
}
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;
connect(options: Dispatcher.ConnectOptions, callback: (err: Error | null, data: Dispatcher.ConnectData) => void): void;
/** Performs an HTTP request. */
request(options: Dispatcher.RequestOptions): Promise;
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;
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;
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;
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;
destroy(err: Error | null): Promise;
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;
/** Default: `null` */
headers?: IncomingHttpHeaders | string[] | null;
/** Query string params to be embedded in the request URL. Default: `null` */
query?: Record;
/** 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 }) => 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 preference order. Default: `'Websocket'` */
protocol?: string;
/** Default: `null` */
signal?: AbortSignal_2 | EventEmitter | null;
/** Default: 0 */
maxRedirections?: number;
/** Default: `null` */
responseHeader?: 'raw' | null;
}
interface ConnectData {
statusCode: number;
headers: IncomingHttpHeaders;
socket: Duplex;
opaque: unknown;
}
interface ResponseData {
statusCode: number;
headers: IncomingHttpHeaders;
body: BodyReadable & BodyMixin;
trailers: Record;
opaque: unknown;
context: object;
}
interface PipelineHandlerData {
statusCode: number;
headers: IncomingHttpHeaders;
opaque: unknown;
body: BodyReadable;
context: object;
}
interface StreamData {
opaque: unknown;
trailers: Record;
}
interface UpgradeData {
headers: IncomingHttpHeaders;
socket: Duplex;
opaque: unknown;
}
interface StreamFactoryData {
statusCode: number;
headers: IncomingHttpHeaders;
opaque: unknown;
context: object;
}
type StreamFactory = (data: StreamFactoryData) => Writable;
interface DispatchHandlers {
/** Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. */
onConnect?(abort: () => void): void;
/** Invoked when an error has occurred. */
onError?(err: Error): void;
/** Invoked when request is upgraded either due to a `Upgrade` header or `CONNECT` method. */
onUpgrade?(statusCode: number, headers: Buffer[] | string[] | null, socket: Duplex): void;
/** Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. */
onHeaders?(statusCode: number, headers: Buffer[] | string[] | null, resume: () => void, statusText: string): boolean;
/** Invoked when response payload data is received. */
onData?(chunk: Buffer): boolean;
/** Invoked when response payload and trailers have been received and the request has completed. */
onComplete?(trailers: string[] | null): void;
/** Invoked when a body chunk is sent to the server. May be invoked multiple times for chunked requests */
onBodySent?(chunkSize: number, totalBytesSent: number): void;
}
type PipelineHandler = (data: PipelineHandlerData) => Readable;
type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH';
/**
* @link https://fetch.spec.whatwg.org/#body-mixin
*/
interface BodyMixin {
readonly body?: never; // throws on node v16.6.0
readonly bodyUsed: boolean;
arrayBuffer(): Promise;
blob(): Promise;
formData(): Promise;
json(): Promise;
text(): Promise;
}
interface DispatchInterceptor {
(dispatch: Dispatcher['dispatch']): Dispatcher['dispatch']
}
}
declare interface DispatchNamespaceOutbound {
/** Name of the service handling the outbound requests */
service: string;
/** (Optional) Name of the environment handling the outbound requests. */
environment?: string;
/** (Optional) List of parameter names, for sending context from your dispatch Worker to the outbound handler */
parameters?: string[];
}
declare type DOMException = typeof globalThis extends { DOMException: infer T }
? T
: any
declare 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;
}[];
declare interface EnablePagesAssetsServiceBindingOptions {
proxyPort?: number;
directory?: 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.
*/
declare type Entry = {
/** A worker's entrypoint */
file: string;
/** A worker's directory. Usually where the wrangler.toml file is located */
directory: string;
/** 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;
};
/**
* 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.
*/
declare interface Environment extends EnvironmentInheritable, EnvironmentNonInheritable {
}
/**
* The environment configuration properties that have been deprecated.
*/
declare interface EnvironmentDeprecated {
/**
* The zone ID of the zone you want to deploy to. You can find this
* in your domain page on the dashboard.
*
* @deprecated This is unnecessary since we can deduce this from routes directly.
*/
zone_id?: string;
/**
* Legacy way of defining KVNamespaces that is no longer supported.
*
* @deprecated DO NOT USE. This was a legacy bug from Wrangler v1, that we do not want to support.
*/
"kv-namespaces"?: string;
/**
* A list of services that your Worker should be bound to.
*
* @default `[]`
* @deprecated DO NOT USE. We'd added this to test the new service binding system, but the proper way to test experimental features is to use `unsafe.bindings` configuration.
*/
experimental_services?: {
/** The binding name used to refer to the Service */
name: string;
/** The name of the Service being bound */
service: string;
/** The Service's environment */
environment: string;
}[];
}
/**
* The `EnvironmentInheritable` interface declares all the configuration fields for an environment
* that can be inherited (and overridden) from the top-level environment.
*/
declare 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/platform/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_flags.
*
* More details at https://developers.cloudflare.com/workers/platform/compatibility-dates
*
* @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 ..workers.dev to
* test and deploy your Worker.
*
* // Carmen according to our tests the default is undefined
* @default `true` (This is a breaking change from Wrangler v1)
* @breaking
* @inheritable
*/
workers_dev: 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`)
*
* @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;
/**
* "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
*
* @default `{crons:[]}`
* @inheritable
*/
triggers: {
crons: string[];
};
/**
* Specifies the Usage Model for your Worker. There are two options -
* [bundled](https://developers.cloudflare.com/workers/platform/limits#bundled-usage-model) and
* [unbound](https://developers.cloudflare.com/workers/platform/limits#unbound-usage-model).
* For newly created Workers, if the Usage Model is omitted
* it will be set to the [default Usage Model set on the account](https://dash.cloudflare.com/?account=workers/default-usage-model).
* For existing Workers, if the Usage Model is omitted, it will be
* set to the Usage Model configured in the dashboard for that Worker.
*
* @inheritable
*/
usage_model: "bundled" | "unbound" | undefined;
/**
* Specify limits for runtime behavior.
* Only supported for the "standard" Usage Model
*
* @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.
*
* @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.
*
* @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[];
/**
* Deprecated field previously used to configure the build and upload of the script.
* @deprecated
*/
upload?: DeprecatedUpload;
};
/**
* Skip internal build steps and directly deploy script
* @inheritable
*/
no_bundle: boolean | undefined;
/**
* Minify the script before uploading.
* @inheritable
*/
minify: boolean | undefined;
/**
* Add polyfills for node builtin modules and globals
* @inheritable
*/
node_compat: boolean | undefined;
/**
* Designates this Worker as an internal-only "first-party" Worker.
*
* @inheritable
*/
first_party_worker: boolean | undefined;
/**
* TODO: remove this as it has been deprecated.
*
* This is just here for now because the `route` commands use it.
* So we need to include it in this type so it is available.
*/
zone_id?: string;
/**
* 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.
* @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";
} | undefined;
}
declare interface EnvironmentMap {
/**
* The `env` section defines overrides for the configuration for different environments.
*
* All environment fields can be specified at the top level of the config indicating the default environment settings.
*
* - Some fields are inherited and overridable in each environment.
* - But some are not inherited and must be explicitly specified in every environment, if they are specified at the top level.
*
* For more information, see the documentation at https://developers.cloudflare.com/workers/cli-wrangler/configuration#environments
*
* @default {}
*/
env?: {
[envName: string]: RawEnvironment;
};
}
/**
* 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.
*/
declare 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.
*
* @default `{}`
* @nonInheritable
*/
define: Record;
/**
* A map of environment variables to set 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.
*
* @default `{}`
* @nonInheritable
*/
vars: Record;
/**
* A list of durable objects that your Worker should be bound to.
*
* For more information about Durable Objects, see the documentation at
* https://developers.cloudflare.com/workers/learning/using-durable-objects
*
* NOTE: This field is not automatically inherited from the top level environment,
* and so must be specified in every named environment.
*
* @default `{bindings:[]}`
* @nonInheritable
*/
durable_objects: {
bindings: DurableObjectBindings;
};
/**
* Cloudchamber configuration
*
* NOTE: This field is not automatically inherited from the top level environment,
* and so must be specified in every named environment.
*
* @default `{}`
* @nonInheritable
*/
cloudchamber: CloudchamberConfig;
/**
* These specify any Workers KV Namespaces you want to
* access from inside your Worker.
*
* To learn more about KV Namespaces,
* see the documentation at https://developers.cloudflare.com/workers/learning/how-kv-works
*
* NOTE: This field is not automatically inherited from the top level environment,
* and so must be specified in every named environment.
*
* @default `[]`
* @nonInheritable
*/
kv_namespaces: {
/** The binding name used to refer to the KV Namespace */
binding: string;
/** The ID of the KV namespace */
id: string;
/** The ID of the KV namespace used during `wrangler dev` */
preview_id?: string;
}[];
/**
* These specify bindings to send email from inside your Worker.
*
* NOTE: This field is not automatically inherited from the top level environment,
* and so must be specified in every named environment.
*
* @default `[]`
* @nonInheritable
*/
send_email: {
/** The binding name used to refer to the this binding */
name: string;
/** If this binding should be restricted to a specific verified address */
destination_address?: string;
/** If this binding should be restricted to a set of verified addresses */
allowed_destination_addresses?: string[];
}[];
/**
* Specifies Queues that are bound to this Worker environment.
*
* NOTE: This field is not automatically inherited from the top level environment,
* and so must be specified in every named environment.
*
* @default `{consumers:[],producers:[]}`
* @nonInheritable
*/
queues: {
/** Producer bindings */
producers?: {
/** The binding name used to refer to the Queue in the Worker. */
binding: string;
/** The name of this Queue. */
queue: string;
/** The number of seconds to wait before delivering a message */
delivery_delay?: number;
}[];
/** Consumer configuration */
consumers?: {
/** The name of the queue from which this consumer should consume. */
queue: string;
/** The consumer type, e.g., worker, http-pull, r2-bucket, etc. Default is worker. */
type?: string;
/** The maximum number of messages per batch */
max_batch_size?: number;
/** The maximum number of seconds to wait to fill a batch with messages. */
max_batch_timeout?: number;
/** The maximum number of retries for each message. */
max_retries?: number;
/** The queue to send messages that failed to be consumed. */
dead_letter_queue?: string;
/** The maximum number of concurrent consumer Worker invocations. Leaving this unset will allow your consumer to scale to the maximum concurrency needed to keep up with the message backlog. */
max_concurrency?: number | null;
/** The number of milliseconds to wait for pulled messages to become visible again */
visibility_timeout_ms?: number;
/** The number of seconds to wait before retrying a message */
retry_delay?: number;
}[];
};
/**
* Specifies R2 buckets that are bound to this Worker environment.
*
* NOTE: This field is not automatically inherited from the top level environment,
* and so must be specified in every named environment.
*
* @default `[]`
* @nonInheritable
*/
r2_buckets: {
/** The binding name used to refer to the R2 bucket in the Worker. */
binding: string;
/** The name of this R2 bucket at the edge. */
bucket_name: string;
/** The preview name of this R2 bucket at the edge. */
preview_bucket_name?: string;
/** The jurisdiction that the bucket exists in. Default if not present. */
jurisdiction?: string;
}[];
/**
* Specifies D1 databases that are bound to this Worker environment.
*
* NOTE: This field is not automatically inherited from the top level environment,
* and so must be specified in every named environment.
*
* @default `[]`
* @nonInheritable
*/
d1_databases: {
/** The binding name used to refer to the D1 database in the Worker. */
binding: string;
/** The name of this D1 database. */
database_name: string;
/** The UUID of this D1 database (not required). */
database_id: string;
/** The UUID of this D1 database for Wrangler Dev (if specified). */
preview_database_id?: string;
/** The name of the migrations table for this D1 database (defaults to 'd1_migrations'). */
migrations_table?: string;
/** The path to the directory of migrations for this D1 database (defaults to './migrations'). */
migrations_dir?: string;
/** Internal use only. */
database_internal_env?: string;
}[];
/**
* Specifies Vectorize indexes that are bound to this Worker environment.
*
* NOTE: This field is not automatically inherited from the top level environment,
* and so must be specified in every named environment.
*
* @default `[]`
* @nonInheritable
*/
vectorize: {
/** The binding name used to refer to the Vectorize index in the Worker. */
binding: string;
/** The name of the index. */
index_name: string;
}[];
/**
* Specifies Constellation projects that are bound to this Worker environment.
*
* NOTE: This field is not automatically inherited from the top level environment,
* and so must be specified in every named environment.
*
* @default `[]`
* @nonInheritable
*/
constellation: {
/** The binding name used to refer to the project in the Worker. */
binding: string;
/** The id of the project. */
project_id: string;
}[];
/**
* Specifies Hyperdrive configs that are bound to this Worker environment.
*
* NOTE: This field is not automatically inherited from the top level environment,
* and so must be specified in every named environment.
*
* @default `[]`
* @nonInheritable
*/
hyperdrive: {
/** The binding name used to refer to the project in the Worker. */
binding: string;
/** The id of the database. */
id: string;
/** The local database connection string for `wrangler dev` */
localConnectionString?: string;
}[];
/**
* Specifies service bindings (Worker-to-Worker) that are bound to this Worker environment.
*
* NOTE: This field is not automatically inherited from the top level environment,
* and so must be specified in every named environment.
*
* @default `[]`
* @nonInheritable
*/
services: {
/** The binding name used to refer to the bound service. */
binding: string;
/** The name of the service. */
service: string;
/** The environment of the service (e.g. production, staging, etc). */
environment?: string;
/** Optionally, the entrypoint (named export) of the service to bind to. */
entrypoint?: string;
}[] | undefined;
/**
* Specifies analytics engine datasets that are bound to this Worker environment.
*
* NOTE: This field is not automatically inherited from the top level environment,
* and so must be specified in every named environment.
*
* @default `[]`
* @nonInheritable
*/
analytics_engine_datasets: {
/** The binding name used to refer to the dataset in the Worker. */
binding: string;
/** The name of this dataset to write to. */
dataset?: string;
}[];
/**
* A browser that will be usable from the Worker.
*
* NOTE: This field is not automatically inherited from the top level environment,
* and so must be specified in every named environment.
*
* @default `{}`
* @nonInheritable
*/
browser: {
binding: string;
} | undefined;
/**
* Binding to the AI project.
*
* NOTE: This field is not automatically inherited from the top level environment,
* and so must be specified in every named environment.
*
* @default `{}`
* @nonInheritable
*/
ai: {
binding: string;
staging?: boolean;
} | undefined;
/**
* Binding to the Worker Version's metadata
*/
version_metadata: {
binding: string;
} | undefined;
/**
* "Unsafe" tables for features that aren't directly supported by wrangler.
*
* NOTE: This field is not automatically inherited from the top level environment,
* and so must be specified in every named environment.
*
* @default `{}`
* @nonInheritable
*/
unsafe: {
/**
* A set of bindings that should be put into a Worker's upload metadata without changes. These
* can be used to implement bindings for features that haven't released and aren't supported
* directly by wrangler or miniflare.
*/
bindings?: {
name: string;
type: string;
[key: string]: unknown;
}[];
/**
* Arbitrary key/value pairs that will be included in the uploaded metadata. Values specified
* here will always be applied to metadata last, so can add new or override existing fields.
*/
metadata?: {
[key: string]: unknown;
};
/**
* Used for internal capnp uploads for the Workers runtime
*/
capnp?: {
base_path: string;
source_schemas: string[];
compiled_schema?: never;
} | {
base_path?: never;
source_schemas?: never;
compiled_schema: string;
};
};
/**
* Specifies a list of mTLS certificates that are bound to this Worker environment.
*
* NOTE: This field is not automatically inherited from the top level environment,
* and so must be specified in every named environment.
*
* @default `[]`
* @nonInheritable
*/
mtls_certificates: {
/** The binding name used to refer to the certificate in the Worker */
binding: string;
/** The uuid of the uploaded mTLS certificate */
certificate_id: string;
}[];
/**
* Specifies a list of Tail Workers that are bound to this Worker environment
*
* NOTE: This field is not automatically inherited from the top level environment,
* and so must be specified in every named environment.
*
* @default `[]`
* @nonInheritable
*/
tail_consumers?: TailConsumer[];
/**
* Specifies namespace bindings that are bound to this Worker environment.
*
* NOTE: This field is not automatically inherited from the top level environment,
* and so must be specified in every named environment.
*
* @default `[]`
* @nonInheritable
*/
dispatch_namespaces: {
/** The binding name used to refer to the bound service. */
binding: string;
/** The namespace to bind to. */
namespace: string;
/** Details about the outbound Worker which will handle outbound requests from your namespace */
outbound?: DispatchNamespaceOutbound;
}[];
}
declare type ErrorEvent = BaseErrorEvent<"ConfigController" | "BundlerController" | "LocalRuntimeController" | "RemoteRuntimeController" | "ProxyWorker" | "InspectorProxyWorker"> | BaseErrorEvent<"ProxyController", {
config?: StartDevWorkerOptions;
bundle?: EsbuildBundle;
}>;
declare namespace Errors {
class UndiciError extends Error {
name: string;
code: string;
}
/** Connect timeout error. */
class ConnectTimeoutError extends UndiciError {
name: 'ConnectTimeoutError';
code: 'UND_ERR_CONNECT_TIMEOUT';
}
/** A header exceeds the `headersTimeout` option. */
class HeadersTimeoutError extends UndiciError {
name: 'HeadersTimeoutError';
code: 'UND_ERR_HEADERS_TIMEOUT';
}
/** Headers overflow error. */
class HeadersOverflowError extends UndiciError {
name: 'HeadersOverflowError'
code: 'UND_ERR_HEADERS_OVERFLOW'
}
/** A body exceeds the `bodyTimeout` option. */
class BodyTimeoutError extends UndiciError {
name: 'BodyTimeoutError';
code: 'UND_ERR_BODY_TIMEOUT';
}
class ResponseStatusCodeError extends UndiciError {
constructor (
message?: string,
statusCode?: number,
headers?: IncomingHttpHeaders | string[] | null,
body?: null | Record | string
);
name: 'ResponseStatusCodeError';
code: 'UND_ERR_RESPONSE_STATUS_CODE';
body: null | Record | string
status: number
statusCode: number
headers: IncomingHttpHeaders | string[] | null;
}
/** Passed an invalid argument. */
class InvalidArgumentError extends UndiciError {
name: 'InvalidArgumentError';
code: 'UND_ERR_INVALID_ARG';
}
/** Returned an invalid value. */
class InvalidReturnValueError extends UndiciError {
name: 'InvalidReturnValueError';
code: 'UND_ERR_INVALID_RETURN_VALUE';
}
/** The request has been aborted by the user. */
class RequestAbortedError extends UndiciError {
name: 'AbortError';
code: 'UND_ERR_ABORTED';
}
/** Expected error with reason. */
class InformationalError extends UndiciError {
name: 'InformationalError';
code: 'UND_ERR_INFO';
}
/** Request body length does not match content-length header. */
class RequestContentLengthMismatchError extends UndiciError {
name: 'RequestContentLengthMismatchError';
code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH';
}
/** Response body length does not match content-length header. */
class ResponseContentLengthMismatchError extends UndiciError {
name: 'ResponseContentLengthMismatchError';
code: 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH';
}
/** Trying to use a destroyed client. */
class ClientDestroyedError extends UndiciError {
name: 'ClientDestroyedError';
code: 'UND_ERR_DESTROYED';
}
/** Trying to use a closed client. */
class ClientClosedError extends UndiciError {
name: 'ClientClosedError';
code: 'UND_ERR_CLOSED';
}
/** There is an error with the socket. */
class SocketError extends UndiciError {
name: 'SocketError';
code: 'UND_ERR_SOCKET';
socket: Client.SocketInfo | null
}
/** Encountered unsupported functionality. */
class NotSupportedError extends UndiciError {
name: 'NotSupportedError';
code: 'UND_ERR_NOT_SUPPORTED';
}
/** No upstream has been added to the BalancedPool. */
class BalancedPoolMissingUpstreamError extends UndiciError {
name: 'MissingUpstreamError';
code: 'UND_ERR_BPL_MISSING_UPSTREAM';
}
class HTTPParserError extends UndiciError {
name: 'HTTPParserError';
code: string;
}
/** The response exceed the length allowed. */
class ResponseExceededMaxSizeError extends UndiciError {
name: 'ResponseExceededMaxSizeError';
code: 'UND_ERR_RES_EXCEEDED_MAX_SIZE';
}
}
declare type EsbuildBundle = {
id: number;
path: string;
entry: Entry;
type: CfModuleType;
modules: CfModule[];
dependencies: Metafile["outputs"][string]["inputs"];
sourceMapPath: string | undefined;
sourceMapMetadata: SourceMapMetadata | undefined;
};
declare type Event_2 = typeof globalThis extends { Event: infer T }
? T
: {
readonly bubbles: boolean
cancelBubble: () => void
readonly cancelable: boolean
readonly composed: boolean
composedPath(): [EventTarget_2?]
readonly currentTarget: EventTarget_2 | null
readonly defaultPrevented: boolean
readonly eventPhase: 0 | 2
readonly isTrusted: boolean
preventDefault(): void
returnValue: boolean
readonly srcElement: EventTarget_2 | null
stopImmediatePropagation(): void
stopPropagation(): void
readonly target: EventTarget_2 | null
readonly timeStamp: number
readonly type: string
}
declare interface EventInit {
bubbles?: boolean
cancelable?: boolean
composed?: boolean
}
declare interface EventListener {
(evt: Event_2): void
}
declare interface EventListenerObject {
handleEvent (object: Event_2): void
}
declare interface EventListenerOptions {
capture?: boolean
}
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject
declare type _EventMethods = keyof ProtocolMapping.Events;
declare type EventTarget_2 = typeof globalThis extends { EventTarget: infer T }
? T
: {
addEventListener(
type: string,
listener: any,
options?: any,
): void
dispatchEvent(event: Event_2): boolean
removeEventListener(
type: string,
listener: any,
options?: any | boolean,
): void
}
declare class ExecutionContext {
waitUntil(promise: Promise): void;
passThroughOnException(): void;
}
declare function fetch (
input: RequestInfo,
init?: RequestInit
): Promise
declare class File extends Blob_2 {
/**
* Creates a new File instance.
*
* @param fileBits An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File).
* @param fileName The name of the file.
* @param options An options object containing optional attributes for the file.
*/
constructor(fileBits: ReadonlyArray, fileName: string, options?: FilePropertyBag)
/**
* Name of the file referenced by the File object.
*/
readonly name: string
/**
* The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date.
*/
readonly lastModified: number
readonly [Symbol.toStringTag]: string
}
declare type File_2 = {
path: string;
} | {
contents: Contents;
path?: string;
};
declare interface FilePropertyBag extends BlobPropertyBag {
/**
* The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date.
*/
lastModified?: number
}
declare class FileReader {
__proto__: EventTarget_2 & FileReader
constructor ()
readAsArrayBuffer (blob: Blob_2): void
readAsBinaryString (blob: Blob_2): void
readAsText (blob: Blob_2, encoding?: string): void
readAsDataURL (blob: Blob_2): void
abort (): void
static readonly EMPTY = 0
static readonly LOADING = 1
static readonly DONE = 2
readonly EMPTY = 0
readonly LOADING = 1
readonly DONE = 2
readonly readyState: number
readonly result: string | ArrayBuffer | null
readonly error: DOMException | null
onloadstart: null | ((this: FileReader, event: ProgressEvent) => void)
onprogress: null | ((this: FileReader, event: ProgressEvent) => void)
onload: null | ((this: FileReader, event: ProgressEvent) => void)
onabort: null | ((this: FileReader, event: ProgressEvent) => void)
onerror: null | ((this: FileReader, event: ProgressEvent) => void)
onloadend: null | ((this: FileReader, event: ProgressEvent) => void)
}
/**
* Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using fetch().
*/
declare class FormData {
/**
* Appends a new value onto an existing key inside a FormData object,
* or adds the key if it does not already exist.
*
* The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values.
*
* @param name The name of the field whose data is contained in `value`.
* @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.
* @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.
*/
append(name: string, value: unknown, fileName?: string): void
/**
* Set a new value for an existing key inside FormData,
* or add the new field if it does not already exist.
*
* @param name The name of the field whose data is contained in `value`.
* @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.
* @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.
*
*/
set(name: string, value: unknown, fileName?: string): void
/**
* Returns the first value associated with a given key from within a `FormData` object.
* If you expect multiple values and want all of them, use the `getAll()` method instead.
*
* @param {string} name A name of the value you want to retrieve.
*
* @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null.
*/
get(name: string): FormDataEntryValue | null
/**
* Returns all the values associated with a given key from within a `FormData` object.
*
* @param {string} name A name of the value you want to retrieve.
*
* @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list.
*/
getAll(name: string): FormDataEntryValue[]
/**
* Returns a boolean stating whether a `FormData` object contains a certain key.
*
* @param name A string representing the name of the key you want to test for.
*
* @return A boolean value.
*/
has(name: string): boolean
/**
* Deletes a key and its value(s) from a `FormData` object.
*
* @param name The name of the key you want to delete.
*/
delete(name: string): void
/**
* Executes given callback function for each field of the FormData instance
*/
forEach: (
callbackfn: (value: FormDataEntryValue, key: string, iterable: FormData) => void,
thisArg?: unknown
) => void
/**
* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object.
* Each key is a `string`.
*/
keys: () => SpecIterableIterator
/**
* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object.
* Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).
*/
values: () => SpecIterableIterator
/**
* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs.
* The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).
*/
entries: () => SpecIterableIterator<[string, FormDataEntryValue]>
/**
* An alias for FormData#entries()
*/
[Symbol.iterator]: () => SpecIterableIterator<[string, FormDataEntryValue]>
readonly [Symbol.toStringTag]: string
}
/**
* A `string` or `File` that represents a single value from a set of `FormData` key-value pairs.
*/
declare type FormDataEntryValue = string | File
/**
* By reading from a `wrangler.toml` file this function generates proxy binding objects that can be
* used to simulate the interaction with bindings during local development in a Node.js environment
*
* @deprecated use `getPlatformProxy` instead
*
* @param options The various options that can tweak this function's behavior
* @returns An Object containing the generated proxies alongside other related utilities
*/
export declare function getBindingsProxy, CfProperties extends Record = IncomingRequestCfProperties>(options?: GetBindingsProxyOptions): Promise>;
/** Options for the `getBindingsProxy` utility */
export declare type GetBindingsProxyOptions = GetPlatformProxyOptions;
declare function getCookies (headers: Headers): Record
declare function getGlobalDispatcher(): Dispatcher;
declare function getGlobalOrigin(): URL | undefined;
/**
* By reading from a `wrangler.toml` file this function generates proxy objects that can be
* used to simulate the interaction with the Cloudflare platform during local development
* in a Node.js environment
*
* @param options The various options that can tweak this function's behavior
* @returns An Object containing the generated proxies alongside other related utilities
*/
export declare function getPlatformProxy, CfProperties extends Record = IncomingRequestCfProperties>(options?: GetPlatformProxyOptions): Promise>;
/**
* Options for the `getPlatformProxy` utility
*/
export declare type GetPlatformProxyOptions = {
/**
* The name of the environment to use
*/
environment?: string;
/**
* The path to the config object to use (default `wrangler.toml`)
*/
configPath?: string;
/**
* Flag to indicate the utility to read a json config file (`wrangler.json`)
* instead of the toml one (`wrangler.toml`)
*
* Note: this feature is experimental
*/
experimentalJsonConfig?: boolean;
/**
* Indicates if and where to persist the bindings data, if not present or `true` it defaults to the same location
* used by wrangler v3: `.wrangler/state/v3` (so that the same data can be easily used by the caller and wrangler).
* If `false` is specified no data is persisted on the filesystem.
*/
persist?: boolean | {
path: string;
};
};
declare function getSetCookies (headers: Headers): Cookie[]
declare class Headers implements SpecIterable<[string, string]> {
constructor (init?: HeadersInit)
readonly append: (name: string, value: string) => void
readonly delete: (name: string) => void
readonly get: (name: string) => string | null
readonly has: (name: string) => boolean
readonly set: (name: string, value: string) => void
readonly getSetCookie: () => string[]
readonly forEach: (
callbackfn: (value: string, key: string, iterable: Headers) => void,
thisArg?: unknown
) => void
readonly keys: () => SpecIterableIterator
readonly values: () => SpecIterableIterator
readonly entries: () => SpecIterableIterator<[string, string]>
readonly [Symbol.iterator]: () => SpecIterator<[string, string]>
}
declare type HeadersInit = string[][] | Record> | Headers
declare type Hook = T | Promise | ((...args: Args) => T | Promise);
/**
* @property terminate Terminates HTTP server.
*/
declare type HttpTerminator = {
readonly terminate: () => Promise;
};
/**
* The header type declaration of `undici`.
*/
declare type IncomingHttpHeaders = Record;
declare type InspectorProxyWorkerIncomingWebSocketMessage = {
type: ReloadStartEvent["type"];
} | {
type: ReloadCompleteEvent["type"];
proxyData: ProxyData;
};
declare type InspectorProxyWorkerOutgoingRequestBody = {
type: "error";
error: SerializedError;
} | {
type: "runtime-websocket-error";
error: SerializedError;
} | {
type: "debug-log";
args: Parameters;
} | {
type: "load-network-resource";
url: string;
};
declare type InspectorProxyWorkerOutgoingWebsocketMessage = DevToolsEvent<"Runtime.consoleAPICalled"> | DevToolsEvent<"Runtime.exceptionThrown">;
declare interface Interceptable extends Dispatcher {
/** Intercepts any matching requests that use the same origin as this mock client. */
intercept(options: MockInterceptor.Options): MockInterceptor;
}
declare type LogLevel = "debug" | "info" | "log" | "warn" | "error" | "none";
declare type MaybePromise = T | Promise;
declare interface MessageEvent extends Event_2 {
readonly data: T
readonly lastEventId: string
readonly origin: string
readonly ports: ReadonlyArray
readonly source: typeof MessagePort_2 | null
initMessageEvent(
type: string,
bubbles?: boolean,
cancelable?: boolean,
data?: any,
origin?: string,
lastEventId?: string,
source?: typeof MessagePort_2 | null,
ports?: (typeof MessagePort_2)[]
): void;
}
declare const MessageEvent: {
prototype: MessageEvent
new(type: string, eventInitDict?: MessageEventInit): MessageEvent
};
declare interface MessageEventInit extends EventInit {
data?: T
lastEventId?: string
origin?: string
ports?: (typeof MessagePort_2)[]
source?: typeof MessagePort_2 | null
}
declare interface MIMEType {
type: string
subtype: string
parameters: Map
essence: string
}
/** A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. */
declare class MockAgent extends Dispatcher {
constructor(options?: MockAgent.Options)
/** Creates and retrieves mock Dispatcher instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. */
get(origin: string): TInterceptable;
get(origin: RegExp): TInterceptable;
get(origin: ((origin: string) => boolean)): TInterceptable;
/** Dispatches a mocked request. */
dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean;
/** Closes the mock agent and waits for registered mock pools and clients to also close before resolving. */
close(): Promise;
/** Disables mocking in MockAgent. */
deactivate(): void;
/** Enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. */
activate(): void;
/** Define host matchers so only matching requests that aren't intercepted by the mock dispatchers will be attempted. */
enableNetConnect(): void;
enableNetConnect(host: string): void;
enableNetConnect(host: RegExp): void;
enableNetConnect(host: ((host: string) => boolean)): void;
/** Causes all requests to throw when requests are not matched in a MockAgent intercept. */
disableNetConnect(): void;
pendingInterceptors(): PendingInterceptor[];
assertNoPendingInterceptors(options?: {
pendingInterceptorsFormatter?: PendingInterceptorsFormatter;
}): void;
}
declare namespace MockAgent {
/** MockAgent options. */
interface Options extends Agent.Options {
/** A custom agent to be encapsulated by the MockAgent. */
agent?: Agent;
}
}
/** MockClient extends the Client API and allows one to mock requests. */
declare class MockClient extends Client implements Interceptable {
constructor(origin: string, options: MockClient.Options);
/** Intercepts any matching requests that use the same origin as this mock client. */
intercept(options: MockInterceptor.Options): MockInterceptor;
/** Dispatches a mocked request. */
dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean;
/** Closes the mock client and gracefully waits for enqueued requests to complete. */
close(): Promise;
}
declare namespace MockClient {
/** MockClient options. */
interface Options extends Client.Options {
/** The agent to associate this MockClient with. */
agent: MockAgent;
}
}
declare namespace MockErrors {
/** The request does not match any registered mock dispatches. */
class MockNotMatchedError extends Errors.UndiciError {
constructor(message?: string);
name: 'MockNotMatchedError';
code: 'UND_MOCK_ERR_MOCK_NOT_MATCHED';
}
}
/** The interceptor for a Mock. */
declare class MockInterceptor {
constructor(options: MockInterceptor.Options, mockDispatches: MockInterceptor.MockDispatch[]);
/** Mock an undici request with the defined reply. */
reply(replyOptionsCallback: MockInterceptor.MockReplyOptionsCallback): MockScope;
reply(
statusCode: number,
data?: TData | Buffer | string | MockInterceptor.MockResponseDataHandler,
responseOptions?: MockInterceptor.MockResponseOptions
): MockScope;
/** Mock an undici request by throwing the defined reply error. */
replyWithError(error: TError): MockScope;
/** Set default reply headers on the interceptor for subsequent mocked replies. */
defaultReplyHeaders(headers: IncomingHttpHeaders): MockInterceptor;
/** Set default reply trailers on the interceptor for subsequent mocked replies. */
defaultReplyTrailers(trailers: Record): MockInterceptor;
/** Set automatically calculated content-length header on subsequent mocked replies. */
replyContentLength(): MockInterceptor;
}
declare namespace MockInterceptor {
/** MockInterceptor options. */
interface Options {
/** Path to intercept on. */
path: string | RegExp | ((path: string) => boolean);
/** Method to intercept on. Defaults to GET. */
method?: string | RegExp | ((method: string) => boolean);
/** Body to intercept on. */
body?: string | RegExp | ((body: string) => boolean);
/** Headers to intercept on. */
headers?: Record boolean)> | ((headers: Record) => boolean);
/** Query params to intercept on */
query?: Record;
}
interface MockDispatch extends Options {
times: number | null;
persist: boolean;
consumed: boolean;
data: MockDispatchData;
}
interface MockDispatchData extends MockResponseOptions {
error: TError | null;
statusCode?: number;
data?: TData | string;
}
interface MockResponseOptions {
headers?: IncomingHttpHeaders;
trailers?: Record;
}
interface MockResponseCallbackOptions {
path: string;
origin: string;
method: string;
body?: BodyInit | Dispatcher.DispatchOptions['body'];
headers: Headers | Record;
maxRedirections: number;
}
type MockResponseDataHandler = (
opts: MockResponseCallbackOptions
) => TData | Buffer | string;
type MockReplyOptionsCallback = (
opts: MockResponseCallbackOptions
) => { statusCode: number, data?: TData | Buffer | string, responseOptions?: MockResponseOptions }
}
/** MockPool extends the Pool API and allows one to mock requests. */
declare class MockPool extends Pool implements Interceptable {
constructor(origin: string, options: MockPool.Options);
/** Intercepts any matching requests that use the same origin as this mock pool. */
intercept(options: MockInterceptor.Options): MockInterceptor;
/** Dispatches a mocked request. */
dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean;
/** Closes the mock pool and gracefully waits for enqueued requests to complete. */
close(): Promise;
}
declare namespace MockPool {
/** MockPool options. */
interface Options extends Pool.Options {
/** The agent to associate this MockPool with. */
agent: MockAgent;
}
}
/** The scope associated with a mock dispatch. */
declare class MockScope {
constructor(mockDispatch: MockInterceptor.MockDispatch);
/** Delay a reply by a set amount of time in ms. */
delay(waitInMs: number): MockScope;
/** Persist the defined mock data for the associated reply. It will return the defined mock data indefinitely. */
persist(): MockScope;
/** Define a reply for a set amount of matching requests. */
times(repeatTimes: number): MockScope;
}
declare interface ModuleRule {
type: "ESModule" | "CommonJS" | "NodeJSCompat" | "CompiledWasm" | "Text" | "Data";
include?: string[];
fallthrough?: boolean;
}
declare interface MultiCacheQueryOptions extends CacheQueryOptions {
cacheName?: string
}
declare interface PagesConfigFields {
/**
* The directory of static assets to serve.
*
* The presence of this field in `wrangler.toml` indicates a Pages project,
* and will prompt the handling of the configuration file according to the
* Pages-specific validation rules.
*/
pages_build_output_dir?: string;
}
declare interface PagesConfigFields {
/**
* The directory of static assets to serve.
*
* The presence of this field in `wrangler.toml` indicates a Pages project,
* and will prompt the handling of the configuration file according to the
* Pages-specific validation rules.
*/
pages_build_output_dir?: string;
}
declare 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;
/**
* Command line args passed to the `pages deploy` cmd
*/
args?: Record;
}
declare type _Params = ParamsArray extends [infer P] ? P : undefined;
/**
* Parse a string to a {@link MIMEType} object. Returns `failure` if the string
* couldn't be parsed.
* @see https://mimesniff.spec.whatwg.org/#parse-a-mime-type
*/
declare function parseMIMEType (input: string): 'failure' | MIMEType
declare interface PendingInterceptor extends MockDispatch {
origin: string;
}
declare interface PendingInterceptorsFormatter {
format(pendingInterceptors: readonly PendingInterceptor[]): string;
}
/** For easy use with `stream.pipeline`. */
declare function pipeline(
url: string | URL_2 | UrlObject,
options: { dispatcher?: Dispatcher } & Omit,
handler: Dispatcher.PipelineHandler
): Duplex;
/**
* Result of the `getPlatformProxy` utility
*/
export declare type PlatformProxy, CfProperties extends Record = IncomingRequestCfProperties> = {
/**
* Environment object containing the various Cloudflare bindings
*/
env: Env;
/**
* Mock of the context object that Workers received in their request handler, all the object's methods are no-op
*/
cf: CfProperties;
/**
* Mock of the context object that Workers received in their request handler, all the object's methods are no-op
*/
ctx: ExecutionContext;
/**
* Caches object emulating the Workers Cache runtime API
*/
caches: CacheStorage_2;
/**
* Function used to dispose of the child process providing the bindings implementation
*/
dispose: () => Promise;
};
declare class Pool extends Dispatcher {
constructor(url: string | URL_2, options?: Pool.Options)
/** `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;
/** Aggregate stats for a Pool. */
readonly stats: PoolStats;
}
declare namespace Pool {
type PoolStats = PoolStats;
interface Options extends Client.Options {
/** Default: `(origin, opts) => new Client(origin, opts)`. */
factory?(origin: URL_2, opts: object): Dispatcher;
/** The max number of clients to create. `null` if no limit. Default `null`. */
connections?: number | null;
interceptors?: { Pool?: readonly Dispatcher.DispatchInterceptor[] } & Client.Options["interceptors"]
}
}
declare class PoolStats {
constructor(pool: Pool);
/** Number of open socket connections in this pool. */
connected: number;
/** Number of open socket connections in this pool that do not have an active request. */
free: number;
/** Number of pending requests across all clients in this pool. */
pending: number;
/** Number of queued requests across all clients in this pool. */
queued: number;
/** Number of currently active requests across all clients in this pool. */
running: number;
/** Number of active, pending, or queued requests across all clients in this pool. */
size: number;
}
declare type PreviewTokenExpiredEvent = {
type: "previewTokenExpired";
proxyData: ProxyData;
};
declare class ProgressEvent {
__proto__: Event_2 & ProgressEvent
constructor (type: string, eventInitDict?: ProgressEventInit)
readonly lengthComputable: boolean
readonly loaded: number
readonly total: number
}
declare interface ProgressEventInit extends EventInit {
lengthComputable?: boolean
loaded?: number
total?: number
}
/**********************************************************************
* Auto-generated by protocol-dts-generator.ts, do not edit manually. *
**********************************************************************/
/**
* The Chrome DevTools Protocol.
* @public
*/
declare namespace Protocol {
type integer = number
/**
* This domain is deprecated - use Runtime or Log instead.
*/
namespace Console {
const enum ConsoleMessageSource {
XML = 'xml',
Javascript = 'javascript',
Network = 'network',
ConsoleAPI = 'console-api',
Storage = 'storage',
Appcache = 'appcache',
Rendering = 'rendering',
Security = 'security',
Other = 'other',
Deprecation = 'deprecation',
Worker = 'worker',
}
const enum ConsoleMessageLevel {
Log = 'log',
Warning = 'warning',
Error = 'error',
Debug = 'debug',
Info = 'info',
}
/**
* Console message.
*/
interface ConsoleMessage {
/**
* Message source. (ConsoleMessageSource enum)
*/
source: ('xml' | 'javascript' | 'network' | 'console-api' | 'storage' | 'appcache' | 'rendering' | 'security' | 'other' | 'deprecation' | 'worker');
/**
* Message severity. (ConsoleMessageLevel enum)
*/
level: ('log' | 'warning' | 'error' | 'debug' | 'info');
/**
* Message text.
*/
text: string;
/**
* URL of the message origin.
*/
url?: string;
/**
* Line number in the resource that generated this message (1-based).
*/
line?: integer;
/**
* Column number in the resource that generated this message (1-based).
*/
column?: integer;
}
/**
* Issued when new console message is added.
*/
interface MessageAddedEvent {
/**
* Console message that has been added.
*/
message: ConsoleMessage;
}
}
/**
* Debugger domain exposes JavaScript debugging capabilities. It allows setting and removing
* breakpoints, stepping through execution, exploring stack traces, etc.
*/
namespace Debugger {
/**
* Breakpoint identifier.
*/
type BreakpointId = string;
/**
* Call frame identifier.
*/
type CallFrameId = string;
/**
* Location in the source code.
*/
interface Location {
/**
* Script identifier as reported in the `Debugger.scriptParsed`.
*/
scriptId: Runtime.ScriptId;
/**
* Line number in the script (0-based).
*/
lineNumber: integer;
/**
* Column number in the script (0-based).
*/
columnNumber?: integer;
}
/**
* Location in the source code.
*/
interface ScriptPosition {
lineNumber: integer;
columnNumber: integer;
}
/**
* Location range within one script.
*/
interface LocationRange {
scriptId: Runtime.ScriptId;
start: ScriptPosition;
end: ScriptPosition;
}
/**
* JavaScript call frame. Array of call frames form the call stack.
*/
interface CallFrame {
/**
* Call frame identifier. This identifier is only valid while the virtual machine is paused.
*/
callFrameId: CallFrameId;
/**
* Name of the JavaScript function called on this call frame.
*/
functionName: string;
/**
* Location in the source code.
*/
functionLocation?: Location;
/**
* Location in the source code.
*/
location: Location;
/**
* JavaScript script name or url.
*/
url: string;
/**
* Scope chain for this call frame.
*/
scopeChain: Scope[];
/**
* `this` object for this call frame.
*/
this: Runtime.RemoteObject;
/**
* The value being returned, if the function is at return point.
*/
returnValue?: Runtime.RemoteObject;
}
const enum ScopeType {
Global = 'global',
Local = 'local',
With = 'with',
Closure = 'closure',
Catch = 'catch',
Block = 'block',
Script = 'script',
Eval = 'eval',
Module = 'module',
WasmExpressionStack = 'wasm-expression-stack',
}
/**
* Scope description.
*/
interface Scope {
/**
* Scope type. (ScopeType enum)
*/
type: ('global' | 'local' | 'with' | 'closure' | 'catch' | 'block' | 'script' | 'eval' | 'module' | 'wasm-expression-stack');
/**
* Object representing the scope. For `global` and `with` scopes it represents the actual
* object; for the rest of the scopes, it is artificial transient object enumerating scope
* variables as its properties.
*/
object: Runtime.RemoteObject;
name?: string;
/**
* Location in the source code where scope starts
*/
startLocation?: Location;
/**
* Location in the source code where scope ends
*/
endLocation?: Location;
}
/**
* Search match for resource.
*/
interface SearchMatch {
/**
* Line number in resource content.
*/
lineNumber: number;
/**
* Line with match content.
*/
lineContent: string;
}
const enum BreakLocationType {
DebuggerStatement = 'debuggerStatement',
Call = 'call',
Return = 'return',
}
interface BreakLocation {
/**
* Script identifier as reported in the `Debugger.scriptParsed`.
*/
scriptId: Runtime.ScriptId;
/**
* Line number in the script (0-based).
*/
lineNumber: integer;
/**
* Column number in the script (0-based).
*/
columnNumber?: integer;
/**
* (BreakLocationType enum)
*/
type?: ('debuggerStatement' | 'call' | 'return');
}
/**
* Enum of possible script languages.
*/
type ScriptLanguage = ('JavaScript' | 'WebAssembly');
const enum DebugSymbolsType {
None = 'None',
SourceMap = 'SourceMap',
EmbeddedDWARF = 'EmbeddedDWARF',
ExternalDWARF = 'ExternalDWARF',
}
/**
* Debug symbols available for a wasm script.
*/
interface DebugSymbols {
/**
* Type of the debug symbols. (DebugSymbolsType enum)
*/
type: ('None' | 'SourceMap' | 'EmbeddedDWARF' | 'ExternalDWARF');
/**
* URL of the external symbol source.
*/
externalURL?: string;
}
const enum ContinueToLocationRequestTargetCallFrames {
Any = 'any',
Current = 'current',
}
interface ContinueToLocationRequest {
/**
* Location to continue to.
*/
location: Location;
/**
* (ContinueToLocationRequestTargetCallFrames enum)
*/
targetCallFrames?: ('any' | 'current');
}
interface EnableRequest {
/**
* The maximum size in bytes of collected scripts (not referenced by other heap objects)
* the debugger can hold. Puts no limit if parameter is omitted.
*/
maxScriptsCacheSize?: number;
}
interface EnableResponse {
/**
* Unique identifier of the debugger.
*/
debuggerId: Runtime.UniqueDebuggerId;
}
interface EvaluateOnCallFrameRequest {
/**
* Call frame identifier to evaluate on.
*/
callFrameId: CallFrameId;
/**
* Expression to evaluate.
*/
expression: string;
/**
* String object group name to put result into (allows rapid releasing resulting object handles
* using `releaseObjectGroup`).
*/
objectGroup?: string;
/**
* Specifies whether command line API should be available to the evaluated expression, defaults
* to false.
*/
includeCommandLineAPI?: boolean;
/**
* In silent mode exceptions thrown during evaluation are not reported and do not pause
* execution. Overrides `setPauseOnException` state.
*/
silent?: boolean;
/**
* Whether the result is expected to be a JSON object that should be sent by value.
*/
returnByValue?: boolean;
/**
* Whether preview should be generated for the result.
*/
generatePreview?: boolean;
/**
* Whether to throw an exception if side effect cannot be ruled out during evaluation.
*/
throwOnSideEffect?: boolean;
/**
* Terminate execution after timing out (number of milliseconds).
*/
timeout?: Runtime.TimeDelta;
}
interface EvaluateOnCallFrameResponse {
/**
* Object wrapper for the evaluation result.
*/
result: Runtime.RemoteObject;
/**
* Exception details.
*/
exceptionDetails?: Runtime.ExceptionDetails;
}
interface GetPossibleBreakpointsRequest {
/**
* Start of range to search possible breakpoint locations in.
*/
start: Location;
/**
* End of range to search possible breakpoint locations in (excluding). When not specified, end
* of scripts is used as end of range.
*/
end?: Location;
/**
* Only consider locations which are in the same (non-nested) function as start.
*/
restrictToFunction?: boolean;
}
interface GetPossibleBreakpointsResponse {
/**
* List of the possible breakpoint locations.
*/
locations: BreakLocation[];
}
interface GetScriptSourceRequest {
/**
* Id of the script to get source for.
*/
scriptId: Runtime.ScriptId;
}
interface GetScriptSourceResponse {
/**
* Script source (empty in case of Wasm bytecode).
*/
scriptSource: string;
/**
* Wasm bytecode. (Encoded as a base64 string when passed over JSON)
*/
bytecode?: string;
}
interface GetWasmBytecodeRequest {
/**
* Id of the Wasm script to get source for.
*/
scriptId: Runtime.ScriptId;
}
interface GetWasmBytecodeResponse {
/**
* Script source. (Encoded as a base64 string when passed over JSON)
*/
bytecode: string;
}
interface GetStackTraceRequest {
stackTraceId: Runtime.StackTraceId;
}
interface GetStackTraceResponse {
stackTrace: Runtime.StackTrace;
}
interface PauseOnAsyncCallRequest {
/**
* Debugger will pause when async call with given stack trace is started.
*/
parentStackTraceId: Runtime.StackTraceId;
}
interface RemoveBreakpointRequest {
breakpointId: BreakpointId;
}
interface RestartFrameRequest {
/**
* Call frame identifier to evaluate on.
*/
callFrameId: CallFrameId;
}
interface RestartFrameResponse {
/**
* New stack trace.
*/
callFrames: CallFrame[];
/**
* Async stack trace, if any.
*/
asyncStackTrace?: Runtime.StackTrace;
/**
* Async stack trace, if any.
*/
asyncStackTraceId?: Runtime.StackTraceId;
}
interface ResumeRequest {
/**
* Set to true to terminate execution upon resuming execution. In contrast
* to Runtime.terminateExecution, this will allows to execute further
* JavaScript (i.e. via evaluation) until execution of the paused code
* is actually resumed, at which point termination is triggered.
* If execution is currently not paused, this parameter has no effect.
*/
terminateOnResume?: boolean;
}
interface SearchInContentRequest {
/**
* Id of the script to search in.
*/
scriptId: Runtime.ScriptId;
/**
* String to search for.
*/
query: string;
/**
* If true, search is case sensitive.
*/
caseSensitive?: boolean;
/**
* If true, treats string parameter as regex.
*/
isRegex?: boolean;
}
interface SearchInContentResponse {
/**
* List of search matches.
*/
result: SearchMatch[];
}
interface SetAsyncCallStackDepthRequest {
/**
* Maximum depth of async call stacks. Setting to `0` will effectively disable collecting async
* call stacks (default).
*/
maxDepth: integer;
}
interface SetBlackboxPatternsRequest {
/**
* Array of regexps that will be used to check script url for blackbox state.
*/
patterns: string[];
}
interface SetBlackboxedRangesRequest {
/**
* Id of the script.
*/
scriptId: Runtime.ScriptId;
positions: ScriptPosition[];
}
interface SetBreakpointRequest {
/**
* Location to set breakpoint in.
*/
location: Location;
/**
* Expression to use as a breakpoint condition. When specified, debugger will only stop on the
* breakpoint if this expression evaluates to true.
*/
condition?: string;
}
interface SetBreakpointResponse {
/**
* Id of the created breakpoint for further reference.
*/
breakpointId: BreakpointId;
/**
* Location this breakpoint resolved into.
*/
actualLocation: Location;
}
const enum SetInstrumentationBreakpointRequestInstrumentation {
BeforeScriptExecution = 'beforeScriptExecution',
BeforeScriptWithSourceMapExecution = 'beforeScriptWithSourceMapExecution',
}
interface SetInstrumentationBreakpointRequest {
/**
* Instrumentation name. (SetInstrumentationBreakpointRequestInstrumentation enum)
*/
instrumentation: ('beforeScriptExecution' | 'beforeScriptWithSourceMapExecution');
}
interface SetInstrumentationBreakpointResponse {
/**
* Id of the created breakpoint for further reference.
*/
breakpointId: BreakpointId;
}
interface SetBreakpointByUrlRequest {
/**
* Line number to set breakpoint at.
*/
lineNumber: integer;
/**
* URL of the resources to set breakpoint on.
*/
url?: string;
/**
* Regex pattern for the URLs of the resources to set breakpoints on. Either `url` or
* `urlRegex` must be specified.
*/
urlRegex?: string;
/**
* Script hash of the resources to set breakpoint on.
*/
scriptHash?: string;
/**
* Offset in the line to set breakpoint at.
*/
columnNumber?: integer;
/**
* Expression to use as a breakpoint condition. When specified, debugger will only stop on the
* breakpoint if this expression evaluates to true.
*/
condition?: string;
}
interface SetBreakpointByUrlResponse {
/**
* Id of the created breakpoint for further reference.
*/
breakpointId: BreakpointId;
/**
* List of the locations this breakpoint resolved into upon addition.
*/
locations: Location[];
}
interface SetBreakpointOnFunctionCallRequest {
/**
* Function object id.
*/
objectId: Runtime.RemoteObjectId;
/**
* Expression to use as a breakpoint condition. When specified, debugger will
* stop on the breakpoint if this expression evaluates to true.
*/
condition?: string;
}
interface SetBreakpointOnFunctionCallResponse {
/**
* Id of the created breakpoint for further reference.
*/
breakpointId: BreakpointId;
}
interface SetBreakpointsActiveRequest {
/**
* New value for breakpoints active state.
*/
active: boolean;
}
const enum SetPauseOnExceptionsRequestState {
None = 'none',
Uncaught = 'uncaught',
All = 'all',
}
interface SetPauseOnExceptionsRequest {
/**
* Pause on exceptions mode. (SetPauseOnExceptionsRequestState enum)
*/
state: ('none' | 'uncaught' | 'all');
}
interface SetReturnValueRequest {
/**
* New return value.
*/
newValue: Runtime.CallArgument;
}
interface SetScriptSourceRequest {
/**
* Id of the script to edit.
*/
scriptId: Runtime.ScriptId;
/**
* New content of the script.
*/
scriptSource: string;
/**
* If true the change will not actually be applied. Dry run may be used to get result
* description without actually modifying the code.
*/
dryRun?: boolean;
}
interface SetScriptSourceResponse {
/**
* New stack trace in case editing has happened while VM was stopped.
*/
callFrames?: CallFrame[];
/**
* Whether current call stack was modified after applying the changes.
*/
stackChanged?: boolean;
/**
* Async stack trace, if any.
*/
asyncStackTrace?: Runtime.StackTrace;
/**
* Async stack trace, if any.
*/
asyncStackTraceId?: Runtime.StackTraceId;
/**
* Exception details if any.
*/
exceptionDetails?: Runtime.ExceptionDetails;
}
interface SetSkipAllPausesRequest {
/**
* New value for skip pauses state.
*/
skip: boolean;
}
interface SetVariableValueRequest {
/**
* 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch'
* scope types are allowed. Other scopes could be manipulated manually.
*/
scopeNumber: integer;
/**
* Variable name.
*/
variableName: string;
/**
* New variable value.
*/
newValue: Runtime.CallArgument;
/**
* Id of callframe that holds variable.
*/
callFrameId: CallFrameId;
}
interface StepIntoRequest {
/**
* Debugger will pause on the execution of the first async task which was scheduled
* before next pause.
*/
breakOnAsyncCall?: boolean;
/**
* The skipList specifies location ranges that should be skipped on step into.
*/
skipList?: LocationRange[];
}
interface StepOverRequest {
/**
* The skipList specifies location ranges that should be skipped on step over.
*/
skipList?: LocationRange[];
}
/**
* Fired when breakpoint is resolved to an actual script and location.
*/
interface BreakpointResolvedEvent {
/**
* Breakpoint unique identifier.
*/
breakpointId: BreakpointId;
/**
* Actual breakpoint location.
*/
location: Location;
}
const enum PausedEventReason {
Ambiguous = 'ambiguous',
Assert = 'assert',
CSPViolation = 'CSPViolation',
DebugCommand = 'debugCommand',
DOM = 'DOM',
EventListener = 'EventListener',
Exception = 'exception',
Instrumentation = 'instrumentation',
OOM = 'OOM',
Other = 'other',
PromiseRejection = 'promiseRejection',
XHR = 'XHR',
}
/**
* Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria.
*/
interface PausedEvent {
/**
* Call stack the virtual machine stopped on.
*/
callFrames: CallFrame[];
/**
* Pause reason. (PausedEventReason enum)
*/
reason: ('ambiguous' | 'assert' | 'CSPViolation' | 'debugCommand' | 'DOM' | 'EventListener' | 'exception' | 'instrumentation' | 'OOM' | 'other' | 'promiseRejection' | 'XHR');
/**
* Object containing break-specific auxiliary properties.
*/
data?: any;
/**
* Hit breakpoints IDs
*/
hitBreakpoints?: string[];
/**
* Async stack trace, if any.
*/
asyncStackTrace?: Runtime.StackTrace;
/**
* Async stack trace, if any.
*/
asyncStackTraceId?: Runtime.StackTraceId;
/**
* Never present, will be removed.
*/
asyncCallStackTraceId?: Runtime.StackTraceId;
}
/**
* Fired when virtual machine fails to parse the script.
*/
interface ScriptFailedToParseEvent {
/**
* Identifier of the script parsed.
*/
scriptId: Runtime.ScriptId;
/**
* URL or name of the script parsed (if any).
*/
url: string;
/**
* Line offset of the script within the resource with given URL (for script tags).
*/
startLine: integer;
/**
* Column offset of the script within the resource with given URL.
*/
startColumn: integer;
/**
* Last line of the script.
*/
endLine: integer;
/**
* Length of the last line of the script.
*/
endColumn: integer;
/**
* Specifies script creation context.
*/
executionContextId: Runtime.ExecutionContextId;
/**
* Content hash of the script.
*/
hash: string;
/**
* Embedder-specific auxiliary data.
*/
executionContextAuxData?: any;
/**
* URL of source map associated with script (if any).
*/
sourceMapURL?: string;
/**
* True, if this script has sourceURL.
*/
hasSourceURL?: boolean;
/**
* True, if this script is ES6 module.
*/
isModule?: boolean;
/**
* This script length.
*/
length?: integer;
/**
* JavaScript top stack frame of where the script parsed event was triggered if available.
*/
stackTrace?: Runtime.StackTrace;
/**
* If the scriptLanguage is WebAssembly, the code section offset in the module.
*/
codeOffset?: integer;
/**
* The language of the script.
*/
scriptLanguage?: Debugger.ScriptLanguage;
/**
* The name the embedder supplied for this script.
*/
embedderName?: string;
}
/**
* Fired when virtual machine parses script. This event is also fired for all known and uncollected
* scripts upon enabling debugger.
*/
interface ScriptParsedEvent {
/**
* Identifier of the script parsed.
*/
scriptId: Runtime.ScriptId;
/**
* URL or name of the script parsed (if any).
*/
url: string;
/**
* Line offset of the script within the resource with given URL (for script tags).
*/
startLine: integer;
/**
* Column offset of the script within the resource with given URL.
*/
startColumn: integer;
/**
* Last line of the script.
*/
endLine: integer;
/**
* Length of the last line of the script.
*/
endColumn: integer;
/**
* Specifies script creation context.
*/
executionContextId: Runtime.ExecutionContextId;
/**
* Content hash of the script.
*/
hash: string;
/**
* Embedder-specific auxiliary data.
*/
executionContextAuxData?: any;
/**
* True, if this script is generated as a result of the live edit operation.
*/
isLiveEdit?: boolean;
/**
* URL of source map associated with script (if any).
*/
sourceMapURL?: string;
/**
* True, if this script has sourceURL.
*/
hasSourceURL?: boolean;
/**
* True, if this script is ES6 module.
*/
isModule?: boolean;
/**
* This script length.
*/
length?: integer;
/**
* JavaScript top stack frame of where the script parsed event was triggered if available.
*/
stackTrace?: Runtime.StackTrace;
/**
* If the scriptLanguage is WebAssembly, the code section offset in the module.
*/
codeOffset?: integer;
/**
* The language of the script.
*/
scriptLanguage?: Debugger.ScriptLanguage;
/**
* If the scriptLanguage is WebASsembly, the source of debug symbols for the module.
*/
debugSymbols?: Debugger.DebugSymbols;
/**
* The name the embedder supplied for this script.
*/
embedderName?: string;
}
}
namespace HeapProfiler {
/**
* Heap snapshot object id.
*/
type HeapSnapshotObjectId = string;
/**
* Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes.
*/
interface SamplingHeapProfileNode {
/**
* Function location.
*/
callFrame: Runtime.CallFrame;
/**
* Allocations size in bytes for the node excluding children.
*/
selfSize: number;
/**
* Node id. Ids are unique across all profiles collected between startSampling and stopSampling.
*/
id: integer;
/**
* Child nodes.
*/
children: SamplingHeapProfileNode[];
}
/**
* A single sample from a sampling profile.
*/
interface SamplingHeapProfileSample {
/**
* Allocation size in bytes attributed to the sample.
*/
size: number;
/**
* Id of the corresponding profile tree node.
*/
nodeId: integer;
/**
* Time-ordered sample ordinal number. It is unique across all profiles retrieved
* between startSampling and stopSampling.
*/
ordinal: number;
}
/**
* Sampling profile.
*/
interface SamplingHeapProfile {
head: SamplingHeapProfileNode;
samples: SamplingHeapProfileSample[];
}
interface AddInspectedHeapObjectRequest {
/**
* Heap snapshot object id to be accessible by means of $x command line API.
*/
heapObjectId: HeapSnapshotObjectId;
}
interface GetHeapObjectIdRequest {
/**
* Identifier of the object to get heap object id for.
*/
objectId: Runtime.RemoteObjectId;
}
interface GetHeapObjectIdResponse {
/**
* Id of the heap snapshot object corresponding to the passed remote object id.
*/
heapSnapshotObjectId: HeapSnapshotObjectId;
}
interface GetObjectByHeapObjectIdRequest {
objectId: HeapSnapshotObjectId;
/**
* Symbolic group name that can be used to release multiple objects.
*/
objectGroup?: string;
}
interface GetObjectByHeapObjectIdResponse {
/**
* Evaluation result.
*/
result: Runtime.RemoteObject;
}
interface GetSamplingProfileResponse {
/**
* Return the sampling profile being collected.
*/
profile: SamplingHeapProfile;
}
interface StartSamplingRequest {
/**
* Average sample interval in bytes. Poisson distribution is used for the intervals. The
* default value is 32768 bytes.
*/
samplingInterval?: number;
}
interface StartTrackingHeapObjectsRequest {
trackAllocations?: boolean;
}
interface StopSamplingResponse {
/**
* Recorded sampling heap profile.
*/
profile: SamplingHeapProfile;
}
interface StopTrackingHeapObjectsRequest {
/**
* If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken
* when the tracking is stopped.
*/
reportProgress?: boolean;
treatGlobalObjectsAsRoots?: boolean;
/**
* If true, numerical values are included in the snapshot
*/
captureNumericValue?: boolean;
}
interface TakeHeapSnapshotRequest {
/**
* If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken.
*/
reportProgress?: boolean;
/**
* If true, a raw snapshot without artificial roots will be generated
*/
treatGlobalObjectsAsRoots?: boolean;
/**
* If true, numerical values are included in the snapshot
*/
captureNumericValue?: boolean;
}
interface AddHeapSnapshotChunkEvent {
chunk: string;
}
/**
* If heap objects tracking has been started then backend may send update for one or more fragments
*/
interface HeapStatsUpdateEvent {
/**
* An array of triplets. Each triplet describes a fragment. The first integer is the fragment
* index, the second integer is a total count of objects for the fragment, the third integer is
* a total size of the objects for the fragment.
*/
statsUpdate: integer[];
}
/**
* If heap objects tracking has been started then backend regularly sends a current value for last
* seen object id and corresponding timestamp. If the were changes in the heap since last event
* then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event.
*/
interface LastSeenObjectIdEvent {
lastSeenObjectId: integer;
timestamp: number;
}
interface ReportHeapSnapshotProgressEvent {
done: integer;
total: integer;
finished?: boolean;
}
}
namespace Profiler {
/**
* Profile node. Holds callsite information, execution statistics and child nodes.
*/
interface ProfileNode {
/**
* Unique id of the node.
*/
id: integer;
/**
* Function location.
*/
callFrame: Runtime.CallFrame;
/**
* Number of samples where this node was on top of the call stack.
*/
hitCount?: integer;
/**
* Child node ids.
*/
children?: integer[];
/**
* The reason of being not optimized. The function may be deoptimized or marked as don't
* optimize.
*/
deoptReason?: string;
/**
* An array of source position ticks.
*/
positionTicks?: PositionTickInfo[];
}
/**
* Profile.
*/
interface Profile {
/**
* The list of profile nodes. First item is the root node.
*/
nodes: ProfileNode[];
/**
* Profiling start timestamp in microseconds.
*/
startTime: number;
/**
* Profiling end timestamp in microseconds.
*/
endTime: number;
/**
* Ids of samples top nodes.
*/
samples?: integer[];
/**
* Time intervals between adjacent samples in microseconds. The first delta is relative to the
* profile startTime.
*/
timeDeltas?: integer[];
}
/**
* Specifies a number of samples attributed to a certain source position.
*/
interface PositionTickInfo {
/**
* Source line number (1-based).
*/
line: integer;
/**
* Number of samples attributed to the source line.
*/
ticks: integer;
}
/**
* Coverage data for a source range.
*/
interface CoverageRange {
/**
* JavaScript script source offset for the range start.
*/
startOffset: integer;
/**
* JavaScript script source offset for the range end.
*/
endOffset: integer;
/**
* Collected execution count of the source range.
*/
count: integer;
}
/**
* Coverage data for a JavaScript function.
*/
interface FunctionCoverage {
/**
* JavaScript function name.
*/
functionName: string;
/**
* Source ranges inside the function with coverage data.
*/
ranges: CoverageRange[];
/**
* Whether coverage data for this function has block granularity.
*/
isBlockCoverage: boolean;
}
/**
* Coverage data for a JavaScript script.
*/
interface ScriptCoverage {
/**
* JavaScript script id.
*/
scriptId: Runtime.ScriptId;
/**
* JavaScript script name or url.
*/
url: string;
/**
* Functions contained in the script that has coverage data.
*/
functions: FunctionCoverage[];
}
/**
* Describes a type collected during runtime.
*/
interface TypeObject {
/**
* Name of a type collected with type profiling.
*/
name: string;
}
/**
* Source offset and types for a parameter or return value.
*/
interface TypeProfileEntry {
/**
* Source offset of the parameter or end of function for return values.
*/
offset: integer;
/**
* The types for this parameter or return value.
*/
types: TypeObject[];
}
/**
* Type profile data collected during runtime for a JavaScript script.
*/
interface ScriptTypeProfile {
/**
* JavaScript script id.
*/
scriptId: Runtime.ScriptId;
/**
* JavaScript script name or url.
*/
url: string;
/**
* Type profile entries for parameters and return values of the functions in the script.
*/
entries: TypeProfileEntry[];
}
interface GetBestEffortCoverageResponse {
/**
* Coverage data for the current isolate.
*/
result: ScriptCoverage[];
}
interface SetSamplingIntervalRequest {
/**
* New sampling interval in microseconds.
*/
interval: integer;
}
interface StartPreciseCoverageRequest {
/**
* Collect accurate call counts beyond simple 'covered' or 'not covered'.
*/
callCount?: boolean;
/**
* Collect block-based coverage.
*/
detailed?: boolean;
/**
* Allow the backend to send updates on its own initiative
*/
allowTriggeredUpdates?: boolean;
}
interface StartPreciseCoverageResponse {
/**
* Monotonically increasing time (in seconds) when the coverage update was taken in the backend.
*/
timestamp: number;
}
interface StopResponse {
/**
* Recorded profile.
*/
profile: Profile;
}
interface TakePreciseCoverageResponse {
/**
* Coverage data for the current isolate.
*/
result: ScriptCoverage[];
/**
* Monotonically increasing time (in seconds) when the coverage update was taken in the backend.
*/
timestamp: number;
}
interface TakeTypeProfileResponse {
/**
* Type profile for all scripts since startTypeProfile() was turned on.
*/
result: ScriptTypeProfile[];
}
interface ConsoleProfileFinishedEvent {
id: string;
/**
* Location of console.profileEnd().
*/
location: Debugger.Location;
profile: Profile;
/**
* Profile title passed as an argument to console.profile().
*/
title?: string;
}
/**
* Sent when new profile recording is started using console.profile() call.
*/
interface ConsoleProfileStartedEvent {
id: string;
/**
* Location of console.profile().
*/
location: Debugger.Location;
/**
* Profile title passed as an argument to console.profile().
*/
title?: string;
}
/**
* Reports coverage delta since the last poll (either from an event like this, or from
* `takePreciseCoverage` for the current isolate. May only be sent if precise code
* coverage has been started. This event can be trigged by the embedder to, for example,
* trigger collection of coverage data immediately at a certain point in time.
*/
interface PreciseCoverageDeltaUpdateEvent {
/**
* Monotonically increasing time (in seconds) when the coverage update was taken in the backend.
*/
timestamp: number;
/**
* Identifier for distinguishing coverage events.
*/
occasion: string;
/**
* Coverage data for the current isolate.
*/
result: ScriptCoverage[];
}
}
/**
* Runtime domain exposes JavaScript runtime by means of remote evaluation and mirror objects.
* Evaluation results are returned as mirror object that expose object type, string representation
* and unique identifier that can be used for further object reference. Original objects are
* maintained in memory unless they are either explicitly released or are released along with the
* other objects in their object group.
*/
namespace Runtime {
/**
* Unique script identifier.
*/
type ScriptId = string;
/**
* Unique object identifier.
*/
type RemoteObjectId = string;
/**
* Primitive value which cannot be JSON-stringified. Includes values `-0`, `NaN`, `Infinity`,
* `-Infinity`, and bigint literals.
*/
type UnserializableValue = string;
const enum RemoteObjectType {
Object = 'object',
Function = 'function',
Undefined = 'undefined',
String = 'string',
Number = 'number',
Boolean = 'boolean',
Symbol = 'symbol',
Bigint = 'bigint',
}
const enum RemoteObjectSubtype {
Array = 'array',
Null = 'null',
Node = 'node',
Regexp = 'regexp',
Date = 'date',
Map = 'map',
Set = 'set',
Weakmap = 'weakmap',
Weakset = 'weakset',
Iterator = 'iterator',
Generator = 'generator',
Error = 'error',
Proxy = 'proxy',
Promise = 'promise',
Typedarray = 'typedarray',
Arraybuffer = 'arraybuffer',
Dataview = 'dataview',
Webassemblymemory = 'webassemblymemory',
Wasmvalue = 'wasmvalue',
}
/**
* Mirror object referencing original JavaScript object.
*/
interface RemoteObject {
/**
* Object type. (RemoteObjectType enum)
*/
type: ('object' | 'function' | 'undefined' | 'string' | 'number' | 'boolean' | 'symbol' | 'bigint');
/**
* Object subtype hint. Specified for `object` type values only.
* NOTE: If you change anything here, make sure to also update
* `subtype` in `ObjectPreview` and `PropertyPreview` below. (RemoteObjectSubtype enum)
*/
subtype?: ('array' | 'null' | 'node' | 'regexp' | 'date' | 'map' | 'set' | 'weakmap' | 'weakset' | 'iterator' | 'generator' | 'error' | 'proxy' | 'promise' | 'typedarray' | 'arraybuffer' | 'dataview' | 'webassemblymemory' | 'wasmvalue');
/**
* Object class (constructor) name. Specified for `object` type values only.
*/
className?: string;
/**
* Remote object value in case of primitive values or JSON values (if it was requested).
*/
value?: any;
/**
* Primitive value which can not be JSON-stringified does not have `value`, but gets this
* property.
*/
unserializableValue?: UnserializableValue;
/**
* String representation of the object.
*/
description?: string;
/**
* Unique object identifier (for non-primitive values).
*/
objectId?: RemoteObjectId;
/**
* Preview containing abbreviated property values. Specified for `object` type values only.
*/
preview?: ObjectPreview;
customPreview?: CustomPreview;
}
interface CustomPreview {
/**
* The JSON-stringified result of formatter.header(object, config) call.
* It contains json ML array that represents RemoteObject.
*/
header: string;
/**
* If formatter returns true as a result of formatter.hasBody call then bodyGetterId will
* contain RemoteObjectId for the function that returns result of formatter.body(object, config) call.
* The result value is json ML array.
*/
bodyGetterId?: RemoteObjectId;
}
const enum ObjectPreviewType {
Object = 'object',
Function = 'function',
Undefined = 'undefined',
String = 'string',
Number = 'number',
Boolean = 'boolean',
Symbol = 'symbol',
Bigint = 'bigint',
}
const enum ObjectPreviewSubtype {
Array = 'array',
Null = 'null',
Node = 'node',
Regexp = 'regexp',
Date = 'date',
Map = 'map',
Set = 'set',
Weakmap = 'weakmap',
Weakset = 'weakset',
Iterator = 'iterator',
Generator = 'generator',
Error = 'error',
Proxy = 'proxy',
Promise = 'promise',
Typedarray = 'typedarray',
Arraybuffer = 'arraybuffer',
Dataview = 'dataview',
Webassemblymemory = 'webassemblymemory',
Wasmvalue = 'wasmvalue',
}
/**
* Object containing abbreviated remote object value.
*/
interface ObjectPreview {
/**
* Object type. (ObjectPreviewType enum)
*/
type: ('object' | 'function' | 'undefined' | 'string' | 'number' | 'boolean' | 'symbol' | 'bigint');
/**
* Object subtype hint. Specified for `object` type values only. (ObjectPreviewSubtype enum)
*/
subtype?: ('array' | 'null' | 'node' | 'regexp' | 'date' | 'map' | 'set' | 'weakmap' | 'weakset' | 'iterator' | 'generator' | 'error' | 'proxy' | 'promise' | 'typedarray' | 'arraybuffer' | 'dataview' | 'webassemblymemory' | 'wasmvalue');
/**
* String representation of the object.
*/
description?: string;
/**
* True iff some of the properties or entries of the original object did not fit.
*/
overflow: boolean;
/**
* List of the properties.
*/
properties: PropertyPreview[];
/**
* List of the entries. Specified for `map` and `set` subtype values only.
*/
entries?: EntryPreview[];
}
const enum PropertyPreviewType {
Object = 'object',
Function = 'function',
Undefined = 'undefined',
String = 'string',
Number = 'number',
Boolean = 'boolean',
Symbol = 'symbol',
Accessor = 'accessor',
Bigint = 'bigint',
}
const enum PropertyPreviewSubtype {
Array = 'array',
Null = 'null',
Node = 'node',
Regexp = 'regexp',
Date = 'date',
Map = 'map',
Set = 'set',
Weakmap = 'weakmap',
Weakset = 'weakset',
Iterator = 'iterator',
Generator = 'generator',
Error = 'error',
Proxy = 'proxy',
Promise = 'promise',
Typedarray = 'typedarray',
Arraybuffer = 'arraybuffer',
Dataview = 'dataview',
Webassemblymemory = 'webassemblymemory',
Wasmvalue = 'wasmvalue',
}
interface PropertyPreview {
/**
* Property name.
*/
name: string;
/**
* Object type. Accessor means that the property itself is an accessor property. (PropertyPreviewType enum)
*/
type: ('object' | 'function' | 'undefined' | 'string' | 'number' | 'boolean' | 'symbol' | 'accessor' | 'bigint');
/**
* User-friendly property value string.
*/
value?: string;
/**
* Nested value preview.
*/
valuePreview?: ObjectPreview;
/**
* Object subtype hint. Specified for `object` type values only. (PropertyPreviewSubtype enum)
*/
subtype?: ('array' | 'null' | 'node' | 'regexp' | 'date' | 'map' | 'set' | 'weakmap' | 'weakset' | 'iterator' | 'generator' | 'error' | 'proxy' | 'promise' | 'typedarray' | 'arraybuffer' | 'dataview' | 'webassemblymemory' | 'wasmvalue');
}
interface EntryPreview {
/**
* Preview of the key. Specified for map-like collection entries.
*/
key?: ObjectPreview;
/**
* Preview of the value.
*/
value: ObjectPreview;
}
/**
* Object property descriptor.
*/
interface PropertyDescriptor {
/**
* Property name or symbol description.
*/
name: string;
/**
* The value associated with the property.
*/
value?: RemoteObject;
/**
* True if the value associated with the property may be changed (data descriptors only).
*/
writable?: boolean;
/**
* A function which serves as a getter for the property, or `undefined` if there is no getter
* (accessor descriptors only).
*/
get?: RemoteObject;
/**
* A function which serves as a setter for the property, or `undefined` if there is no setter
* (accessor descriptors only).
*/
set?: RemoteObject;
/**
* True if the type of this property descriptor may be changed and if the property may be
* deleted from the corresponding object.
*/
configurable: boolean;
/**
* True if this property shows up during enumeration of the properties on the corresponding
* object.
*/
enumerable: boolean;
/**
* True if the result was thrown during the evaluation.
*/
wasThrown?: boolean;
/**
* True if the property is owned for the object.
*/
isOwn?: boolean;
/**
* Property symbol object, if the property is of the `symbol` type.
*/
symbol?: RemoteObject;
}
/**
* Object internal property descriptor. This property isn't normally visible in JavaScript code.
*/
interface InternalPropertyDescriptor {
/**
* Conventional property name.
*/
name: string;
/**
* The value associated with the property.
*/
value?: RemoteObject;
}
/**
* Object private field descriptor.
*/
interface PrivatePropertyDescriptor {
/**
* Private property name.
*/
name: string;
/**
* The value associated with the private property.
*/
value?: RemoteObject;
/**
* A function which serves as a getter for the private property,
* or `undefined` if there is no getter (accessor descriptors only).
*/
get?: RemoteObject;
/**
* A function which serves as a setter for the private property,
* or `undefined` if there is no setter (accessor descriptors only).
*/
set?: RemoteObject;
}
/**
* Represents function call argument. Either remote object id `objectId`, primitive `value`,
* unserializable primitive value or neither of (for undefined) them should be specified.
*/
interface CallArgument {
/**
* Primitive value or serializable javascript object.
*/
value?: any;
/**
* Primitive value which can not be JSON-stringified.
*/
unserializableValue?: UnserializableValue;
/**
* Remote object handle.
*/
objectId?: RemoteObjectId;
}
/**
* Id of an execution context.
*/
type ExecutionContextId = integer;
/**
* Description of an isolated world.
*/
interface ExecutionContextDescription {
/**
* Unique id of the execution context. It can be used to specify in which execution context
* script evaluation should be performed.
*/
id: ExecutionContextId;
/**
* Execution context origin.
*/
origin: string;
/**
* Human readable name describing given context.
*/
name: string;
/**
* A system-unique execution context identifier. Unlike the id, this is unique across
* multiple processes, so can be reliably used to identify specific context while backend
* performs a cross-process navigation.
*/
uniqueId: string;
/**
* Embedder-specific auxiliary data.
*/
auxData?: any;
}
/**
* Detailed information about exception (or error) that was thrown during script compilation or
* execution.
*/
interface ExceptionDetails {
/**
* Exception id.
*/
exceptionId: integer;
/**
* Exception text, which should be used together with exception object when available.
*/
text: string;
/**
* Line number of the exception location (0-based).
*/
lineNumber: integer;
/**
* Column number of the exception location (0-based).
*/
columnNumber: integer;
/**
* Script ID of the exception location.
*/
scriptId?: ScriptId;
/**
* URL of the exception location, to be used when the script was not reported.
*/
url?: string;
/**
* JavaScript stack trace if available.
*/
stackTrace?: StackTrace;
/**
* Exception object if available.
*/
exception?: RemoteObject;
/**
* Identifier of the context where exception happened.
*/
executionContextId?: ExecutionContextId;
/**
* Dictionary with entries of meta data that the client associated
* with this exception, such as information about associated network
* requests, etc.
*/
exceptionMetaData?: any;
}
/**
* Number of milliseconds since epoch.
*/
type Timestamp = number;
/**
* Number of milliseconds.
*/
type TimeDelta = number;
/**
* Stack entry for runtime errors and assertions.
*/
interface CallFrame {
/**
* JavaScript function name.
*/
functionName: string;
/**
* JavaScript script id.
*/
scriptId: ScriptId;
/**
* JavaScript script name or url.
*/
url: string;
/**
* JavaScript script line number (0-based).
*/
lineNumber: integer;
/**
* JavaScript script column number (0-based).
*/
columnNumber: integer;
}
/**
* Call frames for assertions or error messages.
*/
interface StackTrace {
/**
* String label of this stack trace. For async traces this may be a name of the function that
* initiated the async call.
*/
description?: string;
/**
* JavaScript function name.
*/
callFrames: CallFrame[];
/**
* Asynchronous JavaScript stack trace that preceded this stack, if available.
*/
parent?: StackTrace;
/**
* Asynchronous JavaScript stack trace that preceded this stack, if available.
*/
parentId?: StackTraceId;
}
/**
* Unique identifier of current debugger.
*/
type UniqueDebuggerId = string;
/**
* If `debuggerId` is set stack trace comes from another debugger and can be resolved there. This
* allows to track cross-debugger calls. See `Runtime.StackTrace` and `Debugger.paused` for usages.
*/
interface StackTraceId {
id: string;
debuggerId?: UniqueDebuggerId;
}
interface AwaitPromiseRequest {
/**
* Identifier of the promise.
*/
promiseObjectId: RemoteObjectId;
/**
* Whether the result is expected to be a JSON object that should be sent by value.
*/
returnByValue?: boolean;
/**
* Whether preview should be generated for the result.
*/
generatePreview?: boolean;
}
interface AwaitPromiseResponse {
/**
* Promise result. Will contain rejected value if promise was rejected.
*/
result: RemoteObject;
/**
* Exception details if stack strace is available.
*/
exceptionDetails?: ExceptionDetails;
}
interface CallFunctionOnRequest {
/**
* Declaration of the function to call.
*/
functionDeclaration: string;
/**
* Identifier of the object to call function on. Either objectId or executionContextId should
* be specified.
*/
objectId?: RemoteObjectId;
/**
* Call arguments. All call arguments must belong to the same JavaScript world as the target
* object.
*/
arguments?: CallArgument[];
/**
* In silent mode exceptions thrown during evaluation are not reported and do not pause
* execution. Overrides `setPauseOnException` state.
*/
silent?: boolean;
/**
* Whether the result is expected to be a JSON object which should be sent by value.
*/
returnByValue?: boolean;
/**
* Whether preview should be generated for the result.
*/
generatePreview?: boolean;
/**
* Whether execution should be treated as initiated by user in the UI.
*/
userGesture?: boolean;
/**
* Whether execution should `await` for resulting value and return once awaited promise is
* resolved.
*/
awaitPromise?: boolean;
/**
* Specifies execution context which global object will be used to call function on. Either
* executionContextId or objectId should be specified.
*/
executionContextId?: ExecutionContextId;
/**
* Symbolic group name that can be used to release multiple objects. If objectGroup is not
* specified and objectId is, objectGroup will be inherited from object.
*/
objectGroup?: string;
/**
* Whether to throw an exception if side effect cannot be ruled out during evaluation.
*/
throwOnSideEffect?: boolean;
}
interface CallFunctionOnResponse {
/**
* Call result.
*/
result: RemoteObject;
/**
* Exception details.
*/
exceptionDetails?: ExceptionDetails;
}
interface CompileScriptRequest {
/**
* Expression to compile.
*/
expression: string;
/**
* Source url to be set for the script.
*/
sourceURL: string;
/**
* Specifies whether the compiled script should be persisted.
*/
persistScript: boolean;
/**
* Specifies in which execution context to perform script run. If the parameter is omitted the
* evaluation will be performed in the context of the inspected page.
*/
executionContextId?: ExecutionContextId;
}
interface CompileScriptResponse {
/**
* Id of the script.
*/
scriptId?: ScriptId;
/**
* Exception details.
*/
exceptionDetails?: ExceptionDetails;
}
interface EvaluateRequest {
/**
* Expression to evaluate.
*/
expression: string;
/**
* Symbolic group name that can be used to release multiple objects.
*/
objectGroup?: string;
/**
* Determines whether Command Line API should be available during the evaluation.
*/
includeCommandLineAPI?: boolean;
/**
* In silent mode exceptions thrown during evaluation are not reported and do not pause
* execution. Overrides `setPauseOnException` state.
*/
silent?: boolean;
/**
* Specifies in which execution context to perform evaluation. If the parameter is omitted the
* evaluation will be performed in the context of the inspected page.
* This is mutually exclusive with `uniqueContextId`, which offers an
* alternative way to identify the execution context that is more reliable
* in a multi-process environment.
*/
contextId?: ExecutionContextId;
/**
* Whether the result is expected to be a JSON object that should be sent by value.
*/
returnByValue?: boolean;
/**
* Whether preview should be generated for the result.
*/
generatePreview?: boolean;
/**
* Whether execution should be treated as initiated by user in the UI.
*/
userGesture?: boolean;
/**
* Whether execution should `await` for resulting value and return once awaited promise is
* resolved.
*/
awaitPromise?: boolean;
/**
* Whether to throw an exception if side effect cannot be ruled out during evaluation.
* This implies `disableBreaks` below.
*/
throwOnSideEffect?: boolean;
/**
* Terminate execution after timing out (number of milliseconds).
*/
timeout?: TimeDelta;
/**
* Disable breakpoints during execution.
*/
disableBreaks?: boolean;
/**
* Setting this flag to true enables `let` re-declaration and top-level `await`.
* Note that `let` variables can only be re-declared if they originate from
* `replMode` themselves.
*/
replMode?: boolean;
/**
* The Content Security Policy (CSP) for the target might block 'unsafe-eval'
* which includes eval(), Function(), setTimeout() and setInterval()
* when called with non-callable arguments. This flag bypasses CSP for this
* evaluation and allows unsafe-eval. Defaults to true.
*/
allowUnsafeEvalBlockedByCSP?: boolean;
/**
* An alternative way to specify the execution context to evaluate in.
* Compared to contextId that may be reused across processes, this is guaranteed to be
* system-unique, so it can be used to prevent accidental evaluation of the expression
* in context different than intended (e.g. as a result of navigation across process
* boundaries).
* This is mutually exclusive with `contextId`.
*/
uniqueContextId?: string;
}
interface EvaluateResponse {
/**
* Evaluation result.
*/
result: RemoteObject;
/**
* Exception details.
*/
exceptionDetails?: ExceptionDetails;
}
interface GetIsolateIdResponse {
/**
* The isolate id.
*/
id: string;
}
interface GetHeapUsageResponse {
/**
* Used heap size in bytes.
*/
usedSize: number;
/**
* Allocated heap size in bytes.
*/
totalSize: number;
}
interface GetPropertiesRequest {
/**
* Identifier of the object to return properties for.
*/
objectId: RemoteObjectId;
/**
* If true, returns properties belonging only to the element itself, not to its prototype
* chain.
*/
ownProperties?: boolean;
/**
* If true, returns accessor properties (with getter/setter) only; internal properties are not
* returned either.
*/
accessorPropertiesOnly?: boolean;
/**
* Whether preview should be generated for the results.
*/
generatePreview?: boolean;
/**
* If true, returns non-indexed properties only.
*/
nonIndexedPropertiesOnly?: boolean;
}
interface GetPropertiesResponse {
/**
* Object properties.
*/
result: PropertyDescriptor[];
/**
* Internal object properties (only of the element itself).
*/
internalProperties?: InternalPropertyDescriptor[];
/**
* Object private properties.
*/
privateProperties?: PrivatePropertyDescriptor[];
/**
* Exception details.
*/
exceptionDetails?: ExceptionDetails;
}
interface GlobalLexicalScopeNamesRequest {
/**
* Specifies in which execution context to lookup global scope variables.
*/
executionContextId?: ExecutionContextId;
}
interface GlobalLexicalScopeNamesResponse {
names: string[];
}
interface QueryObjectsRequest {
/**
* Identifier of the prototype to return objects for.
*/
prototypeObjectId: RemoteObjectId;
/**
* Symbolic group name that can be used to release the results.
*/
objectGroup?: string;
}
interface QueryObjectsResponse {
/**
* Array with objects.
*/
objects: RemoteObject;
}
interface ReleaseObjectRequest {
/**
* Identifier of the object to release.
*/
objectId: RemoteObjectId;
}
interface ReleaseObjectGroupRequest {
/**
* Symbolic object group name.
*/
objectGroup: string;
}
interface RunScriptRequest {
/**
* Id of the script to run.
*/
scriptId: ScriptId;
/**
* Specifies in which execution context to perform script run. If the parameter is omitted the
* evaluation will be performed in the context of the inspected page.
*/
executionContextId?: ExecutionContextId;
/**
* Symbolic group name that can be used to release multiple objects.
*/
objectGroup?: string;
/**
* In silent mode exceptions thrown during evaluation are not reported and do not pause
* execution. Overrides `setPauseOnException` state.
*/
silent?: boolean;
/**
* Determines whether Command Line API should be available during the evaluation.
*/
includeCommandLineAPI?: boolean;
/**
* Whether the result is expected to be a JSON object which should be sent by value.
*/
returnByValue?: boolean;
/**
* Whether preview should be generated for the result.
*/
generatePreview?: boolean;
/**
* Whether execution should `await` for resulting value and return once awaited promise is
* resolved.
*/
awaitPromise?: boolean;
}
interface RunScriptResponse {
/**
* Run result.
*/
result: RemoteObject;
/**
* Exception details.
*/
exceptionDetails?: ExceptionDetails;
}
interface SetAsyncCallStackDepthRequest {
/**
* Maximum depth of async call stacks. Setting to `0` will effectively disable collecting async
* call stacks (default).
*/
maxDepth: integer;
}
interface SetCustomObjectFormatterEnabledRequest {
enabled: boolean;
}
interface SetMaxCallStackSizeToCaptureRequest {
size: integer;
}
interface AddBindingRequest {
name: string;
/**
* If specified, the binding would only be exposed to the specified
* execution context. If omitted and `executionContextName` is not set,
* the binding is exposed to all execution contexts of the target.
* This parameter is mutually exclusive with `executionContextName`.
* Deprecated in favor of `executionContextName` due to an unclear use case
* and bugs in implementation (crbug.com/1169639). `executionContextId` will be
* removed in the future.
*/
executionContextId?: ExecutionContextId;
/**
* If specified, the binding is exposed to the executionContext with
* matching name, even for contexts created after the binding is added.
* See also `ExecutionContext.name` and `worldName` parameter to
* `Page.addScriptToEvaluateOnNewDocument`.
* This parameter is mutually exclusive with `executionContextId`.
*/
executionContextName?: string;
}
interface RemoveBindingRequest {
name: string;
}
/**
* Notification is issued every time when binding is called.
*/
interface BindingCalledEvent {
name: string;
payload: string;
/**
* Identifier of the context where the call was made.
*/
executionContextId: ExecutionContextId;
}
const enum ConsoleAPICalledEventType {
Log = 'log',
Debug = 'debug',
Info = 'info',
Error = 'error',
Warning = 'warning',
Dir = 'dir',
DirXML = 'dirxml',
Table = 'table',
Trace = 'trace',
Clear = 'clear',
StartGroup = 'startGroup',
StartGroupCollapsed = 'startGroupCollapsed',
EndGroup = 'endGroup',
Assert = 'assert',
Profile = 'profile',
ProfileEnd = 'profileEnd',
Count = 'count',
TimeEnd = 'timeEnd',
}
/**
* Issued when console API was called.
*/
interface ConsoleAPICalledEvent {
/**
* Type of the call. (ConsoleAPICalledEventType enum)
*/
type: ('log' | 'debug' | 'info' | 'error' | 'warning' | 'dir' | 'dirxml' | 'table' | 'trace' | 'clear' | 'startGroup' | 'startGroupCollapsed' | 'endGroup' | 'assert' | 'profile' | 'profileEnd' | 'count' | 'timeEnd');
/**
* Call arguments.
*/
args: RemoteObject[];
/**
* Identifier of the context where the call was made.
*/
executionContextId: ExecutionContextId;
/**
* Call timestamp.
*/
timestamp: Timestamp;
/**
* Stack trace captured when the call was made. The async stack chain is automatically reported for
* the following call types: `assert`, `error`, `trace`, `warning`. For other types the async call
* chain can be retrieved using `Debugger.getStackTrace` and `stackTrace.parentId` field.
*/
stackTrace?: StackTrace;
/**
* Console context descriptor for calls on non-default console context (not console.*):
* 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call
* on named context.
*/
context?: string;
}
/**
* Issued when unhandled exception was revoked.
*/
interface ExceptionRevokedEvent {
/**
* Reason describing why exception was revoked.
*/
reason: string;
/**
* The id of revoked exception, as reported in `exceptionThrown`.
*/
exceptionId: integer;
}
/**
* Issued when exception was thrown and unhandled.
*/
interface ExceptionThrownEvent {
/**
* Timestamp of the exception.
*/
timestamp: Timestamp;
exceptionDetails: ExceptionDetails;
}
/**
* Issued when new execution context is created.
*/
interface ExecutionContextCreatedEvent {
/**
* A newly created execution context.
*/
context: ExecutionContextDescription;
}
/**
* Issued when execution context is destroyed.
*/
interface ExecutionContextDestroyedEvent {
/**
* Id of the destroyed context
*/
executionContextId: ExecutionContextId;
}
/**
* Issued when object should be inspected (for example, as a result of inspect() command line API
* call).
*/
interface InspectRequestedEvent {
object: RemoteObject;
hints: any;
/**
* Identifier of the context where the call was made.
*/
executionContextId?: ExecutionContextId;
}
}
/**
* This domain is deprecated.
*/
namespace Schema {
/**
* Description of the protocol domain.
*/
interface Domain {
/**
* Domain name.
*/
name: string;
/**
* Domain version.
*/
version: string;
}
interface GetDomainsResponse {
/**
* List of supported domains.
*/
domains: Domain[];
}
}
namespace Accessibility {
/**
* Unique accessibility node identifier.
*/
type AXNodeId = string;
/**
* Enum of possible property types.
*/
type AXValueType = ('boolean' | 'tristate' | 'booleanOrUndefined' | 'idref' | 'idrefList' | 'integer' | 'node' | 'nodeList' | 'number' | 'string' | 'computedString' | 'token' | 'tokenList' | 'domRelation' | 'role' | 'internalRole' | 'valueUndefined');
/**
* Enum of possible property sources.
*/
type AXValueSourceType = ('attribute' | 'implicit' | 'style' | 'contents' | 'placeholder' | 'relatedElement');
/**
* Enum of possible native property sources (as a subtype of a particular AXValueSourceType).
*/
type AXValueNativeSourceType = ('description' | 'figcaption' | 'label' | 'labelfor' | 'labelwrapped' | 'legend' | 'rubyannotation' | 'tablecaption' | 'title' | 'other');
/**
* A single source for a computed AX property.
*/
interface AXValueSource {
/**
* What type of source this is.
*/
type: AXValueSourceType;
/**
* The value of this property source.
*/
value?: AXValue;
/**
* The name of the relevant attribute, if any.
*/
attribute?: string;
/**
* The value of the relevant attribute, if any.
*/
attributeValue?: AXValue;
/**
* Whether this source is superseded by a higher priority source.
*/
superseded?: boolean;
/**
* The native markup source for this value, e.g. a