clone

a browser-first diagram editor with live svg previews, local drafts and encrypted, accountless sharing

main
diagramzip / renderers / catalog / worker-configuration.d.ts
worker-configuration.d.ts 568.1K
1/* eslint-disable */2// Generated by Wrangler by running `wrangler types` (hash: 3d3fdd145760295159fc1eac24135779)3// Runtime types generated with workerd@1.20260820.1 2026-08-20 nodejs_compat4interface __BaseEnv_Env {5}6declare namespace Cloudflare {7 interface GlobalProps {8 mainModule: typeof import("./src/index");9 }10 interface Env extends __BaseEnv_Env {}11}12interface Env extends __BaseEnv_Env {}1314// Begin runtime types15/*! *****************************************************************************16Copyright (c) Cloudflare. All rights reserved.17Copyright (c) Microsoft Corporation. All rights reserved.1819Licensed under the Apache License, Version 2.0 (the "License"); you may not use20this file except in compliance with the License. You may obtain a copy of the21License at http://www.apache.org/licenses/LICENSE-2.022THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY23KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED24WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,25MERCHANTABLITY OR NON-INFRINGEMENT.26See the Apache Version 2.0 License for specific language governing permissions27and limitations under the License.28***************************************************************************** */29/* eslint-disable */30// noinspection JSUnusedGlobalSymbols31declare var onmessage: never;32/**33 * The **`DOMException`** interface represents an abnormal event (called an exception) that occurs as a result of calling a method or accessing a property of a web API. This is how error conditions are described in web APIs.34 *35 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException)36 */37declare class DOMException extends Error {38 constructor(message?: string, name?: string);39 /**40 * The **`message`** read-only property of the DOMException interface returns a string representing a message or description associated with the given error name.41 *42 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message)43 */44 readonly message: string;45 /**46 * The **`name`** read-only property of the DOMException interface returns a string that contains one of the strings associated with an error name.47 *48 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name)49 */50 readonly name: string;51 /**52 * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or 0 if none match.53 * @deprecated54 *55 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code)56 */57 readonly code: number;58 static readonly INDEX_SIZE_ERR: number;59 static readonly DOMSTRING_SIZE_ERR: number;60 static readonly HIERARCHY_REQUEST_ERR: number;61 static readonly WRONG_DOCUMENT_ERR: number;62 static readonly INVALID_CHARACTER_ERR: number;63 static readonly NO_DATA_ALLOWED_ERR: number;64 static readonly NO_MODIFICATION_ALLOWED_ERR: number;65 static readonly NOT_FOUND_ERR: number;66 static readonly NOT_SUPPORTED_ERR: number;67 static readonly INUSE_ATTRIBUTE_ERR: number;68 static readonly INVALID_STATE_ERR: number;69 static readonly SYNTAX_ERR: number;70 static readonly INVALID_MODIFICATION_ERR: number;71 static readonly NAMESPACE_ERR: number;72 static readonly INVALID_ACCESS_ERR: number;73 static readonly VALIDATION_ERR: number;74 static readonly TYPE_MISMATCH_ERR: number;75 static readonly SECURITY_ERR: number;76 static readonly NETWORK_ERR: number;77 static readonly ABORT_ERR: number;78 static readonly URL_MISMATCH_ERR: number;79 static readonly QUOTA_EXCEEDED_ERR: number;80 static readonly TIMEOUT_ERR: number;81 static readonly INVALID_NODE_TYPE_ERR: number;82 static readonly DATA_CLONE_ERR: number;83 get stack(): any;84 set stack(value: any);85}86type WorkerGlobalScopeEventMap = {87 fetch: FetchEvent;88 scheduled: ScheduledEvent;89 queue: QueueEvent;90 unhandledrejection: PromiseRejectionEvent;91 rejectionhandled: PromiseRejectionEvent;92};93declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> {94 EventTarget: typeof EventTarget;95}96/* The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). *97 * The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox).98 *99 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console)100 */101interface Console {102 "assert"(condition?: boolean, ...data: any[]): void;103 /**104 * The **`console.clear()`** static method clears the console if possible.105 *106 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static)107 */108 clear(): void;109 /**110 * The **`console.count()`** static method logs the number of times that this particular call to count() has been called.111 *112 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static)113 */114 count(label?: string): void;115 /**116 * The **`console.countReset()`** static method resets counter used with console.count().117 *118 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static)119 */120 countReset(label?: string): void;121 /**122 * The **`console.debug()`** static method outputs a message to the console at the "debug" log level. The message is only displayed to the user if the console is configured to display debug output. In most cases, the log level is configured within the console UI. This log level might correspond to the Debug or Verbose log level.123 *124 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static)125 */126 debug(...data: any[]): void;127 /**128 * The **`console.dir()`** static method displays a list of the properties of the specified JavaScript object. In browser consoles, the output is presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects.129 *130 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static)131 */132 dir(item?: any, options?: any): void;133 /**134 * The **`console.dirxml()`** static method displays an interactive tree of the descendant elements of the specified XML/HTML element. If it is not possible to display as an element the JavaScript Object view is shown instead. The output is presented as a hierarchical listing of expandable nodes that let you see the contents of child nodes.135 *136 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static)137 */138 dirxml(...data: any[]): void;139 /**140 * The **`console.error()`** static method outputs a message to the console at the "error" log level. The message is only displayed to the user if the console is configured to display error output. In most cases, the log level is configured within the console UI. The message may be formatted as an error, with red colors and call stack information.141 *142 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static)143 */144 error(...data: any[]): void;145 /**146 * The **`console.group()`** static method creates a new inline group in the Web console log, causing any subsequent console messages to be indented by an additional level, until console.groupEnd() is called.147 *148 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static)149 */150 group(...data: any[]): void;151 /**152 * The **`console.groupCollapsed()`** static method creates a new inline group in the console. Unlike console.group(), however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group.153 *154 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static)155 */156 groupCollapsed(...data: any[]): void;157 /**158 * The **`console.groupEnd()`** static method exits the current inline group in the console. See Using groups in the console in the console documentation for details and examples.159 *160 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static)161 */162 groupEnd(): void;163 /**164 * The **`console.info()`** static method outputs a message to the console at the "info" log level. The message is only displayed to the user if the console is configured to display info output. In most cases, the log level is configured within the console UI. The message may receive special formatting, such as a small "i" icon next to it.165 *166 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static)167 */168 info(...data: any[]): void;169 /**170 * The **`console.log()`** static method outputs a message to the console.171 *172 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)173 */174 log(...data: any[]): void;175 /**176 * The **`console.table()`** static method displays tabular data as a table.177 *178 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static)179 */180 table(tabularData?: any, properties?: string[]): void;181 /**182 * The **`console.time()`** static method starts a timer you can use to track how long an operation takes. You give each timer a unique name, and may have up to 10,000 timers running on a given page. When you call console.timeEnd() with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started.183 *184 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static)185 */186 time(label?: string): void;187 /**188 * The **`console.timeEnd()`** static method stops a timer that was previously started by calling console.time().189 *190 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static)191 */192 timeEnd(label?: string): void;193 /**194 * The **`console.timeLog()`** static method logs the current value of a timer that was previously started by calling console.time().195 *196 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static)197 */198 timeLog(label?: string, ...data: any[]): void;199 /* The **`console.timeStamp()`** static method adds a single marker to the browser's Performance tool (Firefox bug 1387528, Chrome). This lets you correlate a point in your code with the other events recorded in the timeline, such as layout and paint events. */200 timeStamp(label?: string): void;201 /**202 * The **`console.trace()`** static method outputs a stack trace to the console.203 *204 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static)205 */206 trace(...data: any[]): void;207 /**208 * The **`console.warn()`** static method outputs a warning message to the console at the "warning" log level. The message is only displayed to the user if the console is configured to display warning output. In most cases, the log level is configured within the console UI. The message may receive special formatting, such as yellow colors and a warning icon.209 *210 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static)211 */212 warn(...data: any[]): void;213}214declare const console: Console;215type BufferSource = ArrayBufferView | ArrayBuffer;216type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;217declare namespace WebAssembly {218 class CompileError extends Error {219 constructor(message?: string);220 }221 class RuntimeError extends Error {222 constructor(message?: string);223 }224 type ValueType = "anyfunc" | "externref" | "f32" | "f64" | "i32" | "i64" | "v128";225 interface GlobalDescriptor {226 value: ValueType;227 mutable?: boolean;228 }229 class Global {230 constructor(descriptor: GlobalDescriptor, value?: any);231 value: any;232 valueOf(): any;233 }234 type ImportValue = ExportValue | number;235 type ModuleImports = Record<string, ImportValue>;236 type Imports = Record<string, ModuleImports>;237 type ExportValue = Function | Global | Memory | Table;238 type Exports = Record<string, ExportValue>;239 class Instance {240 constructor(module: Module, imports?: Imports);241 readonly exports: Exports;242 }243 interface MemoryDescriptor {244 initial: number;245 maximum?: number;246 shared?: boolean;247 }248 class Memory {249 constructor(descriptor: MemoryDescriptor);250 readonly buffer: ArrayBuffer;251 grow(delta: number): number;252 }253 type ImportExportKind = "function" | "global" | "memory" | "table";254 interface ModuleExportDescriptor {255 kind: ImportExportKind;256 name: string;257 }258 interface ModuleImportDescriptor {259 kind: ImportExportKind;260 module: string;261 name: string;262 }263 abstract class Module {264 static customSections(module: Module, sectionName: string): ArrayBuffer[];265 static exports(module: Module): ModuleExportDescriptor[];266 static imports(module: Module): ModuleImportDescriptor[];267 }268 type TableKind = "anyfunc" | "externref";269 interface TableDescriptor {270 element: TableKind;271 initial: number;272 maximum?: number;273 }274 class Table {275 constructor(descriptor: TableDescriptor, value?: any);276 readonly length: number;277 get(index: number): any;278 grow(delta: number, value?: any): number;279 set(index: number, value?: any): void;280 }281 function instantiate(module: Module, imports?: Imports): Promise<Instance>;282 function validate(bytes: BufferSource): boolean;283}284/**285 * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker.286 * Available only in secure contexts.287 *288 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope)289 */290interface ServiceWorkerGlobalScope extends WorkerGlobalScope {291 DOMException: typeof DOMException;292 WorkerGlobalScope: typeof WorkerGlobalScope;293 btoa(data: string): string;294 atob(data: string): string;295 setTimeout(callback: (...args: any[]) => void, msDelay?: number): number;296 setTimeout<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;297 clearTimeout(timeoutId: number | null): void;298 setInterval(callback: (...args: any[]) => void, msDelay?: number): number;299 setInterval<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;300 clearInterval(timeoutId: number | null): void;301 queueMicrotask(task: Function): void;302 structuredClone<T>(value: T, options?: StructuredSerializeOptions): T;303 reportError(error: any): void;304 fetch(input: RequestInfo | URL, init?: RequestInit<RequestInitCfProperties>): Promise<Response>;305 self: ServiceWorkerGlobalScope;306 crypto: Crypto;307 caches: CacheStorage;308 scheduler: Scheduler;309 performance: Performance;310 Cloudflare: Cloudflare;311 readonly origin: string;312 Event: typeof Event;313 ExtendableEvent: typeof ExtendableEvent;314 CustomEvent: typeof CustomEvent;315 PromiseRejectionEvent: typeof PromiseRejectionEvent;316 FetchEvent: typeof FetchEvent;317 TailEvent: typeof TailEvent;318 TraceEvent: typeof TailEvent;319 ScheduledEvent: typeof ScheduledEvent;320 MessageEvent: typeof MessageEvent;321 CloseEvent: typeof CloseEvent;322 ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader;323 ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader;324 ReadableStream: typeof ReadableStream;325 WritableStream: typeof WritableStream;326 WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter;327 TransformStream: typeof TransformStream;328 ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy;329 CountQueuingStrategy: typeof CountQueuingStrategy;330 ErrorEvent: typeof ErrorEvent;331 MessageChannel: typeof MessageChannel;332 MessagePort: typeof MessagePort;333 EventSource: typeof EventSource;334 ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest;335 ReadableStreamDefaultController: typeof ReadableStreamDefaultController;336 ReadableByteStreamController: typeof ReadableByteStreamController;337 WritableStreamDefaultController: typeof WritableStreamDefaultController;338 TransformStreamDefaultController: typeof TransformStreamDefaultController;339 CompressionStream: typeof CompressionStream;340 DecompressionStream: typeof DecompressionStream;341 TextEncoderStream: typeof TextEncoderStream;342 TextDecoderStream: typeof TextDecoderStream;343 Headers: typeof Headers;344 Body: typeof Body;345 Request: typeof Request;346 Response: typeof Response;347 WebSocket: typeof WebSocket;348 WebSocketPair: typeof WebSocketPair;349 WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair;350 AbortController: typeof AbortController;351 AbortSignal: typeof AbortSignal;352 TextDecoder: typeof TextDecoder;353 TextEncoder: typeof TextEncoder;354 navigator: Navigator;355 Navigator: typeof Navigator;356 URL: typeof URL;357 URLSearchParams: typeof URLSearchParams;358 URLPattern: typeof URLPattern;359 Blob: typeof Blob;360 File: typeof File;361 FormData: typeof FormData;362 Crypto: typeof Crypto;363 SubtleCrypto: typeof SubtleCrypto;364 CryptoKey: typeof CryptoKey;365 CacheStorage: typeof CacheStorage;366 Cache: typeof Cache;367 FixedLengthStream: typeof FixedLengthStream;368 IdentityTransformStream: typeof IdentityTransformStream;369 HTMLRewriter: typeof HTMLRewriter;370}371declare function addEventListener<Type extends keyof WorkerGlobalScopeEventMap>(type: Type, handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, options?: EventTargetAddEventListenerOptions | boolean): void;372declare function removeEventListener<Type extends keyof WorkerGlobalScopeEventMap>(type: Type, handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, options?: EventTargetEventListenerOptions | boolean): void;373/**374 * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent().375 *376 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent)377 */378declare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean;379/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */380declare function btoa(data: string): string;381/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */382declare function atob(data: string): string;383/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */384declare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number;385/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */386declare function setTimeout<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;387/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */388declare function clearTimeout(timeoutId: number | null): void;389/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */390declare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number;391/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */392declare function setInterval<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;393/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */394declare function clearInterval(timeoutId: number | null): void;395/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */396declare function queueMicrotask(task: Function): void;397/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */398declare function structuredClone<T>(value: T, options?: StructuredSerializeOptions): T;399/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */400declare function reportError(error: any): void;401/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */402declare function fetch(input: RequestInfo | URL, init?: RequestInit<RequestInitCfProperties>): Promise<Response>;403declare const self: ServiceWorkerGlobalScope;404/**405* The Web Crypto API provides a set of low-level functions for common cryptographic tasks.406* The Workers runtime implements the full surface of this API, but with some differences in407* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms)408* compared to those implemented in most browsers.409*410* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/)411*/412declare const crypto: Crypto;413/**414* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.415*416* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)417*/418declare const caches: CacheStorage;419/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/scheduler) */420declare const scheduler: Scheduler;421/**422* The Workers runtime supports a subset of the Performance API, used to measure timing and performance,423* as well as timing of subrequests and other operations.424*425* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/)426*/427declare const performance: Performance;428declare const Cloudflare: Cloudflare;429declare const origin: string;430declare const navigator: Navigator;431interface TestController {432}433interface ExecutionContext<Props = unknown> {434 waitUntil(promise: Promise<any>): void;435 passThroughOnException(): void;436 readonly exports: Cloudflare.Exports;437 readonly props: Props;438 cache?: CacheContext;439 readonly access?: CloudflareAccessContext;440 tracing: Tracing;441 abort(reason?: any): void;442}443type ExportedHandlerFetchHandler<Env = unknown, CfHostMetadata = unknown, Props = unknown> = (request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, env: Env, ctx: ExecutionContext<Props>) => Response | Promise<Response>;444type ExportedHandlerConnectHandler<Env = unknown, Props = unknown> = (socket: Socket, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;445type ExportedHandlerTailHandler<Env = unknown, Props = unknown> = (events: TraceItem[], env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;446type ExportedHandlerTraceHandler<Env = unknown, Props = unknown> = (traces: TraceItem[], env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;447type ExportedHandlerTailStreamHandler<Env = unknown, Props = unknown> = (event: TailStream.TailEvent<TailStream.Onset>, env: Env, ctx: ExecutionContext<Props>) => TailStream.TailEventHandlerType | Promise<TailStream.TailEventHandlerType>;448type ExportedHandlerScheduledHandler<Env = unknown, Props = unknown> = (controller: ScheduledController, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;449type ExportedHandlerQueueHandler<Env = unknown, Message = unknown, Props = unknown> = (batch: MessageBatch<Message>, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;450type ExportedHandlerTestHandler<Env = unknown, Props = unknown> = (controller: TestController, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;451interface ExportedHandler<Env = unknown, QueueHandlerMessage = unknown, CfHostMetadata = unknown, Props = unknown> {452 fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata, Props>;453 connect?: ExportedHandlerConnectHandler<Env, Props>;454 tail?: ExportedHandlerTailHandler<Env, Props>;455 trace?: ExportedHandlerTraceHandler<Env, Props>;456 tailStream?: ExportedHandlerTailStreamHandler<Env, Props>;457 scheduled?: ExportedHandlerScheduledHandler<Env, Props>;458 test?: ExportedHandlerTestHandler<Env, Props>;459 email?: EmailExportedHandler<Env, Props>;460 queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage, Props>;461}462interface StructuredSerializeOptions {463 transfer?: any[];464}465declare abstract class Navigator {466 sendBeacon(url: string, body?: BodyInit): boolean;467 readonly userAgent: string;468 readonly hardwareConcurrency: number;469 readonly platform: string;470 readonly language: string;471 readonly languages: string[];472}473interface AlarmInvocationInfo {474 readonly isRetry: boolean;475 readonly retryCount: number;476 readonly scheduledTime: number;477}478interface Cloudflare {479 readonly compatibilityFlags: Record<string, boolean>;480}481interface CachePurgeError {482 code: number;483 message: string;484}485interface CachePurgeResult {486 success: boolean;487 errors: CachePurgeError[];488}489interface CachePurgeOptions {490 tags?: string[];491 pathPrefixes?: string[];492 purgeEverything?: boolean;493}494interface CacheContext {495 purge(options: CachePurgeOptions): Promise<CachePurgeResult>;496}497interface CloudflareAccessContext {498 readonly aud: string;499 getIdentity(): Promise<CloudflareAccessIdentity | undefined>;500}501declare abstract class ColoLocalActorNamespace {502 get(actorId: string): Fetcher;503}504interface DurableObject {505 fetch(request: Request): Response | Promise<Response>;506 connect?(socket: Socket): void | Promise<void>;507 alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise<void>;508 webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise<void>;509 webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise<void>;510 webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>;511}512type DurableObjectStub<T extends Rpc.DurableObjectBranded | undefined = undefined> = Fetcher<T, "alarm" | "connect" | "webSocketMessage" | "webSocketClose" | "webSocketError"> & {513 readonly id: DurableObjectId;514 readonly name?: string;515};516interface DurableObjectId {517 toString(): string;518 equals(other: DurableObjectId): boolean;519 readonly name?: string;520 readonly jurisdiction?: string;521}522declare abstract class DurableObjectNamespace<T extends Rpc.DurableObjectBranded | undefined = undefined> {523 newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId;524 idFromName(name: string): DurableObjectId;525 idFromString(id: string): DurableObjectId;526 get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub<T>;527 getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub<T>;528 jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace<T>;529}530type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high" | "us";531interface DurableObjectNamespaceNewUniqueIdOptions {532 jurisdiction?: DurableObjectJurisdiction;533}534type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "apac-ne" | "apac-se" | "oc" | "afr" | "me";535type DurableObjectRoutingMode = "primary-only";536interface DurableObjectNamespaceGetDurableObjectOptions {537 locationHint?: DurableObjectLocationHint;538 routingMode?: DurableObjectRoutingMode;539}540interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> {541}542interface DurableObjectState<Props = unknown> {543 waitUntil(promise: Promise<any>): void;544 readonly exports: Cloudflare.Exports;545 readonly props: Props;546 readonly id: DurableObjectId;547 readonly storage: DurableObjectStorage;548 container?: Container;549 facets: DurableObjectFacets;550 blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>;551 acceptWebSocket(ws: WebSocket, tags?: string[]): void;552 getWebSockets(tag?: string): WebSocket[];553 setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void;554 getWebSocketAutoResponse(): WebSocketRequestResponsePair | null;555 getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null;556 setHibernatableWebSocketEventTimeout(timeoutMs?: number): void;557 getHibernatableWebSocketEventTimeout(): number | null;558 getTags(ws: WebSocket): string[];559 abort(reason?: string): void;560}561interface DurableObjectTransaction {562 get<T = unknown>(key: string, options?: DurableObjectGetOptions): Promise<T | undefined>;563 get<T = unknown>(keys: string[], options?: DurableObjectGetOptions): Promise<Map<string, T>>;564 list<T = unknown>(options?: DurableObjectListOptions): Promise<Map<string, T>>;565 put<T>(key: string, value: T, options?: DurableObjectPutOptions): Promise<void>;566 put<T>(entries: Record<string, T>, options?: DurableObjectPutOptions): Promise<void>;567 delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>;568 delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>;569 rollback(): void;570 getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>;571 setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise<void>;572 deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>;573}574interface DurableObjectStorage {575 get<T = unknown>(key: string, options?: DurableObjectGetOptions): Promise<T | undefined>;576 get<T = unknown>(keys: string[], options?: DurableObjectGetOptions): Promise<Map<string, T>>;577 list<T = unknown>(options?: DurableObjectListOptions): Promise<Map<string, T>>;578 put<T>(key: string, value: T, options?: DurableObjectPutOptions): Promise<void>;579 put<T>(entries: Record<string, T>, options?: DurableObjectPutOptions): Promise<void>;580 delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>;581 delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>;582 deleteAll(options?: DurableObjectPutOptions): Promise<void>;583 transaction<T>(closure: (txn: DurableObjectTransaction) => Promise<T>): Promise<T>;584 getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>;585 setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise<void>;586 deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>;587 sync(): Promise<void>;588 sql: SqlStorage;589 kv: SyncKvStorage;590 transactionSync<T>(closure: () => T): T;591 getCurrentBookmark(): Promise<string>;592 getBookmarkForTime(timestamp: number | Date): Promise<string>;593 onNextSessionRestoreBookmark(bookmark: string): Promise<string>;594}595interface DurableObjectListOptions {596 start?: string;597 startAfter?: string;598 end?: string;599 prefix?: string;600 reverse?: boolean;601 limit?: number;602 allowConcurrency?: boolean;603 noCache?: boolean;604}605interface DurableObjectGetOptions {606 allowConcurrency?: boolean;607 noCache?: boolean;608}609interface DurableObjectGetAlarmOptions {610 allowConcurrency?: boolean;611}612interface DurableObjectPutOptions {613 allowConcurrency?: boolean;614 allowUnconfirmed?: boolean;615 noCache?: boolean;616}617interface DurableObjectSetAlarmOptions {618 allowConcurrency?: boolean;619 allowUnconfirmed?: boolean;620}621declare class WebSocketRequestResponsePair {622 constructor(request: string, response: string);623 get request(): string;624 get response(): string;625}626interface DurableObjectFacets {627 get<T extends Rpc.DurableObjectBranded | undefined = undefined>(name: string, getStartupOptions: () => FacetStartupOptions<T> | Promise<FacetStartupOptions<T>>): Fetcher<T>;628 abort(name: string, reason: any): void;629 delete(name: string): void;630 clone(src: string, dst: string): void;631}632interface FacetStartupOptions<T extends Rpc.DurableObjectBranded | undefined = undefined> {633 id?: DurableObjectId | string;634 class: DurableObjectClass<T>;635}636interface AnalyticsEngineDataset {637 writeDataPoint(event?: AnalyticsEngineDataPoint): void;638}639interface AnalyticsEngineDataPoint {640 indexes?: ((ArrayBuffer | string) | null)[];641 doubles?: number[];642 blobs?: ((ArrayBuffer | string) | null)[];643}644/**645 * The **`Event`** interface represents an event which takes place on an EventTarget.646 *647 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event)648 */649declare class Event {650 constructor(type: string, init?: EventInit);651 /**652 * The **`type`** read-only property of the Event interface returns a string containing the event's type. It is set when the event is constructed and is the name commonly used to refer to the specific event, such as click, load, or error.653 *654 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type)655 */656 get type(): string;657 /**658 * The **`eventPhase`** read-only property of the Event interface indicates which phase of the event flow is currently being evaluated.659 *660 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase)661 */662 get eventPhase(): number;663 /**664 * The read-only **`composed`** property of the Event interface returns a boolean value which indicates whether or not the event will propagate across the shadow DOM boundary into the standard DOM.665 *666 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed)667 */668 get composed(): boolean;669 /**670 * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not.671 *672 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles)673 */674 get bubbles(): boolean;675 /**676 * The **`cancelable`** read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened.677 *678 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable)679 */680 get cancelable(): boolean;681 /**682 * The **`defaultPrevented`** read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event.683 *684 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented)685 */686 get defaultPrevented(): boolean;687 /**688 * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not.689 * @deprecated690 *691 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue)692 */693 get returnValue(): boolean;694 /**695 * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached.696 *697 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget)698 */699 get currentTarget(): EventTarget | undefined;700 /**701 * The read-only **`target`** property of the Event interface is a reference to the object onto which the event was dispatched. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event.702 *703 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target)704 */705 get target(): EventTarget | undefined;706 /**707 * The deprecated **`Event.srcElement`** is an alias for the Event.target property. Use Event.target instead.708 * @deprecated709 *710 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement)711 */712 get srcElement(): EventTarget | undefined;713 /**714 * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created.715 *716 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp)717 */718 get timeStamp(): number;719 /**720 * The **`isTrusted`** read-only property of the Event interface is a boolean value that is true when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and false when the event was dispatched via EventTarget.dispatchEvent(). The only exception is the click event, which initializes the isTrusted property to false in user agents.721 *722 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted)723 */724 get isTrusted(): boolean;725 /**726 * The **`cancelBubble`** property of the Event interface is deprecated. Use Event.stopPropagation() instead. Setting its value to true before returning from an event handler prevents propagation of the event. In later implementations, setting this to false does nothing. See Browser compatibility for details.727 * @deprecated728 *729 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble)730 */731 get cancelBubble(): boolean;732 /**733 * The **`cancelBubble`** property of the Event interface is deprecated. Use Event.stopPropagation() instead. Setting its value to true before returning from an event handler prevents propagation of the event. In later implementations, setting this to false does nothing. See Browser compatibility for details.734 * @deprecated735 *736 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble)737 */738 set cancelBubble(value: boolean);739 /**740 * The **`stopImmediatePropagation()`** method of the Event interface prevents other listeners of the same event from being called.741 *742 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation)743 */744 stopImmediatePropagation(): void;745 /**746 * The **`preventDefault()`** method of the Event interface tells the user agent that the event is being explicitly handled, so its default action, such as page scrolling, link navigation, or pasting text, should not be taken.747 *748 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault)749 */750 preventDefault(): void;751 /**752 * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed. If you want to stop those behaviors, see the preventDefault() method. It also does not prevent propagation to other event-handlers of the current element. If you want to stop those, see stopImmediatePropagation().753 *754 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation)755 */756 stopPropagation(): void;757 /**758 * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. This does not include nodes in shadow trees if the shadow root was created with its ShadowRoot.mode closed.759 *760 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath)761 */762 composedPath(): EventTarget[];763 static readonly NONE: number;764 static readonly CAPTURING_PHASE: number;765 static readonly AT_TARGET: number;766 static readonly BUBBLING_PHASE: number;767}768interface EventInit {769 bubbles?: boolean;770 cancelable?: boolean;771 composed?: boolean;772}773type EventListener<EventType extends Event = Event> = (event: EventType) => void;774interface EventListenerObject<EventType extends Event = Event> {775 handleEvent(event: EventType): void;776}777type EventListenerOrEventListenerObject<EventType extends Event = Event> = EventListener<EventType> | EventListenerObject<EventType>;778/**779 * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them. In other words, any target of events implements the three methods associated with this interface.780 *781 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget)782 */783declare class EventTarget<EventMap extends Record<string, Event> = Record<string, Event>> {784 constructor();785 /**786 * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.787 *788 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener)789 */790 addEventListener<Type extends keyof EventMap>(type: Type, handler: EventListenerOrEventListenerObject<EventMap[Type]>, options?: EventTargetAddEventListenerOptions | boolean): void;791 /**792 * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. The event listener to be removed is identified using a combination of the event type, the event listener function itself, and various optional options that may affect the matching process; see Matching event listeners for removal.793 *794 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener)795 */796 removeEventListener<Type extends keyof EventMap>(type: Type, handler: EventListenerOrEventListenerObject<EventMap[Type]>, options?: EventTargetEventListenerOptions | boolean): void;797 /**798 * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent().799 *800 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent)801 */802 dispatchEvent(event: EventMap[keyof EventMap]): boolean;803}804interface EventTargetEventListenerOptions {805 capture?: boolean;806}807interface EventTargetAddEventListenerOptions {808 capture?: boolean;809 passive?: boolean;810 once?: boolean;811 signal?: AbortSignal;812}813interface EventTargetHandlerObject {814 handleEvent: (event: Event) => any | undefined;815}816/**817 * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired.818 *819 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController)820 */821declare class AbortController {822 constructor();823 /**824 * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired.825 *826 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal)827 */828 get signal(): AbortSignal;829 /**830 * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. This is able to abort fetch requests, the consumption of any response bodies, or streams.831 *832 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort)833 */834 abort(reason?: any): void;835}836/**837 * The **`AbortSignal`** interface represents a signal object that allows you to communicate with an asynchronous operation (such as a fetch request) and abort it if required via an AbortController object.838 *839 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal)840 */841declare abstract class AbortSignal extends EventTarget {842 /**843 * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an abort event).844 *845 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static)846 */847 static abort(reason?: any): AbortSignal;848 /**849 * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time.850 *851 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static)852 */853 static timeout(delay: number): AbortSignal;854 /**855 * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. The returned abort signal is aborted when any of the input iterable abort signals are aborted. The abort reason will be set to the reason of the first signal that is aborted. If any of the given abort signals are already aborted then so will be the returned AbortSignal.856 *857 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static)858 */859 static any(signals: AbortSignal[]): AbortSignal;860 /**861 * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (true) or not (false).862 *863 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted)864 */865 get aborted(): boolean;866 /**867 * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason.868 *869 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason)870 */871 get reason(): any;872 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */873 get onabort(): any | null;874 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */875 set onabort(value: any | null);876 /**877 * The **`throwIfAborted()`** method throws the signal's abort reason if the signal has been aborted; otherwise it does nothing.878 *879 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted)880 */881 throwIfAborted(): void;882}883/**884 * The **`Scheduler`** interface of the Prioritized Task Scheduling API provides methods for scheduling prioritized tasks.885 *886 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Scheduler)887 */888interface Scheduler {889 wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>;890}891interface SchedulerWaitOptions {892 signal?: AbortSignal;893}894/**895 * The **`ExtendableEvent`** interface extends the lifetime of the install and activate events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like FetchEvent) are not dispatched until it upgrades database schemas and deletes the outdated cache entries.896 *897 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent)898 */899declare abstract class ExtendableEvent extends Event {900 /**901 * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. It can also be used to detect whether that work was successful. In service workers, waitUntil() tells the browser that work is ongoing until the promise settles, and it shouldn't terminate the service worker if it wants that work to complete.902 *903 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil)904 */905 waitUntil(promise: Promise<any>): void;906}907/**908 * The **`CustomEvent`** interface can be used to attach custom data to an event generated by an application.909 *910 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent)911 */912declare class CustomEvent<T = any> extends Event {913 constructor(type: string, init?: CustomEventCustomEventInit);914 /**915 * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event.916 *917 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail)918 */919 get detail(): T;920}921interface CustomEventCustomEventInit {922 bubbles?: boolean;923 cancelable?: boolean;924 composed?: boolean;925 detail?: any;926}927/**928 * The **`Blob`** interface represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data.929 *930 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob)931 */932declare class Blob {933 constructor(bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions);934 /**935 * The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes.936 *937 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size)938 */939 get size(): number;940 /**941 * The **`type`** read-only property of the Blob interface returns the MIME type of the file.942 *943 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type)944 */945 get type(): string;946 /**947 * The **`slice()`** method of the Blob interface creates and returns a new Blob object which contains data from a subset of the blob on which it's called.948 *949 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice)950 */951 slice(start?: number, end?: number, type?: string): Blob;952 /**953 * The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer.954 *955 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer)956 */957 arrayBuffer(): Promise<ArrayBuffer>;958 /**959 * The **`bytes()`** method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes.960 *961 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes)962 */963 bytes(): Promise<Uint8Array>;964 /**965 * The **`text()`** method of the Blob interface returns a Promise that resolves with a string containing the contents of the blob, interpreted as UTF-8.966 *967 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text)968 */969 text(): Promise<string>;970 /**971 * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the Blob.972 *973 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream)974 */975 stream(): ReadableStream;976}977interface BlobOptions {978 type?: string;979}980/**981 * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content.982 *983 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File)984 */985declare class File extends Blob {986 constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions);987 /**988 * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. For security reasons, the path is excluded from this property.989 *990 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name)991 */992 get name(): string;993 /**994 * The **`lastModified`** read-only property of the File interface provides 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.995 *996 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified)997 */998 get lastModified(): number;999}1000interface FileOptions {1001 type?: string;1002 lastModified?: number;1003}1004/**1005* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.1006*1007* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)1008*/1009declare abstract class CacheStorage {1010 /**1011 * The **`open()`** method of the CacheStorage interface returns a Promise that resolves to the Cache object matching the cacheName.1012 *1013 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open)1014 */1015 open(cacheName: string): Promise<Cache>;1016 readonly default: Cache;1017}1018/**1019* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.1020*1021* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)1022*/1023declare abstract class Cache {1024 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */1025 delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<boolean>;1026 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */1027 match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<Response | undefined>;1028 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */1029 put(request: RequestInfo | URL, response: Response): Promise<void>;1030}1031interface CacheQueryOptions {1032 ignoreMethod?: boolean;1033}1034/**1035* The Web Crypto API provides a set of low-level functions for common cryptographic tasks.1036* The Workers runtime implements the full surface of this API, but with some differences in1037* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms)1038* compared to those implemented in most browsers.1039*1040* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/)1041*/1042declare abstract class Crypto {1043 /**1044 * The **`Crypto.subtle`** read-only property returns a SubtleCrypto which can then be used to perform low-level cryptographic operations.1045 * Available only in secure contexts.1046 *1047 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle)1048 */1049 get subtle(): SubtleCrypto;1050 /**1051 * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning).1052 *1053 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues)1054 */1055 getRandomValues<T extends Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | BigInt64Array | BigUint64Array>(buffer: T): T;1056 /**1057 * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator.1058 * Available only in secure contexts.1059 *1060 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID)1061 */1062 randomUUID(): string;1063 DigestStream: typeof DigestStream;1064}1065/**1066 * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions.1067 * Available only in secure contexts.1068 *1069 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto)1070 */1071declare abstract class SubtleCrypto {1072 /**1073 * The **`encrypt()`** method of the SubtleCrypto interface encrypts data.1074 *1075 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt)1076 */1077 encrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;1078 /**1079 * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. It takes as arguments a key to decrypt with, some optional extra parameters, and the data to decrypt (also known as "ciphertext"). It returns a Promise which will be fulfilled with the decrypted data (also known as "plaintext").1080 *1081 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt)1082 */1083 decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;1084 /**1085 * The **`sign()`** method of the SubtleCrypto interface generates a digital signature.1086 *1087 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign)1088 */1089 sign(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;1090 /**1091 * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature.1092 *1093 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify)1094 */1095 verify(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView): Promise<boolean>;1096 /**1097 * The **`digest()`** method of the SubtleCrypto interface generates a digest of the given data, using the specified hash function. A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value.1098 *1099 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest)1100 */1101 digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;1102 /**1103 * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms).1104 *1105 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey)1106 */1107 generateKey(algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey | CryptoKeyPair>;1108 /**1109 * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key.1110 *1111 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey)1112 */1113 deriveKey(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;1114 /**1115 * The **`deriveBits()`** method of the SubtleCrypto interface can be used to derive an array of bits from a base key.1116 *1117 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits)1118 */1119 deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise<ArrayBuffer>;1120 /**1121 * The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API.1122 *1123 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey)1124 */1125 importKey(format: string, keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;1126 /**1127 * The **`exportKey()`** method of the SubtleCrypto interface exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format.1128 *1129 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey)1130 */1131 exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>;1132 /**1133 * The **`wrapKey()`** method of the SubtleCrypto interface "wraps" a key. This means that it exports the key in an external, portable format, then encrypts the exported key. Wrapping a key helps protect it in untrusted environments, such as inside an otherwise unprotected data store or in transmission over an unprotected network.1134 *1135 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey)1136 */1137 wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise<ArrayBuffer>;1138 /**1139 * The **`unwrapKey()`** method of the SubtleCrypto interface "unwraps" a key. This means that it takes as its input a key that has been exported and then encrypted (also called "wrapped"). It decrypts the key and then imports it, returning a CryptoKey object that can be used in the Web Crypto API.1140 *1141 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey)1142 */1143 unwrapKey(format: string, wrappedKey: ArrayBuffer | ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;1144 timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean;1145}1146/**1147 * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods generateKey(), deriveKey(), importKey(), or unwrapKey().1148 * Available only in secure contexts.1149 *1150 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey)1151 */1152declare abstract class CryptoKey {1153 /**1154 * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. It can have the following values:1155 *1156 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type)1157 */1158 readonly type: string;1159 /**1160 * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using SubtleCrypto.exportKey() or SubtleCrypto.wrapKey().1161 *1162 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable)1163 */1164 readonly extractable: boolean;1165 /**1166 * The read-only **`algorithm`** property of the CryptoKey interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters.1167 *1168 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm)1169 */1170 readonly algorithm: CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm;1171 /**1172 * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key.1173 *1174 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages)1175 */1176 readonly usages: string[];1177}1178interface CryptoKeyPair {1179 publicKey: CryptoKey;1180 privateKey: CryptoKey;1181}1182interface JsonWebKey {1183 kty: string;1184 use?: string;1185 key_ops?: string[];1186 alg?: string;1187 ext?: boolean;1188 crv?: string;1189 x?: string;1190 y?: string;1191 d?: string;1192 n?: string;1193 e?: string;1194 p?: string;1195 q?: string;1196 dp?: string;1197 dq?: string;1198 qi?: string;1199 oth?: RsaOtherPrimesInfo[];1200 k?: string;1201}1202interface RsaOtherPrimesInfo {1203 r?: string;1204 d?: string;1205 t?: string;1206}1207interface SubtleCryptoDeriveKeyAlgorithm {1208 name: string;1209 salt?: (ArrayBuffer | ArrayBufferView);1210 iterations?: number;1211 hash?: (string | SubtleCryptoHashAlgorithm);1212 $public?: CryptoKey;1213 info?: (ArrayBuffer | ArrayBufferView);1214}1215interface SubtleCryptoEncryptAlgorithm {1216 name: string;1217 iv?: (ArrayBuffer | ArrayBufferView);1218 additionalData?: (ArrayBuffer | ArrayBufferView);1219 tagLength?: number;1220 counter?: (ArrayBuffer | ArrayBufferView);1221 length?: number;1222 label?: (ArrayBuffer | ArrayBufferView);1223}1224interface SubtleCryptoGenerateKeyAlgorithm {1225 name: string;1226 hash?: (string | SubtleCryptoHashAlgorithm);1227 modulusLength?: number;1228 publicExponent?: (ArrayBuffer | ArrayBufferView);1229 length?: number;1230 namedCurve?: string;1231}1232interface SubtleCryptoHashAlgorithm {1233 name: string;1234}1235interface SubtleCryptoImportKeyAlgorithm {1236 name: string;1237 hash?: (string | SubtleCryptoHashAlgorithm);1238 length?: number;1239 namedCurve?: string;1240 compressed?: boolean;1241}1242interface SubtleCryptoSignAlgorithm {1243 name: string;1244 hash?: (string | SubtleCryptoHashAlgorithm);1245 dataLength?: number;1246 saltLength?: number;1247}1248interface CryptoKeyKeyAlgorithm {1249 name: string;1250}1251interface CryptoKeyAesKeyAlgorithm {1252 name: string;1253 length: number;1254}1255interface CryptoKeyHmacKeyAlgorithm {1256 name: string;1257 hash: CryptoKeyKeyAlgorithm;1258 length: number;1259}1260interface CryptoKeyRsaKeyAlgorithm {1261 name: string;1262 modulusLength: number;1263 publicExponent: ArrayBuffer | ArrayBufferView;1264 hash?: CryptoKeyKeyAlgorithm;1265}1266interface CryptoKeyEllipticKeyAlgorithm {1267 name: string;1268 namedCurve: string;1269}1270interface CryptoKeyArbitraryKeyAlgorithm {1271 name: string;1272 hash?: CryptoKeyKeyAlgorithm;1273 namedCurve?: string;1274 length?: number;1275}1276declare class DigestStream extends WritableStream<ArrayBuffer | ArrayBufferView> {1277 constructor(algorithm: string | SubtleCryptoHashAlgorithm);1278 readonly digest: Promise<ArrayBuffer>;1279 get bytesWritten(): number | bigint;1280}1281/**1282 * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as UTF-8, ISO-8859-2, or GBK. A decoder takes an array of bytes as input and returns a JavaScript string.1283 *1284 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder)1285 */1286declare class TextDecoder {1287 constructor(label?: string, options?: TextDecoderConstructorOptions);1288 /**1289 * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter.1290 *1291 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode)1292 */1293 decode(input?: (ArrayBuffer | ArrayBufferView), options?: TextDecoderDecodeOptions): string;1294 get encoding(): string;1295 get fatal(): boolean;1296 get ignoreBOM(): boolean;1297}1298/**1299 * The **`TextEncoder`** interface enables you to encode a JavaScript string using UTF-8.1300 *1301 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder)1302 */1303declare class TextEncoder {1304 constructor();1305 /**1306 * The **`TextEncoder.encode()`** method takes a string as input, and returns a Uint8Array containing the string encoded using UTF-8.1307 *1308 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode)1309 */1310 encode(input?: string): Uint8Array;1311 /**1312 * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns an object indicating the progress of the encoding. This is potentially more performant than the encode() method — especially when the target buffer is a view into a Wasm heap.1313 *1314 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto)1315 */1316 encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult;1317 get encoding(): string;1318}1319interface TextDecoderConstructorOptions {1320 fatal: boolean;1321 ignoreBOM: boolean;1322}1323interface TextDecoderDecodeOptions {1324 stream: boolean;1325}1326interface TextEncoderEncodeIntoResult {1327 read: number;1328 written: number;1329}1330/**1331 * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files.1332 *1333 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent)1334 */1335declare class ErrorEvent extends Event {1336 constructor(type: string, init?: ErrorEventErrorEventInit);1337 /**1338 * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred.1339 *1340 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename)1341 */1342 get filename(): string;1343 /**1344 * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem.1345 *1346 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message)1347 */1348 get message(): string;1349 /**1350 * The **`lineno`** read-only property of the ErrorEvent interface returns an integer containing the line number of the script file on which the error occurred.1351 *1352 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno)1353 */1354 get lineno(): number;1355 /**1356 * The **`colno`** read-only property of the ErrorEvent interface returns an integer containing the column number of the script file on which the error occurred.1357 *1358 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno)1359 */1360 get colno(): number;1361 /**1362 * The **`error`** read-only property of the ErrorEvent interface returns a JavaScript value, such as an Error or DOMException, representing the error associated with this event.1363 *1364 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error)1365 */1366 get error(): any;1367}1368interface ErrorEventErrorEventInit {1369 message?: string;1370 filename?: string;1371 lineno?: number;1372 colno?: number;1373 error?: any;1374}1375/**1376 * The **`MessageEvent`** interface represents a message received by a target object.1377 *1378 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent)1379 */1380declare class MessageEvent extends Event {1381 constructor(type: string, initializer: MessageEventInit);1382 /**1383 * The **`data`** read-only property of the MessageEvent interface represents the data sent by the message emitter.1384 *1385 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data)1386 */1387 readonly data: any;1388 /**1389 * The **`origin`** read-only property of the MessageEvent interface is a string representing the origin of the message emitter.1390 *1391 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin)1392 */1393 readonly origin: string | null;1394 /**1395 * The **`lastEventId`** read-only property of the MessageEvent interface is a string representing a unique ID for the event.1396 *1397 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId)1398 */1399 readonly lastEventId: string;1400 /**1401 * The **`source`** read-only property of the MessageEvent interface is a MessageEventSource (which can be a WindowProxy, MessagePort, or ServiceWorker object) representing the message emitter.1402 *1403 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source)1404 */1405 readonly source: MessagePort | null;1406 /**1407 * The **`ports`** read-only property of the MessageEvent interface is an array of MessagePort objects containing all MessagePort objects sent with the message, in order.1408 *1409 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports)1410 */1411 readonly ports: MessagePort[];1412}1413interface MessageEventInit {1414 data: ArrayBuffer | string;1415}1416/**1417 * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. These events are particularly useful for telemetry and debugging purposes.1418 *1419 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent)1420 */1421declare abstract class PromiseRejectionEvent extends Event {1422 /**1423 * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript Promise which was rejected. You can examine the event's PromiseRejectionEvent.reason property to learn why the promise was rejected.1424 *1425 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise)1426 */1427 readonly promise: Promise<any>;1428 /**1429 * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). This in theory provides information about why the promise was rejected.1430 *1431 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason)1432 */1433 readonly reason: any;1434}1435/**1436 * The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the fetch(), XMLHttpRequest.send() or navigator.sendBeacon() methods. It uses the same format a form would use if the encoding type were set to "multipart/form-data".1437 *1438 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData)1439 */1440declare class FormData {1441 constructor();1442 /**1443 * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.1444 *1445 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append)1446 */1447 append(name: string, value: string | Blob): void;1448 /**1449 * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.1450 *1451 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append)1452 */1453 append(name: string, value: string): void;1454 /**1455 * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.1456 *1457 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append)1458 */1459 append(name: string, value: Blob, filename?: string): void;1460 /**1461 * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a FormData object.1462 *1463 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete)1464 */1465 delete(name: string): void;1466 /**1467 * The **`get()`** method of the FormData interface 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.1468 *1469 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get)1470 */1471 get(name: string): (File | string) | null;1472 /**1473 * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a FormData object.1474 *1475 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll)1476 */1477 getAll(name: string): (File | string)[];1478 /**1479 * The **`has()`** method of the FormData interface returns whether a FormData object contains a certain key.1480 *1481 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has)1482 */1483 has(name: string): boolean;1484 /**1485 * The **`set()`** method of the FormData interface sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist.1486 *1487 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set)1488 */1489 set(name: string, value: string | Blob): void;1490 /**1491 * The **`set()`** method of the FormData interface sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist.1492 *1493 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set)1494 */1495 set(name: string, value: string): void;1496 /**1497 * The **`set()`** method of the FormData interface sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist.1498 *1499 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set)1500 */1501 set(name: string, value: Blob, filename?: string): void;1502 entries(): IterableIterator<[1503 key: string,1504 value: File | string1505 ]>;1506 keys(): IterableIterator<string>;1507 values(): IterableIterator<(File | string)>;1508 forEach<This = unknown>(callback: (this: This, value: File | string, key: string, parent: FormData) => void, thisArg?: This): void;1509 [Symbol.iterator](): IterableIterator<[1510 key: string,1511 value: File | string1512 ]>;1513}1514interface ContentOptions {1515 html?: boolean;1516}1517declare class HTMLRewriter {1518 constructor();1519 on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter;1520 onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter;1521 transform(response: Response): Response;1522}1523interface HTMLRewriterElementContentHandlers {1524 element?(element: Element): void | Promise<void>;1525 comments?(comment: Comment): void | Promise<void>;1526 text?(element: Text): void | Promise<void>;1527}1528interface HTMLRewriterDocumentContentHandlers {1529 doctype?(doctype: Doctype): void | Promise<void>;1530 comments?(comment: Comment): void | Promise<void>;1531 text?(text: Text): void | Promise<void>;1532 end?(end: DocumentEnd): void | Promise<void>;1533}1534interface Doctype {1535 readonly name: string | null;1536 readonly publicId: string | null;1537 readonly systemId: string | null;1538}1539interface Element {1540 tagName: string;1541 readonly attributes: IterableIterator<string[]>;1542 readonly removed: boolean;1543 readonly namespaceURI: string;1544 getAttribute(name: string): string | null;1545 hasAttribute(name: string): boolean;1546 setAttribute(name: string, value: string): Element;1547 removeAttribute(name: string): Element;1548 before(content: string | ReadableStream | Response, options?: ContentOptions): Element;1549 after(content: string | ReadableStream | Response, options?: ContentOptions): Element;1550 prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element;1551 append(content: string | ReadableStream | Response, options?: ContentOptions): Element;1552 replace(content: string | ReadableStream | Response, options?: ContentOptions): Element;1553 remove(): Element;1554 removeAndKeepContent(): Element;1555 setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element;1556 onEndTag(handler: (tag: EndTag) => void | Promise<void>): void;1557}1558interface EndTag {1559 name: string;1560 before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag;1561 after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag;1562 remove(): EndTag;1563}1564interface Comment {1565 text: string;1566 readonly removed: boolean;1567 before(content: string, options?: ContentOptions): Comment;1568 after(content: string, options?: ContentOptions): Comment;1569 replace(content: string, options?: ContentOptions): Comment;1570 remove(): Comment;1571}1572interface Text {1573 readonly text: string;1574 readonly lastInTextNode: boolean;1575 readonly removed: boolean;1576 before(content: string | ReadableStream | Response, options?: ContentOptions): Text;1577 after(content: string | ReadableStream | Response, options?: ContentOptions): Text;1578 replace(content: string | ReadableStream | Response, options?: ContentOptions): Text;1579 remove(): Text;1580}1581interface DocumentEnd {1582 append(content: string, options?: ContentOptions): DocumentEnd;1583}1584/**1585 * This is the event type for fetch events dispatched on the service worker global scope. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the event.respondWith() method, which allows us to provide a response to this fetch.1586 *1587 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent)1588 */1589declare abstract class FetchEvent extends ExtendableEvent {1590 /**1591 * The **`request`** read-only property of the FetchEvent interface returns the Request that triggered the event handler.1592 *1593 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request)1594 */1595 readonly request: Request;1596 /**1597 * The **`respondWith()`** method of FetchEvent prevents the browser's default fetch handling, and allows you to provide a promise for a Response yourself.1598 *1599 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith)1600 */1601 respondWith(promise: Response | Promise<Response>): void;1602 passThroughOnException(): void;1603}1604type HeadersInit = Headers | Iterable<Iterable<string>> | Record<string, string>;1605/**1606 * The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing headers from the list of the request's headers.1607 *1608 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers)1609 */1610declare class Headers {1611 constructor(init?: HeadersInit);1612 /**1613 * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a Headers object with a given name. If the requested header doesn't exist in the Headers object, it returns null.1614 *1615 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get)1616 */1617 get(name: string): string | null;1618 getAll(name: string): string[];1619 /**1620 * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. This allows Headers objects to handle having multiple Set-Cookie headers, which wasn't possible prior to its implementation.1621 *1622 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie)1623 */1624 getSetCookie(): string[];1625 /**1626 * The **`has()`** method of the Headers interface returns a boolean stating whether a Headers object contains a certain header.1627 *1628 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has)1629 */1630 has(name: string): boolean;1631 /**1632 * The **`set()`** method of the Headers interface sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist.1633 *1634 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set)1635 */1636 set(name: string, value: string): void;1637 /**1638 * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a Headers object, or adds the header if it does not already exist.1639 *1640 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append)1641 */1642 append(name: string, value: string): void;1643 /**1644 * The **`delete()`** method of the Headers interface deletes a header from the current Headers object.1645 *1646 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete)1647 */1648 delete(name: string): void;1649 forEach<This = unknown>(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void;1650 entries(): IterableIterator<[1651 key: string,1652 value: string1653 ]>;1654 keys(): IterableIterator<string>;1655 values(): IterableIterator<string>;1656 [Symbol.iterator](): IterableIterator<[1657 key: string,1658 value: string1659 ]>;1660}1661type BodyInit = ReadableStream<Uint8Array> | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData | Iterable<ArrayBuffer | ArrayBufferView> | AsyncIterable<ArrayBuffer | ArrayBufferView>;1662declare abstract class Body {1663 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */1664 get body(): ReadableStream | null;1665 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */1666 get bodyUsed(): boolean;1667 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */1668 arrayBuffer(): Promise<ArrayBuffer>;1669 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */1670 bytes(): Promise<Uint8Array>;1671 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */1672 text(): Promise<string>;1673 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */1674 json<T>(): Promise<T>;1675 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */1676 formData(): Promise<FormData>;1677 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */1678 blob(): Promise<Blob>;1679}1680/**1681 * The **`Response`** interface of the Fetch API represents the response to a request.1682 *1683 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)1684 */1685declare var Response: {1686 prototype: Response;1687 new (body?: BodyInit | null, init?: ResponseInit): Response;1688 error(): Response;1689 redirect(url: string, status?: number): Response;1690 json(any: any, maybeInit?: (ResponseInit | Response)): Response;1691};1692/**1693 * The **`Response`** interface of the Fetch API represents the response to a request.1694 *1695 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)1696 */1697interface Response extends Body {1698 /**1699 * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable.1700 *1701 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone)1702 */1703 clone(): Response;1704 /**1705 * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response.1706 *1707 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status)1708 */1709 status: number;1710 /**1711 * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status.1712 *1713 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText)1714 */1715 statusText: string;1716 /**1717 * The **`headers`** read-only property of the Response interface contains the Headers object associated with the response.1718 *1719 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers)1720 */1721 headers: Headers;1722 /**1723 * The **`ok`** read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not.1724 *1725 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok)1726 */1727 ok: boolean;1728 /**1729 * The **`redirected`** read-only property of the Response interface indicates whether or not the response is the result of a request you made which was redirected.1730 *1731 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected)1732 */1733 redirected: boolean;1734 /**1735 * The **`url`** read-only property of the Response interface contains the URL of the response. The value of the url property will be the final URL obtained after any redirects.1736 *1737 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url)1738 */1739 url: string;1740 webSocket: WebSocket | null;1741 cf: any | undefined;1742 /**1743 * The **`type`** read-only property of the Response interface contains the type of the response. The type determines whether scripts are able to access the response body and headers.1744 *1745 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type)1746 */1747 type: "default" | "error";1748}1749interface ResponseInit {1750 status?: number;1751 statusText?: string;1752 headers?: HeadersInit;1753 cf?: any;1754 webSocket?: (WebSocket | null);1755 encodeBody?: "automatic" | "manual";1756}1757type RequestInfo<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>> = Request<CfHostMetadata, Cf> | string;1758/**1759 * The **`Request`** interface of the Fetch API represents a resource request.1760 *1761 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request)1762 */1763declare var Request: {1764 prototype: Request;1765 new <CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>>(input: RequestInfo<CfProperties> | URL, init?: RequestInit<Cf>): Request<CfHostMetadata, Cf>;1766};1767/**1768 * The **`Request`** interface of the Fetch API represents a resource request.1769 *1770 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request)1771 */1772interface Request<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>> extends Body {1773 /**1774 * The **`clone()`** method of the Request interface creates a copy of the current Request object.1775 *1776 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone)1777 */1778 clone(): Request<CfHostMetadata, Cf>;1779 /**1780 * The **`method`** read-only property of the Request interface contains the request's method (GET, POST, etc.)1781 *1782 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method)1783 */1784 method: string;1785 /**1786 * The **`url`** read-only property of the Request interface contains the URL of the request.1787 *1788 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url)1789 */1790 url: string;1791 /**1792 * The **`headers`** read-only property of the Request interface contains the Headers object associated with the request.1793 *1794 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers)1795 */1796 headers: Headers;1797 /**1798 * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled.1799 *1800 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect)1801 */1802 redirect: string;1803 fetcher: Fetcher | null;1804 /**1805 * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request.1806 *1807 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal)1808 */1809 signal: AbortSignal;1810 cf?: Cf;1811 /**1812 * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request.1813 *1814 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity)1815 */1816 integrity: string;1817 /**1818 * The **`keepalive`** read-only property of the Request interface contains the request's keepalive setting (true or false), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete.1819 *1820 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive)1821 */1822 keepalive: boolean;1823 /**1824 * The **`cache`** read-only property of the Request interface contains the cache mode of the request. It controls how the request will interact with the browser's HTTP cache.1825 *1826 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache)1827 */1828 cache?: "no-store" | "no-cache";1829}1830interface RequestInit<Cf = CfProperties> {1831 /* A string to set request's method. */1832 method?: string;1833 /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */1834 headers?: HeadersInit;1835 /* A BodyInit object or null to set request's body. */1836 body?: BodyInit | null;1837 /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */1838 redirect?: string;1839 fetcher?: (Fetcher | null);1840 cf?: Cf;1841 /* A string indicating how the request will interact with the browser's cache to set request's cache. */1842 cache?: "no-store" | "no-cache";1843 /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */1844 integrity?: string;1845 /* An AbortSignal to set request's signal. */1846 signal?: (AbortSignal | null);1847 encodeResponseBody?: "automatic" | "manual";1848}1849type Service<T extends (new (...args: any[]) => Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler<any, any, any> | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher<InstanceType<T>> : T extends Rpc.WorkerEntrypointBranded ? Fetcher<T> : T extends Exclude<Rpc.EntrypointBranded, Rpc.WorkerEntrypointBranded> ? never : Fetcher<undefined>;1850type Fetcher<T extends Rpc.EntrypointBranded | undefined = undefined, Reserved extends string = never> = (T extends Rpc.EntrypointBranded ? Rpc.Provider<T, Reserved | "fetch" | "connect"> : unknown) & {1851 fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;1852 connect(address: SocketAddress | string, options?: SocketOptions): Socket;1853};1854interface KVNamespaceListKey<Metadata, Key extends string = string> {1855 name: Key;1856 expiration?: number;1857 metadata?: Metadata;1858}1859type KVNamespaceListResult<Metadata, Key extends string = string> = {1860 list_complete: false;1861 keys: KVNamespaceListKey<Metadata, Key>[];1862 cursor: string;1863 cacheStatus: string | null;1864} | {1865 list_complete: true;1866 keys: KVNamespaceListKey<Metadata, Key>[];1867 cacheStatus: string | null;1868};1869interface KVNamespace<Key extends string = string> {1870 get(key: Key, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<string | null>;1871 get(key: Key, type: "text"): Promise<string | null>;1872 get<ExpectedValue = unknown>(key: Key, type: "json"): Promise<ExpectedValue | null>;1873 get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>;1874 get(key: Key, type: "stream"): Promise<ReadableStream | null>;1875 get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise<string | null>;1876 get<ExpectedValue = unknown>(key: Key, options?: KVNamespaceGetOptions<"json">): Promise<ExpectedValue | null>;1877 get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise<ArrayBuffer | null>;1878 get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise<ReadableStream | null>;1879 get(key: Array<Key>, type: "text"): Promise<Map<string, string | null>>;1880 get<ExpectedValue = unknown>(key: Array<Key>, type: "json"): Promise<Map<string, ExpectedValue | null>>;1881 get(key: Array<Key>, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<Map<string, string | null>>;1882 get(key: Array<Key>, options?: KVNamespaceGetOptions<"text">): Promise<Map<string, string | null>>;1883 get<ExpectedValue = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<"json">): Promise<Map<string, ExpectedValue | null>>;1884 list<Metadata = unknown>(options?: KVNamespaceListOptions): Promise<KVNamespaceListResult<Metadata, Key>>;1885 put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise<void>;1886 getWithMetadata<Metadata = unknown>(key: Key, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;1887 getWithMetadata<Metadata = unknown>(key: Key, type: "text"): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;1888 getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Key, type: "json"): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>;1889 getWithMetadata<Metadata = unknown>(key: Key, type: "arrayBuffer"): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>;1890 getWithMetadata<Metadata = unknown>(key: Key, type: "stream"): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>;1891 getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"text">): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;1892 getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"json">): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>;1893 getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"arrayBuffer">): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>;1894 getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"stream">): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>;1895 getWithMetadata<Metadata = unknown>(key: Array<Key>, type: "text"): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;1896 getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Array<Key>, type: "json"): Promise<Map<string, KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>>;1897 getWithMetadata<Metadata = unknown>(key: Array<Key>, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;1898 getWithMetadata<Metadata = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<"text">): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;1899 getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<"json">): Promise<Map<string, KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>>;1900 delete(key: Key): Promise<void>;1901}1902interface KVNamespaceListOptions {1903 limit?: number;1904 prefix?: (string | null);1905 cursor?: (string | null);1906}1907interface KVNamespaceGetOptions<Type> {1908 type: Type;1909 cacheTtl?: number;1910}1911interface KVNamespacePutOptions {1912 expiration?: number;1913 expirationTtl?: number;1914 metadata?: (any | null);1915}1916interface KVNamespaceGetWithMetadataResult<Value, Metadata> {1917 value: Value | null;1918 metadata: Metadata | null;1919 cacheStatus: string | null;1920}1921type QueueContentType = "text" | "bytes" | "json" | "v8";1922interface Queue<Body = unknown> {1923 metrics(): Promise<QueueMetrics>;1924 send(message: Body, options?: QueueSendOptions): Promise<QueueSendResponse>;1925 sendBatch(messages: Iterable<MessageSendRequest<Body>>, options?: QueueSendBatchOptions): Promise<QueueSendBatchResponse>;1926}1927interface QueueSendMetrics {1928 backlogCount: number;1929 backlogBytes: number;1930 oldestMessageTimestamp?: Date;1931}1932interface QueueSendMetadata {1933 metrics: QueueSendMetrics;1934}1935interface QueueSendResponse {1936 metadata: QueueSendMetadata;1937}1938interface QueueSendBatchMetrics {1939 backlogCount: number;1940 backlogBytes: number;1941 oldestMessageTimestamp?: Date;1942}1943interface QueueSendBatchMetadata {1944 metrics: QueueSendBatchMetrics;1945}1946interface QueueSendBatchResponse {1947 metadata: QueueSendBatchMetadata;1948}1949interface QueueSendOptions {1950 contentType?: QueueContentType;1951 delaySeconds?: number;1952}1953interface QueueSendBatchOptions {1954 delaySeconds?: number;1955}1956interface MessageSendRequest<Body = unknown> {1957 body: Body;1958 contentType?: QueueContentType;1959 delaySeconds?: number;1960}1961interface QueueMetrics {1962 backlogCount: number;1963 backlogBytes: number;1964 oldestMessageTimestamp?: Date;1965}1966interface MessageBatchMetrics {1967 backlogCount: number;1968 backlogBytes: number;1969 oldestMessageTimestamp?: Date;1970}1971interface MessageBatchMetadata {1972 metrics: MessageBatchMetrics;1973}1974interface QueueRetryOptions {1975 delaySeconds?: number;1976}1977interface Message<Body = unknown> {1978 readonly id: string;1979 readonly timestamp: Date;1980 readonly body: Body;1981 readonly attempts: number;1982 retry(options?: QueueRetryOptions): void;1983 ack(): void;1984}1985interface QueueEvent<Body = unknown> extends ExtendableEvent {1986 readonly messages: readonly Message<Body>[];1987 readonly queue: string;1988 readonly metadata: MessageBatchMetadata;1989 retryAll(options?: QueueRetryOptions): void;1990 ackAll(): void;1991}1992interface MessageBatch<Body = unknown> {1993 readonly messages: readonly Message<Body>[];1994 readonly queue: string;1995 readonly metadata: MessageBatchMetadata;1996 retryAll(options?: QueueRetryOptions): void;1997 ackAll(): void;1998}1999interface R2Error extends Error {2000 readonly name: string;2001 readonly code: number;2002 readonly message: string;2003 readonly action: string;2004 readonly stack: any;2005}2006interface R2ListOptions {2007 limit?: number;2008 prefix?: string;2009 cursor?: string;2010 delimiter?: string;2011 startAfter?: string;2012 include?: ("httpMetadata" | "customMetadata")[];2013}2014interface R2Bucket {2015 head(key: string): Promise<R2Object | null>;2016 get(key: string, options: R2GetOptions & {2017 onlyIf: R2Conditional | Headers;2018 }): Promise<R2ObjectBody | R2Object | null>;2019 get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>;2020 put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & {2021 onlyIf: R2Conditional | Headers;2022 }): Promise<R2Object | null>;2023 put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise<R2Object>;2024 createMultipartUpload(key: string, options?: R2MultipartOptions): Promise<R2MultipartUpload>;2025 resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload;2026 delete(keys: string | string[]): Promise<void>;2027 list(options?: R2ListOptions): Promise<R2Objects>;2028}2029interface R2MultipartUpload {2030 readonly key: string;2031 readonly uploadId: string;2032 uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise<R2UploadedPart>;2033 abort(): Promise<void>;2034 complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>;2035}2036interface R2UploadedPart {2037 partNumber: number;2038 etag: string;2039}2040declare abstract class R2Object {2041 readonly key: string;2042 readonly version: string;2043 readonly size: number;2044 readonly etag: string;2045 readonly httpEtag: string;2046 readonly checksums: R2Checksums;2047 readonly uploaded: Date;2048 readonly httpMetadata?: R2HTTPMetadata;2049 readonly customMetadata?: Record<string, string>;2050 readonly range?: R2Range;2051 readonly storageClass: string;2052 readonly ssecKeyMd5?: string;2053 writeHttpMetadata(headers: Headers): void;2054}2055interface R2ObjectBody extends R2Object {2056 get body(): ReadableStream;2057 get bodyUsed(): boolean;2058 arrayBuffer(): Promise<ArrayBuffer>;2059 bytes(): Promise<Uint8Array>;2060 text(): Promise<string>;2061 json<T>(): Promise<T>;2062 blob(): Promise<Blob>;2063}2064type R2Range = {2065 offset: number;2066 length?: number;2067} | {2068 offset?: number;2069 length: number;2070} | {2071 suffix: number;2072};2073interface R2Conditional {2074 etagMatches?: string;2075 etagDoesNotMatch?: string;2076 uploadedBefore?: Date;2077 uploadedAfter?: Date;2078 secondsGranularity?: boolean;2079}2080interface R2GetOptions {2081 onlyIf?: (R2Conditional | Headers);2082 range?: (R2Range | Headers);2083 ssecKey?: (ArrayBuffer | string);2084}2085interface R2PutOptions {2086 onlyIf?: (R2Conditional | Headers);2087 httpMetadata?: (R2HTTPMetadata | Headers);2088 customMetadata?: Record<string, string>;2089 md5?: ((ArrayBuffer | ArrayBufferView) | string);2090 sha1?: ((ArrayBuffer | ArrayBufferView) | string);2091 sha256?: ((ArrayBuffer | ArrayBufferView) | string);2092 sha384?: ((ArrayBuffer | ArrayBufferView) | string);2093 sha512?: ((ArrayBuffer | ArrayBufferView) | string);2094 storageClass?: string;2095 ssecKey?: (ArrayBuffer | string);2096}2097interface R2MultipartOptions {2098 httpMetadata?: (R2HTTPMetadata | Headers);2099 customMetadata?: Record<string, string>;2100 storageClass?: string;2101 ssecKey?: (ArrayBuffer | string);2102}2103interface R2Checksums {2104 readonly md5?: ArrayBuffer;2105 readonly sha1?: ArrayBuffer;2106 readonly sha256?: ArrayBuffer;2107 readonly sha384?: ArrayBuffer;2108 readonly sha512?: ArrayBuffer;2109 toJSON(): R2StringChecksums;2110}2111interface R2StringChecksums {2112 md5?: string;2113 sha1?: string;2114 sha256?: string;2115 sha384?: string;2116 sha512?: string;2117}2118interface R2HTTPMetadata {2119 contentType?: string;2120 contentLanguage?: string;2121 contentDisposition?: string;2122 contentEncoding?: string;2123 cacheControl?: string;2124 cacheExpiry?: Date;2125}2126type R2Objects = {2127 objects: R2Object[];2128 delimitedPrefixes: string[];2129} & ({2130 truncated: true;2131 cursor: string;2132} | {2133 truncated: false;2134});2135interface R2UploadPartOptions {2136 ssecKey?: (ArrayBuffer | string);2137}2138declare abstract class ScheduledEvent extends ExtendableEvent {2139 readonly scheduledTime: number;2140 readonly cron: string;2141 noRetry(): void;2142}2143interface ScheduledController {2144 readonly scheduledTime: number;2145 readonly cron: string;2146 noRetry(): void;2147}2148interface QueuingStrategy<T = any> {2149 highWaterMark?: (number | bigint);2150 size?: (chunk: T) => number | bigint;2151}2152interface UnderlyingSink<W = any> {2153 type?: string;2154 start?: (controller: WritableStreamDefaultController) => void | Promise<void>;2155 write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise<void>;2156 abort?: (reason: any) => void | Promise<void>;2157 close?: () => void | Promise<void>;2158}2159interface UnderlyingByteSource {2160 type: "bytes";2161 autoAllocateChunkSize?: number;2162 start?: (controller: ReadableByteStreamController) => void | Promise<void>;2163 pull?: (controller: ReadableByteStreamController) => void | Promise<void>;2164 cancel?: (reason: any) => void | Promise<void>;2165}2166interface UnderlyingSource<R = any> {2167 type?: "" | undefined;2168 start?: (controller: ReadableStreamDefaultController<R>) => void | Promise<void>;2169 pull?: (controller: ReadableStreamDefaultController<R>) => void | Promise<void>;2170 cancel?: (reason: any) => void | Promise<void>;2171 expectedLength?: (number | bigint);2172}2173interface Transformer<I = any, O = any> {2174 readableType?: string;2175 writableType?: string;2176 start?: (controller: TransformStreamDefaultController<O>) => void | Promise<void>;2177 transform?: (chunk: I, controller: TransformStreamDefaultController<O>) => void | Promise<void>;2178 flush?: (controller: TransformStreamDefaultController<O>) => void | Promise<void>;2179 cancel?: (reason: any) => void | Promise<void>;2180 expectedLength?: number;2181}2182interface StreamPipeOptions {2183 preventAbort?: boolean;2184 preventCancel?: boolean;2185 /**2186 * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered.2187 *2188 * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.2189 *2190 * Errors and closures of the source and destination streams propagate as follows:2191 *2192 * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination.2193 *2194 * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source.2195 *2196 * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error.2197 *2198 * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source.2199 *2200 * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set.2201 */2202 preventClose?: boolean;2203 signal?: AbortSignal;2204}2205type ReadableStreamReadResult<R = any> = {2206 done: false;2207 value: R;2208} | {2209 done: true;2210 value?: undefined;2211};2212/**2213 * The **`ReadableStream`** interface of the Streams API represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.2214 *2215 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream)2216 */2217interface ReadableStream<R = any> {2218 /**2219 * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader.2220 *2221 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked)2222 */2223 get locked(): boolean;2224 /**2225 * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled.2226 *2227 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel)2228 */2229 cancel(reason?: any): Promise<void>;2230 /**2231 * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released.2232 *2233 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader)2234 */2235 getReader(): ReadableStreamDefaultReader<R>;2236 /**2237 * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released.2238 *2239 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader)2240 */2241 getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader;2242 /**2243 * The **`pipeThrough()`** method of the ReadableStream interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair.2244 *2245 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough)2246 */2247 pipeThrough<T>(transform: ReadableWritablePair<T, R>, options?: StreamPipeOptions): ReadableStream<T>;2248 /**2249 * The **`pipeTo()`** method of the ReadableStream interface pipes the current ReadableStream to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered.2250 *2251 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo)2252 */2253 pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>;2254 /**2255 * The **`tee()`** method of the ReadableStream interface tees the current readable stream, returning a two-element array containing the two resulting branches as new ReadableStream instances.2256 *2257 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee)2258 */2259 tee(): [2260 ReadableStream<R>,2261 ReadableStream<R>2262 ];2263 values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>;2264 [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>;2265}2266/**2267 * The **`ReadableStream`** interface of the Streams API represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.2268 *2269 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream)2270 */2271declare const ReadableStream: {2272 prototype: ReadableStream;2273 new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy<Uint8Array>): ReadableStream<Uint8Array>;2274 new <R = any>(underlyingSource?: UnderlyingSource<R>, strategy?: QueuingStrategy<R>): ReadableStream<R>;2275};2276/**2277 * The **`ReadableStreamDefaultReader`** interface of the Streams API represents a default reader that can be used to read stream data supplied from a network (such as a fetch request).2278 *2279 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader)2280 */2281declare class ReadableStreamDefaultReader<R = any> {2282 constructor(stream: ReadableStream);2283 get closed(): Promise<void>;2284 cancel(reason?: any): Promise<void>;2285 /**2286 * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue.2287 *2288 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read)2289 */2290 read(): Promise<ReadableStreamReadResult<R>>;2291 /**2292 * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream.2293 *2294 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock)2295 */2296 releaseLock(): void;2297}2298/**2299 * The **`ReadableStreamBYOBReader`** interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source. It is used for efficient copying from underlying sources where the data is delivered as an "anonymous" sequence of bytes, such as files.2300 *2301 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader)2302 */2303declare class ReadableStreamBYOBReader {2304 constructor(stream: ReadableStream);2305 get closed(): Promise<void>;2306 cancel(reason?: any): Promise<void>;2307 /**2308 * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. A request for data will be satisfied from the stream's internal queues if there is any data present. If the stream queues are empty, the request may be supplied as a zero-copy transfer from the underlying byte source.2309 *2310 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read)2311 */2312 read<T extends ArrayBufferView>(view: T): Promise<ReadableStreamReadResult<T>>;2313 /**2314 * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. After the lock is released, the reader is no longer active.2315 *2316 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock)2317 */2318 releaseLock(): void;2319 readAtLeast<T extends ArrayBufferView>(minElements: number, view: T): Promise<ReadableStreamReadResult<T>>;2320}2321interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions {2322 min?: number;2323}2324interface ReadableStreamGetReaderOptions {2325 /**2326 * Creates a ReadableStreamBYOBReader and locks the stream to the new reader.2327 *2328 * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation.2329 */2330 mode: "byob";2331}2332/**2333 * The **`ReadableStreamBYOBRequest`** interface of the Streams API represents a "pull request" for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues).2334 *2335 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest)2336 */2337declare abstract class ReadableStreamBYOBRequest {2338 /**2339 * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view.2340 *2341 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view)2342 */2343 get view(): Uint8Array | null;2344 /**2345 * The **`respond()`** method of the ReadableStreamBYOBRequest interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the ReadableStreamBYOBRequest.view.2346 *2347 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond)2348 */2349 respond(bytesWritten: number): void;2350 /**2351 * The **`respondWithNewView()`** method of the ReadableStreamBYOBRequest interface specifies a new view that the consumer of the associated readable byte stream should write to instead of ReadableStreamBYOBRequest.view.2352 *2353 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView)2354 */2355 respondWithNewView(view: ArrayBuffer | ArrayBufferView): void;2356 get atLeast(): number | null;2357}2358/**2359 * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue. Default controllers are for streams that are not byte streams.2360 *2361 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController)2362 */2363declare abstract class ReadableStreamDefaultController<R = any> {2364 /**2365 * The **`desiredSize`** read-only property of the ReadableStreamDefaultController interface returns the desired size required to fill the stream's internal queue.2366 *2367 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize)2368 */2369 get desiredSize(): number | null;2370 /**2371 * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream.2372 *2373 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close)2374 */2375 close(): void;2376 /**2377 * The **`enqueue()`** method of the ReadableStreamDefaultController interface enqueues a given chunk in the associated stream.2378 *2379 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue)2380 */2381 enqueue(chunk?: R): void;2382 /**2383 * The **`error()`** method of the ReadableStreamDefaultController interface causes any future interactions with the associated stream to error.2384 *2385 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error)2386 */2387 error(reason: any): void;2388}2389/**2390 * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream. It allows control of the state and internal queue of a ReadableStream with an underlying byte source, and enables efficient zero-copy transfer of data from the underlying source to a consumer when the stream's internal queue is empty.2391 *2392 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController)2393 */2394declare abstract class ReadableByteStreamController {2395 /**2396 * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or null if there are no pending requests.2397 *2398 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest)2399 */2400 get byobRequest(): ReadableStreamBYOBRequest | null;2401 /**2402 * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its "desired size".2403 *2404 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize)2405 */2406 get desiredSize(): number | null;2407 /**2408 * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream.2409 *2410 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close)2411 */2412 close(): void;2413 /**2414 * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is transferred into the stream's internal queues).2415 *2416 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue)2417 */2418 enqueue(chunk: ArrayBuffer | ArrayBufferView): void;2419 /**2420 * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason.2421 *2422 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error)2423 */2424 error(reason: any): void;2425}2426/**2427 * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate.2428 *2429 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController)2430 */2431declare abstract class WritableStreamDefaultController {2432 /**2433 * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller.2434 *2435 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal)2436 */2437 get signal(): AbortSignal;2438 /**2439 * The **`error()`** method of the WritableStreamDefaultController interface causes any future interactions with the associated stream to error.2440 *2441 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error)2442 */2443 error(reason?: any): void;2444}2445/**2446 * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream.2447 *2448 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController)2449 */2450declare abstract class TransformStreamDefaultController<O = any> {2451 /**2452 * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream.2453 *2454 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize)2455 */2456 get desiredSize(): number | null;2457 /**2458 * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream.2459 *2460 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue)2461 */2462 enqueue(chunk?: O): void;2463 /**2464 * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. Any further interactions with it will fail with the given error message, and any chunks in the queue will be discarded.2465 *2466 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error)2467 */2468 error(reason: any): void;2469 /**2470 * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream.2471 *2472 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate)2473 */2474 terminate(): void;2475}2476interface ReadableWritablePair<R = any, W = any> {2477 readable: ReadableStream<R>;2478 /**2479 * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use.2480 *2481 * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.2482 */2483 writable: WritableStream<W>;2484}2485/**2486 * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing.2487 *2488 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream)2489 */2490declare class WritableStream<W = any> {2491 constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy);2492 /**2493 * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the WritableStream is locked to a writer.2494 *2495 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked)2496 */2497 get locked(): boolean;2498 /**2499 * The **`abort()`** method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded.2500 *2501 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort)2502 */2503 abort(reason?: any): Promise<void>;2504 /**2505 * The **`close()`** method of the WritableStream interface closes the associated stream. All chunks written before this method is called are sent before the returned promise is fulfilled.2506 *2507 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close)2508 */2509 close(): Promise<void>;2510 /**2511 * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released.2512 *2513 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter)2514 */2515 getWriter(): WritableStreamDefaultWriter<W>;2516}2517/**2518 * The **`WritableStreamDefaultWriter`** interface of the Streams API is the object returned by WritableStream.getWriter() and once created locks the writer to the WritableStream ensuring that no other streams can write to the underlying sink.2519 *2520 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter)2521 */2522declare class WritableStreamDefaultWriter<W = any> {2523 constructor(stream: WritableStream);2524 /**2525 * The **`closed`** read-only property of the WritableStreamDefaultWriter interface returns a Promise that fulfills if the stream becomes closed, or rejects if the stream errors or the writer's lock is released.2526 *2527 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed)2528 */2529 get closed(): Promise<void>;2530 /**2531 * The **`ready`** read-only property of the WritableStreamDefaultWriter interface returns a Promise that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure.2532 *2533 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready)2534 */2535 get ready(): Promise<void>;2536 /**2537 * The **`desiredSize`** read-only property of the WritableStreamDefaultWriter interface returns the desired size required to fill the stream's internal queue.2538 *2539 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize)2540 */2541 get desiredSize(): number | null;2542 /**2543 * The **`abort()`** method of the WritableStreamDefaultWriter interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded.2544 *2545 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort)2546 */2547 abort(reason?: any): Promise<void>;2548 /**2549 * The **`close()`** method of the WritableStreamDefaultWriter interface closes the associated writable stream.2550 *2551 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close)2552 */2553 close(): Promise<void>;2554 /**2555 * The **`write()`** method of the WritableStreamDefaultWriter interface writes a passed chunk of data to a WritableStream and its underlying sink, then returns a Promise that resolves to indicate the success or failure of the write operation.2556 *2557 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write)2558 */2559 write(chunk?: W): Promise<void>;2560 /**2561 * The **`releaseLock()`** method of the WritableStreamDefaultWriter interface releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed.2562 *2563 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock)2564 */2565 releaseLock(): void;2566}2567/**2568 * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain transform stream concept.2569 *2570 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream)2571 */2572declare class TransformStream<I = any, O = any> {2573 constructor(transformer?: Transformer<I, O>, writableStrategy?: QueuingStrategy<I>, readableStrategy?: QueuingStrategy<O>);2574 /**2575 * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this TransformStream. This stream emits the transformed output data.2576 *2577 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable)2578 */2579 get readable(): ReadableStream<O>;2580 /**2581 * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this TransformStream. This stream accepts input data that will be transformed and emitted to the readable stream.2582 *2583 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable)2584 */2585 get writable(): WritableStream<I>;2586}2587declare class FixedLengthStream extends IdentityTransformStream {2588 constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy);2589}2590declare class IdentityTransformStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {2591 constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy);2592}2593interface IdentityTransformStreamQueuingStrategy {2594 highWaterMark?: (number | bigint);2595}2596interface ReadableStreamValuesOptions {2597 preventCancel?: boolean;2598}2599/**2600 * The **`CompressionStream`** interface of the Compression Streams API compresses a stream of data. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods.2601 *2602 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream)2603 */2604declare class CompressionStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {2605 constructor(format: "gzip" | "deflate" | "deflate-raw");2606}2607/**2608 * The **`DecompressionStream`** interface of the Compression Streams API decompresses a stream of data. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods.2609 *2610 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream)2611 */2612declare class DecompressionStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {2613 constructor(format: "gzip" | "deflate" | "deflate-raw");2614}2615/**2616 * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. It is the streaming equivalent of TextEncoder. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods.2617 *2618 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream)2619 */2620declare class TextEncoderStream extends TransformStream<string, Uint8Array> {2621 constructor();2622 get encoding(): string;2623}2624/**2625 * The **`TextDecoderStream`** interface of the Encoding API converts a stream of text in a binary encoding, such as UTF-8 etc., to a stream of strings. It is the streaming equivalent of TextDecoder. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods.2626 *2627 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream)2628 */2629declare class TextDecoderStream extends TransformStream<ArrayBuffer | ArrayBufferView, string> {2630 constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit);2631 get encoding(): string;2632 get fatal(): boolean;2633 get ignoreBOM(): boolean;2634}2635interface TextDecoderStreamTextDecoderStreamInit {2636 fatal?: boolean;2637 ignoreBOM?: boolean;2638}2639/**2640 * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams.2641 *2642 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy)2643 */2644declare class ByteLengthQueuingStrategy implements QueuingStrategy<ArrayBufferView> {2645 constructor(init: QueuingStrategyInit);2646 /**2647 * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied.2648 *2649 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark)2650 */2651 get highWaterMark(): number;2652 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */2653 get size(): (chunk?: any) => number;2654}2655/**2656 * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams.2657 *2658 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy)2659 */2660declare class CountQueuingStrategy implements QueuingStrategy {2661 constructor(init: QueuingStrategyInit);2662 /**2663 * The read-only **`CountQueuingStrategy.highWaterMark`** property returns the total number of chunks that can be contained in the internal queue before backpressure is applied.2664 *2665 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark)2666 */2667 get highWaterMark(): number;2668 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */2669 get size(): (chunk?: any) => number;2670}2671interface QueuingStrategyInit {2672 /**2673 * Creates a new ByteLengthQueuingStrategy with the provided high water mark.2674 *2675 * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw.2676 */2677 highWaterMark: number;2678}2679interface TracePreviewInfo {2680 id: string;2681 slug: string;2682 name: string;2683}2684interface ScriptVersion {2685 id?: string;2686 tag?: string;2687 message?: string;2688}2689declare abstract class TailEvent extends ExtendableEvent {2690 readonly events: TraceItem[];2691 readonly traces: TraceItem[];2692}2693interface TraceItem {2694 readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemConnectEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null;2695 readonly eventTimestamp: number | null;2696 readonly logs: TraceLog[];2697 readonly exceptions: TraceException[];2698 readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[];2699 readonly scriptName: string | null;2700 readonly entrypoint?: string;2701 readonly scriptVersion?: ScriptVersion;2702 readonly dispatchNamespace?: string;2703 readonly scriptTags?: string[];2704 readonly tailAttributes?: Record<string, boolean | number | string>;2705 readonly preview?: TracePreviewInfo;2706 readonly durableObjectId?: string;2707 readonly outcome: string;2708 readonly executionModel: string;2709 readonly truncated: boolean;2710 readonly cpuTime: number;2711 readonly wallTime: number;2712}2713interface TraceItemAlarmEventInfo {2714 readonly scheduledTime: Date;2715}2716interface TraceItemConnectEventInfo {2717}2718interface TraceItemCustomEventInfo {2719}2720interface TraceItemScheduledEventInfo {2721 readonly scheduledTime: number;2722 readonly cron: string;2723}2724interface TraceItemQueueEventInfo {2725 readonly queue: string;2726 readonly batchSize: number;2727}2728interface TraceItemEmailEventInfo {2729 readonly mailFrom: string;2730 readonly rcptTo: string;2731 readonly rawSize: number;2732}2733interface TraceItemTailEventInfo {2734 readonly consumedEvents: TraceItemTailEventInfoTailItem[];2735}2736interface TraceItemTailEventInfoTailItem {2737 readonly scriptName: string | null;2738}2739interface TraceItemFetchEventInfo {2740 readonly response?: TraceItemFetchEventInfoResponse;2741 readonly request: TraceItemFetchEventInfoRequest;2742}2743interface TraceItemFetchEventInfoRequest {2744 readonly cf?: any;2745 readonly headers: Record<string, string>;2746 readonly method: string;2747 readonly url: string;2748 getUnredacted(): TraceItemFetchEventInfoRequest;2749}2750interface TraceItemFetchEventInfoResponse {2751 readonly status: number;2752}2753interface TraceItemJsRpcEventInfo {2754 readonly rpcMethod: string;2755}2756interface TraceItemHibernatableWebSocketEventInfo {2757 readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError;2758}2759interface TraceItemHibernatableWebSocketEventInfoMessage {2760 readonly webSocketEventType: string;2761}2762interface TraceItemHibernatableWebSocketEventInfoClose {2763 readonly webSocketEventType: string;2764 readonly code: number;2765 readonly wasClean: boolean;2766}2767interface TraceItemHibernatableWebSocketEventInfoError {2768 readonly webSocketEventType: string;2769}2770interface TraceLog {2771 readonly timestamp: number;2772 readonly level: string;2773 readonly message: any;2774 readonly errorInfo?: (TraceLogErrorInfo | null)[];2775}2776interface TraceLogErrorInfo {2777 name: string;2778 message: string;2779 stack?: string;2780}2781interface TraceException {2782 readonly timestamp: number;2783 readonly message: string;2784 readonly name: string;2785 readonly stack?: string;2786}2787interface TraceDiagnosticChannelEvent {2788 readonly timestamp: number;2789 readonly channel: string;2790 readonly message: any;2791}2792interface TraceMetrics {2793 readonly cpuTime: number;2794 readonly wallTime: number;2795}2796interface UnsafeTraceMetrics {2797 fromTrace(item: TraceItem): TraceMetrics;2798}2799/**2800 * The **`URL`** interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.2801 *2802 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL)2803 */2804declare class URL {2805 constructor(url: string | URL, base?: string | URL);2806 /**2807 * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL.2808 *2809 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin)2810 */2811 get origin(): string;2812 /**2813 * The **`href`** property of the URL interface is a string containing the whole URL.2814 *2815 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href)2816 */2817 get href(): string;2818 /**2819 * The **`href`** property of the URL interface is a string containing the whole URL.2820 *2821 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href)2822 */2823 set href(value: string);2824 /**2825 * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final ":".2826 *2827 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol)2828 */2829 get protocol(): string;2830 /**2831 * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final ":".2832 *2833 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol)2834 */2835 set protocol(value: string);2836 /**2837 * The **`username`** property of the URL interface is a string containing the username component of the URL. If the URL does not have a username, this property contains an empty string, "".2838 *2839 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username)2840 */2841 get username(): string;2842 /**2843 * The **`username`** property of the URL interface is a string containing the username component of the URL. If the URL does not have a username, this property contains an empty string, "".2844 *2845 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username)2846 */2847 set username(value: string);2848 /**2849 * The **`password`** property of the URL interface is a string containing the password component of the URL. If the URL does not have a password, this property contains an empty string, "".2850 *2851 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password)2852 */2853 get password(): string;2854 /**2855 * The **`password`** property of the URL interface is a string containing the password component of the URL. If the URL does not have a password, this property contains an empty string, "".2856 *2857 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password)2858 */2859 set password(value: string);2860 /**2861 * The **`host`** property of the URL interface is a string containing the host, which is the hostname, and then, if the port of the URL is nonempty, a ":", followed by the port of the URL. If the URL does not have a hostname, this property contains an empty string, "".2862 *2863 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host)2864 */2865 get host(): string;2866 /**2867 * The **`host`** property of the URL interface is a string containing the host, which is the hostname, and then, if the port of the URL is nonempty, a ":", followed by the port of the URL. If the URL does not have a hostname, this property contains an empty string, "".2868 *2869 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host)2870 */2871 set host(value: string);2872 /**2873 * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. If the URL does not have a hostname, this property contains an empty string, "". IPv4 and IPv6 addresses are normalized, such as stripping leading zeros, and domain names are converted to IDN.2874 *2875 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname)2876 */2877 get hostname(): string;2878 /**2879 * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. If the URL does not have a hostname, this property contains an empty string, "". IPv4 and IPv6 addresses are normalized, such as stripping leading zeros, and domain names are converted to IDN.2880 *2881 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname)2882 */2883 set hostname(value: string);2884 /**2885 * The **`port`** property of the URL interface is a string containing the port number of the URL. If the port is the default for the protocol (80 for ws: and http:, 443 for wss: and https:, and 21 for ftp:), this property contains an empty string, "".2886 *2887 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port)2888 */2889 get port(): string;2890 /**2891 * The **`port`** property of the URL interface is a string containing the port number of the URL. If the port is the default for the protocol (80 for ws: and http:, 443 for wss: and https:, and 21 for ftp:), this property contains an empty string, "".2892 *2893 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port)2894 */2895 set port(value: string);2896 /**2897 * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.2898 *2899 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname)2900 */2901 get pathname(): string;2902 /**2903 * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.2904 *2905 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname)2906 */2907 set pathname(value: string);2908 /**2909 * The **`search`** property of the URL interface is a search string, also called a query string, that is a string containing a "?" followed by the parameters of the URL. If the URL does not have a search query, this property contains an empty string, "".2910 *2911 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search)2912 */2913 get search(): string;2914 /**2915 * The **`search`** property of the URL interface is a search string, also called a query string, that is a string containing a "?" followed by the parameters of the URL. If the URL does not have a search query, this property contains an empty string, "".2916 *2917 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search)2918 */2919 set search(value: string);2920 /**2921 * The **`hash`** property of the URL interface is a string containing a "#" followed by the fragment identifier of the URL. If the URL does not have a fragment identifier, this property contains an empty string, "".2922 *2923 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash)2924 */2925 get hash(): string;2926 /**2927 * The **`hash`** property of the URL interface is a string containing a "#" followed by the fragment identifier of the URL. If the URL does not have a fragment identifier, this property contains an empty string, "".2928 *2929 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash)2930 */2931 set hash(value: string);2932 /**2933 * The **`searchParams`** read-only property of the URL interface returns a URLSearchParams object allowing access to the GET decoded query arguments contained in the URL.2934 *2935 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams)2936 */2937 get searchParams(): URLSearchParams;2938 /**2939 * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as URL.toString().2940 *2941 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON)2942 */2943 toJSON(): string;2944 /*function toString() { [native code] }*/2945 toString(): string;2946 /**2947 * The **`URL.canParse()`** static method of the URL interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid.2948 *2949 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static)2950 */2951 static canParse(url: string, base?: string): boolean;2952 /**2953 * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters.2954 *2955 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static)2956 */2957 static parse(url: string, base?: string): URL | null;2958 /**2959 * The **`createObjectURL()`** static method of the URL interface creates a string containing a blob URL pointing to the object given in the parameter.2960 *2961 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static)2962 */2963 static createObjectURL(object: File | Blob): string;2964 /**2965 * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling URL.createObjectURL().2966 *2967 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static)2968 */2969 static revokeObjectURL(object_url: string): void;2970}2971/**2972 * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL.2973 *2974 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams)2975 */2976declare class URLSearchParams {2977 constructor(init?: (Iterable<Iterable<string>> | Record<string, string> | string));2978 /**2979 * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries.2980 *2981 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size)2982 */2983 get size(): number;2984 /**2985 * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter.2986 *2987 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append)2988 */2989 append(name: string, value: string): void;2990 /**2991 * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters.2992 *2993 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete)2994 */2995 delete(name: string, value?: string): void;2996 /**2997 * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter.2998 *2999 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get)3000 */3001 get(name: string): string | null;3002 /**3003 * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array.3004 *3005 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll)3006 */3007 getAll(name: string): string[];3008 /**3009 * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters.3010 *3011 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has)3012 */3013 has(name: string, value?: string): boolean;3014 /**3015 * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it.3016 *3017 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set)3018 */3019 set(name: string, value: string): void;3020 /**3021 * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns undefined. Key/value pairs are sorted by the values of the UTF-16 code units of the keys. This method uses a stable sorting algorithm (i.e., the relative order between key/value pairs with equal keys will be preserved).3022 *3023 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort)3024 */3025 sort(): void;3026 entries(): IterableIterator<[3027 key: string,3028 value: string3029 ]>;3030 keys(): IterableIterator<string>;3031 values(): IterableIterator<string>;3032 forEach<This = unknown>(callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This): void;3033 /*function toString() { [native code] }*/3034 toString(): string;3035 [Symbol.iterator](): IterableIterator<[3036 key: string,3037 value: string3038 ]>;3039}3040/**3041 * The **`URLPattern`** interface of the URL Pattern API matches URLs or parts of URLs against a pattern. The pattern can contain capturing groups that extract parts of the matched URL.3042 *3043 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern)3044 */3045declare class URLPattern {3046 constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions);3047 /**3048 * The **`protocol`** read-only property of the URLPattern interface is a string containing the pattern used to match the protocol part of a URL.3049 *3050 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/protocol)3051 */3052 get protocol(): string;3053 /**3054 * The **`username`** read-only property of the URLPattern interface is a string containing the pattern used to match the username part of a URL.3055 *3056 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/username)3057 */3058 get username(): string;3059 /**3060 * The **`password`** read-only property of the URLPattern interface is a string containing the pattern used to match the password part of a URL.3061 *3062 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/password)3063 */3064 get password(): string;3065 /**3066 * The **`hostname`** read-only property of the URLPattern interface is a string containing the pattern used to match the hostname part of a URL.3067 *3068 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hostname)3069 */3070 get hostname(): string;3071 /**3072 * The **`port`** read-only property of the URLPattern interface is a string containing the pattern used to match the port part of a URL.3073 *3074 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/port)3075 */3076 get port(): string;3077 /**3078 * The **`pathname`** read-only property of the URLPattern interface is a string containing the pattern used to match the pathname part of a URL.3079 *3080 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/pathname)3081 */3082 get pathname(): string;3083 /**3084 * The **`search`** read-only property of the URLPattern interface is a string containing the pattern used to match the search part of a URL.3085 *3086 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/search)3087 */3088 get search(): string;3089 /**3090 * The **`hash`** read-only property of the URLPattern interface is a string containing the pattern used to match the fragment part of a URL.3091 *3092 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hash)3093 */3094 get hash(): string;3095 /**3096 * The **`hasRegExpGroups`** read-only property of the URLPattern interface is a boolean indicating whether or not any of the URLPattern components contain regular expression capturing groups.3097 *3098 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hasRegExpGroups)3099 */3100 get hasRegExpGroups(): boolean;3101 /**3102 * The **`test()`** method of the URLPattern interface takes a URL string or object of URL parts, and returns a boolean indicating if the given input matches the current pattern.3103 *3104 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/test)3105 */3106 test(input?: (string | URLPatternInit), baseURL?: string): boolean;3107 /**3108 * The **`exec()`** method of the URLPattern interface takes a URL or object of URL parts, and returns either an object containing the results of matching the URL to the pattern, or null if the URL does not match the pattern.3109 *3110 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/exec)3111 */3112 exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null;3113}3114interface URLPatternInit {3115 protocol?: string;3116 username?: string;3117 password?: string;3118 hostname?: string;3119 port?: string;3120 pathname?: string;3121 search?: string;3122 hash?: string;3123 baseURL?: string;3124}3125interface URLPatternComponentResult {3126 input: string;3127 groups: Record<string, string>;3128}3129interface URLPatternResult {3130 inputs: (string | URLPatternInit)[];3131 protocol: URLPatternComponentResult;3132 username: URLPatternComponentResult;3133 password: URLPatternComponentResult;3134 hostname: URLPatternComponentResult;3135 port: URLPatternComponentResult;3136 pathname: URLPatternComponentResult;3137 search: URLPatternComponentResult;3138 hash: URLPatternComponentResult;3139}3140interface URLPatternOptions {3141 ignoreCase?: boolean;3142}3143/**3144 * A **`CloseEvent`** is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute.3145 *3146 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent)3147 */3148declare class CloseEvent extends Event {3149 constructor(type: string, initializer?: CloseEventInit);3150 /**3151 * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed.3152 *3153 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code)3154 */3155 readonly code: number;3156 /**3157 * The **`reason`** read-only property of the CloseEvent interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure.3158 *3159 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason)3160 */3161 readonly reason: string;3162 /**3163 * The **`wasClean`** read-only property of the CloseEvent interface returns true if the connection closed cleanly.3164 *3165 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean)3166 */3167 readonly wasClean: boolean;3168}3169interface CloseEventInit {3170 code?: number;3171 reason?: string;3172 wasClean?: boolean;3173}3174type WebSocketEventMap = {3175 close: CloseEvent;3176 message: MessageEvent;3177 open: Event;3178 error: ErrorEvent;3179};3180/**3181 * The **`WebSocket`** object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.3182 *3183 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket)3184 */3185declare var WebSocket: {3186 prototype: WebSocket;3187 new (url: string, protocols?: (string[] | string)): WebSocket;3188 readonly READY_STATE_CONNECTING: number;3189 readonly CONNECTING: number;3190 readonly READY_STATE_OPEN: number;3191 readonly OPEN: number;3192 readonly READY_STATE_CLOSING: number;3193 readonly CLOSING: number;3194 readonly READY_STATE_CLOSED: number;3195 readonly CLOSED: number;3196};3197/**3198 * The **`WebSocket`** object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.3199 *3200 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket)3201 */3202interface WebSocket extends EventTarget<WebSocketEventMap> {3203 accept(options?: WebSocketAcceptOptions): void;3204 /**3205 * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of bufferedAmount by the number of bytes needed to contain the data. If the data can't be sent (for example, because it needs to be buffered but the buffer is full), the socket is closed automatically. The browser will throw an exception if you call send() when the connection is in the CONNECTING state. If you call send() when the connection is in the CLOSING or CLOSED states, the browser will silently discard the data.3206 *3207 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send)3208 */3209 send(message: (ArrayBuffer | ArrayBufferView) | string): void;3210 /**3211 * The **`WebSocket.close()`** method closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED, this method does nothing.3212 *3213 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close)3214 */3215 close(code?: number, reason?: string): void;3216 serializeAttachment(attachment: any): void;3217 deserializeAttachment(): any | null;3218 /**3219 * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection.3220 *3221 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState)3222 */3223 readyState: number;3224 /**3225 * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor.3226 *3227 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url)3228 */3229 url: string | null;3230 /**3231 * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the protocols parameter when creating the WebSocket object, or the empty string if no connection is established.3232 *3233 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol)3234 */3235 protocol: string | null;3236 /**3237 * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. This is currently only the empty string or a list of extensions as negotiated by the connection.3238 *3239 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions)3240 */3241 extensions: string | null;3242 /**3243 * The **`WebSocket.binaryType`** property controls the type of binary data being received over the WebSocket connection.3244 *3245 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType)3246 */3247 binaryType: "blob" | "arraybuffer";3248}3249interface WebSocketAcceptOptions {3250 /**3251 * When set to `true`, receiving a server-initiated WebSocket Close frame will not3252 * automatically send a reciprocal Close frame, leaving the connection in a half-open3253 * state. This is useful for proxying scenarios where you need to coordinate closing3254 * both sides independently. Defaults to `false` when the3255 * `no_web_socket_half_open_by_default` compatibility flag is enabled.3256 */3257 allowHalfOpen?: boolean;3258}3259declare const WebSocketPair: {3260 new (): {3261 0: WebSocket;3262 1: WebSocket;3263 };3264};3265interface SqlStorage {3266 exec<T extends Record<string, SqlStorageValue>>(query: string, ...bindings: any[]): SqlStorageCursor<T>;3267 get databaseSize(): number;3268 Cursor: typeof SqlStorageCursor;3269 Statement: typeof SqlStorageStatement;3270}3271declare abstract class SqlStorageStatement {3272}3273type SqlStorageValue = ArrayBuffer | string | number | null;3274declare abstract class SqlStorageCursor<T extends Record<string, SqlStorageValue>> {3275 next(): {3276 done?: false;3277 value: T;3278 } | {3279 done: true;3280 value?: never;3281 };3282 toArray(): T[];3283 one(): T;3284 raw<U extends SqlStorageValue[]>(): IterableIterator<U>;3285 columnNames: string[];3286 get rowsRead(): number;3287 get rowsWritten(): number;3288 [Symbol.iterator](): IterableIterator<T>;3289}3290interface Socket {3291 get readable(): ReadableStream;3292 get writable(): WritableStream;3293 get closed(): Promise<void>;3294 get opened(): Promise<SocketInfo>;3295 get upgraded(): boolean;3296 get secureTransport(): "on" | "off" | "starttls";3297 close(): Promise<void>;3298 startTls(options?: TlsOptions): Socket;3299}3300interface SocketOptions {3301 secureTransport?: string;3302 allowHalfOpen: boolean;3303 highWaterMark?: (number | bigint);3304}3305interface SocketAddress {3306 hostname: string;3307 port: number;3308}3309interface TlsOptions {3310 expectedServerHostname?: string;3311}3312interface SocketInfo {3313 remoteAddress?: string;3314 localAddress?: string;3315}3316/**3317 * The **`EventSource`** interface is web content's interface to server-sent events.3318 *3319 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource)3320 */3321declare class EventSource extends EventTarget {3322 constructor(url: string, init?: EventSourceEventSourceInit);3323 /**3324 * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the EventSource.readyState attribute to 2 (closed).3325 *3326 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)3327 */3328 close(): void;3329 /**3330 * The **`url`** read-only property of the EventSource interface returns a string representing the URL of the source.3331 *3332 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)3333 */3334 get url(): string;3335 /**3336 * The **`withCredentials`** read-only property of the EventSource interface returns a boolean value indicating whether the EventSource object was instantiated with CORS credentials set.3337 *3338 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)3339 */3340 get withCredentials(): boolean;3341 /**3342 * The **`readyState`** read-only property of the EventSource interface returns a number representing the state of the connection.3343 *3344 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)3345 */3346 get readyState(): number;3347 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */3348 get onopen(): any | null;3349 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */3350 set onopen(value: any | null);3351 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */3352 get onmessage(): any | null;3353 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */3354 set onmessage(value: any | null);3355 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */3356 get onerror(): any | null;3357 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */3358 set onerror(value: any | null);3359 static readonly CONNECTING: number;3360 static readonly OPEN: number;3361 static readonly CLOSED: number;3362 static from(stream: ReadableStream): EventSource;3363}3364interface EventSourceEventSourceInit {3365 withCredentials?: boolean;3366 fetcher?: Fetcher;3367}3368interface ExecOutput {3369 readonly stdout: ArrayBuffer;3370 readonly stderr: ArrayBuffer;3371 readonly exitCode: number;3372}3373interface ContainerExecOptions {3374 cwd?: string;3375 env?: Record<string, string>;3376 user?: string;3377 signal?: AbortSignal;3378 pty?: boolean | ContainerExecPtyOptions;3379 stdin?: ReadableStream | "pipe";3380 stdout?: "pipe" | "ignore";3381 stderr?: "pipe" | "ignore" | "combined";3382}3383interface ContainerExecPtyOptions {3384 cols?: number;3385 rows?: number;3386}3387interface ExecProcess {3388 readonly stdin: WritableStream | null;3389 readonly stdout: ReadableStream | null;3390 readonly stderr: ReadableStream | null;3391 readonly pid: number;3392 readonly isPty: boolean;3393 readonly exitCode: Promise<number>;3394 output(): Promise<ExecOutput>;3395 kill(signal?: number): void;3396 resize(cols: number, rows: number): void;3397}3398interface Container {3399 get running(): boolean;3400 start(options?: ContainerStartupOptions): void;3401 monitor(): Promise<void>;3402 destroy(error?: any): Promise<void>;3403 signal(signo: number): void;3404 getTcpPort(port: number): Fetcher;3405 setInactivityTimeout(durationMs: number | bigint): Promise<void>;3406 interceptOutboundHttp(addr: string, binding: Fetcher): Promise<void>;3407 interceptAllOutboundHttp(binding: Fetcher): Promise<void>;3408 snapshotDirectory(options: ContainerDirectorySnapshotOptions): Promise<ContainerDirectorySnapshot>;3409 snapshotContainer(options: ContainerSnapshotOptions): Promise<ContainerSnapshot>;3410 interceptOutboundHttps(addr: string, binding: Fetcher): Promise<void>;3411 exec(cmd: string[], options?: ContainerExecOptions): Promise<ExecProcess>;3412}3413interface ContainerDirectorySnapshot {3414 id: string;3415 size: number;3416 dir: string;3417 name?: string;3418}3419interface ContainerDirectorySnapshotOptions {3420 dir: string;3421 name?: string;3422}3423interface ContainerDirectorySnapshotRestoreParams {3424 snapshot: ContainerDirectorySnapshot;3425 mountPoint?: string;3426}3427interface ContainerSnapshot {3428 id: string;3429 size: number;3430 name?: string;3431}3432interface ContainerSnapshotRestoreParams {3433 id: string;3434}3435interface ContainerSnapshotOptions {3436 name?: string;3437}3438type ContainerStartupOptions = {3439 entrypoint?: string[];3440 enableInternet: boolean;3441 env?: Record<string, string>;3442 instance?: "lite" | "standard-1" | "standard-2" | "standard-3" | "standard-4" | ContainerStartResources;3443 labels?: Record<string, string>;3444 directorySnapshots?: ContainerDirectorySnapshotRestoreParams[];3445} & ({3446 image: string;3447 containerSnapshot?: never;3448} | {3449 image?: never;3450 containerSnapshot?: ContainerSnapshotRestoreParams;3451});3452interface ContainerStartResources {3453 vcpu: number;3454 memoryMib: number;3455 diskMb: number;3456}3457/**3458 * The **`MessagePort`** interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other.3459 *3460 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort)3461 */3462declare abstract class MessagePort extends EventTarget {3463 /**3464 * The **`postMessage()`** method of the MessagePort interface sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts.3465 *3466 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage)3467 */3468 postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void;3469 /**3470 * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. This stops the flow of messages to that port.3471 *3472 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close)3473 */3474 close(): void;3475 /**3476 * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. This method is only needed when using EventTarget.addEventListener; it is implied when using onmessage.3477 *3478 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start)3479 */3480 start(): void;3481 get onmessage(): any | null;3482 set onmessage(value: any | null);3483}3484/**3485 * The **`MessageChannel`** interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties.3486 *3487 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel)3488 */3489declare class MessageChannel {3490 constructor();3491 /**3492 * The **`port1`** read-only property of the MessageChannel interface returns the first port of the message channel — the port attached to the context that originated the channel.3493 *3494 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1)3495 */3496 readonly port1: MessagePort;3497 /**3498 * The **`port2`** read-only property of the MessageChannel interface returns the second port of the message channel — the port attached to the context at the other end of the channel, which the message is initially sent to.3499 *3500 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2)3501 */3502 readonly port2: MessagePort;3503}3504interface MessagePortPostMessageOptions {3505 transfer?: any[];3506}3507type LoopbackForExport<T extends (new (...args: any[]) => Rpc.EntrypointBranded) | ExportedHandler<any, any, any> | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? LoopbackServiceStub<InstanceType<T>> : T extends new (...args: any[]) => Rpc.DurableObjectBranded ? LoopbackDurableObjectClass<InstanceType<T>> : T extends ExportedHandler<any, any, any> ? LoopbackServiceStub<undefined> : undefined;3508type LoopbackServiceStub<T extends Rpc.WorkerEntrypointBranded | undefined = undefined> = Fetcher<T> & (T extends CloudflareWorkersModule.WorkerEntrypoint<any, infer Props> ? (opts: {3509 props?: Props;3510}) => Fetcher<T> : (opts: {3511 props?: any;3512}) => Fetcher<T>);3513type LoopbackDurableObjectClass<T extends Rpc.DurableObjectBranded | undefined = undefined> = DurableObjectClass<T> & (T extends CloudflareWorkersModule.DurableObject<any, infer Props> ? (opts: {3514 props?: Props;3515}) => DurableObjectClass<T> : (opts: {3516 props?: any;3517}) => DurableObjectClass<T>);3518interface LoopbackDurableObjectNamespace extends DurableObjectNamespace {3519}3520interface LoopbackColoLocalActorNamespace extends ColoLocalActorNamespace {3521}3522interface SyncKvStorage {3523 get<T = unknown>(key: string): T | undefined;3524 list<T = unknown>(options?: SyncKvListOptions): Iterable<[3525 string,3526 T3527 ]>;3528 put<T>(key: string, value: T): void;3529 delete(key: string): boolean;3530}3531interface SyncKvListOptions {3532 start?: string;3533 startAfter?: string;3534 end?: string;3535 prefix?: string;3536 reverse?: boolean;3537 limit?: number;3538}3539interface WorkerStub {3540 getEntrypoint<T extends Rpc.WorkerEntrypointBranded | undefined>(name?: string, options?: WorkerStubEntrypointOptions): Fetcher<T>;3541 getDurableObjectClass<T extends Rpc.DurableObjectBranded | undefined>(name?: string, options?: WorkerStubEntrypointOptions): DurableObjectClass<T>;3542}3543interface WorkerStubEntrypointOptions {3544 props?: any;3545 limits?: workerdResourceLimits;3546}3547interface WorkerLoader {3548 get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise<WorkerLoaderWorkerCode>): WorkerStub;3549 load(code: WorkerLoaderWorkerCode): WorkerStub;3550}3551interface WorkerLoaderModule {3552 js?: string;3553 cjs?: string;3554 text?: string;3555 data?: ArrayBuffer;3556 json?: any;3557 py?: string;3558 wasm?: ArrayBuffer;3559}3560interface WorkerLoaderWorkerCode {3561 compatibilityDate: string;3562 compatibilityFlags?: string[];3563 allowExperimental?: boolean;3564 limits?: workerdResourceLimits;3565 mainModule: string;3566 modules: Record<string, WorkerLoaderModule | string>;3567 env?: any;3568 globalOutbound?: (Fetcher | null);3569 tails?: Fetcher[];3570 streamingTails?: Fetcher[];3571}3572interface workerdResourceLimits {3573 cpuMs?: number;3574 subRequests?: number;3575}3576/**3577* The Workers runtime supports a subset of the Performance API, used to measure timing and performance,3578* as well as timing of subrequests and other operations.3579*3580* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/)3581*/3582declare abstract class Performance {3583 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */3584 get timeOrigin(): number;3585 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */3586 now(): number;3587 /**3588 * The **`toJSON()`** method of the Performance interface is a serializer; it returns a JSON representation of the Performance object.3589 *3590 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/toJSON)3591 */3592 toJSON(): object;3593}3594interface Tracing {3595 enterSpan<T, A extends unknown[]>(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T;3596 startActiveSpan<T, A extends unknown[]>(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T;3597 startSpan(name: string): Span;3598 Span: typeof Span;3599}3600declare abstract class Span {3601 get isTraced(): boolean;3602 setAttribute(key: string, value: boolean | number | string): this;3603 setAttributes(attributes: Record<string, boolean | number | string | undefined>): this;3604 end(): void;3605}3606/**3607 * Represents the identity of a user authenticated via Cloudflare Access.3608 * This matches the result of calling /cdn-cgi/access/get-identity.3609 *3610 * The exact structure of the returned object depends on the identity provider3611 * configuration for the Access application. The fields below represent commonly3612 * available properties, but additional provider-specific fields may be present.3613 */3614interface CloudflareAccessIdentity extends Record<string, unknown> {3615 /** The user's email address, if available from the identity provider. */3616 email?: string;3617 /** The user's display name. */3618 name?: string;3619 /** The user's unique identifier. */3620 user_uuid?: string;3621 /** The Cloudflare account ID. */3622 account_id?: string;3623 /** Login timestamp (Unix epoch seconds). */3624 iat?: number;3625 /** The user's IP address at authentication time. */3626 ip?: string;3627 /** Authentication methods used (e.g., "pwd"). */3628 amr?: string[];3629 /** Identity provider information. */3630 idp?: {3631 id: string;3632 type: string;3633 };3634 /** Geographic information about where the user authenticated. */3635 geo?: {3636 country: string;3637 };3638 /** Group memberships from the identity provider. */3639 groups?: Array<{3640 id: string;3641 name: string;3642 email?: string;3643 }>;3644 /** Device posture check results, keyed by check ID. */3645 devicePosture?: Record<string, unknown>;3646 /** True if the user connected via Cloudflare WARP. */3647 is_warp?: boolean;3648 /** True if the user is authenticated via Cloudflare Gateway. */3649 is_gateway?: boolean;3650}3651// ============================================================================3652// Agent Memory3653//3654// Public type surface for user Workers binding to an Agent Memory namespace.3655// ============================================================================3656/** Memory type — every memory is classified into exactly one. */3657type AgentMemoryMemoryType = "fact" | "event" | "instruction" | "task";3658/** Search intensity for recall. */3659type AgentMemoryThinkingLevel = "low" | "medium" | "high";3660/** Response verbosity for recall. */3661type AgentMemoryResponseLength = "short" | "medium" | "long";3662/** A conversation message passed to ingest(). */3663interface AgentMemoryMessage {3664 role: "system" | "user" | "assistant";3665 content: string;3666 /** Optional message timestamp. */3667 timestamp?: Date;3668}3669/** Raw memory content passed to remember(). */3670interface AgentMemoryIncomingMemory {3671 /** Raw memory content. The service classifies and summarizes automatically. */3672 content: string;3673 /** Optional session identifier to associate with this memory. */3674 sessionId?: string | null | undefined;3675}3676/** A stored memory returned from remember(), get(), and delete(). */3677interface AgentMemoryMemory {3678 /** Memory ID. */3679 id: string;3680 /** Memory type. */3681 type: AgentMemoryMemoryType;3682 /** Text summary. */3683 summary: string;3684 /** Memory text. */3685 content: string;3686 /** Session that created this memory. */3687 sessionId: string | null;3688 /** Memory creation time. */3689 createdAt: Date;3690 /** Memory last-update time. */3691 updatedAt: Date;3692}3693/** Single entry in a list() response. Same shape as Memory minus full content. */3694type AgentMemoryMemoryListEntry = Omit<AgentMemoryMemory, "content">;3695/** A scored memory candidate in a recall result. */3696interface AgentMemoryScoredCandidate {3697 /** Candidate ID. */3698 id: string;3699 /** Text summary. */3700 summary: string;3701 /** Session that created this candidate, when known. */3702 sessionId: string | null;3703 /** Relevance score (higher is better). Comparable only within a single query. */3704 score: number;3705}3706/** Options for the ingest() method. */3707interface AgentMemoryIngestOptions {3708 /** Session identifier to associate with memories created during ingestion. */3709 sessionId?: string | null | undefined;3710}3711/** Options for the getSummary() method. */3712interface AgentMemoryGetSummaryOptions {3713 /** Session identifier to retrieve session summary for. */3714 sessionId?: string | null | undefined;3715}3716/** Response from the getSummary() method. */3717interface AgentMemoryGetSummaryResponse {3718 /** Markdown summary. */3719 summary: string;3720}3721/**3722 * Options for the recall() method.3723 *3724 * `referenceDate` accepts a Date object, an ISO-8601 date string3725 * (YYYY-MM-DD), or a full ISO-8601 datetime string. When provided, this3726 * date is used as "today" for resolving relative time references3727 * ("how many days ago", "last week") instead of the server's wall-clock time.3728 */3729interface AgentMemoryRecallOptions {3730 /** Recall intensity: "low" (default), "medium", or "high". */3731 thinkingLevel?: AgentMemoryThinkingLevel;3732 /** Response verbosity: "short", "medium" (default), or "long". */3733 responseLength?: AgentMemoryResponseLength;3734 /** Temporal anchor for date arithmetic. */3735 referenceDate?: Date | string;3736}3737/** Response from the recall() method. */3738interface AgentMemoryRecallResult {3739 /** Number of memories retrieved. */3740 count: number;3741 /** LLM-generated answer synthesizing the matching memories. */3742 answer: string;3743 /** Matching memories ranked by relevance. */3744 candidates: AgentMemoryScoredCandidate[];3745}3746/**3747 * Options for the list() method.3748 *3749 * `cursor` is the opaque continuation token returned by the previous page;3750 * pass it back unchanged to fetch the next page. `sessionId` and `type`3751 * are exact-match filters; combining them is allowed.3752 */3753interface AgentMemoryListMemoriesOptions {3754 /** Maximum number of memories to return. Default 20, max 500. */3755 limit?: number;3756 /** Opaque cursor from a previous page. */3757 cursor?: string;3758 /** Exact-match session filter. */3759 sessionId?: string;3760 /** Exact-match memory-type filter. */3761 type?: AgentMemoryMemoryType;3762}3763/** Response from the list() method. */3764interface AgentMemoryListMemoriesResult {3765 memories: AgentMemoryMemoryListEntry[];3766 /** Continuation cursor; absent when this page exhausted the result set. */3767 cursor?: string;3768}3769/**3770 * A single Agent Memory profile, scoped to a profile name.3771 *3772 * Returned by {@link AgentMemoryNamespace.getProfile}.3773 */3774declare abstract class AgentMemoryProfile {3775 /**3776 * Retrieve a memory by ID.3777 *3778 * @param memoryId - ULID of the memory to retrieve.3779 * @throws if the memory does not exist.3780 */3781 get(memoryId: string): Promise<AgentMemoryMemory>;3782 /**3783 * Delete a memory by ID.3784 *3785 * Removes the memory and any source messages linked by the memory's3786 * source message IDs.3787 *3788 * @param memoryId - ULID of the memory to delete.3789 * @throws if the memory does not exist.3790 */3791 delete(memoryId: string): Promise<AgentMemoryMemory>;3792 /**3793 * Store a memory in this profile. The content is automatically classified,3794 * summarized, and indexed.3795 *3796 * @param memory - Raw memory content to persist.3797 */3798 remember(memory: AgentMemoryIncomingMemory): Promise<AgentMemoryMemory>;3799 /**3800 * Extract memories from a conversation.3801 *3802 * @param messages - Conversation messages to extract memories from.3803 * @param options - Optional ingest options.3804 */3805 ingest(messages: Iterable<AgentMemoryMessage>, options?: AgentMemoryIngestOptions): Promise<void>;3806 /**3807 * Get a profile summary.3808 *3809 * @param options - Optional getSummary options.3810 */3811 getSummary(options?: AgentMemoryGetSummaryOptions): Promise<AgentMemoryGetSummaryResponse>;3812 /**3813 * Recall memories in this profile.3814 *3815 * @param query - Recall query matched against memory content and keywords.3816 * @param options - Optional recall parameters.3817 * @returns Matching memories with relevance scores and a synthesized answer.3818 */3819 recall(query: string, options?: AgentMemoryRecallOptions): Promise<AgentMemoryRecallResult>;3820 /**3821 * List active memories in this profile.3822 *3823 * Returns a paginated, filterable view of stored memories. Superseded3824 * versions are excluded. Use the returned `cursor` (when present) to3825 * fetch the next page.3826 *3827 * @param options - Optional pagination and filter options.3828 */3829 list(options?: AgentMemoryListMemoriesOptions): Promise<AgentMemoryListMemoriesResult>;3830 /**3831 * Soft-delete every memory and message in this profile that is tagged3832 * with `sessionId`.3833 *3834 * Idempotent: deleting a sessionId that has no rows is a no-op.3835 *3836 * @param sessionId - Session to delete.3837 */3838 deleteSession(sessionId: string): Promise<void>;3839}3840/**3841 * Namespace-level Agent Memory binding.3842 *3843 * Used as the type of an `env.MEMORY`-style binding backed by the Agent3844 * Memory product.3845 *3846 * @example3847 * ```ts3848 * export default {3849 * async fetch(_request: Request, env: Env): Promise<Response> {3850 * const profile = await env.MEMORY.getProfile("wrangler-e2e");3851 * const summary = await profile.getSummary();3852 * return Response.json(summary);3853 * },3854 * };3855 * ```3856 */3857declare abstract class AgentMemoryNamespace {3858 /**3859 * Get a memory profile by name. Profiles are isolated by namespace and3860 * addressed by a compound key (namespaceId:profileName).3861 *3862 * @param profileName - Profile name (validated against naming rules).3863 * @returns RPC target for interacting with the profile.3864 */3865 getProfile(profileName: string): Promise<AgentMemoryProfile>;3866 /**3867 * Soft-delete a profile and schedule deferred purge. Marks all3868 * memories and messages as deleted.3869 *3870 * @param profileName - Name of the profile to delete.3871 */3872 deleteProfile(profileName: string): Promise<void>;3873}3874// ============ AI Search Error Interfaces ============3875interface AiSearchInternalError extends Error {3876}3877interface AiSearchNotFoundError extends Error {3878}3879// ============ AI Search Common Types ============3880/** A single message in a conversation-style search or chat request. */3881type AiSearchMessage = {3882 role: 'system' | 'developer' | 'user' | 'assistant' | 'tool';3883 content: string | null;3884};3885/**3886 * Common shape for `ai_search_options` used by both single-instance and multi-instance requests.3887 * Contains retrieval, query rewrite, reranking, and cache sub-options.3888 */3889type AiSearchOptions = {3890 retrieval?: {3891 /** Which retrieval backend to use. Defaults to the instance's configured index_method. */3892 retrieval_type?: 'vector' | 'keyword' | 'hybrid';3893 /** Fusion method for combining vector + keyword results. */3894 fusion_method?: 'max' | 'rrf';3895 /** How keyword terms are combined: "and" = all terms must match, "or" = any term matches. */3896 keyword_match_mode?: 'and' | 'or';3897 /** Minimum similarity score (0-1) for a result to be included. Default 0.4. */3898 match_threshold?: number;3899 /** Maximum number of results to return (1-50). Default 10. */3900 max_num_results?: number;3901 /** Vectorize metadata filters applied to the search. */3902 filters?: VectorizeVectorMetadataFilter;3903 /** Number of surrounding chunks to include for context (0-3). Default 0. */3904 context_expansion?: number;3905 /** If true, return only item metadata without chunk text. */3906 metadata_only?: boolean;3907 /** If true (default), return empty results on retrieval failure instead of throwing. */3908 return_on_failure?: boolean;3909 /** Boost results by metadata field values. Max 3 entries. */3910 boost_by?: Array<{3911 field: string;3912 direction?: 'asc' | 'desc' | 'exists' | 'not_exists';3913 }>;3914 [key: string]: unknown;3915 };3916 query_rewrite?: {3917 enabled?: boolean;3918 model?: string;3919 rewrite_prompt?: string;3920 [key: string]: unknown;3921 };3922 reranking?: {3923 enabled?: boolean;3924 model?: string;3925 /** Match threshold (0-1, default 0.4) */3926 match_threshold?: number;3927 [key: string]: unknown;3928 };3929 cache?: {3930 enabled?: boolean;3931 cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes';3932 };3933 [key: string]: unknown;3934};3935// ============ AI Search Request Types ============3936/**3937 * Request body for single-instance search.3938 * Exactly one of `query` or `messages` must be provided.3939 */3940type AiSearchSearchRequest = {3941 /** Simple query string. */3942 query: string;3943 messages?: never;3944 ai_search_options?: AiSearchOptions;3945} | {3946 query?: never;3947 /** Conversation-style input. At least one user message with non-empty content is required. */3948 messages: AiSearchMessage[];3949 ai_search_options?: AiSearchOptions;3950};3951type AiSearchChatCompletionsRequest = {3952 messages: AiSearchMessage[];3953 model?: string;3954 stream?: boolean;3955 ai_search_options?: AiSearchOptions;3956 [key: string]: unknown;3957};3958// ============ AI Search Multi-Instance Types (Namespace-Scoped) ============3959/** `ai_search_options` shape for multi-instance requests — requires `instance_ids`. */3960type AiSearchMultiSearchOptions = AiSearchOptions & {3961 /** Instance IDs to search across (1-10). */3962 instance_ids: string[];3963};3964/**3965 * Request for searching across multiple instances within a namespace.3966 * `ai_search_options` is required and must include `instance_ids`.3967 * Exactly one of `query` or `messages` must be provided.3968 */3969type AiSearchMultiSearchRequest = {3970 /** Simple query string. */3971 query: string;3972 messages?: never;3973 ai_search_options: AiSearchMultiSearchOptions;3974} | {3975 query?: never;3976 /** Conversation-style input. */3977 messages: AiSearchMessage[];3978 ai_search_options: AiSearchMultiSearchOptions;3979};3980/** A search result chunk tagged with the instance it originated from. */3981type AiSearchMultiSearchChunk = AiSearchSearchResponse['chunks'][number] & {3982 instance_id: string;3983};3984/** Describes a per-instance error during a multi-instance operation. */3985type AiSearchMultiSearchError = {3986 instance_id: string;3987 message: string;3988};3989/** Response from a multi-instance search, with chunks tagged by instance and optional partial-failure errors. */3990type AiSearchMultiSearchResponse = {3991 search_query: string;3992 chunks: AiSearchMultiSearchChunk[];3993 errors?: AiSearchMultiSearchError[];3994};3995/** Request for chat completions across multiple instances within a namespace. `ai_search_options` is required and must include `instance_ids`. */3996type AiSearchMultiChatCompletionsRequest = Omit<AiSearchChatCompletionsRequest, 'ai_search_options'> & {3997 ai_search_options: AiSearchMultiSearchOptions;3998};3999/** Response from multi-instance chat completions, with chunks tagged by instance and optional partial-failure errors. */4000type AiSearchMultiChatCompletionsResponse = Omit<AiSearchChatCompletionsResponse, 'chunks'> & {4001 chunks: AiSearchMultiSearchChunk[];4002 errors?: AiSearchMultiSearchError[];4003};4004// ============ AI Search Response Types ============4005type AiSearchSearchResponse = {4006 search_query: string;4007 chunks: Array<{4008 id: string;4009 type: string;4010 /** Match score (0-1) */4011 score: number;4012 text: string;4013 item: {4014 timestamp?: number;4015 key: string;4016 metadata?: Record<string, unknown>;4017 };4018 scoring_details?: {4019 /** Keyword match score (0-1) */4020 keyword_score?: number;4021 /** Vector similarity score (0-1) */4022 vector_score?: number;4023 /** Keyword rank position */4024 keyword_rank?: number;4025 /** Vector rank position */4026 vector_rank?: number;4027 /** Reranking model score */4028 reranking_score?: number;4029 /** Fusion method used to combine results */4030 fusion_method?: 'rrf' | 'max';4031 [key: string]: unknown;4032 };4033 }>;4034};4035type AiSearchChatCompletionsResponse = {4036 id?: string;4037 object?: string;4038 model?: string;4039 choices: Array<{4040 index?: number;4041 message: {4042 role: 'system' | 'developer' | 'user' | 'assistant' | 'tool';4043 content: string | null;4044 [key: string]: unknown;4045 };4046 [key: string]: unknown;4047 }>;4048 chunks: AiSearchSearchResponse['chunks'];4049 [key: string]: unknown;4050};4051type AiSearchStatsResponse = {4052 queued?: number;4053 running?: number;4054 completed?: number;4055 error?: number;4056 skipped?: number;4057 outdated?: number;4058 last_activity?: string;4059 /** Storage engine statistics. */4060 engine?: {4061 vectorize?: {4062 vectorsCount: number;4063 dimensions: number;4064 };4065 r2?: {4066 payloadSizeBytes: number;4067 metadataSizeBytes: number;4068 objectCount: number;4069 };4070 };4071};4072// ============ AI Search Instance Info Types ============4073type AiSearchInstanceInfo = {4074 id: string;4075 type?: 'r2' | 'web-crawler' | string;4076 source?: string;4077 source_params?: unknown;4078 paused?: boolean;4079 status?: string;4080 namespace?: string;4081 created_at?: string;4082 modified_at?: string;4083 token_id?: string;4084 ai_gateway_id?: string;4085 rewrite_query?: boolean;4086 reranking?: boolean;4087 embedding_model?: string;4088 ai_search_model?: string;4089 rewrite_model?: string;4090 reranking_model?: string;4091 /** @deprecated Use index_method instead. */4092 hybrid_search_enabled?: boolean;4093 /** Controls which storage backends are active. */4094 index_method?: {4095 vector?: boolean;4096 keyword?: boolean;4097 };4098 /** Fusion method for combining vector and keyword results. */4099 fusion_method?: 'max' | 'rrf';4100 indexing_options?: {4101 keyword_tokenizer?: 'porter' | 'trigram';4102 } | null;4103 retrieval_options?: {4104 keyword_match_mode?: 'and' | 'or';4105 boost_by?: Array<{4106 field: string;4107 direction?: 'asc' | 'desc' | 'exists' | 'not_exists';4108 }>;4109 } | null;4110 chunk?: boolean;4111 chunk_size?: number;4112 chunk_overlap?: number;4113 score_threshold?: number;4114 max_num_results?: number;4115 cache?: boolean;4116 cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes';4117 custom_metadata?: Array<{4118 field_name: string;4119 data_type: 'text' | 'number' | 'boolean' | 'datetime';4120 }>;4121 /** Sync interval in seconds. */4122 sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400;4123 metadata?: Record<string, unknown>;4124 [key: string]: unknown;4125};4126/** Pagination, search, and ordering parameters for listing instances within a namespace. */4127type AiSearchListInstancesParams = {4128 page?: number;4129 per_page?: number;4130 /** Search instances by ID. */4131 search?: string;4132 /** Field to sort by. */4133 order_by?: 'created_at';4134 /** Sort direction. */4135 order_by_direction?: 'asc' | 'desc';4136};4137type AiSearchListResponse = {4138 result: AiSearchInstanceInfo[];4139 result_info?: {4140 count: number;4141 page: number;4142 per_page: number;4143 total_count: number;4144 };4145};4146// ============ AI Search Config Types ============4147type AiSearchConfig = {4148 /** Instance ID (1-32 chars, pattern: ^[a-z0-9_]+(?:-[a-z0-9_]+)*$) */4149 id: string;4150 /** Instance type. Omit to create with built-in storage. */4151 type?: 'r2' | 'web-crawler' | string;4152 /** Source URL (required for web-crawler type). */4153 source?: string;4154 source_params?: unknown;4155 /** Token ID (UUID format) */4156 token_id?: string;4157 ai_gateway_id?: string;4158 /** Enable query rewriting (default false) */4159 rewrite_query?: boolean;4160 /** Enable reranking (default false) */4161 reranking?: boolean;4162 embedding_model?: string;4163 ai_search_model?: string;4164 rewrite_model?: string;4165 reranking_model?: string;4166 /** @deprecated Use index_method instead. */4167 hybrid_search_enabled?: boolean;4168 /** Controls which storage backends are used during indexing. Defaults to vector-only. */4169 index_method?: {4170 vector?: boolean;4171 keyword?: boolean;4172 };4173 /** Fusion method for combining vector and keyword results. "rrf" = reciprocal rank fusion (default), "max" = maximum score. */4174 fusion_method?: 'max' | 'rrf';4175 indexing_options?: {4176 keyword_tokenizer?: 'porter' | 'trigram';4177 } | null;4178 retrieval_options?: {4179 keyword_match_mode?: 'and' | 'or';4180 boost_by?: Array<{4181 field: string;4182 direction?: 'asc' | 'desc' | 'exists' | 'not_exists';4183 }>;4184 } | null;4185 chunk?: boolean;4186 chunk_size?: number;4187 chunk_overlap?: number;4188 /** Minimum similarity score (0-1) for a result to be included. */4189 score_threshold?: number;4190 max_num_results?: number;4191 cache?: boolean;4192 /** Similarity threshold for cache hits. Stricter = fewer cache hits but higher relevance. */4193 cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes';4194 custom_metadata?: Array<{4195 field_name: string;4196 data_type: 'text' | 'number' | 'boolean' | 'datetime';4197 }>;4198 namespace?: string;4199 /** Sync interval in seconds. 3600=1h, 7200=2h, 14400=4h, 21600=6h, 43200=12h, 86400=24h. */4200 sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400;4201 metadata?: Record<string, unknown>;4202 [key: string]: unknown;4203};4204// ============ AI Search Item Types ============4205type AiSearchItemInfo = {4206 id: string;4207 key: string;4208 status: 'completed' | 'error' | 'skipped' | 'queued' | 'running' | 'outdated';4209 next_action?: 'INDEX' | 'DELETE' | null;4210 error?: string;4211 checksum?: string;4212 namespace?: string;4213 chunks_count?: number | null;4214 file_size?: number | null;4215 source_id?: string | null;4216 last_seen_at?: string;4217 created_at?: string;4218 metadata?: Record<string, unknown>;4219 [key: string]: unknown;4220};4221type AiSearchItemContentResult = {4222 body: ReadableStream;4223 contentType: string;4224 filename: string;4225 size: number;4226};4227type AiSearchUploadItemOptions = {4228 metadata?: Record<string, unknown>;4229};4230type AiSearchListItemsParams = {4231 page?: number;4232 per_page?: number;4233 /** Search items by key name. */4234 search?: string;4235 /** Sort order for results. */4236 sort_by?: 'status' | 'modified_at';4237 /** Filter items by processing status. */4238 status?: 'queued' | 'running' | 'completed' | 'error' | 'skipped' | 'outdated';4239 /** Filter items by source (e.g. "builtin" or "web-crawler:https://example.com"). */4240 source?: string;4241 /** JSON-encoded Vectorize filter for metadata filtering. */4242 metadata_filter?: string;4243 /** Filter items by their unique ID. Returns at most one item. */4244 item_id?: string;4245 /**4246 * Filter items by their exact key (object key / filename). Keys are unique4247 * per source, so combine with `source` to disambiguate across data sources.4248 */4249 key?: string;4250};4251type AiSearchListItemsResponse = {4252 result: AiSearchItemInfo[];4253 result_info?: {4254 count: number;4255 page: number;4256 per_page: number;4257 total_count: number;4258 };4259};4260// ============ AI Search Item Logs Types ============4261type AiSearchItemLogsParams = {4262 /** Maximum number of log entries to return (1-100, default 50). */4263 limit?: number;4264 /** Opaque cursor for pagination. Pass the `cursor` value from a previous response. */4265 cursor?: string;4266};4267type AiSearchItemLog = {4268 timestamp: string;4269 action: string;4270 message: string;4271 fileKey?: string;4272 chunkCount?: number;4273 processingTimeMs?: number;4274 errorType?: string;4275};4276/** Paginated response for item processing logs (cursor-based). */4277type AiSearchItemLogsResponse = {4278 result: AiSearchItemLog[];4279 result_info: {4280 count: number;4281 per_page: number;4282 cursor: string | null;4283 truncated: boolean;4284 };4285};4286// ============ AI Search Item Chunks Types ============4287type AiSearchItemChunksParams = {4288 /** Maximum number of chunks to return (1-100, default 20). */4289 limit?: number;4290 /** Offset into the chunks list (default 0). */4291 offset?: number;4292};4293/** A single indexed chunk belonging to an item, including its text content and byte range. */4294type AiSearchItemChunk = {4295 id: string;4296 text: string;4297 start_byte: number;4298 end_byte: number;4299 item?: {4300 timestamp?: number;4301 key: string;4302 metadata?: Record<string, unknown>;4303 };4304};4305/** Paginated response for item chunks (offset-based). */4306type AiSearchItemChunksResponse = {4307 result: AiSearchItemChunk[];4308 result_info: {4309 count: number;4310 total: number;4311 limit: number;4312 offset: number;4313 };4314};4315// ============ AI Search Job Types ============4316type AiSearchJobInfo = {4317 id: string;4318 source: 'user' | 'schedule';4319 description?: string;4320 last_seen_at?: string;4321 started_at?: string;4322 ended_at?: string;4323 end_reason?: string;4324};4325type AiSearchJobLog = {4326 id: number;4327 message: string;4328 message_type: number;4329 created_at: number;4330};4331type AiSearchCreateJobParams = {4332 description?: string;4333};4334type AiSearchListJobsParams = {4335 page?: number;4336 per_page?: number;4337};4338type AiSearchListJobsResponse = {4339 result: AiSearchJobInfo[];4340 result_info?: {4341 count: number;4342 page: number;4343 per_page: number;4344 total_count: number;4345 };4346};4347type AiSearchJobLogsParams = {4348 page?: number;4349 per_page?: number;4350};4351type AiSearchJobLogsResponse = {4352 result: AiSearchJobLog[];4353 result_info?: {4354 count: number;4355 page: number;4356 per_page: number;4357 total_count: number;4358 };4359};4360// ============ AI Search Sub-Service Classes ============4361/**4362 * Single item service for an AI Search instance.4363 * Provides info, download, sync, logs, and chunks operations on a specific item.4364 */4365declare abstract class AiSearchItem {4366 /** Get metadata about this item. */4367 info(): Promise<AiSearchItemInfo>;4368 /**4369 * Download the item's content.4370 * @returns Object with body stream, content type, filename, and size.4371 */4372 download(): Promise<AiSearchItemContentResult>;4373 /**4374 * Trigger re-indexing of this item.4375 * @returns The updated item info.4376 */4377 sync(): Promise<AiSearchItemInfo>;4378 /**4379 * Retrieve processing logs for this item (cursor-based pagination).4380 * @param params Optional pagination parameters (limit, cursor).4381 * @returns Paginated log entries for this item.4382 */4383 logs(params?: AiSearchItemLogsParams): Promise<AiSearchItemLogsResponse>;4384 /**4385 * List indexed chunks for this item (offset-based pagination).4386 * @param params Optional pagination parameters (limit, offset).4387 * @returns Paginated chunk entries for this item.4388 */4389 chunks(params?: AiSearchItemChunksParams): Promise<AiSearchItemChunksResponse>;4390}4391/**4392 * Items collection service for an AI Search instance.4393 * Provides list, upload, and access to individual items.4394 */4395declare abstract class AiSearchItems {4396 /** List items in this instance. */4397 list(params?: AiSearchListItemsParams): Promise<AiSearchListItemsResponse>;4398 /**4399 * Upload a file as an item. Behaves as an upsert: if an item with the same4400 * filename already exists, it is overwritten and re-indexed.4401 * @param name Filename for the uploaded item.4402 * @param content File content as a ReadableStream, Blob, or string.4403 * @param options Optional metadata to attach to the item.4404 * @returns The created item info.4405 */4406 upload(name: string, content: ReadableStream | Blob | string, options?: AiSearchUploadItemOptions): Promise<AiSearchItemInfo>;4407 /**4408 * Upload a file and poll until processing completes.4409 * Behaves as an upsert: if an item with the same filename already exists,4410 * it is overwritten and re-indexed.4411 * @param name Filename for the uploaded item.4412 * @param content File content as a ReadableStream, Blob, or string.4413 * @param options Optional metadata and polling configuration.4414 * @returns The item info after processing completes (or timeout).4415 */4416 uploadAndPoll(name: string, content: ReadableStream | Blob | string, options?: AiSearchUploadItemOptions & {4417 /** Polling interval in milliseconds (default 1000). */4418 pollIntervalMs?: number;4419 /** Maximum time to wait in milliseconds (default 30000). */4420 timeoutMs?: number;4421 }): Promise<AiSearchItemInfo>;4422 /**4423 * Get an item by ID.4424 * @param itemId The item identifier.4425 * @returns Item service for info, download, sync, logs, and chunks operations.4426 */4427 get(itemId: string): AiSearchItem;4428 /**4429 * Delete an item from the instance.4430 * @param itemId The item identifier.4431 */4432 delete(itemId: string): Promise<void>;4433}4434/**4435 * Single job service for an AI Search instance.4436 * Provides info, logs, and cancel operations for a specific job.4437 */4438declare abstract class AiSearchJob {4439 /** Get metadata about this job. */4440 info(): Promise<AiSearchJobInfo>;4441 /** Get logs for this job. */4442 logs(params?: AiSearchJobLogsParams): Promise<AiSearchJobLogsResponse>;4443 /**4444 * Cancel a running job.4445 * @returns The updated job info.4446 * @throws AiSearchNotFoundError if the job does not exist.4447 */4448 cancel(): Promise<AiSearchJobInfo>;4449}4450/**4451 * Jobs collection service for an AI Search instance.4452 * Provides list, create, and access to individual jobs.4453 */4454declare abstract class AiSearchJobs {4455 /** List jobs for this instance. */4456 list(params?: AiSearchListJobsParams): Promise<AiSearchListJobsResponse>;4457 /**4458 * Create a new indexing job.4459 * @param params Optional job parameters.4460 * @returns The created job info.4461 */4462 create(params?: AiSearchCreateJobParams): Promise<AiSearchJobInfo>;4463 /**4464 * Get a job by ID.4465 * @param jobId The job identifier.4466 * @returns Job service for info, logs, and cancel operations.4467 */4468 get(jobId: string): AiSearchJob;4469}4470// ============ AI Search Binding Classes ============4471/**4472 * Instance-level AI Search service.4473 *4474 * Used as:4475 * - The return type of `AiSearchNamespace.get(name)` (namespace binding)4476 * - The type of `env.BLOG_SEARCH` (single instance binding via `ai_search`)4477 *4478 * Provides search, chat, update, stats, items, and jobs operations.4479 *4480 * @example4481 * ```ts4482 * // Via namespace binding4483 * const instance = env.AI_SEARCH.get("blog");4484 * const results = await instance.search({4485 * query: "How does caching work?",4486 * });4487 *4488 * // Via single instance binding4489 * const results = await env.BLOG_SEARCH.search({4490 * messages: [{ role: "user", content: "How does caching work?" }],4491 * });4492 * ```4493 */4494declare abstract class AiSearchInstance {4495 /**4496 * Search the AI Search instance for relevant chunks.4497 * @param params Search request with query or messages and optional AI search options.4498 * @returns Search response with matching chunks and search query.4499 */4500 search(params: AiSearchSearchRequest): Promise<AiSearchSearchResponse>;4501 /**4502 * Generate chat completions with AI Search context (streaming).4503 * @param params Chat completions request with stream: true.4504 * @returns ReadableStream of server-sent events.4505 */4506 chatCompletions(params: AiSearchChatCompletionsRequest & {4507 stream: true;4508 }): Promise<ReadableStream>;4509 /**4510 * Generate chat completions with AI Search context.4511 * @param params Chat completions request.4512 * @returns Chat completion response with choices and RAG chunks.4513 */4514 chatCompletions(params: AiSearchChatCompletionsRequest): Promise<AiSearchChatCompletionsResponse>;4515 /**4516 * Update the instance configuration.4517 * @param config Partial configuration to update.4518 * @returns Updated instance info.4519 */4520 update(config: Partial<AiSearchConfig>): Promise<AiSearchInstanceInfo>;4521 /** Get metadata about this instance. */4522 info(): Promise<AiSearchInstanceInfo>;4523 /**4524 * Get instance statistics (item count, indexing status, etc.).4525 * @returns Statistics with counts per status, last activity time, and engine details.4526 */4527 stats(): Promise<AiSearchStatsResponse>;4528 /** Items collection — list, upload, and manage items in this instance. */4529 get items(): AiSearchItems;4530 /** Jobs collection — list, create, and inspect indexing jobs. */4531 get jobs(): AiSearchJobs;4532}4533/**4534 * Namespace-level AI Search service.4535 *4536 * Used as the type of `env.AI_SEARCH` (namespace binding via `ai_search_namespaces`).4537 * Scoped to a single namespace. Provides dynamic instance access, creation, deletion,4538 * and multi-instance search/chat operations.4539 *4540 * @example4541 * ```ts4542 * // Access an instance within the namespace4543 * const blog = env.AI_SEARCH.get("blog");4544 * const results = await blog.search({ query: "How does caching work?" });4545 *4546 * // List all instances in the namespace4547 * const instances = await env.AI_SEARCH.list();4548 *4549 * // Create a new instance with built-in storage4550 * const tenant = await env.AI_SEARCH.create({ id: "tenant-123" });4551 *4552 * // Upload items into the instance4553 * await tenant.items.upload("doc.pdf", fileContent);4554 *4555 * // Search across multiple instances4556 * const multi = await env.AI_SEARCH.search({4557 * query: "caching",4558 * ai_search_options: { instance_ids: ["blog", "docs"] },4559 * });4560 *4561 * // Delete an instance4562 * await env.AI_SEARCH.delete("tenant-123");4563 * ```4564 */4565declare abstract class AiSearchNamespace {4566 /**4567 * Get an instance by name within the bound namespace.4568 * @param name Instance name.4569 * @returns Instance service for search, chat, update, stats, items, and jobs.4570 */4571 get(name: string): AiSearchInstance;4572 /**4573 * List instances in the bound namespace.4574 * @param params Optional pagination, search, and ordering parameters.4575 * @returns Array of instance metadata with pagination info.4576 */4577 list(params?: AiSearchListInstancesParams): Promise<AiSearchListResponse>;4578 /**4579 * Create a new instance within the bound namespace.4580 * @param config Instance configuration. Only `id` is required — omit `type` and `source` to create with built-in storage.4581 * @returns Instance service for the newly created instance.4582 *4583 * @example4584 * ```ts4585 * // Create with built-in storage (upload items manually)4586 * const instance = await env.AI_SEARCH.create({ id: "my-search" });4587 *4588 * // Create with web crawler source4589 * const instance = await env.AI_SEARCH.create({4590 * id: "docs-search",4591 * type: "web-crawler",4592 * source: "https://developers.cloudflare.com",4593 * });4594 * ```4595 */4596 create(config: AiSearchConfig): Promise<AiSearchInstance>;4597 /**4598 * Delete an instance from the bound namespace.4599 * @param name Instance name to delete.4600 */4601 delete(name: string): Promise<void>;4602 /**4603 * Search across multiple instances within the bound namespace.4604 * Fans out to the specified instance_ids and merges results.4605 * @param params Search request with required `ai_search_options.instance_ids`.4606 * @returns Search response with chunks tagged by instance_id and optional partial-failure errors.4607 */4608 search(params: AiSearchMultiSearchRequest): Promise<AiSearchMultiSearchResponse>;4609 /**4610 * Generate chat completions across multiple instances within the bound namespace (streaming).4611 * Fans out to the specified instance_ids, merges context, and generates a response.4612 * @param params Chat completions request with stream: true and required `ai_search_options.instance_ids`.4613 * @returns ReadableStream of server-sent events.4614 */4615 chatCompletions(params: AiSearchMultiChatCompletionsRequest & {4616 stream: true;4617 }): Promise<ReadableStream>;4618 /**4619 * Generate chat completions across multiple instances within the bound namespace.4620 * Fans out to the specified instance_ids, merges context, and generates a response.4621 * @param params Chat completions request with required `ai_search_options.instance_ids`.4622 * @returns Chat completion response with choices, chunks tagged by instance_id, and optional partial-failure errors.4623 */4624 chatCompletions(params: AiSearchMultiChatCompletionsRequest): Promise<AiSearchMultiChatCompletionsResponse>;4625}4626type AiImageClassificationInput = {4627 image: number[];4628};4629type AiImageClassificationOutput = {4630 score?: number;4631 label?: string;4632}[];4633declare abstract class BaseAiImageClassification {4634 inputs: AiImageClassificationInput;4635 postProcessedOutputs: AiImageClassificationOutput;4636}4637type AiImageToTextInput = {4638 image: number[];4639 prompt?: string;4640 max_tokens?: number;4641 temperature?: number;4642 top_p?: number;4643 top_k?: number;4644 seed?: number;4645 repetition_penalty?: number;4646 frequency_penalty?: number;4647 presence_penalty?: number;4648 raw?: boolean;4649 messages?: RoleScopedChatInput[];4650};4651type AiImageToTextOutput = {4652 description: string;4653};4654declare abstract class BaseAiImageToText {4655 inputs: AiImageToTextInput;4656 postProcessedOutputs: AiImageToTextOutput;4657}4658type AiImageTextToTextInput = {4659 image: string;4660 prompt?: string;4661 max_tokens?: number;4662 temperature?: number;4663 ignore_eos?: boolean;4664 top_p?: number;4665 top_k?: number;4666 seed?: number;4667 repetition_penalty?: number;4668 frequency_penalty?: number;4669 presence_penalty?: number;4670 raw?: boolean;4671 messages?: RoleScopedChatInput[];4672};4673type AiImageTextToTextOutput = {4674 description: string;4675};4676declare abstract class BaseAiImageTextToText {4677 inputs: AiImageTextToTextInput;4678 postProcessedOutputs: AiImageTextToTextOutput;4679}4680type AiMultimodalEmbeddingsInput = {4681 image: string;4682 text: string[];4683};4684type AiIMultimodalEmbeddingsOutput = {4685 data: number[][];4686 shape: number[];4687};4688declare abstract class BaseAiMultimodalEmbeddings {4689 inputs: AiImageTextToTextInput;4690 postProcessedOutputs: AiImageTextToTextOutput;4691}4692type AiObjectDetectionInput = {4693 image: number[];4694};4695type AiObjectDetectionOutput = {4696 score?: number;4697 label?: string;4698}[];4699declare abstract class BaseAiObjectDetection {4700 inputs: AiObjectDetectionInput;4701 postProcessedOutputs: AiObjectDetectionOutput;4702}4703type AiSentenceSimilarityInput = {4704 source: string;4705 sentences: string[];4706};4707type AiSentenceSimilarityOutput = number[];4708declare abstract class BaseAiSentenceSimilarity {4709 inputs: AiSentenceSimilarityInput;4710 postProcessedOutputs: AiSentenceSimilarityOutput;4711}4712type AiAutomaticSpeechRecognitionInput = {4713 audio: number[];4714};4715type AiAutomaticSpeechRecognitionOutput = {4716 text?: string;4717 words?: {4718 word: string;4719 start: number;4720 end: number;4721 }[];4722 vtt?: string;4723};4724declare abstract class BaseAiAutomaticSpeechRecognition {4725 inputs: AiAutomaticSpeechRecognitionInput;4726 postProcessedOutputs: AiAutomaticSpeechRecognitionOutput;4727}4728type AiSummarizationInput = {4729 input_text: string;4730 max_length?: number;4731};4732type AiSummarizationOutput = {4733 summary: string;4734};4735declare abstract class BaseAiSummarization {4736 inputs: AiSummarizationInput;4737 postProcessedOutputs: AiSummarizationOutput;4738}4739type AiTextClassificationInput = {4740 text: string;4741};4742type AiTextClassificationOutput = {4743 score?: number;4744 label?: string;4745}[];4746declare abstract class BaseAiTextClassification {4747 inputs: AiTextClassificationInput;4748 postProcessedOutputs: AiTextClassificationOutput;4749}4750type AiTextEmbeddingsInput = {4751 text: string | string[];4752};4753type AiTextEmbeddingsOutput = {4754 shape: number[];4755 data: number[][];4756};4757declare abstract class BaseAiTextEmbeddings {4758 inputs: AiTextEmbeddingsInput;4759 postProcessedOutputs: AiTextEmbeddingsOutput;4760}4761type RoleScopedChatInput = {4762 role: "user" | "assistant" | "system" | "tool" | (string & NonNullable<unknown>);4763 content: string;4764 name?: string;4765};4766type AiTextGenerationToolLegacyInput = {4767 name: string;4768 description: string;4769 parameters?: {4770 type: "object" | (string & NonNullable<unknown>);4771 properties: {4772 [key: string]: {4773 type: string;4774 description?: string;4775 };4776 };4777 required: string[];4778 };4779};4780type AiTextGenerationToolInput = {4781 type: "function" | (string & NonNullable<unknown>);4782 function: {4783 name: string;4784 description: string;4785 parameters?: {4786 type: "object" | (string & NonNullable<unknown>);4787 properties: {4788 [key: string]: {4789 type: string;4790 description?: string;4791 };4792 };4793 required: string[];4794 };4795 };4796};4797type AiTextGenerationFunctionsInput = {4798 name: string;4799 code: string;4800};4801type AiTextGenerationResponseFormat = {4802 type: string;4803 json_schema?: any;4804};4805type AiTextGenerationInput = {4806 prompt?: string;4807 raw?: boolean;4808 stream?: boolean;4809 max_tokens?: number;4810 temperature?: number;4811 top_p?: number;4812 top_k?: number;4813 seed?: number;4814 repetition_penalty?: number;4815 frequency_penalty?: number;4816 presence_penalty?: number;4817 messages?: RoleScopedChatInput[];4818 response_format?: AiTextGenerationResponseFormat;4819 tools?: AiTextGenerationToolInput[] | AiTextGenerationToolLegacyInput[] | (object & NonNullable<unknown>);4820 functions?: AiTextGenerationFunctionsInput[];4821};4822type AiTextGenerationToolLegacyOutput = {4823 name: string;4824 arguments: unknown;4825};4826type AiTextGenerationToolOutput = {4827 id: string;4828 type: "function";4829 function: {4830 name: string;4831 arguments: string;4832 };4833};4834type UsageTags = {4835 prompt_tokens: number;4836 completion_tokens: number;4837 total_tokens: number;4838};4839type AiTextGenerationOutput = {4840 response?: string;4841 tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[];4842 usage?: UsageTags;4843};4844declare abstract class BaseAiTextGeneration {4845 inputs: AiTextGenerationInput;4846 postProcessedOutputs: AiTextGenerationOutput;4847}4848type AiTextToSpeechInput = {4849 prompt: string;4850 lang?: string;4851};4852type AiTextToSpeechOutput = Uint8Array | {4853 audio: string;4854};4855declare abstract class BaseAiTextToSpeech {4856 inputs: AiTextToSpeechInput;4857 postProcessedOutputs: AiTextToSpeechOutput;4858}4859type AiTextToImageInput = {4860 prompt: string;4861 negative_prompt?: string;4862 height?: number;4863 width?: number;4864 image?: number[];4865 image_b64?: string;4866 mask?: number[];4867 num_steps?: number;4868 strength?: number;4869 guidance?: number;4870 seed?: number;4871};4872type AiTextToImageOutput = ReadableStream<Uint8Array>;4873declare abstract class BaseAiTextToImage {4874 inputs: AiTextToImageInput;4875 postProcessedOutputs: AiTextToImageOutput;4876}4877type AiTranslationInput = {4878 text: string;4879 target_lang: string;4880 source_lang?: string;4881};4882type AiTranslationOutput = {4883 translated_text?: string;4884};4885declare abstract class BaseAiTranslation {4886 inputs: AiTranslationInput;4887 postProcessedOutputs: AiTranslationOutput;4888}4889/**4890 * Workers AI support for OpenAI's Chat Completions API4891 */4892type ChatCompletionContentPartText = {4893 type: "text";4894 text: string;4895};4896type ChatCompletionContentPartImage = {4897 type: "image_url";4898 image_url: {4899 url: string;4900 detail?: "auto" | "low" | "high";4901 };4902};4903type ChatCompletionContentPartInputAudio = {4904 type: "input_audio";4905 input_audio: {4906 /** Base64 encoded audio data. */4907 data: string;4908 format: "wav" | "mp3";4909 };4910};4911type ChatCompletionContentPartFile = {4912 type: "file";4913 file: {4914 /** Base64 encoded file data. */4915 file_data?: string;4916 /** The ID of an uploaded file. */4917 file_id?: string;4918 filename?: string;4919 };4920};4921type ChatCompletionContentPartRefusal = {4922 type: "refusal";4923 refusal: string;4924};4925type ChatCompletionContentPart = ChatCompletionContentPartText | ChatCompletionContentPartImage | ChatCompletionContentPartInputAudio | ChatCompletionContentPartFile;4926type FunctionDefinition = {4927 name: string;4928 description?: string;4929 parameters?: Record<string, unknown>;4930 strict?: boolean | null;4931};4932type ChatCompletionFunctionTool = {4933 type: "function";4934 function: FunctionDefinition;4935};4936type ChatCompletionCustomToolGrammarFormat = {4937 type: "grammar";4938 grammar: {4939 definition: string;4940 syntax: "lark" | "regex";4941 };4942};4943type ChatCompletionCustomToolTextFormat = {4944 type: "text";4945};4946type ChatCompletionCustomToolFormat = ChatCompletionCustomToolTextFormat | ChatCompletionCustomToolGrammarFormat;4947type ChatCompletionCustomTool = {4948 type: "custom";4949 custom: {4950 name: string;4951 description?: string;4952 format?: ChatCompletionCustomToolFormat;4953 };4954};4955type ChatCompletionTool = ChatCompletionFunctionTool | ChatCompletionCustomTool;4956type ChatCompletionMessageFunctionToolCall = {4957 id: string;4958 type: "function";4959 function: {4960 name: string;4961 /** JSON-encoded arguments string. */4962 arguments: string;4963 };4964};4965type ChatCompletionMessageCustomToolCall = {4966 id: string;4967 type: "custom";4968 custom: {4969 name: string;4970 input: string;4971 };4972};4973type ChatCompletionMessageToolCall = ChatCompletionMessageFunctionToolCall | ChatCompletionMessageCustomToolCall;4974type ChatCompletionToolChoiceFunction = {4975 type: "function";4976 function: {4977 name: string;4978 };4979};4980type ChatCompletionToolChoiceCustom = {4981 type: "custom";4982 custom: {4983 name: string;4984 };4985};4986type ChatCompletionToolChoiceAllowedTools = {4987 type: "allowed_tools";4988 allowed_tools: {4989 mode: "auto" | "required";4990 tools: Array<Record<string, unknown>>;4991 };4992};4993type ChatCompletionToolChoiceOption = "none" | "auto" | "required" | ChatCompletionToolChoiceFunction | ChatCompletionToolChoiceCustom | ChatCompletionToolChoiceAllowedTools;4994type DeveloperMessage = {4995 role: "developer";4996 content: string | Array<{4997 type: "text";4998 text: string;4999 }>;5000 name?: string;5001};5002type SystemMessage = {5003 role: "system";5004 content: string | Array<{5005 type: "text";5006 text: string;5007 }>;5008 name?: string;5009};5010/**5011 * Permissive merged content part used inside UserMessage arrays.5012 *5013 * Cabidela has a limitation where anyOf/oneOf with enum-based discrimination5014 * inside nested array items does not correctly match different branches for5015 * different array elements, so the schema uses a single merged object.5016 */5017type UserMessageContentPart = {5018 type: "text" | "image_url" | "input_audio" | "file";5019 text?: string;5020 image_url?: {5021 url?: string;5022 detail?: "auto" | "low" | "high";5023 };5024 input_audio?: {5025 data?: string;5026 format?: "wav" | "mp3";5027 };5028 file?: {5029 file_data?: string;5030 file_id?: string;5031 filename?: string;5032 };5033};5034type UserMessage = {5035 role: "user";5036 content: string | Array<UserMessageContentPart>;5037 name?: string;5038};5039type AssistantMessageContentPart = {5040 type: "text" | "refusal";5041 text?: string;5042 refusal?: string;5043};5044type AssistantMessage = {5045 role: "assistant";5046 content?: string | null | Array<AssistantMessageContentPart>;5047 refusal?: string | null;5048 name?: string;5049 audio?: {5050 id: string;5051 };5052 tool_calls?: Array<ChatCompletionMessageToolCall>;5053 function_call?: {5054 name: string;5055 arguments: string;5056 };5057};5058type ToolMessage = {5059 role: "tool";5060 content: string | Array<{5061 type: "text";5062 text: string;5063 }>;5064 tool_call_id: string;5065};5066type FunctionMessage = {5067 role: "function";5068 content: string;5069 name: string;5070};5071type ChatCompletionMessageParam = DeveloperMessage | SystemMessage | UserMessage | AssistantMessage | ToolMessage | FunctionMessage;5072type ChatCompletionsResponseFormatText = {5073 type: "text";5074};5075type ChatCompletionsResponseFormatJSONObject = {5076 type: "json_object";5077};5078type ResponseFormatJSONSchema = {5079 type: "json_schema";5080 json_schema: {5081 name: string;5082 description?: string;5083 schema?: Record<string, unknown>;5084 strict?: boolean | null;5085 };5086};5087type ResponseFormat = ChatCompletionsResponseFormatText | ChatCompletionsResponseFormatJSONObject | ResponseFormatJSONSchema;5088type ChatCompletionsStreamOptions = {5089 include_usage?: boolean;5090 include_obfuscation?: boolean;5091};5092type PredictionContent = {5093 type: "content";5094 content: string | Array<{5095 type: "text";5096 text: string;5097 }>;5098};5099type AudioParams = {5100 voice: string | {5101 id: string;5102 };5103 format: "wav" | "aac" | "mp3" | "flac" | "opus" | "pcm16";5104};5105type WebSearchUserLocation = {5106 type: "approximate";5107 approximate: {5108 city?: string;5109 country?: string;5110 region?: string;5111 timezone?: string;5112 };5113};5114type WebSearchOptions = {5115 search_context_size?: "low" | "medium" | "high";5116 user_location?: WebSearchUserLocation;5117};5118type ChatTemplateKwargs = {5119 /** Whether to enable reasoning, enabled by default. */5120 enable_thinking?: boolean;5121 /** If false, preserves reasoning context between turns. */5122 clear_thinking?: boolean;5123};5124/** Shared optional properties used by both Prompt and Messages input branches. */5125type ChatCompletionsCommonOptions = {5126 model?: string;5127 audio?: AudioParams;5128 frequency_penalty?: number | null;5129 logit_bias?: Record<string, unknown> | null;5130 logprobs?: boolean | null;5131 top_logprobs?: number | null;5132 max_tokens?: number | null;5133 max_completion_tokens?: number | null;5134 metadata?: Record<string, unknown> | null;5135 modalities?: Array<"text" | "audio"> | null;5136 n?: number | null;5137 parallel_tool_calls?: boolean;5138 prediction?: PredictionContent;5139 presence_penalty?: number | null;5140 reasoning_effort?: "low" | "medium" | "high" | null;5141 chat_template_kwargs?: ChatTemplateKwargs;5142 response_format?: ResponseFormat;5143 seed?: number | null;5144 service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;5145 stop?: string | Array<string> | null;5146 store?: boolean | null;5147 stream?: boolean | null;5148 stream_options?: ChatCompletionsStreamOptions;5149 temperature?: number | null;5150 tool_choice?: ChatCompletionToolChoiceOption;5151 tools?: Array<ChatCompletionTool>;5152 top_p?: number | null;5153 user?: string;5154 web_search_options?: WebSearchOptions;5155 function_call?: "none" | "auto" | {5156 name: string;5157 };5158 functions?: Array<FunctionDefinition>;5159};5160type PromptTokensDetails = {5161 cached_tokens?: number;5162 audio_tokens?: number;5163};5164type CompletionTokensDetails = {5165 reasoning_tokens?: number;5166 audio_tokens?: number;5167 accepted_prediction_tokens?: number;5168 rejected_prediction_tokens?: number;5169};5170type CompletionUsage = {5171 prompt_tokens: number;5172 completion_tokens: number;5173 total_tokens: number;5174 prompt_tokens_details?: PromptTokensDetails;5175 completion_tokens_details?: CompletionTokensDetails;5176};5177type ChatCompletionTopLogprob = {5178 token: string;5179 logprob: number;5180 bytes: Array<number> | null;5181};5182type ChatCompletionTokenLogprob = {5183 token: string;5184 logprob: number;5185 bytes: Array<number> | null;5186 top_logprobs: Array<ChatCompletionTopLogprob>;5187};5188type ChatCompletionAudio = {5189 id: string;5190 /** Base64 encoded audio bytes. */5191 data: string;5192 expires_at: number;5193 transcript: string;5194};5195type ChatCompletionUrlCitation = {5196 type: "url_citation";5197 url_citation: {5198 url: string;5199 title: string;5200 start_index: number;5201 end_index: number;5202 };5203};5204type ChatCompletionResponseMessage = {5205 role: "assistant";5206 content: string | null;5207 refusal: string | null;5208 annotations?: Array<ChatCompletionUrlCitation>;5209 audio?: ChatCompletionAudio;5210 tool_calls?: Array<ChatCompletionMessageToolCall>;5211 function_call?: {5212 name: string;5213 arguments: string;5214 } | null;5215};5216type ChatCompletionLogprobs = {5217 content: Array<ChatCompletionTokenLogprob> | null;5218 refusal?: Array<ChatCompletionTokenLogprob> | null;5219};5220type ChatCompletionChoice = {5221 index: number;5222 message: ChatCompletionResponseMessage;5223 finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | "function_call";5224 logprobs: ChatCompletionLogprobs | null;5225};5226type ChatCompletionsMessagesInput = {5227 messages: Array<ChatCompletionMessageParam>;5228} & ChatCompletionsCommonOptions;5229type ChatCompletionsOutput = {5230 id: string;5231 object: string;5232 created: number;5233 model: string;5234 choices: Array<ChatCompletionChoice>;5235 usage?: CompletionUsage;5236 system_fingerprint?: string | null;5237 service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;5238};5239/**5240 * Workers AI support for OpenAI's Responses API5241 * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts5242 *5243 * It's a stripped down version from its source.5244 * It currently supports basic function calling, json mode and accepts images as input.5245 *5246 * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools.5247 * We plan to add those incrementally as model + platform capabilities evolve.5248 */5249type ResponsesInput = {5250 background?: boolean | null;5251 conversation?: string | ResponseConversationParam | null;5252 include?: Array<ResponseIncludable> | null;5253 input?: string | ResponseInput;5254 instructions?: string | null;5255 max_output_tokens?: number | null;5256 parallel_tool_calls?: boolean | null;5257 previous_response_id?: string | null;5258 prompt_cache_key?: string;5259 reasoning?: Reasoning | null;5260 safety_identifier?: string;5261 service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;5262 stream?: boolean | null;5263 stream_options?: StreamOptions | null;5264 temperature?: number | null;5265 text?: ResponseTextConfig;5266 tool_choice?: ToolChoiceOptions | ToolChoiceFunction;5267 tools?: Array<Tool>;5268 top_p?: number | null;5269 truncation?: "auto" | "disabled" | null;5270};5271type ResponsesOutput = {5272 id?: string;5273 created_at?: number;5274 output_text?: string;5275 error?: ResponseError | null;5276 incomplete_details?: ResponseIncompleteDetails | null;5277 instructions?: string | Array<ResponseInputItem> | null;5278 object?: "response";5279 output?: Array<ResponseOutputItem>;5280 parallel_tool_calls?: boolean;5281 temperature?: number | null;5282 tool_choice?: ToolChoiceOptions | ToolChoiceFunction;5283 tools?: Array<Tool>;5284 top_p?: number | null;5285 max_output_tokens?: number | null;5286 previous_response_id?: string | null;5287 prompt?: ResponsePrompt | null;5288 reasoning?: Reasoning | null;5289 safety_identifier?: string;5290 service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;5291 status?: ResponseStatus;5292 text?: ResponseTextConfig;5293 truncation?: "auto" | "disabled" | null;5294 usage?: ResponseUsage;5295};5296type EasyInputMessage = {5297 content: string | ResponseInputMessageContentList;5298 role: "user" | "assistant" | "system" | "developer";5299 type?: "message";5300};5301type ResponsesFunctionTool = {5302 name: string;5303 parameters: {5304 [key: string]: unknown;5305 } | null;5306 strict: boolean | null;5307 type: "function";5308 description?: string | null;5309};5310type ResponseIncompleteDetails = {5311 reason?: "max_output_tokens" | "content_filter";5312};5313type ResponsePrompt = {5314 id: string;5315 variables?: {5316 [key: string]: string | ResponseInputText | ResponseInputImage;5317 } | null;5318 version?: string | null;5319};5320type Reasoning = {5321 effort?: ReasoningEffort | null;5322 generate_summary?: "auto" | "concise" | "detailed" | null;5323 summary?: "auto" | "concise" | "detailed" | null;5324};5325type ResponseContent = ResponseInputText | ResponseInputImage | ResponseOutputText | ResponseOutputRefusal | ResponseContentReasoningText;5326type ResponseContentReasoningText = {5327 text: string;5328 type: "reasoning_text";5329};5330type ResponseConversationParam = {5331 id: string;5332};5333type ResponseCreatedEvent = {5334 response: Response;5335 sequence_number: number;5336 type: "response.created";5337};5338type ResponseCustomToolCallOutput = {5339 call_id: string;5340 output: string | Array<ResponseInputText | ResponseInputImage>;5341 type: "custom_tool_call_output";5342 id?: string;5343};5344type ResponseError = {5345 code: "server_error" | "rate_limit_exceeded" | "invalid_prompt" | "vector_store_timeout" | "invalid_image" | "invalid_image_format" | "invalid_base64_image" | "invalid_image_url" | "image_too_large" | "image_too_small" | "image_parse_error" | "image_content_policy_violation" | "invalid_image_mode" | "image_file_too_large" | "unsupported_image_media_type" | "empty_image_file" | "failed_to_download_image" | "image_file_not_found";5346 message: string;5347};5348type ResponseErrorEvent = {5349 code: string | null;5350 message: string;5351 param: string | null;5352 sequence_number: number;5353 type: "error";5354};5355type ResponseFailedEvent = {5356 response: Response;5357 sequence_number: number;5358 type: "response.failed";5359};5360type ResponseFormatText = {5361 type: "text";5362};5363type ResponseFormatJSONObject = {5364 type: "json_object";5365};5366type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject;5367type ResponseFormatTextJSONSchemaConfig = {5368 name: string;5369 schema: {5370 [key: string]: unknown;5371 };5372 type: "json_schema";5373 description?: string;5374 strict?: boolean | null;5375};5376type ResponseFunctionCallArgumentsDeltaEvent = {5377 delta: string;5378 item_id: string;5379 output_index: number;5380 sequence_number: number;5381 type: "response.function_call_arguments.delta";5382};5383type ResponseFunctionCallArgumentsDoneEvent = {5384 arguments: string;5385 item_id: string;5386 name: string;5387 output_index: number;5388 sequence_number: number;5389 type: "response.function_call_arguments.done";5390};5391type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent;5392type ResponseFunctionCallOutputItemList = Array<ResponseFunctionCallOutputItem>;5393type ResponseFunctionToolCall = {5394 arguments: string;5395 call_id: string;5396 name: string;5397 type: "function_call";5398 id?: string;5399 status?: "in_progress" | "completed" | "incomplete";5400};5401interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall {5402 id: string;5403}5404type ResponseFunctionToolCallOutputItem = {5405 id: string;5406 call_id: string;5407 output: string | Array<ResponseInputText | ResponseInputImage>;5408 type: "function_call_output";5409 status?: "in_progress" | "completed" | "incomplete";5410};5411type ResponseIncludable = "message.input_image.image_url" | "message.output_text.logprobs";5412type ResponseIncompleteEvent = {5413 response: Response;5414 sequence_number: number;5415 type: "response.incomplete";5416};5417type ResponseInput = Array<ResponseInputItem>;5418type ResponseInputContent = ResponseInputText | ResponseInputImage;5419type ResponseInputImage = {5420 detail: "low" | "high" | "auto";5421 type: "input_image";5422 /**5423 * Base64 encoded image5424 */5425 image_url?: string | null;5426};5427type ResponseInputImageContent = {5428 type: "input_image";5429 detail?: "low" | "high" | "auto" | null;5430 /**5431 * Base64 encoded image5432 */5433 image_url?: string | null;5434};5435type ResponseInputItem = EasyInputMessage | ResponseInputItemMessage | ResponseOutputMessage | ResponseFunctionToolCall | ResponseInputItemFunctionCallOutput | ResponseReasoningItem;5436type ResponseInputItemFunctionCallOutput = {5437 call_id: string;5438 output: string | ResponseFunctionCallOutputItemList;5439 type: "function_call_output";5440 id?: string | null;5441 status?: "in_progress" | "completed" | "incomplete" | null;5442};5443type ResponseInputItemMessage = {5444 content: ResponseInputMessageContentList;5445 role: "user" | "system" | "developer";5446 status?: "in_progress" | "completed" | "incomplete";5447 type?: "message";5448};5449type ResponseInputMessageContentList = Array<ResponseInputContent>;5450type ResponseInputMessageItem = {5451 id: string;5452 content: ResponseInputMessageContentList;5453 role: "user" | "system" | "developer";5454 status?: "in_progress" | "completed" | "incomplete";5455 type?: "message";5456};5457type ResponseInputText = {5458 text: string;5459 type: "input_text";5460};5461type ResponseInputTextContent = {5462 text: string;5463 type: "input_text";5464};5465type ResponseItem = ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem;5466type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem;5467type ResponseOutputItemAddedEvent = {5468 item: ResponseOutputItem;5469 output_index: number;5470 sequence_number: number;5471 type: "response.output_item.added";5472};5473type ResponseOutputItemDoneEvent = {5474 item: ResponseOutputItem;5475 output_index: number;5476 sequence_number: number;5477 type: "response.output_item.done";5478};5479type ResponseOutputMessage = {5480 id: string;5481 content: Array<ResponseOutputText | ResponseOutputRefusal>;5482 role: "assistant";5483 status: "in_progress" | "completed" | "incomplete";5484 type: "message";5485};5486type ResponseOutputRefusal = {5487 refusal: string;5488 type: "refusal";5489};5490type ResponseOutputText = {5491 text: string;5492 type: "output_text";5493 logprobs?: Array<Logprob>;5494};5495type ResponseReasoningItem = {5496 id: string;5497 summary: Array<ResponseReasoningSummaryItem>;5498 type: "reasoning";5499 content?: Array<ResponseReasoningContentItem>;5500 encrypted_content?: string | null;5501 status?: "in_progress" | "completed" | "incomplete";5502};5503type ResponseReasoningSummaryItem = {5504 text: string;5505 type: "summary_text";5506};5507type ResponseReasoningContentItem = {5508 text: string;5509 type: "reasoning_text";5510};5511type ResponseReasoningTextDeltaEvent = {5512 content_index: number;5513 delta: string;5514 item_id: string;5515 output_index: number;5516 sequence_number: number;5517 type: "response.reasoning_text.delta";5518};5519type ResponseReasoningTextDoneEvent = {5520 content_index: number;5521 item_id: string;5522 output_index: number;5523 sequence_number: number;5524 text: string;5525 type: "response.reasoning_text.done";5526};5527type ResponseRefusalDeltaEvent = {5528 content_index: number;5529 delta: string;5530 item_id: string;5531 output_index: number;5532 sequence_number: number;5533 type: "response.refusal.delta";5534};5535type ResponseRefusalDoneEvent = {5536 content_index: number;5537 item_id: string;5538 output_index: number;5539 refusal: string;5540 sequence_number: number;5541 type: "response.refusal.done";5542};5543type ResponseStatus = "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete";5544type ResponseStreamEvent = ResponseCompletedEvent | ResponseCreatedEvent | ResponseErrorEvent | ResponseFunctionCallArgumentsDeltaEvent | ResponseFunctionCallArgumentsDoneEvent | ResponseFailedEvent | ResponseIncompleteEvent | ResponseOutputItemAddedEvent | ResponseOutputItemDoneEvent | ResponseReasoningTextDeltaEvent | ResponseReasoningTextDoneEvent | ResponseRefusalDeltaEvent | ResponseRefusalDoneEvent | ResponseTextDeltaEvent | ResponseTextDoneEvent;5545type ResponseCompletedEvent = {5546 response: Response;5547 sequence_number: number;5548 type: "response.completed";5549};5550type ResponseTextConfig = {5551 format?: ResponseFormatTextConfig;5552 verbosity?: "low" | "medium" | "high" | null;5553};5554type ResponseTextDeltaEvent = {5555 content_index: number;5556 delta: string;5557 item_id: string;5558 logprobs: Array<Logprob>;5559 output_index: number;5560 sequence_number: number;5561 type: "response.output_text.delta";5562};5563type ResponseTextDoneEvent = {5564 content_index: number;5565 item_id: string;5566 logprobs: Array<Logprob>;5567 output_index: number;5568 sequence_number: number;5569 text: string;5570 type: "response.output_text.done";5571};5572type Logprob = {5573 token: string;5574 logprob: number;5575 top_logprobs?: Array<TopLogprob>;5576};5577type TopLogprob = {5578 token?: string;5579 logprob?: number;5580};5581type ResponseUsage = {5582 input_tokens: number;5583 output_tokens: number;5584 total_tokens: number;5585};5586type Tool = ResponsesFunctionTool;5587type ToolChoiceFunction = {5588 name: string;5589 type: "function";5590};5591type ToolChoiceOptions = "none";5592type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null;5593type StreamOptions = {5594 include_obfuscation?: boolean;5595};5596/** Marks keys from T that aren't in U as optional never */5597type Without<T, U> = {5598 [P in Exclude<keyof T, keyof U>]?: never;5599};5600/** Either T or U, but not both (mutually exclusive) */5601type XOR<T, U> = (T & Without<U, T>) | (U & Without<T, U>);5602type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = {5603 text: string | string[];5604 /**5605 * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.5606 */5607 pooling?: "mean" | "cls";5608} | {5609 /**5610 * Batch of the embeddings requests to run using async-queue5611 */5612 requests: {5613 text: string | string[];5614 /**5615 * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.5616 */5617 pooling?: "mean" | "cls";5618 }[];5619};5620type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = {5621 shape?: number[];5622 /**5623 * Embeddings of the requested text values5624 */5625 data?: number[][];5626 /**5627 * The pooling method used in the embedding process.5628 */5629 pooling?: "mean" | "cls";5630} | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse;5631interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse {5632 /**5633 * The async request id that can be used to obtain the results.5634 */5635 request_id?: string;5636}5637declare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 {5638 inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input;5639 postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output;5640}5641type Ai_Cf_Openai_Whisper_Input = string | {5642 /**5643 * An array of integers that represent the audio data constrained to 8-bit unsigned integer values5644 */5645 audio: number[];5646};5647interface Ai_Cf_Openai_Whisper_Output {5648 /**5649 * The transcription5650 */5651 text: string;5652 word_count?: number;5653 words?: {5654 word?: string;5655 /**5656 * The second this word begins in the recording5657 */5658 start?: number;5659 /**5660 * The ending second when the word completes5661 */5662 end?: number;5663 }[];5664 vtt?: string;5665}5666declare abstract class Base_Ai_Cf_Openai_Whisper {5667 inputs: Ai_Cf_Openai_Whisper_Input;5668 postProcessedOutputs: Ai_Cf_Openai_Whisper_Output;5669}5670type Ai_Cf_Meta_M2M100_1_2B_Input = {5671 /**5672 * The text to be translated5673 */5674 text: string;5675 /**5676 * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified5677 */5678 source_lang?: string;5679 /**5680 * The language code to translate the text into (e.g., 'es' for Spanish)5681 */5682 target_lang: string;5683} | {5684 /**5685 * Batch of the embeddings requests to run using async-queue5686 */5687 requests: {5688 /**5689 * The text to be translated5690 */5691 text: string;5692 /**5693 * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified5694 */5695 source_lang?: string;5696 /**5697 * The language code to translate the text into (e.g., 'es' for Spanish)5698 */5699 target_lang: string;5700 }[];5701};5702type Ai_Cf_Meta_M2M100_1_2B_Output = {5703 /**5704 * The translated text in the target language5705 */5706 translated_text?: string;5707} | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse;5708interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse {5709 /**5710 * The async request id that can be used to obtain the results.5711 */5712 request_id?: string;5713}5714declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B {5715 inputs: Ai_Cf_Meta_M2M100_1_2B_Input;5716 postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output;5717}5718type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = {5719 text: string | string[];5720 /**5721 * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.5722 */5723 pooling?: "mean" | "cls";5724} | {5725 /**5726 * Batch of the embeddings requests to run using async-queue5727 */5728 requests: {5729 text: string | string[];5730 /**5731 * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.5732 */5733 pooling?: "mean" | "cls";5734 }[];5735};5736type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = {5737 shape?: number[];5738 /**5739 * Embeddings of the requested text values5740 */5741 data?: number[][];5742 /**5743 * The pooling method used in the embedding process.5744 */5745 pooling?: "mean" | "cls";5746} | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse;5747interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse {5748 /**5749 * The async request id that can be used to obtain the results.5750 */5751 request_id?: string;5752}5753declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 {5754 inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input;5755 postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output;5756}5757type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = {5758 text: string | string[];5759 /**5760 * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.5761 */5762 pooling?: "mean" | "cls";5763} | {5764 /**5765 * Batch of the embeddings requests to run using async-queue5766 */5767 requests: {5768 text: string | string[];5769 /**5770 * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.5771 */5772 pooling?: "mean" | "cls";5773 }[];5774};5775type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = {5776 shape?: number[];5777 /**5778 * Embeddings of the requested text values5779 */5780 data?: number[][];5781 /**5782 * The pooling method used in the embedding process.5783 */5784 pooling?: "mean" | "cls";5785} | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse;5786interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse {5787 /**5788 * The async request id that can be used to obtain the results.5789 */5790 request_id?: string;5791}5792declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 {5793 inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input;5794 postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output;5795}5796type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = string | {5797 /**5798 * The input text prompt for the model to generate a response.5799 */5800 prompt?: string;5801 /**5802 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.5803 */5804 raw?: boolean;5805 /**5806 * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.5807 */5808 top_p?: number;5809 /**5810 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.5811 */5812 top_k?: number;5813 /**5814 * Random seed for reproducibility of the generation.5815 */5816 seed?: number;5817 /**5818 * Penalty for repeated tokens; higher values discourage repetition.5819 */5820 repetition_penalty?: number;5821 /**5822 * Decreases the likelihood of the model repeating the same lines verbatim.5823 */5824 frequency_penalty?: number;5825 /**5826 * Increases the likelihood of the model introducing new topics.5827 */5828 presence_penalty?: number;5829 image: number[] | (string & NonNullable<unknown>);5830 /**5831 * The maximum number of tokens to generate in the response.5832 */5833 max_tokens?: number;5834};5835interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output {5836 description?: string;5837}5838declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M {5839 inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input;5840 postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output;5841}5842type Ai_Cf_Openai_Whisper_Tiny_En_Input = string | {5843 /**5844 * An array of integers that represent the audio data constrained to 8-bit unsigned integer values5845 */5846 audio: number[];5847};5848interface Ai_Cf_Openai_Whisper_Tiny_En_Output {5849 /**5850 * The transcription5851 */5852 text: string;5853 word_count?: number;5854 words?: {5855 word?: string;5856 /**5857 * The second this word begins in the recording5858 */5859 start?: number;5860 /**5861 * The ending second when the word completes5862 */5863 end?: number;5864 }[];5865 vtt?: string;5866}5867declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En {5868 inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input;5869 postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output;5870}5871interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input {5872 audio: string | {5873 body?: object;5874 contentType?: string;5875 };5876 /**5877 * Supported tasks are 'translate' or 'transcribe'.5878 */5879 task?: string;5880 /**5881 * The language of the audio being transcribed or translated.5882 */5883 language?: string;5884 /**5885 * Preprocess the audio with a voice activity detection model.5886 */5887 vad_filter?: boolean;5888 /**5889 * A text prompt to help provide context to the model on the contents of the audio.5890 */5891 initial_prompt?: string;5892 /**5893 * The prefix appended to the beginning of the output of the transcription and can guide the transcription result.5894 */5895 prefix?: string;5896 /**5897 * The number of beams to use in beam search decoding. Higher values may improve accuracy at the cost of speed.5898 */5899 beam_size?: number;5900 /**5901 * Whether to condition on previous text during transcription. Setting to false may help prevent hallucination loops.5902 */5903 condition_on_previous_text?: boolean;5904 /**5905 * Threshold for detecting no-speech segments. Segments with no-speech probability above this value are skipped.5906 */5907 no_speech_threshold?: number;5908 /**5909 * Threshold for filtering out segments with high compression ratio, which often indicate repetitive or hallucinated text.5910 */5911 compression_ratio_threshold?: number;5912 /**5913 * Threshold for filtering out segments with low average log probability, indicating low confidence.5914 */5915 log_prob_threshold?: number;5916 /**5917 * Optional threshold (in seconds) to skip silent periods that may cause hallucinations.5918 */5919 hallucination_silence_threshold?: number;5920}5921interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output {5922 transcription_info?: {5923 /**5924 * The language of the audio being transcribed or translated.5925 */5926 language?: string;5927 /**5928 * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1.5929 */5930 language_probability?: number;5931 /**5932 * The total duration of the original audio file, in seconds.5933 */5934 duration?: number;5935 /**5936 * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds.5937 */5938 duration_after_vad?: number;5939 };5940 /**5941 * The complete transcription of the audio.5942 */5943 text: string;5944 /**5945 * The total number of words in the transcription.5946 */5947 word_count?: number;5948 segments?: {5949 /**5950 * The starting time of the segment within the audio, in seconds.5951 */5952 start?: number;5953 /**5954 * The ending time of the segment within the audio, in seconds.5955 */5956 end?: number;5957 /**5958 * The transcription of the segment.5959 */5960 text?: string;5961 /**5962 * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs.5963 */5964 temperature?: number;5965 /**5966 * The average log probability of the predictions for the words in this segment, indicating overall confidence.5967 */5968 avg_logprob?: number;5969 /**5970 * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process.5971 */5972 compression_ratio?: number;5973 /**5974 * The probability that the segment contains no speech, represented as a decimal between 0 and 1.5975 */5976 no_speech_prob?: number;5977 words?: {5978 /**5979 * The individual word transcribed from the audio.5980 */5981 word?: string;5982 /**5983 * The starting time of the word within the audio, in seconds.5984 */5985 start?: number;5986 /**5987 * The ending time of the word within the audio, in seconds.5988 */5989 end?: number;5990 }[];5991 }[];5992 /**5993 * The transcription in WebVTT format, which includes timing and text information for use in subtitles.5994 */5995 vtt?: string;5996}5997declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo {5998 inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input;5999 postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output;6000}6001type Ai_Cf_Baai_Bge_M3_Input = Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts | Ai_Cf_Baai_Bge_M3_Input_Embedding | {6002 /**6003 * Batch of the embeddings requests to run using async-queue6004 */6005 requests: (Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 | Ai_Cf_Baai_Bge_M3_Input_Embedding_1)[];6006};6007interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts {6008 /**6009 * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts6010 */6011 query?: string;6012 /**6013 * List of provided contexts. Note that the index in this array is important, as the response will refer to it.6014 */6015 contexts: {6016 /**6017 * One of the provided context content6018 */6019 text?: string;6020 }[];6021 /**6022 * When provided with too long context should the model error out or truncate the context to fit?6023 */6024 truncate_inputs?: boolean;6025}6026interface Ai_Cf_Baai_Bge_M3_Input_Embedding {6027 text: string | string[];6028 /**6029 * When provided with too long context should the model error out or truncate the context to fit?6030 */6031 truncate_inputs?: boolean;6032}6033interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 {6034 /**6035 * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts6036 */6037 query?: string;6038 /**6039 * List of provided contexts. Note that the index in this array is important, as the response will refer to it.6040 */6041 contexts: {6042 /**6043 * One of the provided context content6044 */6045 text?: string;6046 }[];6047 /**6048 * When provided with too long context should the model error out or truncate the context to fit?6049 */6050 truncate_inputs?: boolean;6051}6052interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 {6053 text: string | string[];6054 /**6055 * When provided with too long context should the model error out or truncate the context to fit?6056 */6057 truncate_inputs?: boolean;6058}6059type Ai_Cf_Baai_Bge_M3_Output = Ai_Cf_Baai_Bge_M3_Output_Query | Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts | Ai_Cf_Baai_Bge_M3_Output_Embedding | Ai_Cf_Baai_Bge_M3_AsyncResponse;6060interface Ai_Cf_Baai_Bge_M3_Output_Query {6061 response?: {6062 /**6063 * Index of the context in the request6064 */6065 id?: number;6066 /**6067 * Score of the context under the index.6068 */6069 score?: number;6070 }[];6071}6072interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts {6073 response?: number[][];6074 shape?: number[];6075 /**6076 * The pooling method used in the embedding process.6077 */6078 pooling?: "mean" | "cls";6079}6080interface Ai_Cf_Baai_Bge_M3_Output_Embedding {6081 shape?: number[];6082 /**6083 * Embeddings of the requested text values6084 */6085 data?: number[][];6086 /**6087 * The pooling method used in the embedding process.6088 */6089 pooling?: "mean" | "cls";6090}6091interface Ai_Cf_Baai_Bge_M3_AsyncResponse {6092 /**6093 * The async request id that can be used to obtain the results.6094 */6095 request_id?: string;6096}6097declare abstract class Base_Ai_Cf_Baai_Bge_M3 {6098 inputs: Ai_Cf_Baai_Bge_M3_Input;6099 postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output;6100}6101interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input {6102 /**6103 * A text description of the image you want to generate.6104 */6105 prompt: string;6106 /**6107 * The number of diffusion steps; higher values can improve quality but take longer.6108 */6109 steps?: number;6110}6111interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output {6112 /**6113 * The generated image in Base64 format.6114 */6115 image?: string;6116}6117declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell {6118 inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input;6119 postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output;6120}6121type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages;6122interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt {6123 /**6124 * The input text prompt for the model to generate a response.6125 */6126 prompt: string;6127 image?: number[] | (string & NonNullable<unknown>);6128 /**6129 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.6130 */6131 raw?: boolean;6132 /**6133 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.6134 */6135 stream?: boolean;6136 /**6137 * The maximum number of tokens to generate in the response.6138 */6139 max_tokens?: number;6140 /**6141 * Controls the randomness of the output; higher values produce more random results.6142 */6143 temperature?: number;6144 /**6145 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.6146 */6147 top_p?: number;6148 /**6149 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.6150 */6151 top_k?: number;6152 /**6153 * Random seed for reproducibility of the generation.6154 */6155 seed?: number;6156 /**6157 * Penalty for repeated tokens; higher values discourage repetition.6158 */6159 repetition_penalty?: number;6160 /**6161 * Decreases the likelihood of the model repeating the same lines verbatim.6162 */6163 frequency_penalty?: number;6164 /**6165 * Increases the likelihood of the model introducing new topics.6166 */6167 presence_penalty?: number;6168 /**6169 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.6170 */6171 lora?: string;6172}6173interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages {6174 /**6175 * An array of message objects representing the conversation history.6176 */6177 messages: {6178 /**6179 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').6180 */6181 role?: string;6182 /**6183 * The tool call id. If you don't know what to put here you can fall back to 0000000016184 */6185 tool_call_id?: string;6186 content?: string | {6187 /**6188 * Type of the content provided6189 */6190 type?: string;6191 text?: string;6192 image_url?: {6193 /**6194 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted6195 */6196 url?: string;6197 };6198 }[] | {6199 /**6200 * Type of the content provided6201 */6202 type?: string;6203 text?: string;6204 image_url?: {6205 /**6206 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted6207 */6208 url?: string;6209 };6210 };6211 }[];6212 image?: number[] | (string & NonNullable<unknown>);6213 functions?: {6214 name: string;6215 code: string;6216 }[];6217 /**6218 * A list of tools available for the assistant to use.6219 */6220 tools?: ({6221 /**6222 * The name of the tool. More descriptive the better.6223 */6224 name: string;6225 /**6226 * A brief description of what the tool does.6227 */6228 description: string;6229 /**6230 * Schema defining the parameters accepted by the tool.6231 */6232 parameters: {6233 /**6234 * The type of the parameters object (usually 'object').6235 */6236 type: string;6237 /**6238 * List of required parameter names.6239 */6240 required?: string[];6241 /**6242 * Definitions of each parameter.6243 */6244 properties: {6245 [k: string]: {6246 /**6247 * The data type of the parameter.6248 */6249 type: string;6250 /**6251 * A description of the expected parameter.6252 */6253 description: string;6254 };6255 };6256 };6257 } | {6258 /**6259 * Specifies the type of tool (e.g., 'function').6260 */6261 type: string;6262 /**6263 * Details of the function tool.6264 */6265 function: {6266 /**6267 * The name of the function.6268 */6269 name: string;6270 /**6271 * A brief description of what the function does.6272 */6273 description: string;6274 /**6275 * Schema defining the parameters accepted by the function.6276 */6277 parameters: {6278 /**6279 * The type of the parameters object (usually 'object').6280 */6281 type: string;6282 /**6283 * List of required parameter names.6284 */6285 required?: string[];6286 /**6287 * Definitions of each parameter.6288 */6289 properties: {6290 [k: string]: {6291 /**6292 * The data type of the parameter.6293 */6294 type: string;6295 /**6296 * A description of the expected parameter.6297 */6298 description: string;6299 };6300 };6301 };6302 };6303 })[];6304 /**6305 * If true, the response will be streamed back incrementally.6306 */6307 stream?: boolean;6308 /**6309 * The maximum number of tokens to generate in the response.6310 */6311 max_tokens?: number;6312 /**6313 * Controls the randomness of the output; higher values produce more random results.6314 */6315 temperature?: number;6316 /**6317 * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.6318 */6319 top_p?: number;6320 /**6321 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.6322 */6323 top_k?: number;6324 /**6325 * Random seed for reproducibility of the generation.6326 */6327 seed?: number;6328 /**6329 * Penalty for repeated tokens; higher values discourage repetition.6330 */6331 repetition_penalty?: number;6332 /**6333 * Decreases the likelihood of the model repeating the same lines verbatim.6334 */6335 frequency_penalty?: number;6336 /**6337 * Increases the likelihood of the model introducing new topics.6338 */6339 presence_penalty?: number;6340}6341type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = {6342 /**6343 * The generated text response from the model6344 */6345 response?: string;6346 /**6347 * An array of tool calls requests made during the response generation6348 */6349 tool_calls?: {6350 /**6351 * The arguments passed to be passed to the tool call request6352 */6353 arguments?: object;6354 /**6355 * The name of the tool to be called6356 */6357 name?: string;6358 }[];6359};6360declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct {6361 inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input;6362 postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output;6363}6364type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch;6365interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt {6366 /**6367 * The input text prompt for the model to generate a response.6368 */6369 prompt: string;6370 /**6371 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.6372 */6373 lora?: string;6374 response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode;6375 /**6376 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.6377 */6378 raw?: boolean;6379 /**6380 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.6381 */6382 stream?: boolean;6383 /**6384 * The maximum number of tokens to generate in the response.6385 */6386 max_tokens?: number;6387 /**6388 * Controls the randomness of the output; higher values produce more random results.6389 */6390 temperature?: number;6391 /**6392 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.6393 */6394 top_p?: number;6395 /**6396 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.6397 */6398 top_k?: number;6399 /**6400 * Random seed for reproducibility of the generation.6401 */6402 seed?: number;6403 /**6404 * Penalty for repeated tokens; higher values discourage repetition.6405 */6406 repetition_penalty?: number;6407 /**6408 * Decreases the likelihood of the model repeating the same lines verbatim.6409 */6410 frequency_penalty?: number;6411 /**6412 * Increases the likelihood of the model introducing new topics.6413 */6414 presence_penalty?: number;6415}6416interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode {6417 type?: "json_object" | "json_schema";6418 json_schema?: unknown;6419}6420interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages {6421 /**6422 * An array of message objects representing the conversation history.6423 */6424 messages: {6425 /**6426 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').6427 */6428 role: string;6429 content: string | {6430 /**6431 * Type of the content (text)6432 */6433 type?: string;6434 /**6435 * Text content6436 */6437 text?: string;6438 }[];6439 }[];6440 functions?: {6441 name: string;6442 code: string;6443 }[];6444 /**6445 * A list of tools available for the assistant to use.6446 */6447 tools?: ({6448 /**6449 * The name of the tool. More descriptive the better.6450 */6451 name: string;6452 /**6453 * A brief description of what the tool does.6454 */6455 description: string;6456 /**6457 * Schema defining the parameters accepted by the tool.6458 */6459 parameters: {6460 /**6461 * The type of the parameters object (usually 'object').6462 */6463 type: string;6464 /**6465 * List of required parameter names.6466 */6467 required?: string[];6468 /**6469 * Definitions of each parameter.6470 */6471 properties: {6472 [k: string]: {6473 /**6474 * The data type of the parameter.6475 */6476 type: string;6477 /**6478 * A description of the expected parameter.6479 */6480 description: string;6481 };6482 };6483 };6484 } | {6485 /**6486 * Specifies the type of tool (e.g., 'function').6487 */6488 type: string;6489 /**6490 * Details of the function tool.6491 */6492 function: {6493 /**6494 * The name of the function.6495 */6496 name: string;6497 /**6498 * A brief description of what the function does.6499 */6500 description: string;6501 /**6502 * Schema defining the parameters accepted by the function.6503 */6504 parameters: {6505 /**6506 * The type of the parameters object (usually 'object').6507 */6508 type: string;6509 /**6510 * List of required parameter names.6511 */6512 required?: string[];6513 /**6514 * Definitions of each parameter.6515 */6516 properties: {6517 [k: string]: {6518 /**6519 * The data type of the parameter.6520 */6521 type: string;6522 /**6523 * A description of the expected parameter.6524 */6525 description: string;6526 };6527 };6528 };6529 };6530 })[];6531 response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1;6532 /**6533 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.6534 */6535 raw?: boolean;6536 /**6537 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.6538 */6539 stream?: boolean;6540 /**6541 * The maximum number of tokens to generate in the response.6542 */6543 max_tokens?: number;6544 /**6545 * Controls the randomness of the output; higher values produce more random results.6546 */6547 temperature?: number;6548 /**6549 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.6550 */6551 top_p?: number;6552 /**6553 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.6554 */6555 top_k?: number;6556 /**6557 * Random seed for reproducibility of the generation.6558 */6559 seed?: number;6560 /**6561 * Penalty for repeated tokens; higher values discourage repetition.6562 */6563 repetition_penalty?: number;6564 /**6565 * Decreases the likelihood of the model repeating the same lines verbatim.6566 */6567 frequency_penalty?: number;6568 /**6569 * Increases the likelihood of the model introducing new topics.6570 */6571 presence_penalty?: number;6572}6573interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 {6574 type?: "json_object" | "json_schema";6575 json_schema?: unknown;6576}6577interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch {6578 requests?: {6579 /**6580 * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique.6581 */6582 external_reference?: string;6583 /**6584 * Prompt for the text generation model6585 */6586 prompt?: string;6587 /**6588 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.6589 */6590 stream?: boolean;6591 /**6592 * The maximum number of tokens to generate in the response.6593 */6594 max_tokens?: number;6595 /**6596 * Controls the randomness of the output; higher values produce more random results.6597 */6598 temperature?: number;6599 /**6600 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.6601 */6602 top_p?: number;6603 /**6604 * Random seed for reproducibility of the generation.6605 */6606 seed?: number;6607 /**6608 * Penalty for repeated tokens; higher values discourage repetition.6609 */6610 repetition_penalty?: number;6611 /**6612 * Decreases the likelihood of the model repeating the same lines verbatim.6613 */6614 frequency_penalty?: number;6615 /**6616 * Increases the likelihood of the model introducing new topics.6617 */6618 presence_penalty?: number;6619 response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2;6620 }[];6621}6622interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 {6623 type?: "json_object" | "json_schema";6624 json_schema?: unknown;6625}6626type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = {6627 /**6628 * The generated text response from the model6629 */6630 response: string;6631 /**6632 * Usage statistics for the inference request6633 */6634 usage?: {6635 /**6636 * Total number of tokens in input6637 */6638 prompt_tokens?: number;6639 /**6640 * Total number of tokens in output6641 */6642 completion_tokens?: number;6643 /**6644 * Total number of input and output tokens6645 */6646 total_tokens?: number;6647 };6648 /**6649 * An array of tool calls requests made during the response generation6650 */6651 tool_calls?: {6652 /**6653 * The arguments passed to be passed to the tool call request6654 */6655 arguments?: object;6656 /**6657 * The name of the tool to be called6658 */6659 name?: string;6660 }[];6661} | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse;6662interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse {6663 /**6664 * The async request id that can be used to obtain the results.6665 */6666 request_id?: string;6667}6668declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast {6669 inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input;6670 postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output;6671}6672interface Ai_Cf_Meta_Llama_Guard_3_8B_Input {6673 /**6674 * An array of message objects representing the conversation history.6675 */6676 messages: {6677 /**6678 * The role of the message sender must alternate between 'user' and 'assistant'.6679 */6680 role: "user" | "assistant";6681 /**6682 * The content of the message as a string.6683 */6684 content: string;6685 }[];6686 /**6687 * The maximum number of tokens to generate in the response.6688 */6689 max_tokens?: number;6690 /**6691 * Controls the randomness of the output; higher values produce more random results.6692 */6693 temperature?: number;6694 /**6695 * Dictate the output format of the generated response.6696 */6697 response_format?: {6698 /**6699 * Set to json_object to process and output generated text as JSON.6700 */6701 type?: string;6702 };6703}6704interface Ai_Cf_Meta_Llama_Guard_3_8B_Output {6705 response?: string | {6706 /**6707 * Whether the conversation is safe or not.6708 */6709 safe?: boolean;6710 /**6711 * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe.6712 */6713 categories?: string[];6714 };6715 /**6716 * Usage statistics for the inference request6717 */6718 usage?: {6719 /**6720 * Total number of tokens in input6721 */6722 prompt_tokens?: number;6723 /**6724 * Total number of tokens in output6725 */6726 completion_tokens?: number;6727 /**6728 * Total number of input and output tokens6729 */6730 total_tokens?: number;6731 };6732}6733declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B {6734 inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input;6735 postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output;6736}6737interface Ai_Cf_Baai_Bge_Reranker_Base_Input {6738 /**6739 * A query you wish to perform against the provided contexts.6740 */6741 /**6742 * Number of returned results starting with the best score.6743 */6744 top_k?: number;6745 /**6746 * List of provided contexts. Note that the index in this array is important, as the response will refer to it.6747 */6748 contexts: {6749 /**6750 * One of the provided context content6751 */6752 text?: string;6753 }[];6754}6755interface Ai_Cf_Baai_Bge_Reranker_Base_Output {6756 response?: {6757 /**6758 * Index of the context in the request6759 */6760 id?: number;6761 /**6762 * Score of the context under the index.6763 */6764 score?: number;6765 }[];6766}6767declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base {6768 inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input;6769 postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output;6770}6771type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages;6772interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt {6773 /**6774 * The input text prompt for the model to generate a response.6775 */6776 prompt: string;6777 /**6778 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.6779 */6780 lora?: string;6781 response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode;6782 /**6783 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.6784 */6785 raw?: boolean;6786 /**6787 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.6788 */6789 stream?: boolean;6790 /**6791 * The maximum number of tokens to generate in the response.6792 */6793 max_tokens?: number;6794 /**6795 * Controls the randomness of the output; higher values produce more random results.6796 */6797 temperature?: number;6798 /**6799 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.6800 */6801 top_p?: number;6802 /**6803 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.6804 */6805 top_k?: number;6806 /**6807 * Random seed for reproducibility of the generation.6808 */6809 seed?: number;6810 /**6811 * Penalty for repeated tokens; higher values discourage repetition.6812 */6813 repetition_penalty?: number;6814 /**6815 * Decreases the likelihood of the model repeating the same lines verbatim.6816 */6817 frequency_penalty?: number;6818 /**6819 * Increases the likelihood of the model introducing new topics.6820 */6821 presence_penalty?: number;6822}6823interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode {6824 type?: "json_object" | "json_schema";6825 json_schema?: unknown;6826}6827interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages {6828 /**6829 * An array of message objects representing the conversation history.6830 */6831 messages: {6832 /**6833 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').6834 */6835 role: string;6836 /**6837 * The content of the message as a string.6838 */6839 content: string;6840 }[];6841 functions?: {6842 name: string;6843 code: string;6844 }[];6845 /**6846 * A list of tools available for the assistant to use.6847 */6848 tools?: ({6849 /**6850 * The name of the tool. More descriptive the better.6851 */6852 name: string;6853 /**6854 * A brief description of what the tool does.6855 */6856 description: string;6857 /**6858 * Schema defining the parameters accepted by the tool.6859 */6860 parameters: {6861 /**6862 * The type of the parameters object (usually 'object').6863 */6864 type: string;6865 /**6866 * List of required parameter names.6867 */6868 required?: string[];6869 /**6870 * Definitions of each parameter.6871 */6872 properties: {6873 [k: string]: {6874 /**6875 * The data type of the parameter.6876 */6877 type: string;6878 /**6879 * A description of the expected parameter.6880 */6881 description: string;6882 };6883 };6884 };6885 } | {6886 /**6887 * Specifies the type of tool (e.g., 'function').6888 */6889 type: string;6890 /**6891 * Details of the function tool.6892 */6893 function: {6894 /**6895 * The name of the function.6896 */6897 name: string;6898 /**6899 * A brief description of what the function does.6900 */6901 description: string;6902 /**6903 * Schema defining the parameters accepted by the function.6904 */6905 parameters: {6906 /**6907 * The type of the parameters object (usually 'object').6908 */6909 type: string;6910 /**6911 * List of required parameter names.6912 */6913 required?: string[];6914 /**6915 * Definitions of each parameter.6916 */6917 properties: {6918 [k: string]: {6919 /**6920 * The data type of the parameter.6921 */6922 type: string;6923 /**6924 * A description of the expected parameter.6925 */6926 description: string;6927 };6928 };6929 };6930 };6931 })[];6932 response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1;6933 /**6934 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.6935 */6936 raw?: boolean;6937 /**6938 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.6939 */6940 stream?: boolean;6941 /**6942 * The maximum number of tokens to generate in the response.6943 */6944 max_tokens?: number;6945 /**6946 * Controls the randomness of the output; higher values produce more random results.6947 */6948 temperature?: number;6949 /**6950 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.6951 */6952 top_p?: number;6953 /**6954 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.6955 */6956 top_k?: number;6957 /**6958 * Random seed for reproducibility of the generation.6959 */6960 seed?: number;6961 /**6962 * Penalty for repeated tokens; higher values discourage repetition.6963 */6964 repetition_penalty?: number;6965 /**6966 * Decreases the likelihood of the model repeating the same lines verbatim.6967 */6968 frequency_penalty?: number;6969 /**6970 * Increases the likelihood of the model introducing new topics.6971 */6972 presence_penalty?: number;6973}6974interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 {6975 type?: "json_object" | "json_schema";6976 json_schema?: unknown;6977}6978type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = {6979 /**6980 * The generated text response from the model6981 */6982 response: string;6983 /**6984 * Usage statistics for the inference request6985 */6986 usage?: {6987 /**6988 * Total number of tokens in input6989 */6990 prompt_tokens?: number;6991 /**6992 * Total number of tokens in output6993 */6994 completion_tokens?: number;6995 /**6996 * Total number of input and output tokens6997 */6998 total_tokens?: number;6999 };7000 /**7001 * An array of tool calls requests made during the response generation7002 */7003 tool_calls?: {7004 /**7005 * The arguments passed to be passed to the tool call request7006 */7007 arguments?: object;7008 /**7009 * The name of the tool to be called7010 */7011 name?: string;7012 }[];7013};7014declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct {7015 inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input;7016 postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output;7017}7018type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages;7019interface Ai_Cf_Qwen_Qwq_32B_Prompt {7020 /**7021 * The input text prompt for the model to generate a response.7022 */7023 prompt: string;7024 /**7025 * JSON schema that should be fulfilled for the response.7026 */7027 guided_json?: object;7028 /**7029 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.7030 */7031 raw?: boolean;7032 /**7033 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.7034 */7035 stream?: boolean;7036 /**7037 * The maximum number of tokens to generate in the response.7038 */7039 max_tokens?: number;7040 /**7041 * Controls the randomness of the output; higher values produce more random results.7042 */7043 temperature?: number;7044 /**7045 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.7046 */7047 top_p?: number;7048 /**7049 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.7050 */7051 top_k?: number;7052 /**7053 * Random seed for reproducibility of the generation.7054 */7055 seed?: number;7056 /**7057 * Penalty for repeated tokens; higher values discourage repetition.7058 */7059 repetition_penalty?: number;7060 /**7061 * Decreases the likelihood of the model repeating the same lines verbatim.7062 */7063 frequency_penalty?: number;7064 /**7065 * Increases the likelihood of the model introducing new topics.7066 */7067 presence_penalty?: number;7068}7069interface Ai_Cf_Qwen_Qwq_32B_Messages {7070 /**7071 * An array of message objects representing the conversation history.7072 */7073 messages: {7074 /**7075 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').7076 */7077 role?: string;7078 /**7079 * The tool call id. If you don't know what to put here you can fall back to 0000000017080 */7081 tool_call_id?: string;7082 content?: string | {7083 /**7084 * Type of the content provided7085 */7086 type?: string;7087 text?: string;7088 image_url?: {7089 /**7090 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted7091 */7092 url?: string;7093 };7094 }[] | {7095 /**7096 * Type of the content provided7097 */7098 type?: string;7099 text?: string;7100 image_url?: {7101 /**7102 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted7103 */7104 url?: string;7105 };7106 };7107 }[];7108 functions?: {7109 name: string;7110 code: string;7111 }[];7112 /**7113 * A list of tools available for the assistant to use.7114 */7115 tools?: ({7116 /**7117 * The name of the tool. More descriptive the better.7118 */7119 name: string;7120 /**7121 * A brief description of what the tool does.7122 */7123 description: string;7124 /**7125 * Schema defining the parameters accepted by the tool.7126 */7127 parameters: {7128 /**7129 * The type of the parameters object (usually 'object').7130 */7131 type: string;7132 /**7133 * List of required parameter names.7134 */7135 required?: string[];7136 /**7137 * Definitions of each parameter.7138 */7139 properties: {7140 [k: string]: {7141 /**7142 * The data type of the parameter.7143 */7144 type: string;7145 /**7146 * A description of the expected parameter.7147 */7148 description: string;7149 };7150 };7151 };7152 } | {7153 /**7154 * Specifies the type of tool (e.g., 'function').7155 */7156 type: string;7157 /**7158 * Details of the function tool.7159 */7160 function: {7161 /**7162 * The name of the function.7163 */7164 name: string;7165 /**7166 * A brief description of what the function does.7167 */7168 description: string;7169 /**7170 * Schema defining the parameters accepted by the function.7171 */7172 parameters: {7173 /**7174 * The type of the parameters object (usually 'object').7175 */7176 type: string;7177 /**7178 * List of required parameter names.7179 */7180 required?: string[];7181 /**7182 * Definitions of each parameter.7183 */7184 properties: {7185 [k: string]: {7186 /**7187 * The data type of the parameter.7188 */7189 type: string;7190 /**7191 * A description of the expected parameter.7192 */7193 description: string;7194 };7195 };7196 };7197 };7198 })[];7199 /**7200 * JSON schema that should be fufilled for the response.7201 */7202 guided_json?: object;7203 /**7204 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.7205 */7206 raw?: boolean;7207 /**7208 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.7209 */7210 stream?: boolean;7211 /**7212 * The maximum number of tokens to generate in the response.7213 */7214 max_tokens?: number;7215 /**7216 * Controls the randomness of the output; higher values produce more random results.7217 */7218 temperature?: number;7219 /**7220 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.7221 */7222 top_p?: number;7223 /**7224 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.7225 */7226 top_k?: number;7227 /**7228 * Random seed for reproducibility of the generation.7229 */7230 seed?: number;7231 /**7232 * Penalty for repeated tokens; higher values discourage repetition.7233 */7234 repetition_penalty?: number;7235 /**7236 * Decreases the likelihood of the model repeating the same lines verbatim.7237 */7238 frequency_penalty?: number;7239 /**7240 * Increases the likelihood of the model introducing new topics.7241 */7242 presence_penalty?: number;7243}7244type Ai_Cf_Qwen_Qwq_32B_Output = {7245 /**7246 * The generated text response from the model7247 */7248 response: string;7249 /**7250 * Usage statistics for the inference request7251 */7252 usage?: {7253 /**7254 * Total number of tokens in input7255 */7256 prompt_tokens?: number;7257 /**7258 * Total number of tokens in output7259 */7260 completion_tokens?: number;7261 /**7262 * Total number of input and output tokens7263 */7264 total_tokens?: number;7265 };7266 /**7267 * An array of tool calls requests made during the response generation7268 */7269 tool_calls?: {7270 /**7271 * The arguments passed to be passed to the tool call request7272 */7273 arguments?: object;7274 /**7275 * The name of the tool to be called7276 */7277 name?: string;7278 }[];7279};7280declare abstract class Base_Ai_Cf_Qwen_Qwq_32B {7281 inputs: Ai_Cf_Qwen_Qwq_32B_Input;7282 postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output;7283}7284type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages;7285interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt {7286 /**7287 * The input text prompt for the model to generate a response.7288 */7289 prompt: string;7290 /**7291 * JSON schema that should be fulfilled for the response.7292 */7293 guided_json?: object;7294 /**7295 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.7296 */7297 raw?: boolean;7298 /**7299 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.7300 */7301 stream?: boolean;7302 /**7303 * The maximum number of tokens to generate in the response.7304 */7305 max_tokens?: number;7306 /**7307 * Controls the randomness of the output; higher values produce more random results.7308 */7309 temperature?: number;7310 /**7311 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.7312 */7313 top_p?: number;7314 /**7315 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.7316 */7317 top_k?: number;7318 /**7319 * Random seed for reproducibility of the generation.7320 */7321 seed?: number;7322 /**7323 * Penalty for repeated tokens; higher values discourage repetition.7324 */7325 repetition_penalty?: number;7326 /**7327 * Decreases the likelihood of the model repeating the same lines verbatim.7328 */7329 frequency_penalty?: number;7330 /**7331 * Increases the likelihood of the model introducing new topics.7332 */7333 presence_penalty?: number;7334}7335interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages {7336 /**7337 * An array of message objects representing the conversation history.7338 */7339 messages: {7340 /**7341 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').7342 */7343 role?: string;7344 /**7345 * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 0000000017346 */7347 tool_call_id?: string;7348 content?: string | {7349 /**7350 * Type of the content provided7351 */7352 type?: string;7353 text?: string;7354 image_url?: {7355 /**7356 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted7357 */7358 url?: string;7359 };7360 }[] | {7361 /**7362 * Type of the content provided7363 */7364 type?: string;7365 text?: string;7366 image_url?: {7367 /**7368 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted7369 */7370 url?: string;7371 };7372 };7373 }[];7374 functions?: {7375 name: string;7376 code: string;7377 }[];7378 /**7379 * A list of tools available for the assistant to use.7380 */7381 tools?: ({7382 /**7383 * The name of the tool. More descriptive the better.7384 */7385 name: string;7386 /**7387 * A brief description of what the tool does.7388 */7389 description: string;7390 /**7391 * Schema defining the parameters accepted by the tool.7392 */7393 parameters: {7394 /**7395 * The type of the parameters object (usually 'object').7396 */7397 type: string;7398 /**7399 * List of required parameter names.7400 */7401 required?: string[];7402 /**7403 * Definitions of each parameter.7404 */7405 properties: {7406 [k: string]: {7407 /**7408 * The data type of the parameter.7409 */7410 type: string;7411 /**7412 * A description of the expected parameter.7413 */7414 description: string;7415 };7416 };7417 };7418 } | {7419 /**7420 * Specifies the type of tool (e.g., 'function').7421 */7422 type: string;7423 /**7424 * Details of the function tool.7425 */7426 function: {7427 /**7428 * The name of the function.7429 */7430 name: string;7431 /**7432 * A brief description of what the function does.7433 */7434 description: string;7435 /**7436 * Schema defining the parameters accepted by the function.7437 */7438 parameters: {7439 /**7440 * The type of the parameters object (usually 'object').7441 */7442 type: string;7443 /**7444 * List of required parameter names.7445 */7446 required?: string[];7447 /**7448 * Definitions of each parameter.7449 */7450 properties: {7451 [k: string]: {7452 /**7453 * The data type of the parameter.7454 */7455 type: string;7456 /**7457 * A description of the expected parameter.7458 */7459 description: string;7460 };7461 };7462 };7463 };7464 })[];7465 /**7466 * JSON schema that should be fufilled for the response.7467 */7468 guided_json?: object;7469 /**7470 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.7471 */7472 raw?: boolean;7473 /**7474 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.7475 */7476 stream?: boolean;7477 /**7478 * The maximum number of tokens to generate in the response.7479 */7480 max_tokens?: number;7481 /**7482 * Controls the randomness of the output; higher values produce more random results.7483 */7484 temperature?: number;7485 /**7486 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.7487 */7488 top_p?: number;7489 /**7490 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.7491 */7492 top_k?: number;7493 /**7494 * Random seed for reproducibility of the generation.7495 */7496 seed?: number;7497 /**7498 * Penalty for repeated tokens; higher values discourage repetition.7499 */7500 repetition_penalty?: number;7501 /**7502 * Decreases the likelihood of the model repeating the same lines verbatim.7503 */7504 frequency_penalty?: number;7505 /**7506 * Increases the likelihood of the model introducing new topics.7507 */7508 presence_penalty?: number;7509}7510type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = {7511 /**7512 * The generated text response from the model7513 */7514 response: string;7515 /**7516 * Usage statistics for the inference request7517 */7518 usage?: {7519 /**7520 * Total number of tokens in input7521 */7522 prompt_tokens?: number;7523 /**7524 * Total number of tokens in output7525 */7526 completion_tokens?: number;7527 /**7528 * Total number of input and output tokens7529 */7530 total_tokens?: number;7531 };7532 /**7533 * An array of tool calls requests made during the response generation7534 */7535 tool_calls?: {7536 /**7537 * The arguments passed to be passed to the tool call request7538 */7539 arguments?: object;7540 /**7541 * The name of the tool to be called7542 */7543 name?: string;7544 }[];7545};7546declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct {7547 inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input;7548 postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output;7549}7550type Ai_Cf_Google_Gemma_3_12B_It_Input = Ai_Cf_Google_Gemma_3_12B_It_Prompt | Ai_Cf_Google_Gemma_3_12B_It_Messages;7551interface Ai_Cf_Google_Gemma_3_12B_It_Prompt {7552 /**7553 * The input text prompt for the model to generate a response.7554 */7555 prompt: string;7556 /**7557 * JSON schema that should be fufilled for the response.7558 */7559 guided_json?: object;7560 /**7561 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.7562 */7563 raw?: boolean;7564 /**7565 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.7566 */7567 stream?: boolean;7568 /**7569 * The maximum number of tokens to generate in the response.7570 */7571 max_tokens?: number;7572 /**7573 * Controls the randomness of the output; higher values produce more random results.7574 */7575 temperature?: number;7576 /**7577 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.7578 */7579 top_p?: number;7580 /**7581 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.7582 */7583 top_k?: number;7584 /**7585 * Random seed for reproducibility of the generation.7586 */7587 seed?: number;7588 /**7589 * Penalty for repeated tokens; higher values discourage repetition.7590 */7591 repetition_penalty?: number;7592 /**7593 * Decreases the likelihood of the model repeating the same lines verbatim.7594 */7595 frequency_penalty?: number;7596 /**7597 * Increases the likelihood of the model introducing new topics.7598 */7599 presence_penalty?: number;7600}7601interface Ai_Cf_Google_Gemma_3_12B_It_Messages {7602 /**7603 * An array of message objects representing the conversation history.7604 */7605 messages: {7606 /**7607 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').7608 */7609 role?: string;7610 content?: string | {7611 /**7612 * Type of the content provided7613 */7614 type?: string;7615 text?: string;7616 image_url?: {7617 /**7618 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted7619 */7620 url?: string;7621 };7622 }[];7623 }[];7624 functions?: {7625 name: string;7626 code: string;7627 }[];7628 /**7629 * A list of tools available for the assistant to use.7630 */7631 tools?: ({7632 /**7633 * The name of the tool. More descriptive the better.7634 */7635 name: string;7636 /**7637 * A brief description of what the tool does.7638 */7639 description: string;7640 /**7641 * Schema defining the parameters accepted by the tool.7642 */7643 parameters: {7644 /**7645 * The type of the parameters object (usually 'object').7646 */7647 type: string;7648 /**7649 * List of required parameter names.7650 */7651 required?: string[];7652 /**7653 * Definitions of each parameter.7654 */7655 properties: {7656 [k: string]: {7657 /**7658 * The data type of the parameter.7659 */7660 type: string;7661 /**7662 * A description of the expected parameter.7663 */7664 description: string;7665 };7666 };7667 };7668 } | {7669 /**7670 * Specifies the type of tool (e.g., 'function').7671 */7672 type: string;7673 /**7674 * Details of the function tool.7675 */7676 function: {7677 /**7678 * The name of the function.7679 */7680 name: string;7681 /**7682 * A brief description of what the function does.7683 */7684 description: string;7685 /**7686 * Schema defining the parameters accepted by the function.7687 */7688 parameters: {7689 /**7690 * The type of the parameters object (usually 'object').7691 */7692 type: string;7693 /**7694 * List of required parameter names.7695 */7696 required?: string[];7697 /**7698 * Definitions of each parameter.7699 */7700 properties: {7701 [k: string]: {7702 /**7703 * The data type of the parameter.7704 */7705 type: string;7706 /**7707 * A description of the expected parameter.7708 */7709 description: string;7710 };7711 };7712 };7713 };7714 })[];7715 /**7716 * JSON schema that should be fufilled for the response.7717 */7718 guided_json?: object;7719 /**7720 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.7721 */7722 raw?: boolean;7723 /**7724 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.7725 */7726 stream?: boolean;7727 /**7728 * The maximum number of tokens to generate in the response.7729 */7730 max_tokens?: number;7731 /**7732 * Controls the randomness of the output; higher values produce more random results.7733 */7734 temperature?: number;7735 /**7736 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.7737 */7738 top_p?: number;7739 /**7740 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.7741 */7742 top_k?: number;7743 /**7744 * Random seed for reproducibility of the generation.7745 */7746 seed?: number;7747 /**7748 * Penalty for repeated tokens; higher values discourage repetition.7749 */7750 repetition_penalty?: number;7751 /**7752 * Decreases the likelihood of the model repeating the same lines verbatim.7753 */7754 frequency_penalty?: number;7755 /**7756 * Increases the likelihood of the model introducing new topics.7757 */7758 presence_penalty?: number;7759}7760type Ai_Cf_Google_Gemma_3_12B_It_Output = {7761 /**7762 * The generated text response from the model7763 */7764 response: string;7765 /**7766 * Usage statistics for the inference request7767 */7768 usage?: {7769 /**7770 * Total number of tokens in input7771 */7772 prompt_tokens?: number;7773 /**7774 * Total number of tokens in output7775 */7776 completion_tokens?: number;7777 /**7778 * Total number of input and output tokens7779 */7780 total_tokens?: number;7781 };7782 /**7783 * An array of tool calls requests made during the response generation7784 */7785 tool_calls?: {7786 /**7787 * The arguments passed to be passed to the tool call request7788 */7789 arguments?: object;7790 /**7791 * The name of the tool to be called7792 */7793 name?: string;7794 }[];7795};7796declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It {7797 inputs: Ai_Cf_Google_Gemma_3_12B_It_Input;7798 postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output;7799}7800type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch;7801interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt {7802 /**7803 * The input text prompt for the model to generate a response.7804 */7805 prompt: string;7806 /**7807 * JSON schema that should be fulfilled for the response.7808 */7809 guided_json?: object;7810 response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;7811 /**7812 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.7813 */7814 raw?: boolean;7815 /**7816 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.7817 */7818 stream?: boolean;7819 /**7820 * The maximum number of tokens to generate in the response.7821 */7822 max_tokens?: number;7823 /**7824 * Controls the randomness of the output; higher values produce more random results.7825 */7826 temperature?: number;7827 /**7828 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.7829 */7830 top_p?: number;7831 /**7832 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.7833 */7834 top_k?: number;7835 /**7836 * Random seed for reproducibility of the generation.7837 */7838 seed?: number;7839 /**7840 * Penalty for repeated tokens; higher values discourage repetition.7841 */7842 repetition_penalty?: number;7843 /**7844 * Decreases the likelihood of the model repeating the same lines verbatim.7845 */7846 frequency_penalty?: number;7847 /**7848 * Increases the likelihood of the model introducing new topics.7849 */7850 presence_penalty?: number;7851}7852interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode {7853 type?: "json_object" | "json_schema";7854 json_schema?: unknown;7855}7856interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages {7857 /**7858 * An array of message objects representing the conversation history.7859 */7860 messages: {7861 /**7862 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').7863 */7864 role?: string;7865 /**7866 * The tool call id. If you don't know what to put here you can fall back to 0000000017867 */7868 tool_call_id?: string;7869 content?: string | {7870 /**7871 * Type of the content provided7872 */7873 type?: string;7874 text?: string;7875 image_url?: {7876 /**7877 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted7878 */7879 url?: string;7880 };7881 }[] | {7882 /**7883 * Type of the content provided7884 */7885 type?: string;7886 text?: string;7887 image_url?: {7888 /**7889 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted7890 */7891 url?: string;7892 };7893 };7894 }[];7895 functions?: {7896 name: string;7897 code: string;7898 }[];7899 /**7900 * A list of tools available for the assistant to use.7901 */7902 tools?: ({7903 /**7904 * The name of the tool. More descriptive the better.7905 */7906 name: string;7907 /**7908 * A brief description of what the tool does.7909 */7910 description: string;7911 /**7912 * Schema defining the parameters accepted by the tool.7913 */7914 parameters: {7915 /**7916 * The type of the parameters object (usually 'object').7917 */7918 type: string;7919 /**7920 * List of required parameter names.7921 */7922 required?: string[];7923 /**7924 * Definitions of each parameter.7925 */7926 properties: {7927 [k: string]: {7928 /**7929 * The data type of the parameter.7930 */7931 type: string;7932 /**7933 * A description of the expected parameter.7934 */7935 description: string;7936 };7937 };7938 };7939 } | {7940 /**7941 * Specifies the type of tool (e.g., 'function').7942 */7943 type: string;7944 /**7945 * Details of the function tool.7946 */7947 function: {7948 /**7949 * The name of the function.7950 */7951 name: string;7952 /**7953 * A brief description of what the function does.7954 */7955 description: string;7956 /**7957 * Schema defining the parameters accepted by the function.7958 */7959 parameters: {7960 /**7961 * The type of the parameters object (usually 'object').7962 */7963 type: string;7964 /**7965 * List of required parameter names.7966 */7967 required?: string[];7968 /**7969 * Definitions of each parameter.7970 */7971 properties: {7972 [k: string]: {7973 /**7974 * The data type of the parameter.7975 */7976 type: string;7977 /**7978 * A description of the expected parameter.7979 */7980 description: string;7981 };7982 };7983 };7984 };7985 })[];7986 response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;7987 /**7988 * JSON schema that should be fufilled for the response.7989 */7990 guided_json?: object;7991 /**7992 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.7993 */7994 raw?: boolean;7995 /**7996 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.7997 */7998 stream?: boolean;7999 /**8000 * The maximum number of tokens to generate in the response.8001 */8002 max_tokens?: number;8003 /**8004 * Controls the randomness of the output; higher values produce more random results.8005 */8006 temperature?: number;8007 /**8008 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.8009 */8010 top_p?: number;8011 /**8012 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.8013 */8014 top_k?: number;8015 /**8016 * Random seed for reproducibility of the generation.8017 */8018 seed?: number;8019 /**8020 * Penalty for repeated tokens; higher values discourage repetition.8021 */8022 repetition_penalty?: number;8023 /**8024 * Decreases the likelihood of the model repeating the same lines verbatim.8025 */8026 frequency_penalty?: number;8027 /**8028 * Increases the likelihood of the model introducing new topics.8029 */8030 presence_penalty?: number;8031}8032interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch {8033 requests: (Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner)[];8034}8035interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner {8036 /**8037 * The input text prompt for the model to generate a response.8038 */8039 prompt: string;8040 /**8041 * JSON schema that should be fulfilled for the response.8042 */8043 guided_json?: object;8044 response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;8045 /**8046 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.8047 */8048 raw?: boolean;8049 /**8050 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.8051 */8052 stream?: boolean;8053 /**8054 * The maximum number of tokens to generate in the response.8055 */8056 max_tokens?: number;8057 /**8058 * Controls the randomness of the output; higher values produce more random results.8059 */8060 temperature?: number;8061 /**8062 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.8063 */8064 top_p?: number;8065 /**8066 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.8067 */8068 top_k?: number;8069 /**8070 * Random seed for reproducibility of the generation.8071 */8072 seed?: number;8073 /**8074 * Penalty for repeated tokens; higher values discourage repetition.8075 */8076 repetition_penalty?: number;8077 /**8078 * Decreases the likelihood of the model repeating the same lines verbatim.8079 */8080 frequency_penalty?: number;8081 /**8082 * Increases the likelihood of the model introducing new topics.8083 */8084 presence_penalty?: number;8085}8086interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner {8087 /**8088 * An array of message objects representing the conversation history.8089 */8090 messages: {8091 /**8092 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').8093 */8094 role?: string;8095 /**8096 * The tool call id. If you don't know what to put here you can fall back to 0000000018097 */8098 tool_call_id?: string;8099 content?: string | {8100 /**8101 * Type of the content provided8102 */8103 type?: string;8104 text?: string;8105 image_url?: {8106 /**8107 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted8108 */8109 url?: string;8110 };8111 }[] | {8112 /**8113 * Type of the content provided8114 */8115 type?: string;8116 text?: string;8117 image_url?: {8118 /**8119 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted8120 */8121 url?: string;8122 };8123 };8124 }[];8125 functions?: {8126 name: string;8127 code: string;8128 }[];8129 /**8130 * A list of tools available for the assistant to use.8131 */8132 tools?: ({8133 /**8134 * The name of the tool. More descriptive the better.8135 */8136 name: string;8137 /**8138 * A brief description of what the tool does.8139 */8140 description: string;8141 /**8142 * Schema defining the parameters accepted by the tool.8143 */8144 parameters: {8145 /**8146 * The type of the parameters object (usually 'object').8147 */8148 type: string;8149 /**8150 * List of required parameter names.8151 */8152 required?: string[];8153 /**8154 * Definitions of each parameter.8155 */8156 properties: {8157 [k: string]: {8158 /**8159 * The data type of the parameter.8160 */8161 type: string;8162 /**8163 * A description of the expected parameter.8164 */8165 description: string;8166 };8167 };8168 };8169 } | {8170 /**8171 * Specifies the type of tool (e.g., 'function').8172 */8173 type: string;8174 /**8175 * Details of the function tool.8176 */8177 function: {8178 /**8179 * The name of the function.8180 */8181 name: string;8182 /**8183 * A brief description of what the function does.8184 */8185 description: string;8186 /**8187 * Schema defining the parameters accepted by the function.8188 */8189 parameters: {8190 /**8191 * The type of the parameters object (usually 'object').8192 */8193 type: string;8194 /**8195 * List of required parameter names.8196 */8197 required?: string[];8198 /**8199 * Definitions of each parameter.8200 */8201 properties: {8202 [k: string]: {8203 /**8204 * The data type of the parameter.8205 */8206 type: string;8207 /**8208 * A description of the expected parameter.8209 */8210 description: string;8211 };8212 };8213 };8214 };8215 })[];8216 response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;8217 /**8218 * JSON schema that should be fufilled for the response.8219 */8220 guided_json?: object;8221 /**8222 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.8223 */8224 raw?: boolean;8225 /**8226 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.8227 */8228 stream?: boolean;8229 /**8230 * The maximum number of tokens to generate in the response.8231 */8232 max_tokens?: number;8233 /**8234 * Controls the randomness of the output; higher values produce more random results.8235 */8236 temperature?: number;8237 /**8238 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.8239 */8240 top_p?: number;8241 /**8242 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.8243 */8244 top_k?: number;8245 /**8246 * Random seed for reproducibility of the generation.8247 */8248 seed?: number;8249 /**8250 * Penalty for repeated tokens; higher values discourage repetition.8251 */8252 repetition_penalty?: number;8253 /**8254 * Decreases the likelihood of the model repeating the same lines verbatim.8255 */8256 frequency_penalty?: number;8257 /**8258 * Increases the likelihood of the model introducing new topics.8259 */8260 presence_penalty?: number;8261}8262type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = {8263 /**8264 * The generated text response from the model8265 */8266 response: string;8267 /**8268 * Usage statistics for the inference request8269 */8270 usage?: {8271 /**8272 * Total number of tokens in input8273 */8274 prompt_tokens?: number;8275 /**8276 * Total number of tokens in output8277 */8278 completion_tokens?: number;8279 /**8280 * Total number of input and output tokens8281 */8282 total_tokens?: number;8283 };8284 /**8285 * An array of tool calls requests made during the response generation8286 */8287 tool_calls?: {8288 /**8289 * The tool call id.8290 */8291 id?: string;8292 /**8293 * Specifies the type of tool (e.g., 'function').8294 */8295 type?: string;8296 /**8297 * Details of the function tool.8298 */8299 function?: {8300 /**8301 * The name of the tool to be called8302 */8303 name?: string;8304 /**8305 * The arguments passed to be passed to the tool call request8306 */8307 arguments?: object;8308 };8309 }[];8310};8311declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct {8312 inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input;8313 postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output;8314}8315type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch;8316interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt {8317 /**8318 * The input text prompt for the model to generate a response.8319 */8320 prompt: string;8321 /**8322 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.8323 */8324 lora?: string;8325 response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode;8326 /**8327 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.8328 */8329 raw?: boolean;8330 /**8331 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.8332 */8333 stream?: boolean;8334 /**8335 * The maximum number of tokens to generate in the response.8336 */8337 max_tokens?: number;8338 /**8339 * Controls the randomness of the output; higher values produce more random results.8340 */8341 temperature?: number;8342 /**8343 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.8344 */8345 top_p?: number;8346 /**8347 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.8348 */8349 top_k?: number;8350 /**8351 * Random seed for reproducibility of the generation.8352 */8353 seed?: number;8354 /**8355 * Penalty for repeated tokens; higher values discourage repetition.8356 */8357 repetition_penalty?: number;8358 /**8359 * Decreases the likelihood of the model repeating the same lines verbatim.8360 */8361 frequency_penalty?: number;8362 /**8363 * Increases the likelihood of the model introducing new topics.8364 */8365 presence_penalty?: number;8366}8367interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode {8368 type?: "json_object" | "json_schema";8369 json_schema?: unknown;8370}8371interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages {8372 /**8373 * An array of message objects representing the conversation history.8374 */8375 messages: {8376 /**8377 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').8378 */8379 role: string;8380 content: string | {8381 /**8382 * Type of the content (text)8383 */8384 type?: string;8385 /**8386 * Text content8387 */8388 text?: string;8389 }[];8390 }[];8391 functions?: {8392 name: string;8393 code: string;8394 }[];8395 /**8396 * A list of tools available for the assistant to use.8397 */8398 tools?: ({8399 /**8400 * The name of the tool. More descriptive the better.8401 */8402 name: string;8403 /**8404 * A brief description of what the tool does.8405 */8406 description: string;8407 /**8408 * Schema defining the parameters accepted by the tool.8409 */8410 parameters: {8411 /**8412 * The type of the parameters object (usually 'object').8413 */8414 type: string;8415 /**8416 * List of required parameter names.8417 */8418 required?: string[];8419 /**8420 * Definitions of each parameter.8421 */8422 properties: {8423 [k: string]: {8424 /**8425 * The data type of the parameter.8426 */8427 type: string;8428 /**8429 * A description of the expected parameter.8430 */8431 description: string;8432 };8433 };8434 };8435 } | {8436 /**8437 * Specifies the type of tool (e.g., 'function').8438 */8439 type: string;8440 /**8441 * Details of the function tool.8442 */8443 function: {8444 /**8445 * The name of the function.8446 */8447 name: string;8448 /**8449 * A brief description of what the function does.8450 */8451 description: string;8452 /**8453 * Schema defining the parameters accepted by the function.8454 */8455 parameters: {8456 /**8457 * The type of the parameters object (usually 'object').8458 */8459 type: string;8460 /**8461 * List of required parameter names.8462 */8463 required?: string[];8464 /**8465 * Definitions of each parameter.8466 */8467 properties: {8468 [k: string]: {8469 /**8470 * The data type of the parameter.8471 */8472 type: string;8473 /**8474 * A description of the expected parameter.8475 */8476 description: string;8477 };8478 };8479 };8480 };8481 })[];8482 response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1;8483 /**8484 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.8485 */8486 raw?: boolean;8487 /**8488 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.8489 */8490 stream?: boolean;8491 /**8492 * The maximum number of tokens to generate in the response.8493 */8494 max_tokens?: number;8495 /**8496 * Controls the randomness of the output; higher values produce more random results.8497 */8498 temperature?: number;8499 /**8500 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.8501 */8502 top_p?: number;8503 /**8504 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.8505 */8506 top_k?: number;8507 /**8508 * Random seed for reproducibility of the generation.8509 */8510 seed?: number;8511 /**8512 * Penalty for repeated tokens; higher values discourage repetition.8513 */8514 repetition_penalty?: number;8515 /**8516 * Decreases the likelihood of the model repeating the same lines verbatim.8517 */8518 frequency_penalty?: number;8519 /**8520 * Increases the likelihood of the model introducing new topics.8521 */8522 presence_penalty?: number;8523}8524interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 {8525 type?: "json_object" | "json_schema";8526 json_schema?: unknown;8527}8528interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch {8529 requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[];8530}8531interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 {8532 /**8533 * The input text prompt for the model to generate a response.8534 */8535 prompt: string;8536 /**8537 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.8538 */8539 lora?: string;8540 response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2;8541 /**8542 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.8543 */8544 raw?: boolean;8545 /**8546 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.8547 */8548 stream?: boolean;8549 /**8550 * The maximum number of tokens to generate in the response.8551 */8552 max_tokens?: number;8553 /**8554 * Controls the randomness of the output; higher values produce more random results.8555 */8556 temperature?: number;8557 /**8558 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.8559 */8560 top_p?: number;8561 /**8562 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.8563 */8564 top_k?: number;8565 /**8566 * Random seed for reproducibility of the generation.8567 */8568 seed?: number;8569 /**8570 * Penalty for repeated tokens; higher values discourage repetition.8571 */8572 repetition_penalty?: number;8573 /**8574 * Decreases the likelihood of the model repeating the same lines verbatim.8575 */8576 frequency_penalty?: number;8577 /**8578 * Increases the likelihood of the model introducing new topics.8579 */8580 presence_penalty?: number;8581}8582interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 {8583 type?: "json_object" | "json_schema";8584 json_schema?: unknown;8585}8586interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 {8587 /**8588 * An array of message objects representing the conversation history.8589 */8590 messages: {8591 /**8592 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').8593 */8594 role: string;8595 content: string | {8596 /**8597 * Type of the content (text)8598 */8599 type?: string;8600 /**8601 * Text content8602 */8603 text?: string;8604 }[];8605 }[];8606 functions?: {8607 name: string;8608 code: string;8609 }[];8610 /**8611 * A list of tools available for the assistant to use.8612 */8613 tools?: ({8614 /**8615 * The name of the tool. More descriptive the better.8616 */8617 name: string;8618 /**8619 * A brief description of what the tool does.8620 */8621 description: string;8622 /**8623 * Schema defining the parameters accepted by the tool.8624 */8625 parameters: {8626 /**8627 * The type of the parameters object (usually 'object').8628 */8629 type: string;8630 /**8631 * List of required parameter names.8632 */8633 required?: string[];8634 /**8635 * Definitions of each parameter.8636 */8637 properties: {8638 [k: string]: {8639 /**8640 * The data type of the parameter.8641 */8642 type: string;8643 /**8644 * A description of the expected parameter.8645 */8646 description: string;8647 };8648 };8649 };8650 } | {8651 /**8652 * Specifies the type of tool (e.g., 'function').8653 */8654 type: string;8655 /**8656 * Details of the function tool.8657 */8658 function: {8659 /**8660 * The name of the function.8661 */8662 name: string;8663 /**8664 * A brief description of what the function does.8665 */8666 description: string;8667 /**8668 * Schema defining the parameters accepted by the function.8669 */8670 parameters: {8671 /**8672 * The type of the parameters object (usually 'object').8673 */8674 type: string;8675 /**8676 * List of required parameter names.8677 */8678 required?: string[];8679 /**8680 * Definitions of each parameter.8681 */8682 properties: {8683 [k: string]: {8684 /**8685 * The data type of the parameter.8686 */8687 type: string;8688 /**8689 * A description of the expected parameter.8690 */8691 description: string;8692 };8693 };8694 };8695 };8696 })[];8697 response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3;8698 /**8699 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.8700 */8701 raw?: boolean;8702 /**8703 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.8704 */8705 stream?: boolean;8706 /**8707 * The maximum number of tokens to generate in the response.8708 */8709 max_tokens?: number;8710 /**8711 * Controls the randomness of the output; higher values produce more random results.8712 */8713 temperature?: number;8714 /**8715 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.8716 */8717 top_p?: number;8718 /**8719 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.8720 */8721 top_k?: number;8722 /**8723 * Random seed for reproducibility of the generation.8724 */8725 seed?: number;8726 /**8727 * Penalty for repeated tokens; higher values discourage repetition.8728 */8729 repetition_penalty?: number;8730 /**8731 * Decreases the likelihood of the model repeating the same lines verbatim.8732 */8733 frequency_penalty?: number;8734 /**8735 * Increases the likelihood of the model introducing new topics.8736 */8737 presence_penalty?: number;8738}8739interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 {8740 type?: "json_object" | "json_schema";8741 json_schema?: unknown;8742}8743type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response | string | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse;8744interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response {8745 /**8746 * Unique identifier for the completion8747 */8748 id?: string;8749 /**8750 * Object type identifier8751 */8752 object?: "chat.completion";8753 /**8754 * Unix timestamp of when the completion was created8755 */8756 created?: number;8757 /**8758 * Model used for the completion8759 */8760 model?: string;8761 /**8762 * List of completion choices8763 */8764 choices?: {8765 /**8766 * Index of the choice in the list8767 */8768 index?: number;8769 /**8770 * The message generated by the model8771 */8772 message?: {8773 /**8774 * Role of the message author8775 */8776 role: string;8777 /**8778 * The content of the message8779 */8780 content: string;8781 /**8782 * Internal reasoning content (if available)8783 */8784 reasoning_content?: string;8785 /**8786 * Tool calls made by the assistant8787 */8788 tool_calls?: {8789 /**8790 * Unique identifier for the tool call8791 */8792 id: string;8793 /**8794 * Type of tool call8795 */8796 type: "function";8797 function: {8798 /**8799 * Name of the function to call8800 */8801 name: string;8802 /**8803 * JSON string of arguments for the function8804 */8805 arguments: string;8806 };8807 }[];8808 };8809 /**8810 * Reason why the model stopped generating8811 */8812 finish_reason?: string;8813 /**8814 * Stop reason (may be null)8815 */8816 stop_reason?: string | null;8817 /**8818 * Log probabilities (if requested)8819 */8820 logprobs?: {} | null;8821 }[];8822 /**8823 * Usage statistics for the inference request8824 */8825 usage?: {8826 /**8827 * Total number of tokens in input8828 */8829 prompt_tokens?: number;8830 /**8831 * Total number of tokens in output8832 */8833 completion_tokens?: number;8834 /**8835 * Total number of input and output tokens8836 */8837 total_tokens?: number;8838 };8839 /**8840 * Log probabilities for the prompt (if requested)8841 */8842 prompt_logprobs?: {} | null;8843}8844interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response {8845 /**8846 * Unique identifier for the completion8847 */8848 id?: string;8849 /**8850 * Object type identifier8851 */8852 object?: "text_completion";8853 /**8854 * Unix timestamp of when the completion was created8855 */8856 created?: number;8857 /**8858 * Model used for the completion8859 */8860 model?: string;8861 /**8862 * List of completion choices8863 */8864 choices?: {8865 /**8866 * Index of the choice in the list8867 */8868 index: number;8869 /**8870 * The generated text completion8871 */8872 text: string;8873 /**8874 * Reason why the model stopped generating8875 */8876 finish_reason: string;8877 /**8878 * Stop reason (may be null)8879 */8880 stop_reason?: string | null;8881 /**8882 * Log probabilities (if requested)8883 */8884 logprobs?: {} | null;8885 /**8886 * Log probabilities for the prompt (if requested)8887 */8888 prompt_logprobs?: {} | null;8889 }[];8890 /**8891 * Usage statistics for the inference request8892 */8893 usage?: {8894 /**8895 * Total number of tokens in input8896 */8897 prompt_tokens?: number;8898 /**8899 * Total number of tokens in output8900 */8901 completion_tokens?: number;8902 /**8903 * Total number of input and output tokens8904 */8905 total_tokens?: number;8906 };8907}8908interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse {8909 /**8910 * The async request id that can be used to obtain the results.8911 */8912 request_id?: string;8913}8914declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 {8915 inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input;8916 postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output;8917}8918interface Ai_Cf_Deepgram_Nova_3_Input {8919 audio: {8920 body: object;8921 contentType: string;8922 };8923 /**8924 * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param.8925 */8926 custom_topic_mode?: "extended" | "strict";8927 /**8928 * Custom topics you want the model to detect within your input audio or text if present Submit up to 1008929 */8930 custom_topic?: string;8931 /**8932 * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param8933 */8934 custom_intent_mode?: "extended" | "strict";8935 /**8936 * Custom intents you want the model to detect within your input audio if present8937 */8938 custom_intent?: string;8939 /**8940 * Identifies and extracts key entities from content in submitted audio8941 */8942 detect_entities?: boolean;8943 /**8944 * Identifies the dominant language spoken in submitted audio8945 */8946 detect_language?: boolean;8947 /**8948 * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 08949 */8950 diarize?: boolean;8951 /**8952 * Identify and extract key entities from content in submitted audio8953 */8954 dictation?: boolean;8955 /**8956 * Specify the expected encoding of your submitted audio8957 */8958 encoding?: "linear16" | "flac" | "mulaw" | "amr-nb" | "amr-wb" | "opus" | "speex" | "g729";8959 /**8960 * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing8961 */8962 extra?: string;8963 /**8964 * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um'8965 */8966 filler_words?: boolean;8967 /**8968 * Key term prompting can boost or suppress specialized terminology and brands.8969 */8970 keyterm?: string;8971 /**8972 * Keywords can boost or suppress specialized terminology and brands.8973 */8974 keywords?: string;8975 /**8976 * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available.8977 */8978 language?: string;8979 /**8980 * Spoken measurements will be converted to their corresponding abbreviations.8981 */8982 measurements?: boolean;8983 /**8984 * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip.8985 */8986 mip_opt_out?: boolean;8987 /**8988 * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio8989 */8990 mode?: "general" | "medical" | "finance";8991 /**8992 * Transcribe each audio channel independently.8993 */8994 multichannel?: boolean;8995 /**8996 * Numerals converts numbers from written format to numerical format.8997 */8998 numerals?: boolean;8999 /**9000 * Splits audio into paragraphs to improve transcript readability.9001 */9002 paragraphs?: boolean;9003 /**9004 * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely.9005 */9006 profanity_filter?: boolean;9007 /**9008 * Add punctuation and capitalization to the transcript.9009 */9010 punctuate?: boolean;9011 /**9012 * Redaction removes sensitive information from your transcripts.9013 */9014 redact?: string;9015 /**9016 * Search for terms or phrases in submitted audio and replaces them.9017 */9018 replace?: string;9019 /**9020 * Search for terms or phrases in submitted audio.9021 */9022 search?: string;9023 /**9024 * Recognizes the sentiment throughout a transcript or text.9025 */9026 sentiment?: boolean;9027 /**9028 * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability.9029 */9030 smart_format?: boolean;9031 /**9032 * Detect topics throughout a transcript or text.9033 */9034 topics?: boolean;9035 /**9036 * Segments speech into meaningful semantic units.9037 */9038 utterances?: boolean;9039 /**9040 * Seconds to wait before detecting a pause between words in submitted audio.9041 */9042 utt_split?: number;9043 /**9044 * The number of channels in the submitted audio9045 */9046 channels?: number;9047 /**9048 * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets.9049 */9050 interim_results?: boolean;9051 /**9052 * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing9053 */9054 endpointing?: string;9055 /**9056 * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets.9057 */9058 vad_events?: boolean;9059 /**9060 * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets.9061 */9062 utterance_end_ms?: boolean;9063}9064interface Ai_Cf_Deepgram_Nova_3_Output {9065 results?: {9066 channels?: {9067 alternatives?: {9068 confidence?: number;9069 transcript?: string;9070 words?: {9071 confidence?: number;9072 end?: number;9073 start?: number;9074 word?: string;9075 }[];9076 }[];9077 }[];9078 summary?: {9079 result?: string;9080 short?: string;9081 };9082 sentiments?: {9083 segments?: {9084 text?: string;9085 start_word?: number;9086 end_word?: number;9087 sentiment?: string;9088 sentiment_score?: number;9089 }[];9090 average?: {9091 sentiment?: string;9092 sentiment_score?: number;9093 };9094 };9095 };9096}9097declare abstract class Base_Ai_Cf_Deepgram_Nova_3 {9098 inputs: Ai_Cf_Deepgram_Nova_3_Input;9099 postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output;9100}9101interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input {9102 queries?: string | string[];9103 /**9104 * Optional instruction for the task9105 */9106 instruction?: string;9107 documents?: string | string[];9108 text?: string | string[];9109}9110interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output {9111 data?: number[][];9112 shape?: number[];9113}9114declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B {9115 inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input;9116 postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output;9117}9118type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = {9119 /**9120 * readable stream with audio data and content-type specified for that data9121 */9122 audio: {9123 body: object;9124 contentType: string;9125 };9126 /**9127 * type of data PCM data that's sent to the inference server as raw array9128 */9129 dtype?: "uint8" | "float32" | "float64";9130} | {9131 /**9132 * base64 encoded audio data9133 */9134 audio: string;9135 /**9136 * type of data PCM data that's sent to the inference server as raw array9137 */9138 dtype?: "uint8" | "float32" | "float64";9139};9140interface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output {9141 /**9142 * if true, end-of-turn was detected9143 */9144 is_complete?: boolean;9145 /**9146 * probability of the end-of-turn detection9147 */9148 probability?: number;9149}9150declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 {9151 inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input;9152 postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output;9153}9154declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B {9155 inputs: XOR<ResponsesInput, ChatCompletionsMessagesInput>;9156 postProcessedOutputs: XOR<ResponsesOutput, ChatCompletionsOutput>;9157}9158declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B {9159 inputs: XOR<ResponsesInput, ChatCompletionsMessagesInput>;9160 postProcessedOutputs: XOR<ResponsesOutput, ChatCompletionsOutput>;9161}9162interface Ai_Cf_Leonardo_Phoenix_1_0_Input {9163 /**9164 * A text description of the image you want to generate.9165 */9166 prompt: string;9167 /**9168 * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt9169 */9170 guidance?: number;9171 /**9172 * Random seed for reproducibility of the image generation9173 */9174 seed?: number;9175 /**9176 * The height of the generated image in pixels9177 */9178 height?: number;9179 /**9180 * The width of the generated image in pixels9181 */9182 width?: number;9183 /**9184 * The number of diffusion steps; higher values can improve quality but take longer9185 */9186 num_steps?: number;9187 /**9188 * Specify what to exclude from the generated images9189 */9190 negative_prompt?: string;9191}9192/**9193 * The generated image in JPEG format9194 */9195type Ai_Cf_Leonardo_Phoenix_1_0_Output = string;9196declare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 {9197 inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input;9198 postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output;9199}9200interface Ai_Cf_Leonardo_Lucid_Origin_Input {9201 /**9202 * A text description of the image you want to generate.9203 */9204 prompt: string;9205 /**9206 * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt9207 */9208 guidance?: number;9209 /**9210 * Random seed for reproducibility of the image generation9211 */9212 seed?: number;9213 /**9214 * The height of the generated image in pixels9215 */9216 height?: number;9217 /**9218 * The width of the generated image in pixels9219 */9220 width?: number;9221 /**9222 * The number of diffusion steps; higher values can improve quality but take longer9223 */9224 num_steps?: number;9225 /**9226 * The number of diffusion steps; higher values can improve quality but take longer9227 */9228 steps?: number;9229}9230interface Ai_Cf_Leonardo_Lucid_Origin_Output {9231 /**9232 * The generated image in Base64 format.9233 */9234 image?: string;9235}9236declare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin {9237 inputs: Ai_Cf_Leonardo_Lucid_Origin_Input;9238 postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output;9239}9240interface Ai_Cf_Deepgram_Aura_1_Input {9241 /**9242 * Speaker used to produce the audio.9243 */9244 speaker?: "angus" | "asteria" | "arcas" | "orion" | "orpheus" | "athena" | "luna" | "zeus" | "perseus" | "helios" | "hera" | "stella";9245 /**9246 * Encoding of the output audio.9247 */9248 encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac";9249 /**9250 * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type..9251 */9252 container?: "none" | "wav" | "ogg";9253 /**9254 * The text content to be converted to speech9255 */9256 text: string;9257 /**9258 * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable9259 */9260 sample_rate?: number;9261 /**9262 * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type.9263 */9264 bit_rate?: number;9265}9266/**9267 * The generated audio in MP3 format9268 */9269type Ai_Cf_Deepgram_Aura_1_Output = string;9270declare abstract class Base_Ai_Cf_Deepgram_Aura_1 {9271 inputs: Ai_Cf_Deepgram_Aura_1_Input;9272 postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output;9273}9274interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input {9275 /**9276 * Input text to translate. Can be a single string or a list of strings.9277 */9278 text: string | string[];9279 /**9280 * Target langauge to translate to9281 */9282 target_language: "asm_Beng" | "awa_Deva" | "ben_Beng" | "bho_Deva" | "brx_Deva" | "doi_Deva" | "eng_Latn" | "gom_Deva" | "gon_Deva" | "guj_Gujr" | "hin_Deva" | "hne_Deva" | "kan_Knda" | "kas_Arab" | "kas_Deva" | "kha_Latn" | "lus_Latn" | "mag_Deva" | "mai_Deva" | "mal_Mlym" | "mar_Deva" | "mni_Beng" | "mni_Mtei" | "npi_Deva" | "ory_Orya" | "pan_Guru" | "san_Deva" | "sat_Olck" | "snd_Arab" | "snd_Deva" | "tam_Taml" | "tel_Telu" | "urd_Arab" | "unr_Deva";9283}9284interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output {9285 /**9286 * Translated texts9287 */9288 translations: string[];9289}9290declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B {9291 inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input;9292 postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output;9293}9294type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch;9295interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt {9296 /**9297 * The input text prompt for the model to generate a response.9298 */9299 prompt: string;9300 /**9301 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.9302 */9303 lora?: string;9304 response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode;9305 /**9306 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.9307 */9308 raw?: boolean;9309 /**9310 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.9311 */9312 stream?: boolean;9313 /**9314 * The maximum number of tokens to generate in the response.9315 */9316 max_tokens?: number;9317 /**9318 * Controls the randomness of the output; higher values produce more random results.9319 */9320 temperature?: number;9321 /**9322 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.9323 */9324 top_p?: number;9325 /**9326 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.9327 */9328 top_k?: number;9329 /**9330 * Random seed for reproducibility of the generation.9331 */9332 seed?: number;9333 /**9334 * Penalty for repeated tokens; higher values discourage repetition.9335 */9336 repetition_penalty?: number;9337 /**9338 * Decreases the likelihood of the model repeating the same lines verbatim.9339 */9340 frequency_penalty?: number;9341 /**9342 * Increases the likelihood of the model introducing new topics.9343 */9344 presence_penalty?: number;9345}9346interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode {9347 type?: "json_object" | "json_schema";9348 json_schema?: unknown;9349}9350interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages {9351 /**9352 * An array of message objects representing the conversation history.9353 */9354 messages: {9355 /**9356 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').9357 */9358 role: string;9359 content: string | {9360 /**9361 * Type of the content (text)9362 */9363 type?: string;9364 /**9365 * Text content9366 */9367 text?: string;9368 }[];9369 }[];9370 functions?: {9371 name: string;9372 code: string;9373 }[];9374 /**9375 * A list of tools available for the assistant to use.9376 */9377 tools?: ({9378 /**9379 * The name of the tool. More descriptive the better.9380 */9381 name: string;9382 /**9383 * A brief description of what the tool does.9384 */9385 description: string;9386 /**9387 * Schema defining the parameters accepted by the tool.9388 */9389 parameters: {9390 /**9391 * The type of the parameters object (usually 'object').9392 */9393 type: string;9394 /**9395 * List of required parameter names.9396 */9397 required?: string[];9398 /**9399 * Definitions of each parameter.9400 */9401 properties: {9402 [k: string]: {9403 /**9404 * The data type of the parameter.9405 */9406 type: string;9407 /**9408 * A description of the expected parameter.9409 */9410 description: string;9411 };9412 };9413 };9414 } | {9415 /**9416 * Specifies the type of tool (e.g., 'function').9417 */9418 type: string;9419 /**9420 * Details of the function tool.9421 */9422 function: {9423 /**9424 * The name of the function.9425 */9426 name: string;9427 /**9428 * A brief description of what the function does.9429 */9430 description: string;9431 /**9432 * Schema defining the parameters accepted by the function.9433 */9434 parameters: {9435 /**9436 * The type of the parameters object (usually 'object').9437 */9438 type: string;9439 /**9440 * List of required parameter names.9441 */9442 required?: string[];9443 /**9444 * Definitions of each parameter.9445 */9446 properties: {9447 [k: string]: {9448 /**9449 * The data type of the parameter.9450 */9451 type: string;9452 /**9453 * A description of the expected parameter.9454 */9455 description: string;9456 };9457 };9458 };9459 };9460 })[];9461 response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1;9462 /**9463 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.9464 */9465 raw?: boolean;9466 /**9467 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.9468 */9469 stream?: boolean;9470 /**9471 * The maximum number of tokens to generate in the response.9472 */9473 max_tokens?: number;9474 /**9475 * Controls the randomness of the output; higher values produce more random results.9476 */9477 temperature?: number;9478 /**9479 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.9480 */9481 top_p?: number;9482 /**9483 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.9484 */9485 top_k?: number;9486 /**9487 * Random seed for reproducibility of the generation.9488 */9489 seed?: number;9490 /**9491 * Penalty for repeated tokens; higher values discourage repetition.9492 */9493 repetition_penalty?: number;9494 /**9495 * Decreases the likelihood of the model repeating the same lines verbatim.9496 */9497 frequency_penalty?: number;9498 /**9499 * Increases the likelihood of the model introducing new topics.9500 */9501 presence_penalty?: number;9502}9503interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 {9504 type?: "json_object" | "json_schema";9505 json_schema?: unknown;9506}9507interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch {9508 requests: (Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1)[];9509}9510interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 {9511 /**9512 * The input text prompt for the model to generate a response.9513 */9514 prompt: string;9515 /**9516 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.9517 */9518 lora?: string;9519 response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2;9520 /**9521 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.9522 */9523 raw?: boolean;9524 /**9525 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.9526 */9527 stream?: boolean;9528 /**9529 * The maximum number of tokens to generate in the response.9530 */9531 max_tokens?: number;9532 /**9533 * Controls the randomness of the output; higher values produce more random results.9534 */9535 temperature?: number;9536 /**9537 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.9538 */9539 top_p?: number;9540 /**9541 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.9542 */9543 top_k?: number;9544 /**9545 * Random seed for reproducibility of the generation.9546 */9547 seed?: number;9548 /**9549 * Penalty for repeated tokens; higher values discourage repetition.9550 */9551 repetition_penalty?: number;9552 /**9553 * Decreases the likelihood of the model repeating the same lines verbatim.9554 */9555 frequency_penalty?: number;9556 /**9557 * Increases the likelihood of the model introducing new topics.9558 */9559 presence_penalty?: number;9560}9561interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 {9562 type?: "json_object" | "json_schema";9563 json_schema?: unknown;9564}9565interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 {9566 /**9567 * An array of message objects representing the conversation history.9568 */9569 messages: {9570 /**9571 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').9572 */9573 role: string;9574 content: string | {9575 /**9576 * Type of the content (text)9577 */9578 type?: string;9579 /**9580 * Text content9581 */9582 text?: string;9583 }[];9584 }[];9585 functions?: {9586 name: string;9587 code: string;9588 }[];9589 /**9590 * A list of tools available for the assistant to use.9591 */9592 tools?: ({9593 /**9594 * The name of the tool. More descriptive the better.9595 */9596 name: string;9597 /**9598 * A brief description of what the tool does.9599 */9600 description: string;9601 /**9602 * Schema defining the parameters accepted by the tool.9603 */9604 parameters: {9605 /**9606 * The type of the parameters object (usually 'object').9607 */9608 type: string;9609 /**9610 * List of required parameter names.9611 */9612 required?: string[];9613 /**9614 * Definitions of each parameter.9615 */9616 properties: {9617 [k: string]: {9618 /**9619 * The data type of the parameter.9620 */9621 type: string;9622 /**9623 * A description of the expected parameter.9624 */9625 description: string;9626 };9627 };9628 };9629 } | {9630 /**9631 * Specifies the type of tool (e.g., 'function').9632 */9633 type: string;9634 /**9635 * Details of the function tool.9636 */9637 function: {9638 /**9639 * The name of the function.9640 */9641 name: string;9642 /**9643 * A brief description of what the function does.9644 */9645 description: string;9646 /**9647 * Schema defining the parameters accepted by the function.9648 */9649 parameters: {9650 /**9651 * The type of the parameters object (usually 'object').9652 */9653 type: string;9654 /**9655 * List of required parameter names.9656 */9657 required?: string[];9658 /**9659 * Definitions of each parameter.9660 */9661 properties: {9662 [k: string]: {9663 /**9664 * The data type of the parameter.9665 */9666 type: string;9667 /**9668 * A description of the expected parameter.9669 */9670 description: string;9671 };9672 };9673 };9674 };9675 })[];9676 response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3;9677 /**9678 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.9679 */9680 raw?: boolean;9681 /**9682 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.9683 */9684 stream?: boolean;9685 /**9686 * The maximum number of tokens to generate in the response.9687 */9688 max_tokens?: number;9689 /**9690 * Controls the randomness of the output; higher values produce more random results.9691 */9692 temperature?: number;9693 /**9694 * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.9695 */9696 top_p?: number;9697 /**9698 * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.9699 */9700 top_k?: number;9701 /**9702 * Random seed for reproducibility of the generation.9703 */9704 seed?: number;9705 /**9706 * Penalty for repeated tokens; higher values discourage repetition.9707 */9708 repetition_penalty?: number;9709 /**9710 * Decreases the likelihood of the model repeating the same lines verbatim.9711 */9712 frequency_penalty?: number;9713 /**9714 * Increases the likelihood of the model introducing new topics.9715 */9716 presence_penalty?: number;9717}9718interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 {9719 type?: "json_object" | "json_schema";9720 json_schema?: unknown;9721}9722type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response | string | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse;9723interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response {9724 /**9725 * Unique identifier for the completion9726 */9727 id?: string;9728 /**9729 * Object type identifier9730 */9731 object?: "chat.completion";9732 /**9733 * Unix timestamp of when the completion was created9734 */9735 created?: number;9736 /**9737 * Model used for the completion9738 */9739 model?: string;9740 /**9741 * List of completion choices9742 */9743 choices?: {9744 /**9745 * Index of the choice in the list9746 */9747 index?: number;9748 /**9749 * The message generated by the model9750 */9751 message?: {9752 /**9753 * Role of the message author9754 */9755 role: string;9756 /**9757 * The content of the message9758 */9759 content: string;9760 /**9761 * Internal reasoning content (if available)9762 */9763 reasoning_content?: string;9764 /**9765 * Tool calls made by the assistant9766 */9767 tool_calls?: {9768 /**9769 * Unique identifier for the tool call9770 */9771 id: string;9772 /**9773 * Type of tool call9774 */9775 type: "function";9776 function: {9777 /**9778 * Name of the function to call9779 */9780 name: string;9781 /**9782 * JSON string of arguments for the function9783 */9784 arguments: string;9785 };9786 }[];9787 };9788 /**9789 * Reason why the model stopped generating9790 */9791 finish_reason?: string;9792 /**9793 * Stop reason (may be null)9794 */9795 stop_reason?: string | null;9796 /**9797 * Log probabilities (if requested)9798 */9799 logprobs?: {} | null;9800 }[];9801 /**9802 * Usage statistics for the inference request9803 */9804 usage?: {9805 /**9806 * Total number of tokens in input9807 */9808 prompt_tokens?: number;9809 /**9810 * Total number of tokens in output9811 */9812 completion_tokens?: number;9813 /**9814 * Total number of input and output tokens9815 */9816 total_tokens?: number;9817 };9818 /**9819 * Log probabilities for the prompt (if requested)9820 */9821 prompt_logprobs?: {} | null;9822}9823interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response {9824 /**9825 * Unique identifier for the completion9826 */9827 id?: string;9828 /**9829 * Object type identifier9830 */9831 object?: "text_completion";9832 /**9833 * Unix timestamp of when the completion was created9834 */9835 created?: number;9836 /**9837 * Model used for the completion9838 */9839 model?: string;9840 /**9841 * List of completion choices9842 */9843 choices?: {9844 /**9845 * Index of the choice in the list9846 */9847 index: number;9848 /**9849 * The generated text completion9850 */9851 text: string;9852 /**9853 * Reason why the model stopped generating9854 */9855 finish_reason: string;9856 /**9857 * Stop reason (may be null)9858 */9859 stop_reason?: string | null;9860 /**9861 * Log probabilities (if requested)9862 */9863 logprobs?: {} | null;9864 /**9865 * Log probabilities for the prompt (if requested)9866 */9867 prompt_logprobs?: {} | null;9868 }[];9869 /**9870 * Usage statistics for the inference request9871 */9872 usage?: {9873 /**9874 * Total number of tokens in input9875 */9876 prompt_tokens?: number;9877 /**9878 * Total number of tokens in output9879 */9880 completion_tokens?: number;9881 /**9882 * Total number of input and output tokens9883 */9884 total_tokens?: number;9885 };9886}9887interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse {9888 /**9889 * The async request id that can be used to obtain the results.9890 */9891 request_id?: string;9892}9893declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It {9894 inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input;9895 postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output;9896}9897interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input {9898 /**9899 * Input text to embed. Can be a single string or a list of strings.9900 */9901 text: string | string[];9902}9903interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output {9904 /**9905 * Embedding vectors, where each vector is a list of floats.9906 */9907 data: number[][];9908 /**9909 * Shape of the embedding data as [number_of_embeddings, embedding_dimension].9910 *9911 * @minItems 29912 * @maxItems 29913 */9914 shape: [9915 number,9916 number9917 ];9918}9919declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B {9920 inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input;9921 postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output;9922}9923interface Ai_Cf_Deepgram_Flux_Input {9924 /**9925 * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM.9926 */9927 encoding: "linear16";9928 /**9929 * Sample rate of the audio stream in Hz.9930 */9931 sample_rate: string;9932 /**9933 * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9.9934 */9935 eager_eot_threshold?: string;9936 /**9937 * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9.9938 */9939 eot_threshold?: string;9940 /**9941 * A turn will be finished when this much time has passed after speech, regardless of EOT confidence.9942 */9943 eot_timeout_ms?: string;9944 /**9945 * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms.9946 */9947 keyterm?: string;9948 /**9949 * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip9950 */9951 mip_opt_out?: "true" | "false";9952 /**9953 * Label your requests for the purpose of identification during usage reporting9954 */9955 tag?: string;9956}9957/**9958 * Output will be returned as websocket messages.9959 */9960interface Ai_Cf_Deepgram_Flux_Output {9961 /**9962 * The unique identifier of the request (uuid)9963 */9964 request_id?: string;9965 /**9966 * Starts at 0 and increments for each message the server sends to the client.9967 */9968 sequence_id?: number;9969 /**9970 * The type of event being reported.9971 */9972 event?: "Update" | "StartOfTurn" | "EagerEndOfTurn" | "TurnResumed" | "EndOfTurn";9973 /**9974 * The index of the current turn9975 */9976 turn_index?: number;9977 /**9978 * Start time in seconds of the audio range that was transcribed9979 */9980 audio_window_start?: number;9981 /**9982 * End time in seconds of the audio range that was transcribed9983 */9984 audio_window_end?: number;9985 /**9986 * Text that was said over the course of the current turn9987 */9988 transcript?: string;9989 /**9990 * The words in the transcript9991 */9992 words?: {9993 /**9994 * The individual punctuated, properly-cased word from the transcript9995 */9996 word: string;9997 /**9998 * Confidence that this word was transcribed correctly9999 */10000 confidence: number;10001 }[];10002 /**10003 * Confidence that no more speech is coming in this turn10004 */10005 end_of_turn_confidence?: number;10006}10007declare abstract class Base_Ai_Cf_Deepgram_Flux {10008 inputs: Ai_Cf_Deepgram_Flux_Input;10009 postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output;10010}10011interface Ai_Cf_Deepgram_Aura_2_En_Input {10012 /**10013 * Speaker used to produce the audio.10014 */10015 speaker?: "amalthea" | "andromeda" | "apollo" | "arcas" | "aries" | "asteria" | "athena" | "atlas" | "aurora" | "callista" | "cora" | "cordelia" | "delia" | "draco" | "electra" | "harmonia" | "helena" | "hera" | "hermes" | "hyperion" | "iris" | "janus" | "juno" | "jupiter" | "luna" | "mars" | "minerva" | "neptune" | "odysseus" | "ophelia" | "orion" | "orpheus" | "pandora" | "phoebe" | "pluto" | "saturn" | "thalia" | "theia" | "vesta" | "zeus";10016 /**10017 * Encoding of the output audio.10018 */10019 encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac";10020 /**10021 * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type..10022 */10023 container?: "none" | "wav" | "ogg";10024 /**10025 * The text content to be converted to speech10026 */10027 text: string;10028 /**10029 * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable10030 */10031 sample_rate?: number;10032 /**10033 * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type.10034 */10035 bit_rate?: number;10036}10037/**10038 * The generated audio in MP3 format10039 */10040type Ai_Cf_Deepgram_Aura_2_En_Output = string;10041declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En {10042 inputs: Ai_Cf_Deepgram_Aura_2_En_Input;10043 postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output;10044}10045interface Ai_Cf_Deepgram_Aura_2_Es_Input {10046 /**10047 * Speaker used to produce the audio.10048 */10049 speaker?: "sirio" | "nestor" | "carina" | "celeste" | "alvaro" | "diana" | "aquila" | "selena" | "estrella" | "javier";10050 /**10051 * Encoding of the output audio.10052 */10053 encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac";10054 /**10055 * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type..10056 */10057 container?: "none" | "wav" | "ogg";10058 /**10059 * The text content to be converted to speech10060 */10061 text: string;10062 /**10063 * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable10064 */10065 sample_rate?: number;10066 /**10067 * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type.10068 */10069 bit_rate?: number;10070}10071/**10072 * The generated audio in MP3 format10073 */10074type Ai_Cf_Deepgram_Aura_2_Es_Output = string;10075declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es {10076 inputs: Ai_Cf_Deepgram_Aura_2_Es_Input;10077 postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output;10078}10079interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input {10080 multipart: {10081 body?: object;10082 contentType?: string;10083 };10084}10085interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output {10086 /**10087 * Generated image as Base64 string.10088 */10089 image?: string;10090}10091declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev {10092 inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input;10093 postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output;10094}10095interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input {10096 multipart: {10097 body?: object;10098 contentType?: string;10099 };10100}10101interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output {10102 /**10103 * Generated image as Base64 string.10104 */10105 image?: string;10106}10107declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B {10108 inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input;10109 postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output;10110}10111interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input {10112 multipart: {10113 body?: object;10114 contentType?: string;10115 };10116}10117interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output {10118 /**10119 * Generated image as Base64 string.10120 */10121 image?: string;10122}10123declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B {10124 inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input;10125 postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output;10126}10127declare abstract class Base_Ai_Cf_Zai_Org_Glm_4_7_Flash {10128 inputs: ChatCompletionsInput;10129 postProcessedOutputs: ChatCompletionsOutput;10130}10131declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_5 {10132 inputs: ChatCompletionsInput;10133 postProcessedOutputs: ChatCompletionsOutput;10134}10135declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_6 {10136 inputs: ChatCompletionsInput;10137 postProcessedOutputs: ChatCompletionsOutput;10138}10139declare abstract class Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B {10140 inputs: ChatCompletionsInput;10141 postProcessedOutputs: ChatCompletionsOutput;10142}10143declare abstract class Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT {10144 inputs: ChatCompletionsInput;10145 postProcessedOutputs: ChatCompletionsOutput;10146}10147interface AiModels {10148 "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification;10149 "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage;10150 "@cf/runwayml/stable-diffusion-v1-5-inpainting": BaseAiTextToImage;10151 "@cf/runwayml/stable-diffusion-v1-5-img2img": BaseAiTextToImage;10152 "@cf/lykon/dreamshaper-8-lcm": BaseAiTextToImage;10153 "@cf/bytedance/stable-diffusion-xl-lightning": BaseAiTextToImage;10154 "@cf/myshell-ai/melotts": BaseAiTextToSpeech;10155 "@cf/google/embeddinggemma-300m": BaseAiTextEmbeddings;10156 "@cf/microsoft/resnet-50": BaseAiImageClassification;10157 "@cf/meta/llama-2-7b-chat-int8": BaseAiTextGeneration;10158 "@cf/mistral/mistral-7b-instruct-v0.1": BaseAiTextGeneration;10159 "@cf/meta/llama-2-7b-chat-fp16": BaseAiTextGeneration;10160 "@hf/thebloke/llama-2-13b-chat-awq": BaseAiTextGeneration;10161 "@hf/thebloke/mistral-7b-instruct-v0.1-awq": BaseAiTextGeneration;10162 "@hf/thebloke/zephyr-7b-beta-awq": BaseAiTextGeneration;10163 "@hf/thebloke/openhermes-2.5-mistral-7b-awq": BaseAiTextGeneration;10164 "@hf/thebloke/neural-chat-7b-v3-1-awq": BaseAiTextGeneration;10165 "@hf/thebloke/deepseek-coder-6.7b-base-awq": BaseAiTextGeneration;10166 "@hf/thebloke/deepseek-coder-6.7b-instruct-awq": BaseAiTextGeneration;10167 "@cf/deepseek-ai/deepseek-math-7b-instruct": BaseAiTextGeneration;10168 "@cf/defog/sqlcoder-7b-2": BaseAiTextGeneration;10169 "@cf/openchat/openchat-3.5-0106": BaseAiTextGeneration;10170 "@cf/tiiuae/falcon-7b-instruct": BaseAiTextGeneration;10171 "@cf/thebloke/discolm-german-7b-v1-awq": BaseAiTextGeneration;10172 "@cf/qwen/qwen1.5-0.5b-chat": BaseAiTextGeneration;10173 "@cf/qwen/qwen1.5-7b-chat-awq": BaseAiTextGeneration;10174 "@cf/qwen/qwen1.5-14b-chat-awq": BaseAiTextGeneration;10175 "@cf/tinyllama/tinyllama-1.1b-chat-v1.0": BaseAiTextGeneration;10176 "@cf/microsoft/phi-2": BaseAiTextGeneration;10177 "@cf/qwen/qwen1.5-1.8b-chat": BaseAiTextGeneration;10178 "@cf/mistral/mistral-7b-instruct-v0.2-lora": BaseAiTextGeneration;10179 "@hf/nousresearch/hermes-2-pro-mistral-7b": BaseAiTextGeneration;10180 "@hf/nexusflow/starling-lm-7b-beta": BaseAiTextGeneration;10181 "@hf/google/gemma-7b-it": BaseAiTextGeneration;10182 "@cf/meta-llama/llama-2-7b-chat-hf-lora": BaseAiTextGeneration;10183 "@cf/google/gemma-2b-it-lora": BaseAiTextGeneration;10184 "@cf/google/gemma-7b-it-lora": BaseAiTextGeneration;10185 "@hf/mistral/mistral-7b-instruct-v0.2": BaseAiTextGeneration;10186 "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration;10187 "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration;10188 "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration;10189 "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration;10190 "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration;10191 "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration;10192 "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration;10193 "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration;10194 "@cf/ibm-granite/granite-4.0-h-micro": BaseAiTextGeneration;10195 "@cf/facebook/bart-large-cnn": BaseAiSummarization;10196 "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText;10197 "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5;10198 "@cf/openai/whisper": Base_Ai_Cf_Openai_Whisper;10199 "@cf/meta/m2m100-1.2b": Base_Ai_Cf_Meta_M2M100_1_2B;10200 "@cf/baai/bge-small-en-v1.5": Base_Ai_Cf_Baai_Bge_Small_En_V1_5;10201 "@cf/baai/bge-large-en-v1.5": Base_Ai_Cf_Baai_Bge_Large_En_V1_5;10202 "@cf/unum/uform-gen2-qwen-500m": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M;10203 "@cf/openai/whisper-tiny-en": Base_Ai_Cf_Openai_Whisper_Tiny_En;10204 "@cf/openai/whisper-large-v3-turbo": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo;10205 "@cf/baai/bge-m3": Base_Ai_Cf_Baai_Bge_M3;10206 "@cf/black-forest-labs/flux-1-schnell": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell;10207 "@cf/meta/llama-3.2-11b-vision-instruct": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct;10208 "@cf/meta/llama-3.3-70b-instruct-fp8-fast": Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast;10209 "@cf/meta/llama-guard-3-8b": Base_Ai_Cf_Meta_Llama_Guard_3_8B;10210 "@cf/baai/bge-reranker-base": Base_Ai_Cf_Baai_Bge_Reranker_Base;10211 "@cf/qwen/qwen2.5-coder-32b-instruct": Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct;10212 "@cf/qwen/qwq-32b": Base_Ai_Cf_Qwen_Qwq_32B;10213 "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct;10214 "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It;10215 "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct;10216 "@cf/qwen/qwen3-30b-a3b-fp8": Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8;10217 "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3;10218 "@cf/qwen/qwen3-embedding-0.6b": Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B;10219 "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2;10220 "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B;10221 "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B;10222 "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0;10223 "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin;10224 "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1;10225 "@cf/ai4bharat/indictrans2-en-indic-1B": Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B;10226 "@cf/aisingapore/gemma-sea-lion-v4-27b-it": Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It;10227 "@cf/pfnet/plamo-embedding-1b": Base_Ai_Cf_Pfnet_Plamo_Embedding_1B;10228 "@cf/deepgram/flux": Base_Ai_Cf_Deepgram_Flux;10229 "@cf/deepgram/aura-2-en": Base_Ai_Cf_Deepgram_Aura_2_En;10230 "@cf/deepgram/aura-2-es": Base_Ai_Cf_Deepgram_Aura_2_Es;10231 "@cf/black-forest-labs/flux-2-dev": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev;10232 "@cf/black-forest-labs/flux-2-klein-4b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B;10233 "@cf/black-forest-labs/flux-2-klein-9b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B;10234 "@cf/zai-org/glm-4.7-flash": Base_Ai_Cf_Zai_Org_Glm_4_7_Flash;10235 "@cf/moonshotai/kimi-k2.5": Base_Ai_Cf_Moonshotai_Kimi_K2_5;10236 "@cf/moonshotai/kimi-k2.6": Base_Ai_Cf_Moonshotai_Kimi_K2_6;10237 "@cf/nvidia/nemotron-3-120b-a12b": Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B;10238 "@cf/google/gemma-4-26b-a4b-it": Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT;10239}10240type AiOptions = {10241 /**10242 * Send requests as an asynchronous batch job, only works for supported models10243 * https://developers.cloudflare.com/workers-ai/features/batch-api10244 */10245 queueRequest?: boolean;10246 /**10247 * Establish websocket connections, only works for supported models10248 */10249 websocket?: boolean;10250 /**10251 * Tag your requests to group and view them in Cloudflare dashboard.10252 *10253 * Rules:10254 * Tags must only contain letters, numbers, and the symbols: : - . / @10255 * Each tag can have maximum 50 characters.10256 * Maximum 5 tags are allowed each request.10257 * Duplicate tags will removed.10258 */10259 tags?: string[];10260 gateway?: GatewayOptions;10261 returnRawResponse?: boolean;10262 prefix?: string;10263 extraHeaders?: object;10264 signal?: AbortSignal;10265};10266type AiModelsSearchParams = {10267 author?: string;10268 hide_experimental?: boolean;10269 page?: number;10270 per_page?: number;10271 search?: string;10272 source?: number;10273 task?: string;10274};10275type AiModelsSearchObject = {10276 id: string;10277 source: number;10278 name: string;10279 description: string;10280 task: {10281 id: string;10282 name: string;10283 description: string;10284 };10285 tags: string[];10286 properties: {10287 property_id: string;10288 value: string;10289 }[];10290};10291type ChatCompletionsBase = ChatCompletionsMessagesInput;10292type ChatCompletionsInput = ChatCompletionsMessagesInput;10293interface InferenceUpstreamError extends Error {10294}10295interface AiInternalError extends Error {10296}10297type AiModelListType = Record<string, any>;10298type AiAsyncBatchResponse = {10299 request_id: string;10300};10301declare abstract class Ai<AiModelList extends AiModelListType = AiModels> {10302 aiGatewayLogId: string | null;10303 gateway(gatewayId: string): AiGateway;10304 /**10305 * @deprecated Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead.10306 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/10307 */10308 aiSearch(): AiSearchNamespace;10309 /**10310 * @deprecated AutoRAG has been replaced by AI Search.10311 * Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead.10312 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/10313 *10314 * @param autoragId Instance ID10315 */10316 autorag(autoragId: string): AutoRAG;10317 // Batch request10318 run<Name extends keyof AiModelList>(model: Name, inputs: {10319 requests: AiModelList[Name]['inputs'][];10320 }, options: AiOptions & {10321 queueRequest: true;10322 }): Promise<AiAsyncBatchResponse>;10323 // Raw response10324 run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & {10325 returnRawResponse: true;10326 }): Promise<Response>;10327 // WebSocket10328 run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & {10329 websocket: true;10330 }): Promise<Response>;10331 // Streaming10332 run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'] & {10333 stream: true;10334 }, options?: AiOptions): Promise<ReadableStream>;10335 // Normal (default) - known model10336 run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'], options?: AiOptions): Promise<AiModelList[Name]['postProcessedOutputs']>;10337 // Unknown model (fallback).10338 //10339 // The `Exclude<..., keyof AiModelList>` constraint forces TypeScript to10340 // route any model name that is a literal key of `AiModelList` to one of10341 // the known-model overloads above (so input/output mismatches surface as10342 // type errors rather than silently falling back to `Record<string, unknown>`).10343 // Names that aren't in `AiModelList` — e.g. third-party gateway models10344 // like `"google/nano-banana"` — still hit this overload.10345 run<Model extends string>(model: Model extends keyof AiModelList ? never : Model, inputs: Record<string, unknown>, options?: AiOptions): Promise<Record<string, unknown>>;10346 models(params?: AiModelsSearchParams): Promise<AiModelsSearchObject[]>;10347 toMarkdown(): ToMarkdownService;10348 toMarkdown(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise<ConversionResponse[]>;10349 toMarkdown(files: MarkdownDocument, options?: ConversionRequestOptions): Promise<ConversionResponse>;10350}10351type GatewayRetries = {10352 maxAttempts?: 1 | 2 | 3 | 4 | 5;10353 retryDelayMs?: number;10354 backoff?: 'constant' | 'linear' | 'exponential';10355};10356type GatewayOptions = {10357 id: string;10358 cacheKey?: string;10359 cacheTtl?: number;10360 skipCache?: boolean;10361 metadata?: Record<string, number | string | boolean | null | bigint>;10362 collectLog?: boolean;10363 eventId?: string;10364 requestTimeoutMs?: number;10365 retries?: GatewayRetries;10366};10367type UniversalGatewayOptions = Exclude<GatewayOptions, 'id'> & {10368 /**10369 ** @deprecated10370 */10371 id?: string;10372};10373type AiGatewayPatchLog = {10374 score?: number | null;10375 feedback?: -1 | 1 | null;10376 metadata?: Record<string, number | string | boolean | null | bigint> | null;10377};10378type AiGatewayLog = {10379 id: string;10380 provider: string;10381 model: string;10382 model_type?: string;10383 path: string;10384 duration: number;10385 request_type?: string;10386 request_content_type?: string;10387 status_code: number;10388 response_content_type?: string;10389 success: boolean;10390 cached: boolean;10391 tokens_in?: number;10392 tokens_out?: number;10393 metadata?: Record<string, number | string | boolean | null | bigint>;10394 step?: number;10395 cost?: number;10396 custom_cost?: boolean;10397 request_size: number;10398 request_head?: string;10399 request_head_complete: boolean;10400 response_size: number;10401 response_head?: string;10402 response_head_complete: boolean;10403 created_at: Date;10404};10405type AIGatewayProviders = 'workers-ai' | 'anthropic' | 'aws-bedrock' | 'azure-openai' | 'google-vertex-ai' | 'huggingface' | 'openai' | 'perplexity-ai' | 'replicate' | 'groq' | 'cohere' | 'google-ai-studio' | 'mistral' | 'grok' | 'openrouter' | 'deepseek' | 'cerebras' | 'cartesia' | 'elevenlabs' | 'adobe-firefly';10406type AIGatewayHeaders = {10407 'cf-aig-metadata': Record<string, number | string | boolean | null | bigint> | string;10408 'cf-aig-custom-cost': {10409 per_token_in?: number;10410 per_token_out?: number;10411 } | {10412 total_cost?: number;10413 } | string;10414 'cf-aig-cache-ttl': number | string;10415 'cf-aig-skip-cache': boolean | string;10416 'cf-aig-cache-key': string;10417 'cf-aig-event-id': string;10418 'cf-aig-request-timeout': number | string;10419 'cf-aig-max-attempts': number | string;10420 'cf-aig-retry-delay': number | string;10421 'cf-aig-backoff': string;10422 'cf-aig-collect-log': boolean | string;10423 Authorization: string;10424 'Content-Type': string;10425 [key: string]: string | number | boolean | object;10426};10427type AIGatewayUniversalRequest = {10428 provider: AIGatewayProviders | string; // eslint-disable-line10429 endpoint: string;10430 headers: Partial<AIGatewayHeaders>;10431 query: unknown;10432};10433interface AiGatewayInternalError extends Error {10434}10435interface AiGatewayLogNotFound extends Error {10436}10437declare abstract class AiGateway {10438 patchLog(logId: string, data: AiGatewayPatchLog): Promise<void>;10439 getLog(logId: string): Promise<AiGatewayLog>;10440 run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: {10441 gateway?: UniversalGatewayOptions;10442 extraHeaders?: object;10443 signal?: AbortSignal;10444 }): Promise<Response>;10445 getUrl(provider?: AIGatewayProviders | string): Promise<string>; // eslint-disable-line10446}10447// Copyright (c) 2022-2025 Cloudflare, Inc.10448// Licensed under the Apache 2.0 license found in the LICENSE file or at:10449// https://opensource.org/licenses/Apache-2.010450/**10451 * Artifacts — Git-compatible file storage on Cloudflare Workers.10452 *10453 * Provides programmatic access to create, manage, and fork repositories,10454 * and to issue and revoke scoped access tokens.10455 */10456/** Information about a repository. */10457interface ArtifactsRepoInfo {10458 /** Unique repository ID. */10459 id: string;10460 /** Repository name. */10461 name: string;10462 /** Repository description, or null if not set. */10463 description: string | null;10464 /** Default branch name (e.g. "main"). */10465 defaultBranch: string;10466 /** ISO 8601 creation timestamp. */10467 createdAt: string;10468 /** ISO 8601 last-updated timestamp. */10469 updatedAt: string;10470 /** ISO 8601 timestamp of the last push, or null if never pushed. */10471 lastPushAt: string | null;10472 /** Fork source (e.g. "github:owner/repo", "artifacts:namespace/repo"), or null if not a fork. */10473 source: string | null;10474 /** Whether the repository is read-only. */10475 readOnly: boolean;10476 /** HTTPS git remote URL. */10477 remote: string;10478}10479/** Result of creating a repository — includes the initial access token. */10480interface ArtifactsCreateRepoResult {10481 /** Unique repository ID. */10482 id: string;10483 /** Repository name. */10484 name: string;10485 /** Repository description, or null if not set. */10486 description: string | null;10487 /** Default branch name. */10488 defaultBranch: string;10489 /** HTTPS git remote URL. */10490 remote: string;10491 /** Plaintext access token (only returned at creation time). */10492 token: string;10493 /** ISO 8601 token expiry timestamp. */10494 tokenExpiresAt: string;10495}10496/** Paginated list of repositories. */10497interface ArtifactsRepoListResult {10498 /** Repositories in this page (without the `remote` field). */10499 repos: Omit<ArtifactsRepoInfo, 'remote'>[];10500 /** Total number of repositories in the namespace. */10501 total: number;10502 /** Cursor for the next page, if there are more results. */10503 cursor?: string;10504}10505/** Result of creating an access token. */10506interface ArtifactsCreateTokenResult {10507 /** Unique token ID. */10508 id: string;10509 /** Plaintext token (only returned at creation time). */10510 plaintext: string;10511 /** Token scope: "read" or "write". */10512 scope: 'read' | 'write';10513 /** ISO 8601 token expiry timestamp. */10514 expiresAt: string;10515}10516/** Token metadata (no plaintext). */10517interface ArtifactsTokenInfo {10518 /** Unique token ID. */10519 id: string;10520 /** Token scope: "read" or "write". */10521 scope: 'read' | 'write';10522 /** Token state: "active", "expired", or "revoked". */10523 state: 'active' | 'expired' | 'revoked';10524 /** ISO 8601 creation timestamp. */10525 createdAt: string;10526 /** ISO 8601 expiry timestamp. */10527 expiresAt: string;10528}10529/** Paginated list of tokens for a repository. */10530interface ArtifactsTokenListResult {10531 /** Tokens in this page. */10532 tokens: ArtifactsTokenInfo[];10533 /** Total number of tokens for the repository. */10534 total: number;10535}10536/**10537 * Handle for a single repository. Returned by Artifacts.get().10538 *10539 * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs.10540 */10541interface ArtifactsRepo extends ArtifactsRepoInfo {10542 /**10543 * Create an access token for this repo.10544 * @param scope Token scope: "write" (default) or "read".10545 * @param ttl Time-to-live in seconds (default 86400, min 60, max 31536000).10546 * @throws {ArtifactsError} with code `INVALID_TTL` if ttl is out of range.10547 */10548 createToken(scope?: 'write' | 'read', ttl?: number): Promise<ArtifactsCreateTokenResult>;10549 /** List tokens for this repo (metadata only, no plaintext). */10550 listTokens(): Promise<ArtifactsTokenListResult>;10551 /**10552 * Revoke a token by plaintext or ID.10553 * @param tokenOrId Plaintext token or token ID.10554 * @returns true if revoked, false if not found.10555 * @throws {ArtifactsError} with code `INVALID_INPUT` if tokenOrId is empty.10556 */10557 revokeToken(tokenOrId: string): Promise<boolean>;10558 // ── Fork ──10559 /**10560 * Fork this repo to a new repo.10561 * @param name Target repository name.10562 * @param opts Optional: description, readOnly flag, defaultBranchOnly (default true).10563 * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid.10564 * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists.10565 * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if a fork is already running.10566 */10567 fork(name: string, opts?: {10568 description?: string;10569 readOnly?: boolean;10570 defaultBranchOnly?: boolean;10571 }): Promise<ArtifactsCreateRepoResult>;10572}10573// ── Error types ──────────────────────────────────────────────────────────────10574/**10575 * Error codes returned by Artifacts binding operations.10576 *10577 * Each code maps to a numeric code available on `ArtifactsError.numericCode`.10578 */10579type ArtifactsErrorCode = 'ALREADY_EXISTS' | 'NOT_FOUND' | 'IMPORT_IN_PROGRESS' | 'FORK_IN_PROGRESS' | 'INVALID_INPUT' | 'INVALID_REPO_NAME' | 'INVALID_TTL' | 'INVALID_URL' | 'REMOTE_AUTH_REQUIRED' | 'UPSTREAM_UNAVAILABLE' | 'MEMORY_LIMIT' | 'INTERNAL_ERROR';10580/**10581 * Error thrown by Artifacts binding operations.10582 *10583 * Uses a string `.code` discriminator following the Cloudflare platform10584 * convention (StreamError, ImagesError, etc.). The `.numericCode` matches10585 * the REST API `errors[].code` values.10586 */10587interface ArtifactsError extends Error {10588 readonly name: 'ArtifactsError';10589 /** String error code for programmatic matching. */10590 readonly code: ArtifactsErrorCode;10591 /** Numeric error code matching the REST API. */10592 readonly numericCode: number;10593}10594// ── Binding ──────────────────────────────────────────────────────────────────10595/**10596 * Artifacts binding — namespace-level operations.10597 *10598 * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs.10599 */10600interface Artifacts {10601 /**10602 * Create a new repository with an initial access token.10603 * @param name Repository name (alphanumeric, dots, hyphens, underscores).10604 * @param opts Optional: readOnly flag, description, default branch name.10605 * @returns Repo metadata with initial token.10606 * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid.10607 * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the repo already exists.10608 */10609 create(name: string, opts?: {10610 readOnly?: boolean;10611 description?: string;10612 setDefaultBranch?: string;10613 }): Promise<ArtifactsCreateRepoResult>;10614 /**10615 * Get a handle to an existing repository.10616 * @param name Repository name.10617 * @returns Repo handle.10618 * @throws {ArtifactsError} with code `NOT_FOUND` if the repo does not exist.10619 * @throws {ArtifactsError} with code `IMPORT_IN_PROGRESS` if the repo is still importing.10620 * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if the repo is still forking.10621 */10622 get(name: string): Promise<ArtifactsRepo>;10623 /**10624 * Import a repository from an external git remote.10625 * @param params Source URL and optional branch/depth, plus target name and options.10626 * @returns Repo metadata with initial token.10627 * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if the target name is invalid.10628 * @throws {ArtifactsError} with code `INVALID_INPUT` if the source URL is not valid HTTPS.10629 * @throws {ArtifactsError} with code `INVALID_URL` if the source URL does not point to a git repository.10630 * @throws {ArtifactsError} with code `REMOTE_AUTH_REQUIRED` if the remote requires authentication.10631 * @throws {ArtifactsError} with code `NOT_FOUND` if the remote repository does not exist.10632 * @throws {ArtifactsError} with code `UPSTREAM_UNAVAILABLE` if the remote cannot be reached.10633 * @throws {ArtifactsError} with code `MEMORY_LIMIT` if the import exceeds service memory limits.10634 * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists.10635 */10636 import(params: {10637 source: {10638 url: string;10639 branch?: string;10640 depth?: number;10641 };10642 target: {10643 name: string;10644 opts?: {10645 description?: string;10646 readOnly?: boolean;10647 };10648 };10649 }): Promise<ArtifactsCreateRepoResult>;10650 /**10651 * List repositories with cursor-based pagination.10652 * @param opts Optional: limit (1–200, default 50), cursor for next page.10653 */10654 list(opts?: {10655 limit?: number;10656 cursor?: string;10657 }): Promise<ArtifactsRepoListResult>;10658 /**10659 * Delete a repository and all associated tokens.10660 * @param name Repository name.10661 * @returns true if deleted, false if not found.10662 * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid.10663 */10664 delete(name: string): Promise<boolean>;10665}10666/**10667 * @deprecated Use the standalone AI Search Workers binding instead.10668 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/10669 */10670interface AutoRAGInternalError extends Error {10671}10672/**10673 * @deprecated Use the standalone AI Search Workers binding instead.10674 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/10675 */10676interface AutoRAGNotFoundError extends Error {10677}10678/**10679 * @deprecated Use the standalone AI Search Workers binding instead.10680 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/10681 */10682interface AutoRAGUnauthorizedError extends Error {10683}10684/**10685 * @deprecated Use the standalone AI Search Workers binding instead.10686 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/10687 */10688interface AutoRAGNameNotSetError extends Error {10689}10690type ComparisonFilter = {10691 key: string;10692 type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte';10693 value: string | number | boolean;10694};10695type CompoundFilter = {10696 type: 'and' | 'or';10697 filters: ComparisonFilter[];10698};10699/**10700 * @deprecated Use the standalone AI Search Workers binding instead.10701 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/10702 */10703type AutoRagSearchRequest = {10704 query: string;10705 filters?: CompoundFilter | ComparisonFilter;10706 max_num_results?: number;10707 ranking_options?: {10708 ranker?: string;10709 score_threshold?: number;10710 };10711 reranking?: {10712 enabled?: boolean;10713 model?: string;10714 };10715 rewrite_query?: boolean;10716};10717/**10718 * @deprecated Use the standalone AI Search Workers binding instead.10719 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/10720 */10721type AutoRagAiSearchRequest = AutoRagSearchRequest & {10722 stream?: boolean;10723 system_prompt?: string;10724};10725/**10726 * @deprecated Use the standalone AI Search Workers binding instead.10727 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/10728 */10729type AutoRagAiSearchRequestStreaming = Omit<AutoRagAiSearchRequest, 'stream'> & {10730 stream: true;10731};10732/**10733 * @deprecated Use the standalone AI Search Workers binding instead.10734 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/10735 */10736type AutoRagSearchResponse = {10737 object: 'vector_store.search_results.page';10738 search_query: string;10739 data: {10740 file_id: string;10741 filename: string;10742 score: number;10743 attributes: Record<string, string | number | boolean | null>;10744 content: {10745 type: 'text';10746 text: string;10747 }[];10748 }[];10749 has_more: boolean;10750 next_page: string | null;10751};10752/**10753 * @deprecated Use the standalone AI Search Workers binding instead.10754 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/10755 */10756type AutoRagListResponse = {10757 id: string;10758 enable: boolean;10759 type: string;10760 source: string;10761 vectorize_name: string;10762 paused: boolean;10763 status: string;10764}[];10765/**10766 * @deprecated Use the standalone AI Search Workers binding instead.10767 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/10768 */10769type AutoRagAiSearchResponse = AutoRagSearchResponse & {10770 response: string;10771};10772/**10773 * @deprecated Use the standalone AI Search Workers binding instead.10774 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/10775 */10776declare abstract class AutoRAG {10777 /**10778 * @deprecated Use the standalone AI Search Workers binding instead.10779 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/10780 */10781 list(): Promise<AutoRagListResponse>;10782 /**10783 * @deprecated Use the standalone AI Search Workers binding instead.10784 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/10785 */10786 search(params: AutoRagSearchRequest): Promise<AutoRagSearchResponse>;10787 /**10788 * @deprecated Use the standalone AI Search Workers binding instead.10789 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/10790 */10791 aiSearch(params: AutoRagAiSearchRequestStreaming): Promise<Response>;10792 /**10793 * @deprecated Use the standalone AI Search Workers binding instead.10794 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/10795 */10796 aiSearch(params: AutoRagAiSearchRequest): Promise<AutoRagAiSearchResponse>;10797 /**10798 * @deprecated Use the standalone AI Search Workers binding instead.10799 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/10800 */10801 aiSearch(params: AutoRagAiSearchRequest): Promise<AutoRagAiSearchResponse | Response>;10802}10803type BrowserRunLifecycleEvent = 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2';10804type BrowserRunResourceType = 'document' | 'stylesheet' | 'image' | 'media' | 'font' | 'script' | 'texttrack' | 'xhr' | 'fetch' | 'prefetch' | 'eventsource' | 'websocket' | 'manifest' | 'signedexchange' | 'ping' | 'cspviolationreport' | 'preflight' | 'other';10805/** Options fields shared by all quick actions. */10806interface BrowserRunBaseOptions {10807 /** Adds `<script>` tags into the page with the desired URL or content.10808 * @see https://pptr.dev/api/puppeteer.frameaddscripttagoptions10809 */10810 addScriptTag?: Array<{10811 content?: string;10812 url?: string;10813 type?: string;10814 id?: string;10815 }>;10816 /** Adds `<link rel="stylesheet">` or `<style>` tags into the page.10817 * @see https://pptr.dev/api/puppeteer.frameaddstyletagoptions10818 */10819 addStyleTag?: Array<{10820 content?: string;10821 url?: string;10822 }>;10823 /** Provide credentials for HTTP authentication. @see https://pptr.dev/api/puppeteer.credentials */10824 authenticate?: {10825 username: string;10826 password: string;10827 };10828 /** Set cookies before navigating. @see https://pptr.dev/api/puppeteer.cookieparam */10829 cookies?: Array<{10830 name: string;10831 value: string;10832 url?: string;10833 domain?: string;10834 path?: string;10835 secure?: boolean;10836 httpOnly?: boolean;10837 sameSite?: 'Strict' | 'Lax' | 'None';10838 expires?: number;10839 priority?: 'Low' | 'Medium' | 'High';10840 sameParty?: boolean;10841 sourceScheme?: 'Unset' | 'NonSecure' | 'Secure';10842 sourcePort?: number;10843 partitionKey?: string;10844 }>;10845 /** Emulate a specific CSS media type (e.g. `"screen"`, `"print"`). */10846 emulateMediaType?: string;10847 /** Navigation options. @see https://pptr.dev/api/puppeteer.gotooptions */10848 gotoOptions?: {10849 /** Navigation timeout in milliseconds (max 60 000). @default 30000 */10850 timeout?: number;10851 /** When to consider navigation complete. @default "domcontentloaded" */10852 waitUntil?: BrowserRunLifecycleEvent | BrowserRunLifecycleEvent[];10853 referer?: string;10854 referrerPolicy?: string;10855 };10856 /** Block requests matching these regex patterns. Mutually exclusive with `allowRequestPattern`. */10857 rejectRequestPattern?: string[];10858 /** Only allow requests matching these regex patterns. Mutually exclusive with `rejectRequestPattern`. */10859 allowRequestPattern?: string[];10860 /** Block requests of these resource types. Mutually exclusive with `allowResourceTypes`. */10861 rejectResourceTypes?: BrowserRunResourceType[];10862 /** Only allow requests of these resource types. Mutually exclusive with `rejectResourceTypes`. */10863 allowResourceTypes?: BrowserRunResourceType[];10864 /** Additional HTTP headers sent with every request. */10865 setExtraHTTPHeaders?: Record<string, string>;10866 /** Whether JavaScript is enabled on the page. */10867 setJavaScriptEnabled?: boolean;10868 /** Override the default user agent string.10869 * @default "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"10870 * */10871 userAgent?: string;10872 /** Set the browser viewport size.10873 * @see https://pptr.dev/api/puppeteer.viewport10874 * @default {width:1920,height:1080}10875 * */10876 viewport?: {10877 width: number;10878 height: number;10879 deviceScaleFactor?: number;10880 isMobile?: boolean;10881 isLandscape?: boolean;10882 hasTouch?: boolean;10883 };10884 /** Wait for a CSS selector to appear in the page before proceeding.10885 * @see https://pptr.dev/api/puppeteer.waitforselectoroptions10886 */10887 waitForSelector?: {10888 selector: string;10889 hidden?: true;10890 visible?: true;10891 /** Timeout in milliseconds. Max 120000 */10892 timeout?: number;10893 };10894 /** Wait for a fixed delay in milliseconds before proceeding. Max 120000 */10895 waitForTimeout?: number;10896 /** When true, continue on best-effort when awaited events fail or timeout. */10897 bestAttempt?: boolean;10898 /** Maximum duration in milliseconds for the browser action after page load. Max 120000 */10899 actionTimeout?: number;10900 /** Cache time to live in seconds (0-86400). Set to 0 to disable.10901 * @default 510902 */10903 cacheTTL?: number;10904}10905/** Common options shared by all quick actions. Exactly one of `url` or `html` must be provided.*/10906type BrowserRunCommonOptions = (BrowserRunBaseOptions & {10907 /** URL to navigate to, e.g. `"https://example.com"`. */10908 url: string;10909}) | (BrowserRunBaseOptions & {10910 /** Set the HTML content of the page directly. */10911 html: string;10912});10913type BrowserRunPuppeteerScreenshotOptions = {10914 /** @default "png" */10915 type?: 'png' | 'jpeg' | 'webp';10916 /** @default "binary" */10917 encoding?: 'binary' | 'base64';10918 quality?: number;10919 fullPage?: boolean;10920 clip?: {10921 x: number;10922 y: number;10923 width: number;10924 height: number;10925 scale?: number;10926 };10927 omitBackground?: boolean;10928 optimizeForSpeed?: boolean;10929 captureBeyondViewport?: boolean;10930 fromSurface?: boolean;10931};10932type BrowserRunScreenshotOptions = BrowserRunCommonOptions & {10933 /** CSS selector of the element to screenshot. */10934 selector?: string;10935 /** When true, scroll the entire page before taking the screenshot. */10936 scrollPage?: boolean;10937 /** @see https://pptr.dev/api/puppeteer.screenshotoptions */10938 screenshotOptions?: BrowserRunPuppeteerScreenshotOptions;10939};10940type BrowserRunPDFOptions = BrowserRunCommonOptions & {10941 /** @see https://pptr.dev/api/puppeteer.pdfoptions */10942 pdfOptions?: {10943 /** @default 1 */10944 scale?: number;10945 /** @default false */10946 displayHeaderFooter?: boolean;10947 headerTemplate?: string;10948 footerTemplate?: string;10949 /** @default false */10950 printBackground?: boolean;10951 /** @default false */10952 landscape?: boolean;10953 pageRanges?: string;10954 /** @default "letter" */10955 format?: 'letter' | 'legal' | 'tabloid' | 'ledger' | 'a0' | 'a1' | 'a2' | 'a3' | 'a4' | 'a5' | 'a6';10956 width?: string | number;10957 height?: string | number;10958 /** @default false */10959 preferCSSPageSize?: boolean;10960 margin?: {10961 top?: string | number;10962 right?: string | number;10963 bottom?: string | number;10964 left?: string | number;10965 };10966 /** @default false */10967 omitBackground?: boolean;10968 /** @default true */10969 tagged?: boolean;10970 /** @default false */10971 outline?: boolean;10972 /** @default 30000 */10973 timeout?: number;10974 };10975};10976type BrowserRunScrapeOptions = BrowserRunCommonOptions & {10977 /** CSS selectors to scrape. At least one element is required. */10978 elements: Array<{10979 selector: string;10980 }>;10981};10982type BrowserRunLinksOptions = BrowserRunCommonOptions & {10983 /** When true, only return links that are visible on the page. @default false */10984 visibleLinksOnly?: boolean;10985 /** When true, exclude links pointing to external domains. @default false */10986 excludeExternalLinks?: boolean;10987};10988type BrowserRunSnapshotFormat = 'content' | 'screenshot' | 'markdown' | 'accessibilityTree';10989type BrowserRunSnapshotOptions = BrowserRunCommonOptions & {10990 /** Which representations of the page to return. At least two distinct formats10991 * are required; request a single format from its dedicated action instead.10992 * @default ["content","screenshot"]10993 */10994 formats?: BrowserRunSnapshotFormat[];10995 /** @see https://pptr.dev/api/puppeteer.screenshotoptions */10996 screenshotOptions?: Omit<BrowserRunPuppeteerScreenshotOptions, 'encoding'>;10997};10998/** Options for the `accessibilityTree` quick action. */10999type BrowserRunAccessibilityTreeOptions = BrowserRunCommonOptions & {11000 /** When true, prune nodes that carry no semantic meaning, such as generic11001 * containers. Defaults to true, or to false when `root` is set so that the11002 * requested subtree is returned as-is.11003 */11004 interestingOnly?: boolean;11005 /** CSS selector limiting the tree to the matching element's subtree.11006 * A selector that matches nothing yields `accessibilityTree: null` with11007 * HTTP 200; a malformed selector is an error.11008 */11009 root?: string;11010};11011interface BrowserRunJsonBaseOptions {11012 /** Custom AI models to try in order. Max 3. Falls back to next on error. */11013 custom_ai?: Array<{11014 /** Model ID in `<provider>/<model_name>` format, e.g. `"workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast"`. */11015 model: string;11016 /** Bearer token. Not needed for workers-ai models. */11017 authorization?: string;11018 }>;11019}11020/**11021 * Options for the `json` quick action.11022 * At least one of `prompt` or `response_format` must be provided.11023 */11024type BrowserRunJsonOptions = BrowserRunCommonOptions & BrowserRunJsonBaseOptions & ({11025 /** Natural-language prompt describing what data to extract. */11026 prompt: string;11027 /** Structured output schema for the AI model. @see https://developers.cloudflare.com/workers-ai/json-mode/ */11028 response_format?: AiTextGenerationResponseFormat;11029} | {11030 /** Natural-language prompt describing what data to extract. */11031 prompt?: string;11032 /** Structured output schema for the AI model. @see https://developers.cloudflare.com/workers-ai/json-mode/ */11033 response_format: AiTextGenerationResponseFormat;11034});11035type BrowserRunContentOptions = BrowserRunCommonOptions;11036type BrowserRunMarkdownOptions = BrowserRunCommonOptions;11037type BrowserRunResponseMeta = {11038 /** HTTP status code of the rendered page */11039 status: number;11040 /** Page title */11041 title: string;11042};11043/**11044 * A node in the page's accessibility tree, as exposed to assistive technology.11045 * `role` is the only field always present; the rest are populated when the11046 * underlying element defines them.11047 * @see https://pptr.dev/api/puppeteer.serializedaxnode11048 */11049interface BrowserRunSerializedAXNode {11050 /** The ARIA role, e.g. `"button"`, `"heading"`, `"RootWebArea"`. */11051 role: string;11052 /** The `aria-autocomplete` value. */11053 autocomplete?: string;11054 /** Checked state of a checkbox, radio, or menu item. */11055 checked?: boolean | 'mixed';11056 /** Accessible description, typically from `aria-describedby` or `title`. */11057 description?: string;11058 disabled?: boolean;11059 expanded?: boolean;11060 /** Whether the element currently holds keyboard focus. */11061 focused?: boolean;11062 /** The kind of popup the element triggers, e.g. `"menu"`, `"dialog"`. */11063 haspopup?: string;11064 /** The `aria-invalid` value. */11065 invalid?: string;11066 /** Keyboard shortcuts bound to the element, from `aria-keyshortcuts`. */11067 keyshortcuts?: string;11068 /** Hierarchical level, e.g. the heading level of an `<h2>`. */11069 level?: number;11070 /** Whether the element is a modal dialog. */11071 modal?: boolean;11072 /** Whether a text input accepts multiple lines. */11073 multiline?: boolean;11074 /** Whether more than one option can be selected. */11075 multiselectable?: boolean;11076 /** Accessible name, e.g. a button's label or an image's alt text. */11077 name?: string;11078 orientation?: string;11079 /** Pressed state of a toggle button. */11080 pressed?: boolean | 'mixed';11081 readonly?: boolean;11082 required?: boolean;11083 /** Author-supplied role description, from `aria-roledescription`. */11084 roledescription?: string;11085 selected?: boolean;11086 /** Current value of an input or range element. */11087 value?: string | number;11088 valuemax?: number;11089 valuemin?: number;11090 /** Human-readable form of `value`, from `aria-valuetext`. */11091 valuetext?: string;11092 /** Child nodes. Absent for leaf nodes. */11093 children?: BrowserRunSerializedAXNode[];11094}11095/** Success response for `content` action. */11096type BrowserRunContentSuccessResponse = {11097 success: true;11098 /** Extracted HTML content */11099 result: string;11100 meta: BrowserRunResponseMeta;11101};11102/** Success response for `links` action. */11103type BrowserRunLinksSuccessResponse = {11104 success: true;11105 /** Extracted links */11106 result: string[];11107};11108/** Success response for `scrape` action. */11109type BrowserRunScrapeSuccessResponse = {11110 success: true;11111 result: Array<{11112 /** The CSS selector used to find elements. */11113 selector: string;11114 /** Array of elements matching the selector. */11115 results: Array<{11116 /** Outer HTML of the element. */11117 html: string;11118 /** Text content of the element. */11119 text: string;11120 /** Width of the element in pixels. */11121 width: number;11122 /** Height of the element in pixels. */11123 height: number;11124 /** Top position of the element relative to the viewport in pixels. */11125 top: number;11126 /** Left position of the element relative to the viewport in pixels. */11127 left: number;11128 /** Array of HTML attributes on the element. */11129 attributes: Array<{11130 /** Attribute name. */11131 name: string;11132 /** Attribute value. */11133 value: string;11134 }>;11135 }>;11136 }>;11137};11138/** Success response for `snapshot` action. Each field is present only when the11139 * corresponding entry was requested in `formats`.11140 */11141type BrowserRunSnapshotSuccessResponse = {11142 success: true;11143 result: {11144 /** HTML content of the page. */11145 content?: string;11146 /** Base64-encoded screenshot image. */11147 screenshot?: string;11148 /** Markdown content. Prefixed with YAML frontmatter (e.g. `title`) when the11149 * page provides that metadata.11150 */11151 markdown?: string;11152 /** Root of the page's accessibility tree. */11153 accessibilityTree?: BrowserRunSerializedAXNode;11154 };11155 meta: BrowserRunResponseMeta;11156};11157/** Success response for `accessibilityTree` action. */11158type BrowserRunAccessibilityTreeSuccessResponse = {11159 success: true;11160 result: {11161 /** Root of the accessibility tree, or `null` when `root` matched no element. */11162 accessibilityTree: BrowserRunSerializedAXNode | null;11163 };11164 meta: BrowserRunResponseMeta;11165};11166/** Success response for `json` action. */11167type BrowserRunJsonSuccessResponse = {11168 success: true;11169 /** JSON data extracted from the page using an AI model */11170 result: Record<string, unknown>;11171};11172/** Success response for `markdown` action. */11173type BrowserRunMarkdownSuccessResponse = {11174 success: true;11175 /** Extracted markdown content */11176 result: string;11177};11178/** Error response for BrowserRun actions. */11179type BrowserRunErrorResponse = {11180 success: false;11181 errors: {11182 message: string;11183 code?: number;11184 detail?: string;11185 path?: string;11186 }[];11187};11188/** Error response for BrowserRun `json` action. */11189type BrowserRunJsonErrorResponse = BrowserRunErrorResponse & {11190 /** Raw AI response text for debugging */11191 rawAiResponse?: string;11192};11193/**11194 * Browser Run API binding for automating headless browsers.11195 * @see https://developers.cloudflare.com/browser-run/11196 */11197declare abstract class BrowserRun {11198 /**11199 * Send a raw HTTP request to the Browser Run API.11200 * Used by libraries like `@cloudflare/puppeteer` to acquire and connect to a browser instance.11201 * @see https://developers.cloudflare.com/browser-run/11202 */11203 fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;11204 /**11205 * Take a screenshot of a web page.11206 * @param action - Must be `'screenshot'`.11207 * @param options - Screenshot options including viewport, selectors, and image format.11208 * @returns A `Response` containing one of:11209 *11210 * **Success (HTTP 200):**11211 * - Binary image data with `Content-Type: image/png`, `image/jpeg`, or `image/webp` (when `encoding: 'binary'`, the default)11212 * - Data URI string with `Content-Type: text/plain` (when `encoding: 'base64'`)11213 *11214 * **Error:**11215 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)11216 *11217 * **Headers:**11218 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)11219 */11220 quickAction(action: 'screenshot', options: BrowserRunScreenshotOptions): Promise<Response>;11221 /**11222 * Generate a PDF of a web page.11223 * @param action - Must be `'pdf'`.11224 * @param options - PDF generation options including page size, margins, and headers/footers.11225 * @returns A `Response` containing one of:11226 *11227 * **Success (HTTP 200):**11228 * - Binary PDF data with `Content-Type: application/pdf`11229 *11230 * **Error:**11231 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)11232 *11233 * **Headers:**11234 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)11235 */11236 quickAction(action: 'pdf', options: BrowserRunPDFOptions): Promise<Response>;11237 /**11238 * Get the HTML content of a web page.11239 * @param action - Must be `'content'`.11240 * @param options - Navigation and page interaction options.11241 * @returns A `Response` containing one of:11242 *11243 * **Success (HTTP 200):**11244 * - `BrowserRunContentSuccessResponse` JSON with `Content-Type: application/json`11245 *11246 * **Error:**11247 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)11248 *11249 * **Headers:**11250 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)11251 */11252 quickAction(action: 'content', options: BrowserRunContentOptions): Promise<Response>;11253 /**11254 * Scrape elements from a web page by CSS selector.11255 * @param action - Must be `'scrape'`.11256 * @param options - Scrape options with CSS selectors for elements to extract.11257 * @returns A `Response` containing one of:11258 *11259 * **Success (HTTP 200):**11260 * - `BrowserRunScrapeSuccessResponse` JSON with `Content-Type: application/json`11261 *11262 * **Error:**11263 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)11264 *11265 * **Headers:**11266 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)11267 */11268 quickAction(action: 'scrape', options: BrowserRunScrapeOptions): Promise<Response>;11269 /**11270 * Extract all links from a web page.11271 * @param action - Must be `'links'`.11272 * @param options - Options to filter visible or internal links only.11273 * @returns A `Response` containing one of:11274 *11275 * **Success (HTTP 200):**11276 * - `BrowserRunLinksSuccessResponse` JSON with `Content-Type: application/json`11277 *11278 * **Error:**11279 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)11280 *11281 * **Headers:**11282 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)11283 */11284 quickAction(action: 'links', options: BrowserRunLinksOptions): Promise<Response>;11285 /**11286 * Get several representations of a web page in one request.11287 * @param action - Must be `'snapshot'`.11288 * @param options - Snapshot options including the `formats` to return and11289 * screenshot settings (encoding is always base64).11290 * @returns A `Response` containing one of:11291 *11292 * **Success (HTTP 200):**11293 * - `BrowserRunSnapshotSuccessResponse` JSON with `Content-Type: application/json`11294 *11295 * **Error:**11296 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)11297 *11298 * **Headers:**11299 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)11300 */11301 quickAction(action: 'snapshot', options: BrowserRunSnapshotOptions): Promise<Response>;11302 /**11303 * Extract structured JSON data from a web page using AI.11304 * @param action - Must be `'json'`.11305 * @param options - JSON extraction options with prompt or response_format schema.11306 * @returns A `Response` containing one of:11307 *11308 * **Success (HTTP 200):**11309 * - `BrowserRunJsonSuccessResponse` JSON with `Content-Type: application/json`11310 *11311 * **Error:**11312 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)11313 * - HTTP 422 with code `2012` for HTML-to-markdown conversion failures11314 * - HTTP 422/500 for AI extraction failures (may include `rawAiResponse` field)11315 *11316 * **Headers:**11317 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)11318 */11319 quickAction(action: 'json', options: BrowserRunJsonOptions): Promise<Response>;11320 /**11321 * Convert a web page to Markdown.11322 * @param action - Must be `'markdown'`.11323 * @param options - Navigation and page interaction options.11324 * @returns A `Response` containing one of:11325 *11326 * **Success (HTTP 200):**11327 * - `BrowserRunMarkdownSuccessResponse` JSON with `Content-Type: application/json`11328 *11329 * **Error:**11330 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)11331 * - HTTP 422 with code `2012` for HTML-to-markdown conversion failures11332 *11333 * **Headers:**11334 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)11335 */11336 quickAction(action: 'markdown', options: BrowserRunMarkdownOptions): Promise<Response>;11337 /**11338 * Get the accessibility tree of a web page.11339 * @param action - Must be `'accessibilityTree'`.11340 * @param options - Options to scope the tree to a subtree and to control11341 * whether semantically uninteresting nodes are pruned.11342 * @returns A `Response` containing one of:11343 *11344 * **Success (HTTP 200):**11345 * - `BrowserRunAccessibilityTreeSuccessResponse` JSON with `Content-Type: application/json`11346 * - `result.accessibilityTree` is `null` when `root` matched no element11347 *11348 * **Error:**11349 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)11350 * - HTTP 422 for a malformed `root` selector11351 * - HTTP 500 with code `2017` or `2018` when the tree could not be built11352 *11353 * **Headers:**11354 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)11355 */11356 quickAction(action: 'accessibilityTree', options: BrowserRunAccessibilityTreeOptions): Promise<Response>;11357}11358/**11359 * In addition to the properties you can set in the RequestInit dict11360 * that you pass as an argument to the Request constructor, you can11361 * set certain properties of a `cf` object to control how Cloudflare11362 * features are applied to that new Request.11363 *11364 * Note: Currently, these properties cannot be tested in the11365 * playground.11366 */11367interface RequestInitCfProperties extends Record<string, unknown> {11368 cacheEverything?: boolean;11369 /**11370 * A request's cache key is what determines if two requests are11371 * "the same" for caching purposes. If a request has the same cache key11372 * as some previous request, then we can serve the same cached response for11373 * both. (e.g. 'some-key')11374 *11375 * Only available for Enterprise customers.11376 */11377 cacheKey?: string;11378 /**11379 * This allows you to append additional Cache-Tag response headers11380 * to the origin response without modifications to the origin server.11381 * This will allow for greater control over the Purge by Cache Tag feature11382 * utilizing changes only in the Workers process.11383 *11384 * Only available for Enterprise customers.11385 */11386 cacheTags?: string[];11387 /**11388 * Force response to be cached for a given number of seconds. (e.g. 300)11389 */11390 cacheTtl?: number;11391 /**11392 * Force response to be cached for a given number of seconds based on the Origin status code.11393 * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 })11394 */11395 cacheTtlByStatus?: Record<string, number>;11396 /** Controls how responses with a `Vary` header are cached for this request. */11397 vary?: RequestInitCfPropertiesVary;11398 /**11399 * Explicit Cache-Control header value to set on the response stored in cache.11400 * This gives full control over cache directives (e.g. 'public, max-age=3600, s-maxage=86400').11401 *11402 * Cannot be used together with `cacheTtl` or the `cache` request option (`no-store`/`no-cache`),11403 * as these are mutually exclusive cache control mechanisms. Setting both will throw a TypeError.11404 *11405 * Can be used together with `cacheTtlByStatus`.11406 */11407 cacheControl?: string;11408 /**11409 * Whether the response should be eligible for Cache Reserve storage.11410 */11411 cacheReserveEligible?: boolean;11412 /**11413 * Whether to respect strong ETags (as opposed to weak ETags) from the origin.11414 */11415 respectStrongEtag?: boolean;11416 /**11417 * Whether to strip ETag headers from the origin response before caching.11418 */11419 stripEtags?: boolean;11420 /**11421 * Whether to strip Last-Modified headers from the origin response before caching.11422 */11423 stripLastModified?: boolean;11424 /**11425 * Whether to enable Cache Deception Armor, which protects against web cache11426 * deception attacks by verifying the Content-Type matches the URL extension.11427 */11428 cacheDeceptionArmor?: boolean;11429 /**11430 * Minimum file size in bytes for a response to be eligible for Cache Reserve storage.11431 */11432 cacheReserveMinimumFileSize?: number;11433 scrapeShield?: boolean;11434 apps?: boolean;11435 /**11436 * Controls whether an outbound gRPC-web subrequest from this Worker is11437 * converted to gRPC at the Cloudflare edge.11438 *11439 * - `"passthrough"`: forward the subrequest unchanged as gRPC-web (default).11440 * - `"convert"`: convert the gRPC-web subrequest to gRPC at the edge.11441 *11442 * Provides per-request control over the same edge conversion behavior11443 * gated by the `auto_grpc_convert` compatibility flag.11444 */11445 grpcWeb?: "passthrough" | "convert";11446 image?: RequestInitCfPropertiesImage;11447 minify?: RequestInitCfPropertiesImageMinify;11448 mirage?: boolean;11449 polish?: "lossy" | "lossless" | "off";11450 r2?: RequestInitCfPropertiesR2;11451 /**11452 * Redirects the request to an alternate origin server. You can use this,11453 * for example, to implement load balancing across several origins.11454 * (e.g.us-east.example.com)11455 *11456 * Note - For security reasons, the hostname set in resolveOverride must11457 * be proxied on the same Cloudflare zone of the incoming request.11458 * Otherwise, the setting is ignored. CNAME hosts are allowed, so to11459 * resolve to a host under a different domain or a DNS only domain first11460 * declare a CNAME record within your own zone’s DNS mapping to the11461 * external hostname, set proxy on Cloudflare, then set resolveOverride11462 * to point to that CNAME record.11463 */11464 resolveOverride?: string;11465}11466/**11467 * Controls how Workers Standard Vary handles a request header listed by an11468 * origin `Vary` response header:11469 *11470 * - `"normalize"`: normalize the request header value before it is used in the11471 * cache variance key.11472 * - `"passthrough"`: use the raw request header value in the cache variance11473 * key.11474 * - `"bypass"`: bypass cache when the header appears in the origin `Vary`11475 * response header.11476 */11477type RequestInitCfPropertiesVaryAction = "normalize" | "passthrough" | "bypass";11478/** Configuration for Workers Standard Vary support. */11479interface RequestInitCfPropertiesVary {11480 /** The fallback action for varied request headers not listed in `headers`. */11481 default: RequestInitCfPropertiesVaryHeader;11482 /**11483 * Lowercase request header names and their Vary configuration.11484 *11485 * The `accept` header can include `media_types`, the `accept-language`11486 * header can include `languages`, and other headers support only `action`.11487 */11488 headers?: RequestInitCfPropertiesVaryHeaders;11489}11490/** Common Vary behavior for a single request header. */11491interface RequestInitCfPropertiesVaryHeader {11492 /** How this request header contributes to cache variance. */11493 action: RequestInitCfPropertiesVaryAction;11494}11495/** Vary behavior for the `accept` request header. */11496interface RequestInitCfPropertiesVaryAcceptHeader extends RequestInitCfPropertiesVaryHeader {11497 /**11498 * Media types to keep when normalizing the `Accept` request header.11499 *11500 * Named `media_types` to match the serialized `cf.vary` configuration.11501 */11502 media_types?: string[];11503}11504/** Vary behavior for the `accept-language` request header. */11505interface RequestInitCfPropertiesVaryAcceptLanguageHeader extends RequestInitCfPropertiesVaryHeader {11506 /**11507 * Language tags to keep when normalizing the `Accept-Language` request11508 * header.11509 */11510 languages?: string[];11511}11512/**11513 * Lowercase request header names and their Vary behavior.11514 *11515 * The index signature allows arbitrary custom request headers beyond the11516 * well-known `accept` and `accept-language` specializations.11517 */11518interface RequestInitCfPropertiesVaryHeaders {11519 accept?: RequestInitCfPropertiesVaryAcceptHeader;11520 "accept-language"?: RequestInitCfPropertiesVaryAcceptLanguageHeader;11521 [header: string]: RequestInitCfPropertiesVaryHeader | RequestInitCfPropertiesVaryAcceptHeader | RequestInitCfPropertiesVaryAcceptLanguageHeader | undefined;11522}11523interface BasicImageTransformations {11524 /**11525 * Maximum width in image pixels. The value must be an integer.11526 */11527 width?: number;11528 /**11529 * Maximum height in image pixels. The value must be an integer.11530 */11531 height?: number;11532 /**11533 * When cropping with fit: "cover", this defines the side or point that should11534 * be left uncropped. The value is either a string11535 * "left", "right", "top", "bottom", "auto", or "center" (the default),11536 * or an object {x, y} containing focal point coordinates in the original11537 * image expressed as fractions ranging from 0.0 (top or left) to 1.011538 * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will11539 * crop bottom or left and right sides as necessary, but won’t crop anything11540 * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to11541 * preserve as much as possible around a point at 20% of the height of the11542 * source image.11543 */11544 gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates;11545 /**11546 * Specifies how closely the image is cropped toward detected faces when combined11547 * with the gravity=face option. Accepts a valid range between 0.0 (includes as much11548 * of the background as possible) and 1.0 (crops the image as closely to the face as11549 * possible). The default is 0.11550 */11551 zoom?: number;11552 /**11553 * Resizing mode as a string. It affects interpretation of width and height11554 * options:11555 * - scale-down: Similar to contain, but the image is never enlarged. If11556 * the image is larger than given width or height, it will be resized.11557 * Otherwise its original size will be kept.11558 * - scale-up: Similar to contain, but the image is never shrunk. If the11559 * image is smaller than the given width or height, it will be resized.11560 * Otherwise its original size will be kept.11561 * - contain: Resizes to maximum size that fits within the given width and11562 * height. If only a single dimension is given (e.g. only width), the11563 * image will be shrunk or enlarged to exactly match that dimension.11564 * Aspect ratio is always preserved.11565 * - cover: Resizes (shrinks or enlarges) to fill the entire area of width11566 * and height. If the image has an aspect ratio different from the ratio11567 * of width and height, it will be cropped to fit.11568 * - crop: The image will be shrunk and cropped to fit within the area11569 * specified by width and height. The image will not be enlarged. For images11570 * smaller than the given dimensions it's the same as scale-down. For11571 * images larger than the given dimensions, it's the same as cover.11572 * See also trim.11573 * - pad: Resizes to the maximum size that fits within the given width and11574 * height, and then fills the remaining area with a background color11575 * (white by default). Use of this mode is not recommended, as the same11576 * effect can be more efficiently achieved with the contain mode and the11577 * CSS object-fit: contain property.11578 * - squeeze: Stretches and deforms to the width and height given, even if it11579 * breaks aspect ratio11580 */11581 fit?: "scale-down" | "scale-up" | "contain" | "cover" | "crop" | "pad" | "squeeze";11582 /**11583 * Allows you to trim your image. Takes dpr into account and is performed before11584 * resizing or rotation.11585 *11586 * It can be used as:11587 * - left, top, right, bottom - it will specify the number of pixels to cut11588 * off each side11589 * - width, height - the width/height you'd like to end up with - can be used11590 * in combination with the properties above11591 * - border - this will automatically trim the surroundings of an image based on11592 * it's color. It consists of three properties:11593 * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit)11594 * - tolerance: difference from color to treat as color11595 * - keep: the number of pixels of border to keep11596 */11597 trim?: "border" | {11598 top?: number;11599 bottom?: number;11600 left?: number;11601 right?: number;11602 width?: number;11603 height?: number;11604 border?: boolean | {11605 color?: string;11606 tolerance?: number;11607 keep?: number;11608 };11609 };11610 /**11611 * Background color to add underneath the image. Applies only to images with11612 * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…),11613 * hsl(…), etc.)11614 */11615 background?: string;11616 /**11617 * Flips the images horizontally, vertically, or both. Flipping is applied before11618 * rotation, so if you apply flip=h,rotate=90 then the image will be flipped11619 * horizontally, then rotated by 90 degrees.11620 */11621 flip?: 'h' | 'v' | 'hv';11622 /**11623 * Number of degrees (90, 180, 270) to rotate the image by. width and height11624 * options refer to axes after rotation.11625 */11626 rotate?: 0 | 90 | 180 | 270 | 360;11627 /**11628 * Strength of sharpening filter to apply to the image. Floating-point11629 * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a11630 * recommended value for downscaled images.11631 */11632 sharpen?: number;11633 /**11634 * Radius of a blur filter (approximate gaussian). Maximum supported radius11635 * is 250.11636 */11637 blur?: number;11638 /**11639 * Increase contrast by a factor. A value of 1.0 equals no change, a value of11640 * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is11641 * ignored.11642 */11643 contrast?: number;11644 /**11645 * Increase brightness by a factor. A value of 1.0 equals no change, a value11646 * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright.11647 * 0 is ignored.11648 */11649 brightness?: number;11650 /**11651 * Increase exposure by a factor. A value of 1.0 equals no change, a value of11652 * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored.11653 */11654 gamma?: number;11655 /**11656 * Increase contrast by a factor. A value of 1.0 equals no change, a value of11657 * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is11658 * ignored.11659 */11660 saturation?: number;11661 /**11662 * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it11663 * easier to specify higher-DPI sizes in <img srcset>.11664 */11665 dpr?: number;11666 /**11667 * Adds a border around the image. The border is added after resizing. Border11668 * width takes dpr into account, and can be specified either using a single11669 * width property, or individually for each side.11670 */11671 border?: {11672 color: string;11673 width: number;11674 } | {11675 color: string;11676 top: number;11677 right: number;11678 bottom: number;11679 left: number;11680 };11681 /**11682 * Image segmentation using artificial intelligence models. Sets pixels not11683 * within selected segment area to transparent e.g "foreground" sets every11684 * background pixel as transparent.11685 */11686 segment?: "foreground";11687 /**11688 * Controls the algorithm used when an image needs to be enlarged. This11689 * parameter works with any fit mode that upscales, such as `contain`,11690 * `cover`, and `scale-up`. It has no effect when `fit=scale-down` or when11691 * the target dimensions are smaller than the source.11692 * - interpolate: Uses bicubic interpolation, which may reduce image quality.11693 * This is the default behavior when `upscale` is not specified.11694 * - generate: Uses AI upscaling to produce sharper, more detailed results11695 * when enlarging images.11696 */11697 upscale?: "interpolate" | "generate";11698}11699interface BasicImageTransformationsGravityCoordinates {11700 x?: number;11701 y?: number;11702 mode?: 'remainder' | 'box-center';11703}11704interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations {11705 /**11706 * Absolute URL of the image file to use for the drawing. It can be any of11707 * the supported file formats. For drawing of watermarks or non-rectangular11708 * overlays we recommend using PNG or WebP images.11709 */11710 url: string;11711 /**11712 * Floating-point number between 0 (transparent) and 1 (opaque).11713 * For example, opacity: 0.5 makes overlay semitransparent.11714 */11715 opacity?: number;11716 /**11717 * - If set to true, the overlay image will be tiled to cover the entire11718 * area. This is useful for stock-photo-like watermarks.11719 * - If set to "x", the overlay image will be tiled horizontally only11720 * (form a line).11721 * - If set to "y", the overlay image will be tiled vertically only11722 * (form a line).11723 */11724 repeat?: true | "x" | "y";11725 /**11726 * How to combine the foreground and backdrop pixels to create the result11727 */11728 composite?:11729 /** Foreground drawn on top of backdrop (default) */11730 'over'11731 /** Foreground shown only where backdrop is opaque */11732 | 'in'11733 /** Foreground drawn on top, but clipped to the backdrop's shape */11734 | 'atop'11735 /** Foreground shown only where backdrop is transparent */11736 | 'out'11737 /** Foreground and backdrop visible only where the other is not */11738 | 'xor'11739 /** Foreground and backdrop channels added (brightening) */11740 | 'lighter';11741 /**11742 * Position of the overlay image relative to a given edge. Each property is11743 * an offset in pixels. 0 aligns exactly to the edge. For example, left: 1011744 * positions left side of the overlay 10 pixels from the left edge of the11745 * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom11746 * of the background image.11747 *11748 * Setting both left & right, or both top & bottom is an error.11749 *11750 * If no position is specified, the image will be centered.11751 */11752 top?: number;11753 left?: number;11754 bottom?: number;11755 right?: number;11756}11757interface RequestInitCfPropertiesImage extends BasicImageTransformations {11758 /**11759 * Quality setting from 1-100 (useful values are in 60-90 range). Lower values11760 * make images look worse, but load faster. The default is 85. It applies only11761 * to JPEG and WebP images. It doesn’t have any effect on PNG.11762 */11763 quality?: number | "low" | "medium-low" | "medium-high" | "high";11764 /**11765 * Output format to generate. It can be:11766 * - avif: generate images in AVIF format.11767 * - webp: generate images in Google WebP format. Set quality to 100 to get11768 * the WebP-lossless format.11769 * - json: instead of generating an image, outputs information about the11770 * image, in JSON format. The JSON object will contain image size11771 * (before and after resizing), source image’s MIME type, file size, etc.11772 * - jpeg: generate images in JPEG format.11773 * - png: generate images in PNG format.11774 */11775 format?: "avif" | "webp" | "json" | "jpeg" | "png" | "baseline-jpeg" | "png-force" | "svg";11776 /**11777 * Whether to preserve animation frames from input files. Default is true.11778 * Setting it to false reduces animations to still images. This setting is11779 * recommended when enlarging images or processing arbitrary user content,11780 * because large GIF animations can weigh tens or even hundreds of megabytes.11781 * It is also useful to set anim:false when using format:"json" to get the11782 * response quicker without the number of frames.11783 */11784 anim?: boolean;11785 /**11786 * What EXIF data should be preserved in the output image. Note that EXIF11787 * rotation and embedded color profiles are always applied ("baked in" into11788 * the image), and aren't affected by this option. Note that if the Polish11789 * feature is enabled, all metadata may have been removed already and this11790 * option may have no effect.11791 * - keep: Preserve most of EXIF metadata, including GPS location if there's11792 * any.11793 * - copyright: Only keep the copyright tag, and discard everything else.11794 * This is the default behavior for JPEG files.11795 * - none: Discard all invisible EXIF metadata. Currently WebP and PNG11796 * output formats always discard metadata.11797 */11798 metadata?: "keep" | "copyright" | "none";11799 /**11800 * Overlays are drawn in the order they appear in the array (last array11801 * entry is the topmost layer).11802 */11803 draw?: RequestInitCfPropertiesImageDraw[];11804 /**11805 * Fetching image from authenticated origin. Setting this property will11806 * pass authentication headers (Authorization, Cookie, etc.) through to11807 * the origin.11808 */11809 "origin-auth"?: "share-publicly";11810 /**11811 * Slightly reduces latency on a cache miss by selecting a11812 * quickest-to-compress file format, at a cost of increased file size and11813 * lower image quality. It will usually override the format option and choose11814 * JPEG over WebP or AVIF. We do not recommend using this option, except in11815 * unusual circumstances like resizing uncacheable dynamically-generated11816 * images.11817 */11818 compression?: "fast";11819}11820interface RequestInitCfPropertiesImageMinify {11821 javascript?: boolean;11822 css?: boolean;11823 html?: boolean;11824}11825interface RequestInitCfPropertiesR2 {11826 /**11827 * Colo id of bucket that an object is stored in11828 */11829 bucketColoId?: number;11830}11831/**11832 * Request metadata provided by Cloudflare's edge.11833 */11834type IncomingRequestCfProperties<HostMetadata = unknown> = IncomingRequestCfPropertiesBase & IncomingRequestCfPropertiesBotManagementEnterprise & IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & IncomingRequestCfPropertiesGeographicInformation & IncomingRequestCfPropertiesCloudflareAccessOrApiShield;11835interface IncomingRequestCfPropertiesBase extends Record<string, unknown> {11836 /**11837 * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request.11838 *11839 * @example 39574711840 */11841 asn?: number;11842 /**11843 * The organization which owns the ASN of the incoming request.11844 *11845 * @example "Google Cloud"11846 */11847 asOrganization?: string;11848 /**11849 * The original value of the `Accept-Encoding` header if Cloudflare modified it.11850 *11851 * @example "gzip, deflate, br"11852 */11853 clientAcceptEncoding?: string;11854 /**11855 * The number of milliseconds it took for the request to reach your worker.11856 *11857 * @example 2211858 */11859 clientTcpRtt?: number;11860 /**11861 * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code)11862 * airport code of the data center that the request hit.11863 *11864 * @example "DFW"11865 */11866 colo: string;11867 /**11868 * Represents the upstream's response to a11869 * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html)11870 * from cloudflare.11871 *11872 * For workers with no upstream, this will always be `1`.11873 *11874 * @example 311875 */11876 edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus;11877 /**11878 * The HTTP Protocol the request used.11879 *11880 * @example "HTTP/2"11881 */11882 httpProtocol: string;11883 /**11884 * The browser-requested prioritization information in the request object.11885 *11886 * If no information was set, defaults to the empty string `""`11887 *11888 * @example "weight=192;exclusive=0;group=3;group-weight=127"11889 * @default ""11890 */11891 requestPriority: string;11892 /**11893 * The TLS version of the connection to Cloudflare.11894 * In requests served over plaintext (without TLS), this property is the empty string `""`.11895 *11896 * @example "TLSv1.3"11897 */11898 tlsVersion: string;11899 /**11900 * The cipher for the connection to Cloudflare.11901 * In requests served over plaintext (without TLS), this property is the empty string `""`.11902 *11903 * @example "AEAD-AES128-GCM-SHA256"11904 */11905 tlsCipher: string;11906 /**11907 * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake.11908 *11909 * If the incoming request was served over plaintext (without TLS) this field is undefined.11910 */11911 tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata;11912}11913interface IncomingRequestCfPropertiesBotManagementBase {11914 /**11915 * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot,11916 * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human).11917 *11918 * @example 5411919 */11920 score: number;11921 /**11922 * A boolean value that is true if the request comes from a good bot, like Google or Bing.11923 * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots).11924 */11925 verifiedBot: boolean;11926 /**11927 * A boolean value that is true if the request originates from a11928 * Cloudflare-verified proxy service.11929 */11930 corporateProxy: boolean;11931 /**11932 * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources.11933 */11934 staticResource: boolean;11935 /**11936 * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request).11937 */11938 detectionIds: number[];11939}11940interface IncomingRequestCfPropertiesBotManagement {11941 /**11942 * Results of Cloudflare's Bot Management analysis11943 */11944 botManagement: IncomingRequestCfPropertiesBotManagementBase;11945 /**11946 * Duplicate of `botManagement.score`.11947 *11948 * @deprecated11949 */11950 clientTrustScore: number;11951}11952interface IncomingRequestCfPropertiesBotManagementEnterprise extends IncomingRequestCfPropertiesBotManagement {11953 /**11954 * Results of Cloudflare's Bot Management analysis11955 */11956 botManagement: IncomingRequestCfPropertiesBotManagementBase & {11957 /**11958 * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients11959 * across different destination IPs, Ports, and X509 certificates.11960 */11961 ja3Hash: string;11962 };11963}11964interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> {11965 /**11966 * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/).11967 *11968 * This field is only present if you have Cloudflare for SaaS enabled on your account11969 * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)).11970 */11971 hostMetadata?: HostMetadata;11972}11973interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield {11974 /**11975 * Information about the client certificate presented to Cloudflare.11976 *11977 * This is populated when the incoming request is served over TLS using11978 * either Cloudflare Access or API Shield (mTLS)11979 * and the presented SSL certificate has a valid11980 * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number)11981 * (i.e., not `null` or `""`).11982 *11983 * Otherwise, a set of placeholder values are used.11984 *11985 * The property `certPresented` will be set to `"1"` when11986 * the object is populated (i.e. the above conditions were met).11987 */11988 tlsClientAuth: IncomingRequestCfPropertiesTLSClientAuth | IncomingRequestCfPropertiesTLSClientAuthPlaceholder;11989}11990/**11991 * Metadata about the request's TLS handshake11992 */11993interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata {11994 /**11995 * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal11996 *11997 * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d"11998 */11999 clientHandshake: string;12000 /**12001 * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal12002 *12003 * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d"12004 */12005 serverHandshake: string;12006 /**12007 * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal12008 *12009 * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b"12010 */12011 clientFinished: string;12012 /**12013 * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal12014 *12015 * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b"12016 */12017 serverFinished: string;12018}12019/**12020 * Geographic data about the request's origin.12021 */12022interface IncomingRequestCfPropertiesGeographicInformation {12023 /**12024 * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from.12025 *12026 * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR.12027 *12028 * If Cloudflare is unable to determine where the request originated this property is omitted.12029 *12030 * The country code `"T1"` is used for requests originating on TOR.12031 *12032 * @example "GB"12033 */12034 country?: Iso3166Alpha2Code | "T1";12035 /**12036 * If present, this property indicates that the request originated in the EU12037 *12038 * @example "1"12039 */12040 isEUCountry?: "1";12041 /**12042 * A two-letter code indicating the continent the request originated from.12043 *12044 * @example "AN"12045 */12046 continent?: ContinentCode;12047 /**12048 * The city the request originated from12049 *12050 * @example "Austin"12051 */12052 city?: string;12053 /**12054 * Postal code of the incoming request12055 *12056 * @example "78701"12057 */12058 postalCode?: string;12059 /**12060 * Latitude of the incoming request12061 *12062 * @example "30.27130"12063 */12064 latitude?: string;12065 /**12066 * Longitude of the incoming request12067 *12068 * @example "-97.74260"12069 */12070 longitude?: string;12071 /**12072 * Timezone of the incoming request12073 *12074 * @example "America/Chicago"12075 */12076 timezone?: string;12077 /**12078 * If known, the ISO 3166-2 name for the first level region associated with12079 * the IP address of the incoming request12080 *12081 * @example "Texas"12082 */12083 region?: string;12084 /**12085 * If known, the ISO 3166-2 code for the first-level region associated with12086 * the IP address of the incoming request12087 *12088 * @example "TX"12089 */12090 regionCode?: string;12091 /**12092 * Metro code (DMA) of the incoming request12093 *12094 * @example "635"12095 */12096 metroCode?: string;12097}12098/** Data about the incoming request's TLS certificate */12099interface IncomingRequestCfPropertiesTLSClientAuth {12100 /** Always `"1"`, indicating that the certificate was presented */12101 certPresented: "1";12102 /**12103 * Result of certificate verification.12104 *12105 * @example "FAILED:self signed certificate"12106 */12107 certVerified: Exclude<CertVerificationStatus, "NONE">;12108 /** The presented certificate's revokation status.12109 *12110 * - A value of `"1"` indicates the certificate has been revoked12111 * - A value of `"0"` indicates the certificate has not been revoked12112 */12113 certRevoked: "1" | "0";12114 /**12115 * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html)12116 *12117 * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"12118 */12119 certIssuerDN: string;12120 /**12121 * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html)12122 *12123 * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"12124 */12125 certSubjectDN: string;12126 /**12127 * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted)12128 *12129 * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"12130 */12131 certIssuerDNRFC2253: string;12132 /**12133 * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted)12134 *12135 * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"12136 */12137 certSubjectDNRFC2253: string;12138 /** The certificate issuer's distinguished name (legacy policies) */12139 certIssuerDNLegacy: string;12140 /** The certificate subject's distinguished name (legacy policies) */12141 certSubjectDNLegacy: string;12142 /**12143 * The certificate's serial number12144 *12145 * @example "00936EACBE07F201DF"12146 */12147 certSerial: string;12148 /**12149 * The certificate issuer's serial number12150 *12151 * @example "2489002934BDFEA34"12152 */12153 certIssuerSerial: string;12154 /**12155 * The certificate's Subject Key Identifier12156 *12157 * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4"12158 */12159 certSKI: string;12160 /**12161 * The certificate issuer's Subject Key Identifier12162 *12163 * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4"12164 */12165 certIssuerSKI: string;12166 /**12167 * The certificate's SHA-1 fingerprint12168 *12169 * @example "6b9109f323999e52259cda7373ff0b4d26bd232e"12170 */12171 certFingerprintSHA1: string;12172 /**12173 * The certificate's SHA-256 fingerprint12174 *12175 * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea"12176 */12177 certFingerprintSHA256: string;12178 /**12179 * The effective starting date of the certificate12180 *12181 * @example "Dec 22 19:39:00 2018 GMT"12182 */12183 certNotBefore: string;12184 /**12185 * The effective expiration date of the certificate12186 *12187 * @example "Dec 22 19:39:00 2018 GMT"12188 */12189 certNotAfter: string;12190 /**12191 * The client leaf certificate in [RFC 9440](https://www.rfc-editor.org/rfc/rfc9440)12192 * format (`:base64-DER:`). Empty if no client certificate was presented or if12193 * the leaf certificate exceeded 10 KB (see {@link certRFC9440TooLarge}).12194 *12195 * Suitable for forwarding to an origin via the `Client-Cert` HTTP header.12196 */12197 certRFC9440: string;12198 /**12199 * `true` if the leaf certificate exceeded 10 KB and was omitted from12200 * {@link certRFC9440}.12201 */12202 certRFC9440TooLarge: boolean;12203 /**12204 * The intermediate certificate chain in [RFC 9440](https://www.rfc-editor.org/rfc/rfc9440)12205 * format as a comma-separated list. Empty if no intermediates were sent or12206 * if the chain exceeded 16 KB (see {@link certChainRFC9440TooLarge}).12207 *12208 * Suitable for forwarding to an origin via the `Client-Cert-Chain` HTTP header.12209 */12210 certChainRFC9440: string;12211 /**12212 * `true` if the intermediate chain exceeded 16 KB and was omitted from12213 * {@link certChainRFC9440}.12214 */12215 certChainRFC9440TooLarge: boolean;12216}12217/** Placeholder values for TLS Client Authorization */12218interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder {12219 certPresented: "0";12220 certVerified: "NONE";12221 certRevoked: "0";12222 certIssuerDN: "";12223 certSubjectDN: "";12224 certIssuerDNRFC2253: "";12225 certSubjectDNRFC2253: "";12226 certIssuerDNLegacy: "";12227 certSubjectDNLegacy: "";12228 certSerial: "";12229 certIssuerSerial: "";12230 certSKI: "";12231 certIssuerSKI: "";12232 certFingerprintSHA1: "";12233 certFingerprintSHA256: "";12234 certNotBefore: "";12235 certNotAfter: "";12236 certRFC9440: "";12237 certRFC9440TooLarge: false;12238 certChainRFC9440: "";12239 certChainRFC9440TooLarge: false;12240}12241/** Possible outcomes of TLS verification */12242declare type CertVerificationStatus =12243/** Authentication succeeded */12244"SUCCESS"12245/** No certificate was presented */12246 | "NONE"12247/** Failed because the certificate was self-signed */12248 | "FAILED:self signed certificate"12249/** Failed because the certificate failed a trust chain check */12250 | "FAILED:unable to verify the first certificate"12251/** Failed because the certificate not yet valid */12252 | "FAILED:certificate is not yet valid"12253/** Failed because the certificate is expired */12254 | "FAILED:certificate has expired"12255/** Failed for another unspecified reason */12256 | "FAILED";12257/**12258 * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare.12259 */12260declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = 0 /** Unknown */ | 1 /** no keepalives (not found) */ | 2 /** no connection re-use, opening keepalive connection failed */ | 3 /** no connection re-use, keepalive accepted and saved */ | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ | 5; /** connection re-use, accepted by the origin server */12261/** ISO 3166-1 Alpha-2 codes */12262declare type Iso3166Alpha2Code = "AD" | "AE" | "AF" | "AG" | "AI" | "AL" | "AM" | "AO" | "AQ" | "AR" | "AS" | "AT" | "AU" | "AW" | "AX" | "AZ" | "BA" | "BB" | "BD" | "BE" | "BF" | "BG" | "BH" | "BI" | "BJ" | "BL" | "BM" | "BN" | "BO" | "BQ" | "BR" | "BS" | "BT" | "BV" | "BW" | "BY" | "BZ" | "CA" | "CC" | "CD" | "CF" | "CG" | "CH" | "CI" | "CK" | "CL" | "CM" | "CN" | "CO" | "CR" | "CU" | "CV" | "CW" | "CX" | "CY" | "CZ" | "DE" | "DJ" | "DK" | "DM" | "DO" | "DZ" | "EC" | "EE" | "EG" | "EH" | "ER" | "ES" | "ET" | "FI" | "FJ" | "FK" | "FM" | "FO" | "FR" | "GA" | "GB" | "GD" | "GE" | "GF" | "GG" | "GH" | "GI" | "GL" | "GM" | "GN" | "GP" | "GQ" | "GR" | "GS" | "GT" | "GU" | "GW" | "GY" | "HK" | "HM" | "HN" | "HR" | "HT" | "HU" | "ID" | "IE" | "IL" | "IM" | "IN" | "IO" | "IQ" | "IR" | "IS" | "IT" | "JE" | "JM" | "JO" | "JP" | "KE" | "KG" | "KH" | "KI" | "KM" | "KN" | "KP" | "KR" | "KW" | "KY" | "KZ" | "LA" | "LB" | "LC" | "LI" | "LK" | "LR" | "LS" | "LT" | "LU" | "LV" | "LY" | "MA" | "MC" | "MD" | "ME" | "MF" | "MG" | "MH" | "MK" | "ML" | "MM" | "MN" | "MO" | "MP" | "MQ" | "MR" | "MS" | "MT" | "MU" | "MV" | "MW" | "MX" | "MY" | "MZ" | "NA" | "NC" | "NE" | "NF" | "NG" | "NI" | "NL" | "NO" | "NP" | "NR" | "NU" | "NZ" | "OM" | "PA" | "PE" | "PF" | "PG" | "PH" | "PK" | "PL" | "PM" | "PN" | "PR" | "PS" | "PT" | "PW" | "PY" | "QA" | "RE" | "RO" | "RS" | "RU" | "RW" | "SA" | "SB" | "SC" | "SD" | "SE" | "SG" | "SH" | "SI" | "SJ" | "SK" | "SL" | "SM" | "SN" | "SO" | "SR" | "SS" | "ST" | "SV" | "SX" | "SY" | "SZ" | "TC" | "TD" | "TF" | "TG" | "TH" | "TJ" | "TK" | "TL" | "TM" | "TN" | "TO" | "TR" | "TT" | "TV" | "TW" | "TZ" | "UA" | "UG" | "UM" | "US" | "UY" | "UZ" | "VA" | "VC" | "VE" | "VG" | "VI" | "VN" | "VU" | "WF" | "WS" | "YE" | "YT" | "ZA" | "ZM" | "ZW";12263/** The 2-letter continent codes Cloudflare uses */12264declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA";12265type CfProperties<HostMetadata = unknown> = IncomingRequestCfProperties<HostMetadata> | RequestInitCfProperties;12266interface D1Meta {12267 duration: number;12268 size_after: number;12269 rows_read: number;12270 rows_written: number;12271 last_row_id: number;12272 changed_db: boolean;12273 changes: number;12274 /**12275 * The region of the database instance that executed the query.12276 */12277 served_by_region?: string;12278 /**12279 * The three letters airport code of the colo that executed the query.12280 */12281 served_by_colo?: string;12282 /**12283 * True if-and-only-if the database instance that executed the query was the primary.12284 */12285 served_by_primary?: boolean;12286 timings?: {12287 /**12288 * The duration of the SQL query execution by the database instance. It doesn't include any network time.12289 */12290 sql_duration_ms: number;12291 };12292 /**12293 * Number of total attempts to execute the query, due to automatic retries.12294 * Note: All other fields in the response like `timings` only apply to the last attempt.12295 */12296 total_attempts?: number;12297}12298interface D1Response {12299 success: true;12300 meta: D1Meta & Record<string, unknown>;12301 error?: never;12302}12303type D1Result<T = unknown> = D1Response & {12304 results: T[];12305};12306interface D1ExecResult {12307 count: number;12308 duration: number;12309}12310type D1SessionConstraint =12311// Indicates that the first query should go to the primary, and the rest queries12312// using the same D1DatabaseSession will go to any replica that is consistent with12313// the bookmark maintained by the session (returned by the first query).12314'first-primary'12315// Indicates that the first query can go anywhere (primary or replica), and the rest queries12316// using the same D1DatabaseSession will go to any replica that is consistent with12317// the bookmark maintained by the session (returned by the first query).12318 | 'first-unconstrained';12319type D1SessionBookmark = string;12320declare abstract class D1Database {12321 prepare(query: string): D1PreparedStatement;12322 batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;12323 exec(query: string): Promise<D1ExecResult>;12324 /**12325 * Creates a new D1 Session anchored at the given constraint or the bookmark.12326 * All queries executed using the created session will have sequential consistency,12327 * meaning that all writes done through the session will be visible in subsequent reads.12328 *12329 * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session.12330 */12331 withSession(constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession;12332 /**12333 * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases.12334 */12335 dump(): Promise<ArrayBuffer>;12336}12337declare abstract class D1DatabaseSession {12338 prepare(query: string): D1PreparedStatement;12339 batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;12340 /**12341 * @returns The latest session bookmark across all executed queries on the session.12342 * If no query has been executed yet, `null` is returned.12343 */12344 getBookmark(): D1SessionBookmark | null;12345}12346declare abstract class D1PreparedStatement {12347 bind(...values: unknown[]): D1PreparedStatement;12348 first<T = unknown>(colName: string): Promise<T | null>;12349 first<T = Record<string, unknown>>(): Promise<T | null>;12350 run<T = Record<string, unknown>>(): Promise<D1Result<T>>;12351 all<T = Record<string, unknown>>(): Promise<D1Result<T>>;12352 raw<T = unknown[]>(options: {12353 columnNames: true;12354 }): Promise<[12355 string[],12356 ...T[]12357 ]>;12358 raw<T = unknown[]>(options?: {12359 columnNames?: false;12360 }): Promise<T[]>;12361}12362// `Disposable` was added to TypeScript's standard lib types in version 5.2.12363// To support older TypeScript versions, define an empty `Disposable` interface.12364// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2,12365// but this will ensure type checking on older versions still passes.12366// TypeScript's interface merging will ensure our empty interface is effectively12367// ignored when `Disposable` is included in the standard lib.12368interface Disposable {12369}12370/**12371 * The returned data after sending an email12372 */12373interface EmailSendResult {12374 /**12375 * The Email Message ID12376 */12377 messageId: string;12378}12379/**12380 * An email message that can be sent from a Worker.12381 */12382interface EmailMessage {12383 /**12384 * Envelope From attribute of the email message.12385 */12386 readonly from: string;12387 /**12388 * Envelope To attribute of the email message.12389 */12390 readonly to: string;12391}12392/**12393 * An email message that is sent to a consumer Worker and can be rejected/forwarded.12394 */12395interface ForwardableEmailMessage extends EmailMessage {12396 /**12397 * Stream of the email message content.12398 */12399 readonly raw: ReadableStream<Uint8Array>;12400 /**12401 * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers).12402 */12403 readonly headers: Headers;12404 /**12405 * Size of the email message content.12406 */12407 readonly rawSize: number;12408 /**12409 * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason.12410 * @param reason The reject reason.12411 * @returns void12412 */12413 setReject(reason: string): void;12414 /**12415 * Forward this email message to a verified destination address of the account.12416 * @param rcptTo Verified destination address.12417 * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers).12418 * @returns A promise that resolves when the email message is forwarded.12419 */12420 forward(rcptTo: string, headers?: Headers): Promise<EmailSendResult>;12421 /**12422 * Reply to the sender of this email message with a new EmailMessage object.12423 * @param message The reply message.12424 * @returns A promise that resolves when the email message is replied.12425 */12426 reply(message: EmailMessage): Promise<EmailSendResult>;12427 /**12428 * Reply to the sender of this email message with a message built from the given12429 * fields. Threading headers (In-Reply-To/References) are set automatically.12430 * @param builder The reply message contents.12431 * @returns A promise that resolves when the email message is replied.12432 */12433 reply(builder: EmailReplyMessageBuilder): Promise<EmailSendResult>;12434}12435/** A file attachment for an email message */12436type EmailAttachment = {12437 disposition: 'inline';12438 contentId: string;12439 filename: string;12440 type: string;12441 content: string | ArrayBuffer | ArrayBufferView;12442} | {12443 disposition: 'attachment';12444 contentId?: undefined;12445 filename: string;12446 type: string;12447 content: string | ArrayBuffer | ArrayBufferView;12448};12449/** An Email Address */12450interface EmailAddress {12451 name: string;12452 email: string;12453}12454/**12455 * Recipient fields for `SendEmail.send()`. At least one of `to`, `cc`, or12456 * `bcc` must be provided.12457 */12458type EmailDestinations = {12459 to?: string | EmailAddress | (string | EmailAddress)[];12460 cc?: string | EmailAddress | (string | EmailAddress)[];12461 bcc?: string | EmailAddress | (string | EmailAddress)[];12462} & ({12463 to: string | EmailAddress | (string | EmailAddress)[];12464} | {12465 cc: string | EmailAddress | (string | EmailAddress)[];12466} | {12467 bcc: string | EmailAddress | (string | EmailAddress)[];12468});12469/**12470 * Fields shared by all composed emails (no recipients). Used directly by12471 * `ForwardableEmailMessage.reply()`, which always replies to the original12472 * sender, and extended by `EmailMessageBuilder` for `SendEmail.send()`.12473 */12474interface EmailReplyMessageBuilder {12475 from: string | EmailAddress;12476 subject: string;12477 replyTo?: string | EmailAddress;12478 headers?: Record<string, string>;12479 text?: string;12480 html?: string;12481 attachments?: EmailAttachment[];12482}12483/**12484 * Fields for composing an email without constructing raw MIME, for12485 * `SendEmail.send()`. Requires at least one of `to`, `cc`, or `bcc`.12486 */12487type EmailMessageBuilder = EmailReplyMessageBuilder & EmailDestinations;12488/**12489 * A binding that allows a Worker to send email messages.12490 */12491interface SendEmail {12492 send(message: EmailMessage): Promise<EmailSendResult>;12493 send(builder: EmailMessageBuilder): Promise<EmailSendResult>;12494}12495declare abstract class EmailEvent extends ExtendableEvent {12496 readonly message: ForwardableEmailMessage;12497}12498declare type EmailExportedHandler<Env = unknown, Props = unknown> = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;12499declare module "cloudflare:email" {12500 let _EmailMessage: {12501 prototype: EmailMessage;12502 new (from: string, to: string, raw: ReadableStream | string): EmailMessage;12503 };12504 export { _EmailMessage as EmailMessage };12505}12506/**12507 * Evaluation context for targeting rules.12508 * Keys are attribute names (e.g. "userId", "country"), values are the attribute values.12509 */12510type FlagshipEvaluationContext = Record<string, string | number | boolean>;12511interface FlagshipEvaluationDetails<T> {12512 flagKey: string;12513 value: T;12514 variant?: string | undefined;12515 reason?: string | undefined;12516 errorCode?: string | undefined;12517 errorMessage?: string | undefined;12518}12519interface FlagshipEvaluationError extends Error {12520}12521/**12522 * Feature flags binding for evaluating feature flags from a Cloudflare Workers script.12523 *12524 * @example12525 * ```typescript12526 * // Get a boolean flag value with a default12527 * const enabled = await env.FLAGS.getBooleanValue('my-feature', false);12528 *12529 * // Get a flag value with evaluation context for targeting12530 * const variant = await env.FLAGS.getStringValue('experiment', 'control', {12531 * userId: 'user-123',12532 * country: 'US',12533 * });12534 *12535 * // Get full evaluation details including variant and reason12536 * const details = await env.FLAGS.getBooleanDetails('my-feature', false);12537 * console.log(details.variant, details.reason);12538 * ```12539 */12540declare abstract class Flagship {12541 /**12542 * Get a flag value without type checking.12543 * @param flagKey The key of the flag to evaluate.12544 * @param defaultValue Optional default value returned when evaluation fails.12545 * @param context Optional evaluation context for targeting rules.12546 */12547 get(flagKey: string, defaultValue?: unknown, context?: FlagshipEvaluationContext): Promise<unknown>;12548 /**12549 * Get a boolean flag value.12550 * @param flagKey The key of the flag to evaluate.12551 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.12552 * @param context Optional evaluation context for targeting rules.12553 */12554 getBooleanValue(flagKey: string, defaultValue: boolean, context?: FlagshipEvaluationContext): Promise<boolean>;12555 /**12556 * Get a string flag value.12557 * @param flagKey The key of the flag to evaluate.12558 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.12559 * @param context Optional evaluation context for targeting rules.12560 */12561 getStringValue(flagKey: string, defaultValue: string, context?: FlagshipEvaluationContext): Promise<string>;12562 /**12563 * Get a number flag value.12564 * @param flagKey The key of the flag to evaluate.12565 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.12566 * @param context Optional evaluation context for targeting rules.12567 */12568 getNumberValue(flagKey: string, defaultValue: number, context?: FlagshipEvaluationContext): Promise<number>;12569 /**12570 * Get an object flag value.12571 * @param flagKey The key of the flag to evaluate.12572 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.12573 * @param context Optional evaluation context for targeting rules.12574 */12575 getObjectValue<T extends object>(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise<T>;12576 /**12577 * Get a boolean flag value with full evaluation details.12578 * @param flagKey The key of the flag to evaluate.12579 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.12580 * @param context Optional evaluation context for targeting rules.12581 */12582 getBooleanDetails(flagKey: string, defaultValue: boolean, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<boolean>>;12583 /**12584 * Get a string flag value with full evaluation details.12585 * @param flagKey The key of the flag to evaluate.12586 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.12587 * @param context Optional evaluation context for targeting rules.12588 */12589 getStringDetails(flagKey: string, defaultValue: string, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<string>>;12590 /**12591 * Get a number flag value with full evaluation details.12592 * @param flagKey The key of the flag to evaluate.12593 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.12594 * @param context Optional evaluation context for targeting rules.12595 */12596 getNumberDetails(flagKey: string, defaultValue: number, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<number>>;12597 /**12598 * Get an object flag value with full evaluation details.12599 * @param flagKey The key of the flag to evaluate.12600 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.12601 * @param context Optional evaluation context for targeting rules.12602 */12603 getObjectDetails<T extends object>(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<T>>;12604}12605/**12606 * Hello World binding to serve as an explanatory example. DO NOT USE12607 */12608interface HelloWorldBinding {12609 /**12610 * Retrieve the current stored value12611 */12612 get(): Promise<{12613 value: string;12614 ms?: number;12615 }>;12616 /**12617 * Set a new stored value12618 */12619 set(value: string): Promise<void>;12620}12621interface Hyperdrive {12622 /**12623 * Connect directly to Hyperdrive as if it's your database, returning a TCP socket.12624 *12625 * Calling this method returns an identical socket to if you call12626 * `connect("host:port")` using the `host` and `port` fields from this object.12627 * Pick whichever approach works better with your preferred DB client library.12628 *12629 * Note that this socket is not yet authenticated -- it's expected that your12630 * code (or preferably, the client library of your choice) will authenticate12631 * using the information in this class's readonly fields.12632 */12633 connect(): Socket;12634 /**12635 * A valid DB connection string that can be passed straight into the typical12636 * client library/driver/ORM. This will typically be the easiest way to use12637 * Hyperdrive.12638 */12639 readonly connectionString: string;12640 /*12641 * A randomly generated hostname that is only valid within the context of the12642 * currently running Worker which, when passed into `connect()` function from12643 * the "cloudflare:sockets" module, will connect to the Hyperdrive instance12644 * for your database.12645 */12646 readonly host: string;12647 /*12648 * A synthetic IPv4 address (in the reserved 240.0.0.0/4 range) that, like the12649 * host field, is only valid within the context of the currently running12650 * Worker and, when passed into the `connect()` function from the12651 * "cloudflare:sockets" module, will connect to the Hyperdrive instance for12652 * your database. This is provided for database drivers that require the host12653 * to be an IP literal rather than a hostname.12654 */12655 readonly ip: string;12656 /*12657 * The port that must be paired the the host field when connecting.12658 */12659 readonly port: number;12660 /*12661 * The username to use when authenticating to your database via Hyperdrive.12662 * Unlike the host and password, this will be the same every time12663 */12664 readonly user: string;12665 /*12666 * The randomly generated password to use when authenticating to your12667 * database via Hyperdrive. Like the host field, this password is only valid12668 * within the context of the currently running Worker instance from which12669 * it's read.12670 */12671 readonly password: string;12672 /*12673 * The name of the database to connect to.12674 */12675 readonly database: string;12676}12677// Copyright (c) 2024 Cloudflare, Inc.12678// Licensed under the Apache 2.0 license found in the LICENSE file or at:12679// https://opensource.org/licenses/Apache-2.012680type ImageInfoResponse = {12681 format: 'image/svg+xml';12682} | {12683 format: string;12684 fileSize: number;12685 width: number;12686 height: number;12687};12688/**12689 * Parameters for rasterizing text into an image.12690 */12691type TextRasterize = {12692 /** The text content to render */12693 content: string;12694 /** rasterization options for the text **/12695 options: TextOptions;12696};12697type TextOptions = {12698 /** Font configuration */12699 font: {12700 /** URL to a font file in TrueType (.ttf), OpenType (.otf), WOFF (.woff), or WOFF2 (.woff2) format */12701 url: string;12702 };12703 /** Font size in points (pt) */12704 size?: number;12705 /** Text color in CSS format: hex (#RRGGBB or #RRGGBBAA), rgb(r,g,b), rgba(r,g,b,a), or named colors */12706 color?: string;12707};12708type ImageSource = ReadableStream<Uint8Array> | TextRasterize;12709type ImageTransform = {12710 width?: number;12711 height?: number;12712 background?: string;12713 blur?: number;12714 border?: {12715 color?: string;12716 width?: number;12717 } | {12718 top?: number;12719 bottom?: number;12720 left?: number;12721 right?: number;12722 };12723 brightness?: number;12724 contrast?: number;12725 fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop';12726 flip?: 'h' | 'v' | 'hv';12727 gamma?: number;12728 segment?: 'foreground';12729 gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | {12730 x?: number;12731 y?: number;12732 mode: 'remainder' | 'box-center';12733 };12734 rotate?: 0 | 90 | 180 | 270;12735 saturation?: number;12736 sharpen?: number;12737 trim?: 'border' | {12738 top?: number;12739 bottom?: number;12740 left?: number;12741 right?: number;12742 width?: number;12743 height?: number;12744 border?: boolean | {12745 color?: string;12746 tolerance?: number;12747 keep?: number;12748 };12749 };12750};12751type ImageDrawOptions = {12752 opacity?: number;12753 repeat?: boolean | string;12754 composite?: ImageCompositeMode;12755 top?: number;12756 left?: number;12757 bottom?: number;12758 right?: number;12759};12760type ImageCompositeMode =12761/** Foreground drawn on top of backdrop (default) */12762'over'12763/** Foreground shown only where backdrop is opaque */12764 | 'in'12765/** Foreground drawn on top, but clipped to the backdrop's shape */12766 | 'atop'12767/** Foreground shown only where backdrop is transparent */12768 | 'out'12769/** Foreground and backdrop visible only where the other is not */12770 | 'xor'12771/** Foreground and backdrop channels added (brightening) */12772 | 'lighter';12773type ImageInputOptions = {12774 encoding?: 'base64';12775};12776type ImageOutputOptions = {12777 format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba';12778 quality?: number;12779 background?: string;12780 anim?: boolean;12781};12782interface ImageMetadata {12783 id: string;12784 filename?: string;12785 uploaded?: string;12786 requireSignedURLs: boolean;12787 meta?: Record<string, unknown>;12788 variants: string[];12789 draft?: boolean;12790 creator?: string;12791}12792interface ImageUploadOptions {12793 id?: string;12794 filename?: string;12795 requireSignedURLs?: boolean;12796 metadata?: Record<string, unknown>;12797 creator?: string;12798 /**12799 * If 'base64', the input data will be decoded from base64 before processing12800 */12801 encoding?: 'base64';12802}12803interface ImageUpdateOptions {12804 requireSignedURLs?: boolean;12805 metadata?: Record<string, unknown>;12806 creator?: string;12807}12808type ImageMetadataFilterOperators = {12809 eq?: string | number | boolean;12810 in?: string[] | number[];12811 gt?: number;12812 gte?: number;12813 lt?: number;12814 lte?: number;12815};12816type ImageMetadataFilterValue = string | number | boolean | ImageMetadataFilterOperators;12817interface ImageListFilter {12818 metadata?: Record<string, ImageMetadataFilterValue>;12819}12820interface ImageListOptions {12821 limit?: number;12822 cursor?: string;12823 sortOrder?: 'asc' | 'desc';12824 creator?: string;12825 filter?: ImageListFilter;12826}12827interface ImageSignedUrlOptions {12828 variant: string;12829 expiresIn?: number;12830 keyName?: string;12831}12832interface ImageDirectUploadOptions {12833 id?: string;12834 requireSignedURLs?: boolean;12835 metadata?: Record<string, unknown>;12836 creator?: string;12837 expiresIn?: number;12838}12839interface ImageDirectUploadResult {12840 id: string;12841 uploadURL: string;12842}12843interface ImageList {12844 images: ImageMetadata[];12845 cursor?: string;12846 listComplete: boolean;12847}12848interface ImageHandle {12849 /**12850 * Get metadata for a hosted image12851 * @returns Image metadata, or null if not found12852 */12853 details(): Promise<ImageMetadata | null>;12854 /**12855 * Get the raw image data for a hosted image12856 * @returns ReadableStream of image bytes, or null if not found12857 */12858 bytes(): Promise<ReadableStream<Uint8Array> | null>;12859 /**12860 * Generate a signed delivery URL for this hosted image.12861 * @param options Signing configuration12862 * @returns A signed image delivery URL12863 * @throws {@link ImagesError} if signing fails12864 */12865 signedUrl(options: ImageSignedUrlOptions): Promise<string>;12866 /**12867 * Update hosted image metadata12868 * @param options Properties to update12869 * @returns Updated image metadata12870 * @throws {@link ImagesError} if update fails12871 */12872 update(options: ImageUpdateOptions): Promise<ImageMetadata>;12873 /**12874 * Delete a hosted image12875 * @returns True if deleted, false if not found12876 */12877 delete(): Promise<boolean>;12878}12879interface HostedImagesBinding {12880 /**12881 * Get a handle for a hosted image12882 * @param imageId The ID of the image (UUID or custom ID)12883 * @returns A handle for per-image operations12884 */12885 image(imageId: string): ImageHandle;12886 /**12887 * Upload a new hosted image12888 * @param image The image file to upload12889 * @param options Upload configuration12890 * @returns Metadata for the uploaded image12891 * @throws {@link ImagesError} if upload fails12892 */12893 upload(image: ReadableStream<Uint8Array> | ArrayBuffer, options?: ImageUploadOptions): Promise<ImageMetadata>;12894 /**12895 * List hosted images with pagination12896 * @param options List configuration12897 * @returns List of images with pagination info12898 * @throws {@link ImagesError} if list fails12899 */12900 list(options?: ImageListOptions): Promise<ImageList>;12901 /**12902 * Create a Direct Creator Upload link, letting an end user upload an12903 * image straight to Cloudflare without exposing an API token12904 * @param options Upload link configuration12905 * @returns The new image ID and the upload URL to hand to the end user12906 * @throws {@link ImagesError} if creation fails12907 */12908 createDirectUpload(options?: ImageDirectUploadOptions): Promise<ImageDirectUploadResult>;12909}12910interface ImagesBinding {12911 /**12912 * Get image metadata (type, width and height)12913 * @throws {@link ImagesError} with code 9412 if input is not an image12914 * @param stream The image bytes12915 */12916 info(stream: ReadableStream<Uint8Array>, options?: ImageInputOptions): Promise<ImageInfoResponse>;12917 /**12918 * Begin applying a series of transformations to an image12919 * @param stream The image bytes12920 * @returns A transform handle12921 */12922 input(stream: ReadableStream<Uint8Array>, options?: ImageInputOptions): ImageTransformer;12923 /**12924 * Begin applying a series of transformations to text12925 * @param content string to be rendered12926 * @param options font, optional color and size to use in rendering text12927 * @returns A transform handle12928 */12929 text(content: string, options: TextOptions): ImageTransformer;12930 /**12931 * Access hosted images CRUD operations12932 */12933 readonly hosted: HostedImagesBinding;12934}12935interface ImageTransformer {12936 /**12937 * Apply transform next, returning a transform handle.12938 * You can then apply more transformations, draw, or retrieve the output.12939 * @param transform12940 */12941 transform(transform: ImageTransform): ImageTransformer;12942 /**12943 * Draw an image on this transformer, returning a transform handle.12944 * You can then apply more transformations, draw, or retrieve the output.12945 * @param image The image (or transformer that will give the image) to draw12946 * @param options The options configuring how to draw the image12947 */12948 draw(image: ReadableStream<Uint8Array> | ImageTransformer, options?: ImageDrawOptions): ImageTransformer;12949 /**12950 * Retrieve the image that results from applying the transforms to the12951 * provided input12952 * @param options Options that apply to the output e.g. output format12953 */12954 output(options: ImageOutputOptions): Promise<ImageTransformationResult>;12955}12956type ImageTransformationOutputOptions = {12957 encoding?: 'base64';12958};12959type ImageTransformationResponseOptions = {12960 headers?: HeadersInit;12961};12962interface ImageTransformationResult {12963 /**12964 * The image as a response, ready to store in cache or return to users12965 * @param options Options that apply to the returned response, e.g. additional headers12966 */12967 response(options?: ImageTransformationResponseOptions): Response;12968 /**12969 * The content type of the returned image12970 */12971 contentType(): string;12972 /**12973 * The bytes of the response12974 */12975 image(options?: ImageTransformationOutputOptions): ReadableStream<Uint8Array>;12976}12977interface ImagesError extends Error {12978 readonly code: number;12979 readonly message: string;12980 readonly stack?: string;12981}12982/**12983 * Media binding for transforming media streams.12984 * Provides the entry point for media transformation operations.12985 */12986interface MediaBinding {12987 /**12988 * Creates a media transformer from an input stream.12989 * @param media - The input media bytes12990 * @returns A MediaTransformer instance for applying transformations12991 */12992 input(media: ReadableStream<Uint8Array>): MediaTransformer;12993}12994/**12995 * Media transformer for applying transformation operations to media content.12996 * Handles sizing, fitting, and other input transformation parameters.12997 */12998interface MediaTransformer {12999 /**13000 * Applies transformation options to the media content.13001 * @param transform - Configuration for how the media should be transformed13002 * @returns A generator for producing the transformed media output13003 */13004 transform(transform?: MediaTransformationInputOptions): MediaTransformationGenerator;13005 /**13006 * Generates the final media output with specified options.13007 * @param output - Configuration for the output format and parameters13008 * @returns The final transformation result containing the transformed media13009 */13010 output(output?: MediaTransformationOutputOptions): MediaTransformationResult;13011}13012/**13013 * Generator for producing media transformation results.13014 * Configures the output format and parameters for the transformed media.13015 */13016interface MediaTransformationGenerator {13017 /**13018 * Generates the final media output with specified options.13019 * @param output - Configuration for the output format and parameters13020 * @returns The final transformation result containing the transformed media13021 */13022 output(output?: MediaTransformationOutputOptions): MediaTransformationResult;13023}13024/**13025 * Result of a media transformation operation.13026 * Provides multiple ways to access the transformed media content.13027 */13028interface MediaTransformationResult {13029 /**13030 * Returns the transformed media as a readable stream of bytes.13031 * @returns A promise containing a readable stream with the transformed media13032 */13033 media(): Promise<ReadableStream<Uint8Array>>;13034 /**13035 * Returns the transformed media as an HTTP response object.13036 * @returns The transformed media as a Promise<Response>, ready to store in cache or return to users13037 */13038 response(): Promise<Response>;13039 /**13040 * Returns the MIME type of the transformed media.13041 * @returns A promise containing the content type string (e.g., 'image/jpeg', 'video/mp4')13042 */13043 contentType(): Promise<string>;13044}13045/**13046 * Configuration options for transforming media input.13047 * Controls how the media should be resized and fitted.13048 */13049type MediaTransformationInputOptions = {13050 /** How the media should be resized to fit the specified dimensions */13051 fit?: 'contain' | 'cover' | 'scale-down';13052 /** Target width in pixels */13053 width?: number;13054 /** Target height in pixels */13055 height?: number;13056};13057/**13058 * Configuration options for Media Transformations output.13059 * Controls the format, timing, and type of the generated output.13060 */13061type MediaTransformationOutputOptions = {13062 /**13063 * Output mode determining the type of media to generate13064 */13065 mode?: 'video' | 'spritesheet' | 'frame' | 'audio';13066 /** Whether to include audio in the output */13067 audio?: boolean;13068 /**13069 * Starting timestamp for frame extraction or start time for clips. (e.g. '2s').13070 */13071 time?: string;13072 /**13073 * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s').13074 */13075 duration?: string;13076 /**13077 * Number of frames in the spritesheet.13078 */13079 imageCount?: number;13080 /**13081 * Output format for the generated media.13082 */13083 format?: 'jpg' | 'png' | 'm4a';13084};13085/**13086 * Error object for media transformation operations.13087 * Extends the standard Error interface with additional media-specific information.13088 */13089interface MediaError extends Error {13090 readonly code: number;13091 readonly message: string;13092 readonly stack?: string;13093}13094declare module 'cloudflare:node' {13095 interface NodeStyleServer {13096 listen(...args: unknown[]): this;13097 address(): {13098 port?: number | null | undefined;13099 };13100 }13101 export function httpServerHandler(port: number): ExportedHandler;13102 export function httpServerHandler(options: {13103 port: number;13104 }): ExportedHandler;13105 export function httpServerHandler(server: NodeStyleServer): ExportedHandler;13106}13107type Params<P extends string = any> = Record<P, string | string[]>;13108type EventContext<Env, P extends string, Data> = {13109 request: Request<unknown, IncomingRequestCfProperties<unknown>>;13110 functionPath: string;13111 waitUntil: (promise: Promise<any>) => void;13112 passThroughOnException: () => void;13113 next: (input?: Request | string, init?: RequestInit) => Promise<Response>;13114 env: Env & {13115 ASSETS: {13116 fetch: typeof fetch;13117 };13118 };13119 params: Params<P>;13120 data: Data;13121};13122type PagesFunction<Env = unknown, Params extends string = any, Data extends Record<string, unknown> = Record<string, unknown>> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>;13123type EventPluginContext<Env, P extends string, Data, PluginArgs> = {13124 request: Request<unknown, IncomingRequestCfProperties<unknown>>;13125 functionPath: string;13126 waitUntil: (promise: Promise<any>) => void;13127 passThroughOnException: () => void;13128 next: (input?: Request | string, init?: RequestInit) => Promise<Response>;13129 env: Env & {13130 ASSETS: {13131 fetch: typeof fetch;13132 };13133 };13134 params: Params<P>;13135 data: Data;13136 pluginArgs: PluginArgs;13137};13138type PagesPluginFunction<Env = unknown, Params extends string = any, Data extends Record<string, unknown> = Record<string, unknown>, PluginArgs = unknown> = (context: EventPluginContext<Env, Params, Data, PluginArgs>) => Response | Promise<Response>;13139declare module "assets:*" {13140 export const onRequest: PagesFunction;13141}13142// Copyright (c) 2022-2023 Cloudflare, Inc.13143// Licensed under the Apache 2.0 license found in the LICENSE file or at:13144// https://opensource.org/licenses/Apache-2.013145declare module "cloudflare:pipelines" {13146 export abstract class PipelineTransformationEntrypoint<Env = unknown, I extends PipelineRecord = PipelineRecord, O extends PipelineRecord = PipelineRecord> {13147 protected env: Env;13148 protected ctx: ExecutionContext;13149 constructor(ctx: ExecutionContext, env: Env);13150 /**13151 * run receives an array of PipelineRecord which can be13152 * transformed and returned to the pipeline13153 * @param records Incoming records from the pipeline to be transformed13154 * @param metadata Information about the specific pipeline calling the transformation entrypoint13155 * @returns A promise containing the transformed PipelineRecord array13156 */13157 public run(records: I[], metadata: PipelineBatchMetadata): Promise<O[]>;13158 }13159 export type PipelineRecord = Record<string, unknown>;13160 export type PipelineBatchMetadata = {13161 pipelineId: string;13162 pipelineName: string;13163 };13164 export interface Pipeline<T extends PipelineRecord = PipelineRecord> {13165 /**13166 * The Pipeline interface represents the type of a binding to a Pipeline13167 *13168 * @param records The records to send to the pipeline13169 */13170 send(records: T[]): Promise<void>;13171 }13172}13173// PubSubMessage represents an incoming PubSub message.13174// The message includes metadata about the broker, the client, and the payload13175// itself.13176// https://developers.cloudflare.com/pub-sub/13177interface PubSubMessage {13178 // Message ID13179 readonly mid: number;13180 // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT13181 readonly broker: string;13182 // The MQTT topic the message was sent on.13183 readonly topic: string;13184 // The client ID of the client that published this message.13185 readonly clientId: string;13186 // The unique identifier (JWT ID) used by the client to authenticate, if token13187 // auth was used.13188 readonly jti?: string;13189 // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker13190 // received the message from the client.13191 readonly receivedAt: number;13192 // An (optional) string with the MIME type of the payload, if set by the13193 // client.13194 readonly contentType: string;13195 // Set to 1 when the payload is a UTF-8 string13196 // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc390106313197 readonly payloadFormatIndicator: number;13198 // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays.13199 // You can use payloadFormatIndicator to inspect this before decoding.13200 payload: string | Uint8Array;13201}13202// JsonWebKey extended by kid parameter13203interface JsonWebKeyWithKid extends JsonWebKey {13204 // Key Identifier of the JWK13205 readonly kid: string;13206}13207interface RateLimitOptions {13208 key: string;13209}13210interface RateLimitOutcome {13211 success: boolean;13212}13213interface RateLimit {13214 /**13215 * Rate limit a request based on the provided options.13216 * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/13217 * @returns A promise that resolves with the outcome of the rate limit.13218 */13219 limit(options: RateLimitOptions): Promise<RateLimitOutcome>;13220}13221// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need13222// to referenced by `Fetcher`. This is included in the "importable" version of the types which13223// strips all `module` blocks.13224declare namespace Rpc {13225 // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s.13226 // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`.13227 // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to13228 // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape)13229 export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND';13230 export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND';13231 export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND';13232 export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND';13233 export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND';13234 export interface RpcTargetBranded {13235 [__RPC_TARGET_BRAND]: never;13236 }13237 export interface WorkerEntrypointBranded {13238 [__WORKER_ENTRYPOINT_BRAND]: never;13239 }13240 export interface DurableObjectBranded {13241 [__DURABLE_OBJECT_BRAND]: never;13242 }13243 export interface WorkflowEntrypointBranded {13244 [__WORKFLOW_ENTRYPOINT_BRAND]: never;13245 }13246 export type EntrypointBranded = WorkerEntrypointBranded | DurableObjectBranded | WorkflowEntrypointBranded;13247 // Types that can be used through `Stub`s13248 export type Stubable = RpcTargetBranded | ((...args: any[]) => any);13249 // Types that can be passed over RPC13250 // The reason for using a generic type here is to build a serializable subset of structured13251 // cloneable composite types. This allows types defined with the "interface" keyword to pass the13252 // serializable check as well. Otherwise, only types defined with the "type" keyword would pass.13253 type Serializable<T> =13254 // Structured cloneables13255 BaseType13256 // Structured cloneable composites13257 | Map<T extends Map<infer U, unknown> ? Serializable<U> : never, T extends Map<unknown, infer U> ? Serializable<U> : never> | Set<T extends Set<infer U> ? Serializable<U> : never> | ReadonlyArray<T extends ReadonlyArray<infer U> ? Serializable<U> : never> | {13258 [K in keyof T]: K extends number | string ? Serializable<T[K]> : never;13259 }13260 // Special types13261 | Stub<Stubable>13262 // Serialized as stubs, see `Stubify`13263 | Stubable;13264 // Base type for all RPC stubs, including common memory management methods.13265 // `T` is used as a marker type for unwrapping `Stub`s later.13266 interface StubBase<T extends Stubable> extends Disposable {13267 [__RPC_STUB_BRAND]: T;13268 dup(): this;13269 }13270 export type Stub<T extends Stubable> = Provider<T> & StubBase<T>;13271 // This represents all the types that can be sent as-is over an RPC boundary13272 type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | ReadableStream<Uint8Array> | WritableStream<Uint8Array> | Request | Response | Headers;13273 // Recursively rewrite all `Stubable` types with `Stub`s13274 // prettier-ignore13275 type Stubify<T> = T extends Stubable ? Stub<T> : T extends Map<infer K, infer V> ? Map<Stubify<K>, Stubify<V>> : T extends Set<infer V> ? Set<Stubify<V>> : T extends Array<infer V> ? Array<Stubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Stubify<V>> : T extends BaseType ? T : T extends {13276 [key: string | number]: any;13277 } ? {13278 [K in keyof T]: Stubify<T[K]>;13279 } : T;13280 // Recursively rewrite all `Stub<T>`s with the corresponding `T`s.13281 // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies:13282 // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`.13283 // prettier-ignore13284 type Unstubify<T> = T extends StubBase<infer V> ? V : T extends Map<infer K, infer V> ? Map<Unstubify<K>, Unstubify<V>> : T extends Set<infer V> ? Set<Unstubify<V>> : T extends Array<infer V> ? Array<Unstubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Unstubify<V>> : T extends BaseType ? T : T extends {13285 [key: string | number]: unknown;13286 } ? {13287 [K in keyof T]: Unstubify<T[K]>;13288 } : T;13289 type UnstubifyAll<A extends any[]> = {13290 [I in keyof A]: Unstubify<A[I]>;13291 };13292 // Utility type for adding `Provider`/`Disposable`s to `object` types only.13293 // Note `unknown & T` is equivalent to `T`.13294 type MaybeProvider<T> = T extends object ? Provider<T> : unknown;13295 type MaybeDisposable<T> = T extends object ? Disposable : unknown;13296 // Type for method return or property on an RPC interface.13297 // - Stubable types are replaced by stubs.13298 // - Serializable types are passed by value, with stubable types replaced by stubs13299 // and a top-level `Disposer`.13300 // Everything else can't be passed over PRC.13301 // Technically, we use custom thenables here, but they quack like `Promise`s.13302 // Intersecting with `(Maybe)Provider` allows pipelining.13303 // prettier-ignore13304 type Result<R> = R extends Stubable ? Promise<Stub<R>> & Provider<R> : R extends Serializable<R> ? Promise<Stubify<R> & MaybeDisposable<R>> & MaybeProvider<R> : never;13305 // Type for method or property on an RPC interface.13306 // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.13307 // Unwrapping `Stub`s allows calling with `Stubable` arguments.13308 // For properties, rewrite types to be `Result`s.13309 // In each case, unwrap `Promise`s.13310 type MethodOrProperty<V> = V extends (...args: infer P) => infer R ? (...args: UnstubifyAll<P>) => Result<Awaited<R>> : Result<Awaited<V>>;13311 // Type for the callable part of an `Provider` if `T` is callable.13312 // This is intersected with methods/properties.13313 type MaybeCallableProvider<T> = T extends (...args: any[]) => any ? MethodOrProperty<T> : unknown;13314 // Base type for all other types providing RPC-like interfaces.13315 // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.13316 // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC.13317 export type Provider<T extends object, Reserved extends string = never> = MaybeCallableProvider<T> & Pick<{13318 [K in keyof T]: MethodOrProperty<T[K]>;13319 }, Exclude<keyof T, Reserved | symbol | keyof StubBase<never>>>;13320}13321declare namespace Cloudflare {13322 // Type of `env`.13323 //13324 // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript13325 // will merge all declarations.13326 //13327 // You can use `wrangler types` to generate the `Env` type automatically.13328 interface Env {13329 }13330 // Project-specific parameters used to inform types.13331 //13332 // This interface is, again, intended to be declared in project-specific files, and then that13333 // declaration will be merged with this one.13334 //13335 // A project should have a declaration like this:13336 //13337 // interface GlobalProps {13338 // // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type13339 // // of `ctx.exports`.13340 // mainModule: typeof import("my-main-module");13341 //13342 // // Declares which of the main module's exports are configured with durable storage, and13343 // // thus should behave as Durable Object namsepace bindings.13344 // durableNamespaces: "MyDurableObject" | "AnotherDurableObject";13345 // }13346 //13347 // You can use `wrangler types` to generate `GlobalProps` automatically.13348 interface GlobalProps {13349 }13350 // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not13351 // present.13352 type GlobalProp<K extends string, Default> = K extends keyof GlobalProps ? GlobalProps[K] : Default;13353 // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the13354 // `mainModule` property.13355 type MainModule = GlobalProp<"mainModule", {}>;13356 // The type of ctx.exports, which contains loopback bindings for all top-level exports.13357 type Exports = {13358 [K in keyof MainModule]: LoopbackForExport<MainModule[K]>13359 // If the export is listed in `durableNamespaces`, then it is also a13360 // DurableObjectNamespace.13361 & (K extends GlobalProp<"durableNamespaces", never> ? MainModule[K] extends new (...args: any[]) => infer DoInstance ? DoInstance extends Rpc.DurableObjectBranded ? DurableObjectNamespace<DoInstance> : DurableObjectNamespace<undefined> : DurableObjectNamespace<undefined> : {});13362 };13363}13364declare namespace CloudflareWorkersModule {13365 export type RpcStub<T extends Rpc.Stubable> = Rpc.Stub<T>;13366 export const RpcStub: {13367 new <T extends Rpc.Stubable>(value: T): Rpc.Stub<T>;13368 };13369 export abstract class RpcTarget implements Rpc.RpcTargetBranded {13370 [Rpc.__RPC_TARGET_BRAND]: never;13371 }13372 // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC13373 export abstract class WorkerEntrypoint<Env = Cloudflare.Env, Props = {}> implements Rpc.WorkerEntrypointBranded {13374 [Rpc.__WORKER_ENTRYPOINT_BRAND]: never;13375 protected ctx: ExecutionContext<Props>;13376 protected env: Env;13377 constructor(ctx: ExecutionContext, env: Env);13378 email?(message: ForwardableEmailMessage): void | Promise<void>;13379 fetch?(request: Request): Response | Promise<Response>;13380 connect?(socket: Socket): void | Promise<void>;13381 queue?(batch: MessageBatch): void | Promise<void>;13382 scheduled?(controller: ScheduledController): void | Promise<void>;13383 tail?(events: TraceItem[]): void | Promise<void>;13384 tailStream?(event: TailStream.TailEvent<TailStream.Onset>): TailStream.TailEventHandlerType | Promise<TailStream.TailEventHandlerType>;13385 test?(controller: TestController): void | Promise<void>;13386 trace?(traces: TraceItem[]): void | Promise<void>;13387 }13388 export abstract class DurableObject<Env = Cloudflare.Env, Props = {}> implements Rpc.DurableObjectBranded {13389 [Rpc.__DURABLE_OBJECT_BRAND]: never;13390 protected ctx: DurableObjectState<Props>;13391 protected env: Env;13392 constructor(ctx: DurableObjectState, env: Env);13393 alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise<void>;13394 fetch?(request: Request): Response | Promise<Response>;13395 connect?(socket: Socket): void | Promise<void>;13396 webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise<void>;13397 webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise<void>;13398 webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>;13399 }13400 export type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';13401 export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number;13402 export type WorkflowDelayDuration = WorkflowSleepDuration;13403 export type WorkflowDynamicDelayContext = {13404 ctx: WorkflowStepContext<WorkflowDelayFunction>;13405 error: Error;13406 };13407 export type WorkflowDelayFunction = (input: WorkflowDynamicDelayContext) => WorkflowDelayDuration | Promise<WorkflowDelayDuration>;13408 export type WorkflowTimeoutDuration = WorkflowSleepDuration;13409 export type WorkflowRetentionDuration = WorkflowSleepDuration;13410 export type WorkflowBackoff = 'constant' | 'linear' | 'exponential';13411 export type WorkflowStepSensitivity = 'output';13412 export type WorkflowStepConfig = {13413 retries?: {13414 limit: number;13415 delay: WorkflowDelayDuration | number | WorkflowDelayFunction;13416 backoff?: WorkflowBackoff;13417 };13418 timeout?: WorkflowTimeoutDuration | number;13419 sensitive?: WorkflowStepSensitivity;13420 };13421 // Internal discriminators used only for `WorkflowStep.do` overload13422 // resolution. They mirror `WorkflowStepConfig` but pin `retries.delay` to a13423 // single kind so the callback context can be narrowed based on the shape of13424 // the config argument (rather than on an inferred type parameter, which is13425 // lost when the caller supplies an explicit return-type argument). Not13426 // exported: they must not widen the public type surface.13427 type WorkflowStepConfigWithStaticDelay = Omit<WorkflowStepConfig, 'retries'> & {13428 retries?: {13429 limit: number;13430 delay: WorkflowDelayDuration | number;13431 backoff?: WorkflowBackoff;13432 };13433 };13434 type WorkflowStepConfigWithDelayFunction = Omit<WorkflowStepConfig, 'retries'> & {13435 retries: {13436 limit: number;13437 delay: WorkflowDelayFunction;13438 backoff?: WorkflowBackoff;13439 };13440 };13441 export type WorkflowStepRollbackConfig = Pick<WorkflowStepConfig, 'retries' | 'timeout'>;13442 export type WorkflowCronSchedule = {13443 /** Cron expression that triggered this event. */13444 cron: string;13445 /** Timestamp of the scheduled trigger, in milliseconds since the Unix epoch. */13446 scheduledTime: number;13447 };13448 export type WorkflowEvent<T> = {13449 payload: Readonly<T>;13450 timestamp: Date;13451 instanceId: string;13452 workflowName: string;13453 schedule?: WorkflowCronSchedule;13454 };13455 export type WorkflowStepEvent<T> = {13456 payload: Readonly<T>;13457 timestamp: Date;13458 type: string;13459 sensitive?: WorkflowStepSensitivity;13460 };13461 export type WorkflowStepContext<Delay = WorkflowDelayDuration | number> = {13462 step: {13463 name: string;13464 count: number;13465 };13466 attempt: number;13467 config: {13468 retries?: {13469 limit: number;13470 backoff?: WorkflowBackoff;13471 } & (Delay extends WorkflowDelayFunction ? {} : {13472 delay: WorkflowDelayDuration | number;13473 });13474 timeout?: WorkflowTimeoutDuration | number;13475 sensitive?: WorkflowStepSensitivity;13476 };13477 };13478 // The rollback handler receives the step context, so it mirrors the same13479 // delay discriminant as the step callback: when the step was configured with13480 // a dynamic delay function the resolved `config.retries.delay` is omitted,13481 // otherwise it is present. `Delay` is threaded from the `WorkflowStep.do`13482 // overload that matched the step config.13483 export type WorkflowRollbackContext<T = unknown, Delay = WorkflowDelayDuration | number> = {13484 ctx: WorkflowStepContext<Delay>;13485 error: Error;13486 output: T | undefined;13487 /** @deprecated Use `ctx.step.name` and `ctx.step.count` instead. */13488 stepName: string;13489 };13490 export type WorkflowRollbackHandler<T = unknown, Delay = WorkflowDelayDuration | number> = (ctx: WorkflowRollbackContext<T, Delay>) => Promise<void>;13491 export type WorkflowStepRollbackOptions<T = unknown, Delay = WorkflowDelayDuration | number> = {13492 rollback: WorkflowRollbackHandler<T, Delay>;13493 rollbackConfig?: WorkflowStepRollbackConfig;13494 };13495 export abstract class WorkflowStep {13496 do<T extends Rpc.Serializable<T>>(name: string, callback: (ctx: WorkflowStepContext) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T>): Promise<T>;13497 // The config overloads discriminate on the shape of `config.retries.delay`13498 // so the callback context reflects whether the resolved delay is present13499 // (static delay) or omitted (dynamic delay function). Each has a single13500 // type parameter, so an explicit return-type argument (`do<T>(...)`) still13501 // resolves here. ORDERING IS LOAD-BEARING: the broad `WorkflowStepConfig`13502 // fallback MUST remain last, otherwise it shadows the discriminating13503 // overloads and narrowing is silently lost.13504 do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfigWithDelayFunction, callback: (ctx: WorkflowStepContext<WorkflowDelayFunction>) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T, WorkflowDelayFunction>): Promise<T>;13505 do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfigWithStaticDelay, callback: (ctx: WorkflowStepContext<WorkflowDelayDuration | number>) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T, WorkflowDelayDuration | number>): Promise<T>;13506 do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfig, callback: (ctx: WorkflowStepContext) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T>): Promise<T>;13507 sleep: (name: string, duration: WorkflowSleepDuration) => Promise<void>;13508 sleepUntil: (name: string, timestamp: Date | number) => Promise<void>;13509 waitForEvent<T extends Rpc.Serializable<T>>(name: string, options: {13510 type: string;13511 timeout?: WorkflowTimeoutDuration | number;13512 }): Promise<WorkflowStepEvent<T>>;13513 }13514 export type WorkflowInstanceStatus = 'queued' | 'running' | 'paused' | 'errored' | 'terminated' | 'complete' | 'waiting' | 'waitingForPause' | 'unknown';13515 export abstract class WorkflowEntrypoint<Env = unknown, T extends Rpc.Serializable<T> | unknown = unknown> implements Rpc.WorkflowEntrypointBranded {13516 [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never;13517 protected ctx: ExecutionContext;13518 protected env: Env;13519 constructor(ctx: ExecutionContext, env: Env);13520 run(event: Readonly<WorkflowEvent<T>>, step: WorkflowStep): Promise<unknown>;13521 }13522 export function waitUntil(promise: Promise<unknown>): void;13523 export function withEnv(newEnv: unknown, fn: () => unknown): unknown;13524 export function withExports(newExports: unknown, fn: () => unknown): unknown;13525 export function withEnvAndExports(newEnv: unknown, newExports: unknown, fn: () => unknown): unknown;13526 export const env: Cloudflare.Env;13527 export const exports: Cloudflare.Exports;13528 export const cache: CacheContext;13529 export const tracing: Tracing;13530}13531declare module 'cloudflare:workers' {13532 export = CloudflareWorkersModule;13533}13534interface SecretsStoreSecret {13535 /**13536 * Get a secret from the Secrets Store, returning a string of the secret value13537 * if it exists, or throws an error if it does not exist13538 */13539 get(): Promise<string>;13540}13541declare module "cloudflare:sockets" {13542 function _connect(address: string | SocketAddress, options?: SocketOptions): Socket;13543 export { _connect as connect };13544}13545/**13546 * Binding entrypoint for Cloudflare Stream.13547 *13548 * Usage:13549 * - Binding-level operations:13550 * `await env.STREAM.videos.upload`13551 * `await env.STREAM.videos.createDirectUpload`13552 * `await env.STREAM.videos.*`13553 * `await env.STREAM.watermarks.*`13554 * - Per-video operations:13555 * `await env.STREAM.video(id).downloads.*`13556 * `await env.STREAM.video(id).captions.*`13557 *13558 * Example usage:13559 * ```ts13560 * await env.STREAM.video(id).downloads.generate();13561 *13562 * const video = env.STREAM.video(id)13563 * const captions = video.captions.list();13564 * const videoDetails = video.details()13565 * ```13566 */13567interface StreamBinding {13568 /**13569 * Returns a handle scoped to a single video for per-video operations.13570 * @param id The unique identifier for the video.13571 * @returns A handle for per-video operations.13572 */13573 video(id: string): StreamVideoHandle;13574 /**13575 * Uploads a new video from a provided URL.13576 * @param url The URL to upload from.13577 * @param params Optional upload parameters.13578 * @returns The uploaded video details.13579 * @throws {BadRequestError} if the upload parameter is invalid or the URL is invalid13580 * @throws {QuotaReachedError} if the account storage capacity is exceeded13581 * @throws {MaxFileSizeError} if the file size is too large13582 * @throws {RateLimitedError} if the server received too many requests13583 * @throws {AlreadyUploadedError} if a video was already uploaded to this URL13584 * @throws {InternalError} if an unexpected error occurs13585 */13586 upload(url: string, params?: StreamUrlUploadParams): Promise<StreamVideo>;13587 /**13588 * Creates a direct upload that allows video uploads without an API key.13589 * @param params Parameters for the direct upload13590 * @returns The direct upload details.13591 * @throws {BadRequestError} if the parameters are invalid13592 * @throws {RateLimitedError} if the server received too many requests13593 * @throws {InternalError} if an unexpected error occurs13594 */13595 createDirectUpload(params: StreamDirectUploadCreateParams): Promise<StreamDirectUpload>;13596 videos: StreamVideos;13597 watermarks: StreamWatermarks;13598}13599/**13600 * Handle for operations scoped to a single Stream video.13601 */13602interface StreamVideoHandle {13603 /**13604 * The unique identifier for the video.13605 */13606 id: string;13607 /**13608 * Get a full videos details13609 * @returns The full video details.13610 * @throws {NotFoundError} if the video is not found13611 * @throws {InternalError} if an unexpected error occurs13612 */13613 details(): Promise<StreamVideo>;13614 /**13615 * Update details for a single video.13616 * @param params The fields to update for the video.13617 * @returns The updated video details.13618 * @throws {NotFoundError} if the video is not found13619 * @throws {BadRequestError} if the parameters are invalid13620 * @throws {InternalError} if an unexpected error occurs13621 */13622 update(params: StreamUpdateVideoParams): Promise<StreamVideo>;13623 /**13624 * Deletes a video and its copies from Cloudflare Stream.13625 * @returns A promise that resolves when deletion completes.13626 * @throws {NotFoundError} if the video is not found13627 * @throws {InternalError} if an unexpected error occurs13628 */13629 delete(): Promise<void>;13630 /**13631 * Creates a signed URL token for a video.13632 * @returns The signed token that was created.13633 * @throws {InternalError} if the signing key cannot be retrieved or the token cannot be signed13634 */13635 generateToken(): Promise<string>;13636 downloads: StreamScopedDownloads;13637 captions: StreamScopedCaptions;13638}13639interface StreamVideo {13640 /**13641 * The unique identifier for the video.13642 */13643 id: string;13644 /**13645 * A user-defined identifier for the media creator.13646 */13647 creator: string | null;13648 /**13649 * The thumbnail URL for the video.13650 */13651 thumbnail: string;13652 /**13653 * The thumbnail timestamp percentage.13654 */13655 thumbnailTimestampPct: number;13656 /**13657 * Indicates whether the video is ready to stream.13658 */13659 readyToStream: boolean;13660 /**13661 * The date and time the video became ready to stream.13662 */13663 readyToStreamAt: string | null;13664 /**13665 * Processing status information.13666 */13667 status: StreamVideoStatus;13668 /**13669 * A user modifiable key-value store.13670 */13671 meta: Record<string, string>;13672 /**13673 * The date and time the video was created.13674 */13675 created: string;13676 /**13677 * The date and time the video was last modified.13678 */13679 modified: string;13680 /**13681 * The date and time at which the video will be deleted.13682 */13683 scheduledDeletion: string | null;13684 /**13685 * The size of the video in bytes.13686 */13687 size: number;13688 /**13689 * The preview URL for the video.13690 */13691 preview?: string;13692 /**13693 * Origins allowed to display the video.13694 */13695 allowedOrigins: Array<string>;13696 /**13697 * Indicates whether signed URLs are required.13698 */13699 requireSignedURLs: boolean | null;13700 /**13701 * The date and time the video was uploaded.13702 */13703 uploaded: string | null;13704 /**13705 * The date and time when the upload URL expires.13706 */13707 uploadExpiry: string | null;13708 /**13709 * The maximum size in bytes for direct uploads.13710 */13711 maxSizeBytes: number | null;13712 /**13713 * The maximum duration in seconds for direct uploads.13714 */13715 maxDurationSeconds: number | null;13716 /**13717 * The video duration in seconds. -1 indicates unknown.13718 */13719 duration: number;13720 /**13721 * Input metadata for the original upload.13722 */13723 input: StreamVideoInput;13724 /**13725 * Playback URLs for the video.13726 */13727 hlsPlaybackUrl: string;13728 dashPlaybackUrl: string;13729 /**13730 * The watermark applied to the video, if any.13731 */13732 watermark: StreamWatermark | null;13733 /**13734 * The live input id associated with the video, if any.13735 */13736 liveInputId?: string | null;13737 /**13738 * The source video id if this is a clip.13739 */13740 clippedFromId: string | null;13741 /**13742 * Public details associated with the video.13743 */13744 publicDetails: StreamPublicDetails | null;13745}13746type StreamVideoStatus = {13747 /**13748 * The current processing state.13749 */13750 state: string;13751 /**13752 * The current processing step.13753 */13754 step?: string;13755 /**13756 * The percent complete as a string.13757 */13758 pctComplete?: string;13759 /**13760 * An error reason code, if applicable.13761 */13762 errorReasonCode: string;13763 /**13764 * An error reason text, if applicable.13765 */13766 errorReasonText: string;13767};13768type StreamVideoInput = {13769 /**13770 * The input width in pixels.13771 */13772 width: number;13773 /**13774 * The input height in pixels.13775 */13776 height: number;13777};13778type StreamPublicDetails = {13779 /**13780 * The public title for the video.13781 */13782 title: string | null;13783 /**13784 * The public share link.13785 */13786 share_link: string | null;13787 /**13788 * The public channel link.13789 */13790 channel_link: string | null;13791 /**13792 * The public logo URL.13793 */13794 logo: string | null;13795};13796type StreamDirectUpload = {13797 /**13798 * The URL an unauthenticated upload can use for a single multipart request.13799 */13800 uploadURL: string;13801 /**13802 * A Cloudflare-generated unique identifier for a media item.13803 */13804 id: string;13805 /**13806 * The watermark profile applied to the upload.13807 */13808 watermark: StreamWatermark | null;13809 /**13810 * The scheduled deletion time, if any.13811 */13812 scheduledDeletion: string | null;13813};13814type StreamDirectUploadCreateParams = {13815 /**13816 * The maximum duration in seconds for a video upload.13817 */13818 maxDurationSeconds: number;13819 /**13820 * The date and time after upload when videos will not be accepted.13821 */13822 expiry?: string;13823 /**13824 * A user-defined identifier for the media creator.13825 */13826 creator?: string;13827 /**13828 * A user modifiable key-value store used to reference other systems of record for13829 * managing videos.13830 */13831 meta?: Record<string, string>;13832 /**13833 * Lists the origins allowed to display the video.13834 */13835 allowedOrigins?: Array<string>;13836 /**13837 * Indicates whether the video can be accessed using the id. When set to `true`,13838 * a signed token must be generated with a signing key to view the video.13839 */13840 requireSignedURLs?: boolean;13841 /**13842 * The thumbnail timestamp percentage.13843 */13844 thumbnailTimestampPct?: number;13845 /**13846 * The date and time at which the video will be deleted. Include `null` to remove13847 * a scheduled deletion.13848 */13849 scheduledDeletion?: string | null;13850 /**13851 * The watermark profile to apply.13852 */13853 watermark?: StreamDirectUploadWatermark;13854};13855type StreamDirectUploadWatermark = {13856 /**13857 * The unique identifier for the watermark profile.13858 */13859 id: string;13860};13861type StreamUrlUploadParams = {13862 /**13863 * Lists the origins allowed to display the video. Enter allowed origin13864 * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the13865 * video to be viewed on any origin.13866 */13867 allowedOrigins?: Array<string>;13868 /**13869 * A user-defined identifier for the media creator.13870 */13871 creator?: string;13872 /**13873 * A user modifiable key-value store used to reference other systems of13874 * record for managing videos.13875 */13876 meta?: Record<string, string>;13877 /**13878 * Indicates whether the video can be a accessed using the id. When13879 * set to `true`, a signed token must be generated with a signing key to view the13880 * video.13881 */13882 requireSignedURLs?: boolean;13883 /**13884 * Indicates the date and time at which the video will be deleted. Omit13885 * the field to indicate no change, or include with a `null` value to remove an13886 * existing scheduled deletion. If specified, must be at least 30 days from upload13887 * time.13888 */13889 scheduledDeletion?: string | null;13890 /**13891 * The timestamp for a thumbnail image calculated as a percentage value13892 * of the video's duration. To convert from a second-wise timestamp to a13893 * percentage, divide the desired timestamp by the total duration of the video. If13894 * this value is not set, the default thumbnail image is taken from 0s of the13895 * video.13896 */13897 thumbnailTimestampPct?: number;13898 /**13899 * The identifier for the watermark profile13900 */13901 watermarkId?: string;13902};13903interface StreamScopedCaptions {13904 /**13905 * Uploads the caption or subtitle file to the endpoint for a specific BCP47 language.13906 * One caption or subtitle file per language is allowed.13907 * @param language The BCP 47 language tag for the caption or subtitle.13908 * @param input The caption or subtitle stream to upload.13909 * @returns The created caption entry.13910 * @throws {NotFoundError} if the video is not found13911 * @throws {BadRequestError} if the language or file is invalid13912 * @throws {InternalError} if an unexpected error occurs13913 */13914 upload(language: string, input: ReadableStream): Promise<StreamCaption>;13915 /**13916 * Generate captions or subtitles for the provided language via AI.13917 * @param language The BCP 47 language tag to generate.13918 * @returns The generated caption entry.13919 * @throws {NotFoundError} if the video is not found13920 * @throws {BadRequestError} if the language is invalid13921 * @throws {StreamError} if a generated caption already exists13922 * @throws {StreamError} if the video duration is too long13923 * @throws {StreamError} if the video is missing audio13924 * @throws {StreamError} if the requested language is not supported13925 * @throws {InternalError} if an unexpected error occurs13926 */13927 generate(language: string): Promise<StreamCaption>;13928 /**13929 * Lists the captions or subtitles.13930 * Use the language parameter to filter by a specific language.13931 * @param language The optional BCP 47 language tag to filter by.13932 * @returns The list of captions or subtitles.13933 * @throws {NotFoundError} if the video or caption is not found13934 * @throws {InternalError} if an unexpected error occurs13935 */13936 list(language?: string): Promise<StreamCaption[]>;13937 /**13938 * Removes the captions or subtitles from a video.13939 * @param language The BCP 47 language tag to remove.13940 * @returns A promise that resolves when deletion completes.13941 * @throws {NotFoundError} if the video or caption is not found13942 * @throws {InternalError} if an unexpected error occurs13943 */13944 delete(language: string): Promise<void>;13945}13946interface StreamScopedDownloads {13947 /**13948 * Generates a download for a video when a video is ready to view. Available13949 * types are `default` and `audio`. Defaults to `default` when omitted.13950 * @param downloadType The download type to create.13951 * @returns The current downloads for the video.13952 * @throws {NotFoundError} if the video is not found13953 * @throws {BadRequestError} if the download type is invalid13954 * @throws {StreamError} if the video duration is too long to generate a download13955 * @throws {StreamError} if the video is not ready to stream13956 * @throws {InternalError} if an unexpected error occurs13957 */13958 generate(downloadType?: StreamDownloadType): Promise<StreamDownloadGetResponse>;13959 /**13960 * Lists the downloads created for a video.13961 * @returns The current downloads for the video.13962 * @throws {NotFoundError} if the video or downloads are not found13963 * @throws {InternalError} if an unexpected error occurs13964 */13965 get(): Promise<StreamDownloadGetResponse>;13966 /**13967 * Delete the downloads for a video. Available types are `default` and `audio`.13968 * Defaults to `default` when omitted.13969 * @param downloadType The download type to delete.13970 * @returns A promise that resolves when deletion completes.13971 * @throws {NotFoundError} if the video or downloads are not found13972 * @throws {InternalError} if an unexpected error occurs13973 */13974 delete(downloadType?: StreamDownloadType): Promise<void>;13975}13976interface StreamVideos {13977 /**13978 * Lists all videos in a users account.13979 * @returns The list of videos.13980 * @throws {BadRequestError} if the parameters are invalid13981 * @throws {InternalError} if an unexpected error occurs13982 */13983 list(params?: StreamVideosListParams): Promise<StreamVideo[]>;13984}13985interface StreamWatermarks {13986 /**13987 * Generate a new watermark profile13988 * @param input The image stream to upload13989 * @param params The watermark creation parameters.13990 * @returns The created watermark profile.13991 * @throws {BadRequestError} if the parameters are invalid13992 * @throws {InvalidURLError} if the URL is invalid13993 * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached13994 * @throws {InternalError} if an unexpected error occurs13995 */13996 generate(input: ReadableStream, params: StreamWatermarkCreateParams): Promise<StreamWatermark>;13997 /**13998 * Generate a new watermark profile13999 * @param url The image url to upload14000 * @param params The watermark creation parameters.14001 * @returns The created watermark profile.14002 * @throws {BadRequestError} if the parameters are invalid14003 * @throws {InvalidURLError} if the URL is invalid14004 * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached14005 * @throws {InternalError} if an unexpected error occurs14006 */14007 generate(url: string, params: StreamWatermarkCreateParams): Promise<StreamWatermark>;14008 /**14009 * Lists all watermark profiles for an account.14010 * @returns The list of watermark profiles.14011 * @throws {InternalError} if an unexpected error occurs14012 */14013 list(): Promise<StreamWatermark[]>;14014 /**14015 * Retrieves details for a single watermark profile.14016 * @param watermarkId The watermark profile identifier.14017 * @returns The watermark profile details.14018 * @throws {NotFoundError} if the watermark is not found14019 * @throws {InternalError} if an unexpected error occurs14020 */14021 get(watermarkId: string): Promise<StreamWatermark>;14022 /**14023 * Deletes a watermark profile.14024 * @param watermarkId The watermark profile identifier.14025 * @returns A promise that resolves when deletion completes.14026 * @throws {NotFoundError} if the watermark is not found14027 * @throws {InternalError} if an unexpected error occurs14028 */14029 delete(watermarkId: string): Promise<void>;14030}14031type StreamUpdateVideoParams = {14032 /**14033 * Lists the origins allowed to display the video. Enter allowed origin14034 * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the14035 * video to be viewed on any origin.14036 */14037 allowedOrigins?: Array<string>;14038 /**14039 * A user-defined identifier for the media creator.14040 */14041 creator?: string;14042 /**14043 * The maximum duration in seconds for a video upload. Can be set for a14044 * video that is not yet uploaded to limit its duration. Uploads that exceed the14045 * specified duration will fail during processing. A value of `-1` means the value14046 * is unknown.14047 */14048 maxDurationSeconds?: number;14049 /**14050 * A user modifiable key-value store used to reference other systems of14051 * record for managing videos.14052 */14053 meta?: Record<string, string>;14054 /**14055 * Indicates whether the video can be a accessed using the id. When14056 * set to `true`, a signed token must be generated with a signing key to view the14057 * video.14058 */14059 requireSignedURLs?: boolean;14060 /**14061 * Indicates the date and time at which the video will be deleted. Omit14062 * the field to indicate no change, or include with a `null` value to remove an14063 * existing scheduled deletion. If specified, must be at least 30 days from upload14064 * time.14065 */14066 scheduledDeletion?: string | null;14067 /**14068 * The timestamp for a thumbnail image calculated as a percentage value14069 * of the video's duration. To convert from a second-wise timestamp to a14070 * percentage, divide the desired timestamp by the total duration of the video. If14071 * this value is not set, the default thumbnail image is taken from 0s of the14072 * video.14073 */14074 thumbnailTimestampPct?: number;14075};14076type StreamCaption = {14077 /**14078 * Whether the caption was generated via AI.14079 */14080 generated?: boolean;14081 /**14082 * The language label displayed in the native language to users.14083 */14084 label: string;14085 /**14086 * The language tag in BCP 47 format.14087 */14088 language: string;14089 /**14090 * The status of a generated caption.14091 */14092 status?: 'ready' | 'inprogress' | 'error';14093};14094type StreamDownloadStatus = 'ready' | 'inprogress' | 'error';14095type StreamDownloadType = 'default' | 'audio';14096type StreamDownload = {14097 /**14098 * Indicates the progress as a percentage between 0 and 100.14099 */14100 percentComplete: number;14101 /**14102 * The status of a generated download.14103 */14104 status: StreamDownloadStatus;14105 /**14106 * The URL to access the generated download.14107 */14108 url?: string;14109};14110/**14111 * An object with download type keys. Each key is optional and only present if that14112 * download type has been created.14113 */14114type StreamDownloadGetResponse = {14115 /**14116 * The audio-only download. Only present if this download type has been created.14117 */14118 audio?: StreamDownload;14119 /**14120 * The default video download. Only present if this download type has been created.14121 */14122 default?: StreamDownload;14123};14124type StreamWatermarkPosition = 'upperRight' | 'upperLeft' | 'lowerLeft' | 'lowerRight' | 'center';14125type StreamWatermark = {14126 /**14127 * The unique identifier for a watermark profile.14128 */14129 id: string;14130 /**14131 * The size of the image in bytes.14132 */14133 size: number;14134 /**14135 * The height of the image in pixels.14136 */14137 height: number;14138 /**14139 * The width of the image in pixels.14140 */14141 width: number;14142 /**14143 * The date and a time a watermark profile was created.14144 */14145 created: string;14146 /**14147 * The source URL for a downloaded image. If the watermark profile was created via14148 * direct upload, this field is null.14149 */14150 downloadedFrom: string | null;14151 /**14152 * A short description of the watermark profile.14153 */14154 name: string;14155 /**14156 * The translucency of the image. A value of `0.0` makes the image completely14157 * transparent, and `1.0` makes the image completely opaque. Note that if the image14158 * is already semi-transparent, setting this to `1.0` will not make the image14159 * completely opaque.14160 */14161 opacity: number;14162 /**14163 * The whitespace between the adjacent edges (determined by position) of the video14164 * and the image. `0.0` indicates no padding, and `1.0` indicates a fully padded14165 * video width or length, as determined by the algorithm.14166 */14167 padding: number;14168 /**14169 * The size of the image relative to the overall size of the video. This parameter14170 * will adapt to horizontal and vertical videos automatically. `0.0` indicates no14171 * scaling (use the size of the image as-is), and `1.0 `fills the entire video.14172 */14173 scale: number;14174 /**14175 * The location of the image. Valid positions are: `upperRight`, `upperLeft`,14176 * `lowerLeft`, `lowerRight`, and `center`. Note that `center` ignores the14177 * `padding` parameter.14178 */14179 position: StreamWatermarkPosition;14180};14181type StreamWatermarkCreateParams = {14182 /**14183 * A short description of the watermark profile.14184 */14185 name?: string;14186 /**14187 * The translucency of the image. A value of `0.0` makes the image completely14188 * transparent, and `1.0` makes the image completely opaque. Note that if the14189 * image is already semi-transparent, setting this to `1.0` will not make the14190 * image completely opaque.14191 */14192 opacity?: number;14193 /**14194 * The whitespace between the adjacent edges (determined by position) of the14195 * video and the image. `0.0` indicates no padding, and `1.0` indicates a fully14196 * padded video width or length, as determined by the algorithm.14197 */14198 padding?: number;14199 /**14200 * The size of the image relative to the overall size of the video. This14201 * parameter will adapt to horizontal and vertical videos automatically. `0.0`14202 * indicates no scaling (use the size of the image as-is), and `1.0 `fills the14203 * entire video.14204 */14205 scale?: number;14206 /**14207 * The location of the image.14208 */14209 position?: StreamWatermarkPosition;14210};14211type StreamVideosListParams = {14212 /**14213 * The maximum number of videos to return.14214 */14215 limit?: number;14216 /**14217 * Return videos created before this timestamp.14218 * (RFC3339/RFC3339Nano)14219 */14220 before?: string;14221 /**14222 * Comparison operator for the `before` field.14223 * @default 'lt'14224 */14225 beforeComp?: StreamPaginationComparison;14226 /**14227 * Return videos created after this timestamp.14228 * (RFC3339/RFC3339Nano)14229 */14230 after?: string;14231 /**14232 * Comparison operator for the `after` field.14233 * @default 'gte'14234 */14235 afterComp?: StreamPaginationComparison;14236};14237type StreamPaginationComparison = 'eq' | 'gt' | 'gte' | 'lt' | 'lte';14238/**14239 * Error object for Stream binding operations.14240 */14241interface StreamError extends Error {14242 readonly code: number;14243 readonly statusCode: number;14244 readonly message: string;14245 readonly stack?: string;14246}14247interface InternalError extends StreamError {14248 name: 'InternalError';14249}14250interface BadRequestError extends StreamError {14251 name: 'BadRequestError';14252}14253interface NotFoundError extends StreamError {14254 name: 'NotFoundError';14255}14256interface ForbiddenError extends StreamError {14257 name: 'ForbiddenError';14258}14259interface RateLimitedError extends StreamError {14260 name: 'RateLimitedError';14261}14262interface QuotaReachedError extends StreamError {14263 name: 'QuotaReachedError';14264}14265interface MaxFileSizeError extends StreamError {14266 name: 'MaxFileSizeError';14267}14268interface InvalidURLError extends StreamError {14269 name: 'InvalidURLError';14270}14271interface AlreadyUploadedError extends StreamError {14272 name: 'AlreadyUploadedError';14273}14274interface TooManyWatermarksError extends StreamError {14275 name: 'TooManyWatermarksError';14276}14277type MarkdownDocument = {14278 name: string;14279 blob: Blob;14280};14281type OutputFormat = 'markdown' | 'text';14282type ConversionResponse = {14283 id: string;14284 name: string;14285 mimeType: string;14286 format: OutputFormat;14287 tokens: number;14288 data: string;14289} | {14290 id: string;14291 name: string;14292 mimeType: string;14293 format: 'error';14294 error: string;14295};14296type ImageConversionOptions = {14297 descriptionLanguage?: 'en' | 'es' | 'fr' | 'it' | 'pt' | 'de';14298};14299type EmbeddedImageConversionOptions = ImageConversionOptions & {14300 convert?: boolean;14301 maxConvertedImages?: number;14302};14303type ConversionOutputOptions = {14304 format?: OutputFormat;14305};14306type ConversionOptions = {14307 output?: ConversionOutputOptions;14308 html?: {14309 images?: EmbeddedImageConversionOptions & {14310 convertOGImage?: boolean;14311 };14312 hostname?: string;14313 cssSelector?: string;14314 };14315 docx?: {14316 images?: EmbeddedImageConversionOptions;14317 };14318 image?: ImageConversionOptions;14319 pdf?: {14320 images?: EmbeddedImageConversionOptions;14321 metadata?: boolean;14322 };14323};14324type ConversionRequestOptions = {14325 gateway?: GatewayOptions;14326 extraHeaders?: object;14327 conversionOptions?: ConversionOptions;14328};14329type SupportedFileFormat = {14330 mimeType: string;14331 extension: string;14332};14333declare abstract class ToMarkdownService {14334 transform(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise<ConversionResponse[]>;14335 transform(files: MarkdownDocument, options?: ConversionRequestOptions): Promise<ConversionResponse>;14336 supported(): Promise<SupportedFileFormat[]>;14337}14338declare namespace TailStream {14339 interface Header {14340 readonly name: string;14341 readonly value: string;14342 }14343 interface FetchEventInfo {14344 readonly type: "fetch";14345 readonly method: string;14346 readonly url: string;14347 readonly cfJson?: object;14348 readonly headers: Header[];14349 }14350 interface JsRpcEventInfo {14351 readonly type: "jsrpc";14352 }14353 interface ScheduledEventInfo {14354 readonly type: "scheduled";14355 readonly scheduledTime: Date;14356 readonly cron: string;14357 }14358 interface AlarmEventInfo {14359 readonly type: "alarm";14360 readonly scheduledTime: Date;14361 }14362 interface QueueEventInfo {14363 readonly type: "queue";14364 readonly queueName: string;14365 readonly batchSize: number;14366 }14367 interface EmailEventInfo {14368 readonly type: "email";14369 readonly mailFrom: string;14370 readonly rcptTo: string;14371 readonly rawSize: number;14372 }14373 interface TraceEventInfo {14374 readonly type: "trace";14375 readonly traces: (string | null)[];14376 }14377 interface HibernatableWebSocketEventInfoMessage {14378 readonly type: "message";14379 }14380 interface HibernatableWebSocketEventInfoError {14381 readonly type: "error";14382 }14383 interface HibernatableWebSocketEventInfoClose {14384 readonly type: "close";14385 readonly code: number;14386 readonly wasClean: boolean;14387 }14388 interface HibernatableWebSocketEventInfo {14389 readonly type: "hibernatableWebSocket";14390 readonly info: HibernatableWebSocketEventInfoClose | HibernatableWebSocketEventInfoError | HibernatableWebSocketEventInfoMessage;14391 }14392 interface CustomEventInfo {14393 readonly type: "custom";14394 }14395 interface FetchResponseInfo {14396 readonly type: "fetch";14397 readonly statusCode: number;14398 }14399 interface ConnectEventInfo {14400 readonly type: "connect";14401 }14402 type EventOutcome = "ok" | "canceled" | "exception" | "unknown" | "killSwitch" | "daemonDown" | "exceededCpu" | "exceededMemory" | "loadShed" | "responseStreamDisconnected" | "scriptNotFound" | "internalError" | "exceededWallTime";14403 interface ScriptVersion {14404 readonly id: string;14405 readonly tag?: string;14406 readonly message?: string;14407 }14408 interface TracePreviewInfo {14409 readonly id: string;14410 readonly slug: string;14411 readonly name: string;14412 }14413 interface Onset {14414 readonly type: "onset";14415 readonly attributes: Attribute[];14416 // id for the span being opened by this Onset event.14417 readonly spanId: string;14418 readonly dispatchNamespace?: string;14419 readonly entrypoint?: string;14420 readonly executionModel: string;14421 readonly durableObjectId?: string;14422 readonly scriptName?: string;14423 readonly scriptTags?: string[];14424 readonly scriptVersion?: ScriptVersion;14425 readonly preview?: TracePreviewInfo;14426 readonly info: FetchEventInfo | ConnectEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | CustomEventInfo;14427 }14428 interface Outcome {14429 readonly type: "outcome";14430 readonly outcome: EventOutcome;14431 readonly cpuTime: number;14432 readonly wallTime: number;14433 }14434 interface SpanOpen {14435 readonly type: "spanOpen";14436 readonly name: string;14437 // id for the span being opened by this SpanOpen event.14438 readonly spanId: string;14439 readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes;14440 }14441 interface SpanClose {14442 readonly type: "spanClose";14443 readonly outcome: EventOutcome;14444 }14445 interface DiagnosticChannelEvent {14446 readonly type: "diagnosticChannel";14447 readonly channel: string;14448 readonly message: any;14449 }14450 interface Exception {14451 readonly type: "exception";14452 readonly name: string;14453 readonly message: string;14454 readonly stack?: string;14455 }14456 interface TailStreamErrorInfo {14457 readonly name: string;14458 readonly message: string;14459 readonly stack?: string;14460 }14461 type Log = {14462 readonly type: "log";14463 readonly level: "debug" | "error" | "info" | "log" | "warn";14464 readonly errorInfo?: readonly (TailStreamErrorInfo | null)[];14465 } & ({14466 readonly message: object;14467 readonly truncated?: false;14468 } | {14469 readonly message: string;14470 readonly truncated: true;14471 });14472 interface DroppedEventsDiagnostic {14473 readonly diagnosticsType: "droppedEvents";14474 readonly count: number;14475 }14476 interface StreamDiagnostic {14477 readonly type: 'streamDiagnostic';14478 // To add new diagnostic types, define a new interface and add it to this union type.14479 readonly diagnostic: DroppedEventsDiagnostic;14480 }14481 // This marks the worker handler return information.14482 // This is separate from Outcome because the worker invocation can live for a long time after14483 // returning. For example - Websockets that return an http upgrade response but then continue14484 // streaming information or SSE http connections.14485 interface Return {14486 readonly type: "return";14487 readonly info?: FetchResponseInfo;14488 }14489 interface Attribute {14490 readonly name: string;14491 readonly value: string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[];14492 }14493 interface Attributes {14494 readonly type: "attributes";14495 readonly info: Attribute[];14496 }14497 type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | StreamDiagnostic | Return | Attributes;14498 // Context in which this trace event lives.14499 interface SpanContext {14500 // Single id for the entire top-level invocation14501 // This should be a new traceId for the first worker stage invoked in the eyeball request and then14502 // same-account service-bindings should reuse the same traceId but cross-account service-bindings14503 // should use a new traceId.14504 readonly traceId: string;14505 // spanId in which this event is handled14506 // for Onset and SpanOpen events this would be the parent span id14507 // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events14508 // For Hibernate and Mark this would be the span under which they were emitted.14509 // spanId is not set ONLY if:14510 // 1. This is an Onset event14511 // 2. We are not inheriting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation)14512 readonly spanId?: string;14513 // W3C trace flags from an upstream traceparent. Absent when no upstream14514 // sampling decision was made.14515 readonly traceFlags?: number;14516 }14517 interface TailEvent<Event extends EventType> {14518 // invocation id of the currently invoked worker stage.14519 // invocation id will always be unique to every Onset event and will be the same until the Outcome event.14520 readonly invocationId: string;14521 // Inherited spanContext for this event.14522 readonly spanContext: SpanContext;14523 readonly timestamp: Date;14524 readonly sequence: number;14525 readonly event: Event;14526 }14527 type TailEventHandler<Event extends EventType = EventType> = (event: TailEvent<Event>) => void | Promise<void>;14528 type TailEventHandlerObject = {14529 outcome?: TailEventHandler<Outcome>;14530 spanOpen?: TailEventHandler<SpanOpen>;14531 spanClose?: TailEventHandler<SpanClose>;14532 diagnosticChannel?: TailEventHandler<DiagnosticChannelEvent>;14533 exception?: TailEventHandler<Exception>;14534 log?: TailEventHandler<Log>;14535 return?: TailEventHandler<Return>;14536 attributes?: TailEventHandler<Attributes>;14537 };14538 type TailEventHandlerType = TailEventHandler | TailEventHandlerObject;14539}14540// Copyright (c) 2022-2023 Cloudflare, Inc.14541// Licensed under the Apache 2.0 license found in the LICENSE file or at:14542// https://opensource.org/licenses/Apache-2.014543/**14544 * Data types supported for holding vector metadata.14545 */14546type VectorizeVectorMetadataValue = string | number | boolean | string[];14547/**14548 * Additional information to associate with a vector.14549 */14550type VectorizeVectorMetadata = VectorizeVectorMetadataValue | Record<string, VectorizeVectorMetadataValue>;14551type VectorFloatArray = Float32Array | Float64Array;14552interface VectorizeError {14553 code?: number;14554 error: string;14555}14556/**14557 * Comparison logic/operation to use for metadata filtering.14558 *14559 * This list is expected to grow as support for more operations are released.14560 */14561type VectorizeVectorMetadataFilterOp = '$eq' | '$ne' | '$lt' | '$lte' | '$gt' | '$gte';14562type VectorizeVectorMetadataFilterCollectionOp = '$in' | '$nin';14563/**14564 * Filter criteria for vector metadata used to limit the retrieved query result set.14565 */14566type VectorizeVectorMetadataFilter = {14567 [field: string]: Exclude<VectorizeVectorMetadataValue, string[]> | null | {14568 [Op in VectorizeVectorMetadataFilterOp]?: Exclude<VectorizeVectorMetadataValue, string[]> | null;14569 } | {14570 [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude<VectorizeVectorMetadataValue, string[]>[];14571 };14572};14573/**14574 * Supported distance metrics for an index.14575 * Distance metrics determine how other "similar" vectors are determined.14576 */14577type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product";14578/**14579 * Metadata return levels for a Vectorize query.14580 *14581 * Default to "none".14582 *14583 * @property all Full metadata for the vector return set, including all fields (including those un-indexed) without truncation. This is a more expensive retrieval, as it requires additional fetching & reading of un-indexed data.14584 * @property indexed Return all metadata fields configured for indexing in the vector return set. This level of retrieval is "free" in that no additional overhead is incurred returning this data. However, note that indexed metadata is subject to truncation (especially for larger strings).14585 * @property none No indexed metadata will be returned.14586 */14587type VectorizeMetadataRetrievalLevel = "all" | "indexed" | "none";14588interface VectorizeQueryOptions {14589 topK?: number;14590 namespace?: string;14591 returnValues?: boolean;14592 returnMetadata?: boolean | VectorizeMetadataRetrievalLevel;14593 filter?: VectorizeVectorMetadataFilter;14594}14595/**14596 * Information about the configuration of an index.14597 */14598type VectorizeIndexConfig = {14599 dimensions: number;14600 metric: VectorizeDistanceMetric;14601} | {14602 preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity14603};14604/**14605 * Metadata about an existing index.14606 *14607 * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.14608 * See {@link VectorizeIndexInfo} for its post-beta equivalent.14609 */14610interface VectorizeIndexDetails {14611 /** The unique ID of the index */14612 readonly id: string;14613 /** The name of the index. */14614 name: string;14615 /** (optional) A human readable description for the index. */14616 description?: string;14617 /** The index configuration, including the dimension size and distance metric. */14618 config: VectorizeIndexConfig;14619 /** The number of records containing vectors within the index. */14620 vectorsCount: number;14621}14622/**14623 * Metadata about an existing index.14624 */14625interface VectorizeIndexInfo {14626 /** The number of records containing vectors within the index. */14627 vectorCount: number;14628 /** Number of dimensions the index has been configured for. */14629 dimensions: number;14630 /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */14631 processedUpToDatetime: number;14632 /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */14633 processedUpToMutation: number;14634}14635/**14636 * Represents a single vector value set along with its associated metadata.14637 */14638interface VectorizeVector {14639 /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */14640 id: string;14641 /** The vector values */14642 values: VectorFloatArray | number[];14643 /** The namespace this vector belongs to. */14644 namespace?: string;14645 /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */14646 metadata?: Record<string, VectorizeVectorMetadata>;14647}14648/**14649 * Represents a matched vector for a query along with its score and (if specified) the matching vector information.14650 */14651type VectorizeMatch = Pick<Partial<VectorizeVector>, "values"> & Omit<VectorizeVector, "values"> & {14652 /** The score or rank for similarity, when returned as a result */14653 score: number;14654};14655/**14656 * A set of matching {@link VectorizeMatch} for a particular query.14657 */14658interface VectorizeMatches {14659 matches: VectorizeMatch[];14660 count: number;14661}14662/**14663 * Results of an operation that performed a mutation on a set of vectors.14664 * Here, `ids` is a list of vectors that were successfully processed.14665 *14666 * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.14667 * See {@link VectorizeAsyncMutation} for its post-beta equivalent.14668 */14669interface VectorizeVectorMutation {14670 /* List of ids of vectors that were successfully processed. */14671 ids: string[];14672 /* Total count of the number of processed vectors. */14673 count: number;14674}14675/**14676 * Result type indicating a mutation on the Vectorize Index.14677 * Actual mutations are processed async where the `mutationId` is the unique identifier for the operation.14678 */14679interface VectorizeAsyncMutation {14680 /** The unique identifier for the async mutation operation containing the changeset. */14681 mutationId: string;14682}14683/**14684 * A Vectorize Vector Search Index for querying vectors/embeddings.14685 *14686 * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.14687 * See {@link Vectorize} for its new implementation.14688 */14689declare abstract class VectorizeIndex {14690 /**14691 * Get information about the currently bound index.14692 * @returns A promise that resolves with information about the current index.14693 */14694 public describe(): Promise<VectorizeIndexDetails>;14695 /**14696 * Use the provided vector to perform a similarity search across the index.14697 * @param vector Input vector that will be used to drive the similarity search.14698 * @param options Configuration options to massage the returned data.14699 * @returns A promise that resolves with matched and scored vectors.14700 */14701 public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise<VectorizeMatches>;14702 /**14703 * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown.14704 * @param vectors List of vectors that will be inserted.14705 * @returns A promise that resolves with the ids & count of records that were successfully processed.14706 */14707 public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>;14708 /**14709 * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values.14710 * @param vectors List of vectors that will be upserted.14711 * @returns A promise that resolves with the ids & count of records that were successfully processed.14712 */14713 public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>;14714 /**14715 * Delete a list of vectors with a matching id.14716 * @param ids List of vector ids that should be deleted.14717 * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted).14718 */14719 public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>;14720 /**14721 * Get a list of vectors with a matching id.14722 * @param ids List of vector ids that should be returned.14723 * @returns A promise that resolves with the raw unscored vectors matching the id set.14724 */14725 public getByIds(ids: string[]): Promise<VectorizeVector[]>;14726}14727/**14728 * A Vectorize Vector Search Index for querying vectors/embeddings.14729 *14730 * Mutations in this version are async, returning a mutation id.14731 */14732declare abstract class Vectorize {14733 /**14734 * Get information about the currently bound index.14735 * @returns A promise that resolves with information about the current index.14736 */14737 public describe(): Promise<VectorizeIndexInfo>;14738 /**14739 * Use the provided vector to perform a similarity search across the index.14740 * @param vector Input vector that will be used to drive the similarity search.14741 * @param options Configuration options to massage the returned data.14742 * @returns A promise that resolves with matched and scored vectors.14743 */14744 public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise<VectorizeMatches>;14745 /**14746 * Use the provided vector-id to perform a similarity search across the index.14747 * @param vectorId Id for a vector in the index against which the index should be queried.14748 * @param options Configuration options to massage the returned data.14749 * @returns A promise that resolves with matched and scored vectors.14750 */14751 public queryById(vectorId: string, options?: VectorizeQueryOptions): Promise<VectorizeMatches>;14752 /**14753 * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown.14754 * @param vectors List of vectors that will be inserted.14755 * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset.14756 */14757 public insert(vectors: VectorizeVector[]): Promise<VectorizeAsyncMutation>;14758 /**14759 * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values.14760 * @param vectors List of vectors that will be upserted.14761 * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset.14762 */14763 public upsert(vectors: VectorizeVector[]): Promise<VectorizeAsyncMutation>;14764 /**14765 * Delete a list of vectors with a matching id.14766 * @param ids List of vector ids that should be deleted.14767 * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset.14768 */14769 public deleteByIds(ids: string[]): Promise<VectorizeAsyncMutation>;14770 /**14771 * Get a list of vectors with a matching id.14772 * @param ids List of vector ids that should be returned.14773 * @returns A promise that resolves with the raw unscored vectors matching the id set.14774 */14775 public getByIds(ids: string[]): Promise<VectorizeVector[]>;14776}14777/**14778 * The interface for "version_metadata" binding14779 * providing metadata about the Worker Version using this binding.14780 */14781type WorkerVersionMetadata = {14782 /** The ID of the Worker Version using this binding */14783 id: string;14784 /** The tag of the Worker Version using this binding */14785 tag: string;14786 /** The timestamp of when the Worker Version was uploaded */14787 timestamp: string;14788};14789// ============ Web Search Request Types ============14790/**14791 * Options for a Web Search query.14792 */14793type WebSearchSearchOptions = {14794 /** The search query. */14795 query: string;14796 /**14797 * Maximum number of results to return. Defaults to 10, capped at 20.14798 * The actual count may be lower if fewer matches exist.14799 */14800 limit?: number;14801};14802// ============ Web Search Response Types ============14803/**14804 * A single Web Search result.14805 *14806 * Web Search is discovery-only -- results carry catalog metadata about a page14807 * but never the page body. To read a result's content the caller invokes the14808 * global `fetch()` API against the result's `url`, at which point the14809 * destination's own access controls apply (including Cloudflare Pay-per-Crawl).14810 */14811type WebSearchResult = {14812 /** Canonical URL. */14813 url: string;14814 /** Page title. */14815 title: string;14816 /** Page-level description. May be absent. */14817 description?: string;14818 /**14819 * Last-modified date for the page, when known. Naive (no timezone)14820 * ISO-8601 datetime, e.g. `"2025-11-30T04:39:48"`.14821 */14822 lastModifiedDate?: string;14823 /**14824 * Page meta image URL (typically the `og:image`). May be absent.14825 */14826 imageUrl?: string;14827 /** Optional favicon URL for UI hints. */14828 faviconUrl?: string;14829};14830/**14831 * Per-response metadata for a Web Search query. Carries operational14832 * fields useful for support and debugging.14833 */14834type WebSearchResponseMetadata = {14835 /** The query that was executed. */14836 query: string;14837 /** Opaque request identifier used for support and debugging. */14838 requestId: string;14839 /** End-to-end latency for this search request, in milliseconds. */14840 latencyMs: number;14841};14842/**14843 * Response from a Web Search query.14844 */14845type WebSearchSearchResponse = {14846 items: WebSearchResult[];14847 metadata: WebSearchResponseMetadata;14848};14849// ============ Web Search Binding Class ============14850/**14851 * Cloudflare Web Search binding.14852 *14853 * Discovery-only primitive for agents and Workers. Returns URLs and catalog14854 * metadata for a query; never returns page content or excerpts. To read a14855 * result's body, fetch the URL with the global `fetch()` API.14856 *14857 * Declared in wrangler with a single object (there is exactly one corpus, the14858 * public web, so there is no name, namespace, or instance to specify):14859 *14860 * ```jsonc14861 * { "web_search": { "binding": "WEBSEARCH" } }14862 * ```14863 *14864 * @example14865 * ```ts14866 * const { items, metadata } = await env.WEBSEARCH.search({14867 * query: "Cloudflare Workers",14868 * });14869 *14870 * const top = items[0];14871 * console.log(top.url, top.title, metadata.latencyMs);14872 *14873 * // Read content yourself; pay-per-crawl and other publisher14874 * // controls apply at the fetch site, not at search time.14875 * const page = await fetch(top.url);14876 * ```14877 */14878declare abstract class WebSearch {14879 /**14880 * Run a Web Search query.14881 * @param options Search options. Only `query` is required.14882 * @returns The matching results plus per-response metadata.14883 */14884 search(options: WebSearchSearchOptions): Promise<WebSearchSearchResponse>;14885}14886interface DynamicDispatchLimits {14887 /**14888 * Limit CPU time in milliseconds.14889 */14890 cpuMs?: number;14891 /**14892 * Limit number of subrequests.14893 */14894 subRequests?: number;14895}14896interface DynamicDispatchOptions {14897 /**14898 * Limit resources of invoked Worker script.14899 */14900 limits?: DynamicDispatchLimits;14901 /**14902 * Arguments for outbound Worker script, if configured.14903 */14904 outbound?: {14905 [key: string]: any;14906 };14907}14908interface DispatchNamespace {14909 /**14910 * @param name Name of the Worker script.14911 * @param args Arguments to Worker script.14912 * @param options Options for Dynamic Dispatch invocation.14913 * @returns A Fetcher object that allows you to send requests to the Worker script.14914 * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown.14915 */14916 get(name: string, args?: {14917 [key: string]: any;14918 }, options?: DynamicDispatchOptions): Fetcher;14919}14920declare module 'cloudflare:workflows' {14921 /**14922 * NonRetryableError allows for a user to throw a fatal error14923 * that makes a Workflow instance fail immediately without triggering a retry14924 */14925 export class NonRetryableError extends Error {14926 public constructor(message: string, name?: string);14927 }14928}14929declare abstract class Workflow<PARAMS = unknown> {14930 /**14931 * Get a handle to an existing instance of the Workflow.14932 * @param id Id for the instance of this Workflow14933 * @returns A promise that resolves with a handle for the Instance14934 */14935 public get(id: string): Promise<WorkflowInstance>;14936 /**14937 * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown.14938 * @param options Options when creating an instance including id and params14939 * @returns A promise that resolves with a handle for the Instance14940 */14941 public create(options?: WorkflowInstanceCreateOptions<PARAMS>): Promise<WorkflowInstance>;14942 /**14943 * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown.14944 * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached.14945 * @param batch List of Options when creating an instance including name and params14946 * @returns A promise that resolves with a list of handles for the created instances.14947 */14948 public createBatch(batch: WorkflowInstanceCreateOptions<PARAMS>[]): Promise<WorkflowInstance[]>;14949 /**14950 * Delete a batch of Workflow instances and their stored state.14951 * `deleteBatch` is limited to 100 instances at a time. Duplicate IDs are deleted once.14952 * The result contains one entry for each input position; IDs that do not exist are returned as per-instance errors.14953 * @param instanceIds IDs of the Workflow instances to delete14954 * @returns A promise that resolves with the successfully deleted instances and any per-instance errors.14955 */14956 public deleteBatch(instanceIds: string[]): Promise<WorkflowBatchDeleteResult>;14957}14958type WorkflowBatchDeleteResult = {14959 deleted: {14960 id: string;14961 }[];14962 errors: {14963 id: string;14964 code: number;14965 message: string;14966 }[];14967};14968type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';14969type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number;14970type WorkflowRetentionDuration = WorkflowSleepDuration;14971/** Geographic regions supported when creating a Workflow instance.14972 * Location hints are best-effort placement preferences. */14973type WorkflowInstanceLocationHint = 'wnam' | 'enam' | 'sam' | 'weur' | 'eeur' | 'apac' | 'apac-ne' | 'apac-se' | 'oc' | 'afr' | 'me';14974interface WorkflowInstanceCreateOptions<PARAMS = unknown> {14975 /**14976 * An id for your Workflow instance. Must be unique within the Workflow.14977 */14978 id?: string;14979 /**14980 * The event payload the Workflow instance is triggered with14981 */14982 params?: PARAMS;14983 /**14984 * The retention policy for Workflow instance.14985 * Defaults to the maximum retention period available for the owner's account.14986 */14987 retention?: {14988 successRetention?: WorkflowRetentionDuration;14989 errorRetention?: WorkflowRetentionDuration;14990 };14991 /** A best-effort geographic placement preference for the Workflow instance.14992 * See `WorkflowInstanceLocationHint` for supported regions. */14993 locationHint?: WorkflowInstanceLocationHint;14994}14995type InstanceStatus = {14996 status: 'queued' // means that instance is waiting to be started (see concurrency limits)14997 | 'running' | 'paused' | 'errored' | 'terminated' // user terminated the instance while it was running14998 | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish14999 | 'waitingForPause' // instance is finishing the current work to pause15000 | 'unknown';15001 error?: {15002 name: string;15003 message: string;15004 };15005 output?: unknown;15006};15007interface WorkflowError {15008 code?: number;15009 message: string;15010}15011interface WorkflowInstanceTerminateOptions {15012 /**15013 * If true, run registered rollback handlers before terminating the instance.15014 * Only steps that registered rollback handlers are rolled back.15015 */15016 rollback?: boolean;15017}15018interface WorkflowInstanceRestartOptions {15019 /**15020 * Restart from a specific step. If omitted, the instance restarts from the beginning.15021 * The step must exist in the instance's execution history.15022 */15023 from?: {15024 /**15025 * The step name as defined in your workflow code.15026 */15027 name: string;15028 /**15029 * 1-indexed occurrence of this step name. Use when the same step name appears multiple times (e.g. in a loop).15030 * @default 115031 */15032 count?: number;15033 /**15034 * Step type filter. Use when different step types share the same name.15035 */15036 type?: 'do' | 'sleep' | 'waitForEvent';15037 };15038}15039declare abstract class WorkflowInstance {15040 public id: string;15041 /**15042 * Pause the instance.15043 */15044 public pause(): Promise<void>;15045 /**15046 * Resume the instance. If it is already running, an error will be thrown.15047 */15048 public resume(): Promise<void>;15049 /**15050 * Terminate the instance. If it is errored, terminated or complete, an error will be thrown.15051 * @param options Options for termination, including whether registered rollback handlers should run.15052 */15053 public terminate(options?: WorkflowInstanceTerminateOptions): Promise<void>;15054 /**15055 * Restart the instance. Optionally restart from a specific step, preserving15056 * cached results for all steps before it.15057 * @param options Options for the restart, including an optional step to restart from.15058 */15059 public restart(options?: WorkflowInstanceRestartOptions): Promise<void>;15060 /**15061 * Delete the instance and its stored state.15062 */15063 public delete(): Promise<void>;15064 /**15065 * Returns the current status of the instance.15066 */15067 public status(): Promise<InstanceStatus>;15068 /**15069 * Send an event to this instance.15070 */15071 public sendEvent({ type, payload, }: {15072 type: string;15073 payload: unknown;15074 }): Promise<void>;15075}