Skip to content
refs
History
16210 lines · 609.1 KBRaw
1/* eslint-disable */
2// Generated by Wrangler by running `wrangler types` (hash: 6d39024096408965119062d8b2f0c689)
3// Runtime types generated with workerd@1.20261001.1 2026-10-02
4interface __BaseEnv_Env {
5 OAUTH_KV: KVNamespace;
6 DB: D1Database;
7 EMAIL: SendEmail;
8 PUSHES: Queue;
9 AGENT_RUNS: Queue;
10 ARTIFACTS: Artifacts;
11 LOGIN_LIMITER: RateLimit;
12 AI: Ai;
13 ADMIN_EMAILS: "thisisamank@gmail.com";
14 EMAIL_FROM: "noreply@useref.dev";
15 PUBLIC_ORIGIN: "https://useref.dev";
16 USER_HUB: DurableObjectNamespace<import("./workers/main").UserHub>;
17 REPO_HUB: DurableObjectNamespace<import("./workers/main").RepoHub>;
18 RUN_HUB: DurableObjectNamespace<import("./workers/main").RunHub>;
19 JOB_RUNNER: DurableObjectNamespace<import("./workers/main").JobRunner>;
20 JOB_SLOTS: DurableObjectNamespace<import("./workers/main").JobSlots>;
21 RUNS: Workflow<Parameters<import("./workers/main").RunPipeline['run']>[0]['payload']>;
22}
23declare namespace Cloudflare {
24 interface GlobalProps {
25 mainModule: typeof import("./workers/main");
26 durableNamespaces: "UserHub" | "RepoHub" | "RunHub" | "JobRunner" | "JobSlots";
27 }
28 interface Env extends __BaseEnv_Env {}
29}
30interface Env extends __BaseEnv_Env {}
31type StringifyValues<EnvType extends Record<string, unknown>> = {
32 [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string;
33};
34declare namespace NodeJS {
35 interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "ADMIN_EMAILS" | "EMAIL_FROM" | "PUBLIC_ORIGIN">> {}
36}
37
38// Begin runtime types
39/*! *****************************************************************************
40Copyright (c) Cloudflare. All rights reserved.
41Copyright (c) Microsoft Corporation. All rights reserved.
42
43Licensed under the Apache License, Version 2.0 (the "License"); you may not use
44this file except in compliance with the License. You may obtain a copy of the
45License at http://www.apache.org/licenses/LICENSE-2.0
46THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
47KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
48WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
49MERCHANTABLITY OR NON-INFRINGEMENT.
50See the Apache Version 2.0 License for specific language governing permissions
51and limitations under the License.
52***************************************************************************** */
53/* eslint-disable */
54// noinspection JSUnusedGlobalSymbols
55declare var onmessage: never;
56/**
57 * 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.
58 *
59 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException)
60 */
61declare class DOMException extends Error {
62 constructor(message?: string, name?: string);
63 /**
64 * The **`message`** read-only property of the DOMException interface returns a string representing a message or description associated with the given error name.
65 *
66 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message)
67 */
68 readonly message: string;
69 /**
70 * The **`name`** read-only property of the DOMException interface returns a string that contains one of the strings associated with an error name.
71 *
72 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name)
73 */
74 readonly name: string;
75 /**
76 * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or 0 if none match.
77 * @deprecated
78 *
79 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code)
80 */
81 readonly code: number;
82 static readonly INDEX_SIZE_ERR: number;
83 static readonly DOMSTRING_SIZE_ERR: number;
84 static readonly HIERARCHY_REQUEST_ERR: number;
85 static readonly WRONG_DOCUMENT_ERR: number;
86 static readonly INVALID_CHARACTER_ERR: number;
87 static readonly NO_DATA_ALLOWED_ERR: number;
88 static readonly NO_MODIFICATION_ALLOWED_ERR: number;
89 static readonly NOT_FOUND_ERR: number;
90 static readonly NOT_SUPPORTED_ERR: number;
91 static readonly INUSE_ATTRIBUTE_ERR: number;
92 static readonly INVALID_STATE_ERR: number;
93 static readonly SYNTAX_ERR: number;
94 static readonly INVALID_MODIFICATION_ERR: number;
95 static readonly NAMESPACE_ERR: number;
96 static readonly INVALID_ACCESS_ERR: number;
97 static readonly VALIDATION_ERR: number;
98 static readonly TYPE_MISMATCH_ERR: number;
99 static readonly SECURITY_ERR: number;
100 static readonly NETWORK_ERR: number;
101 static readonly ABORT_ERR: number;
102 static readonly URL_MISMATCH_ERR: number;
103 static readonly QUOTA_EXCEEDED_ERR: number;
104 static readonly TIMEOUT_ERR: number;
105 static readonly INVALID_NODE_TYPE_ERR: number;
106 static readonly DATA_CLONE_ERR: number;
107 get stack(): any;
108 set stack(value: any);
109}
110type WorkerGlobalScopeEventMap = {
111 fetch: FetchEvent;
112 scheduled: ScheduledEvent;
113 queue: QueueEvent;
114 unhandledrejection: PromiseRejectionEvent;
115 rejectionhandled: PromiseRejectionEvent;
116};
117declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> {
118 EventTarget: typeof EventTarget;
119}
120/* The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). *
121 * The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox).
122 *
123 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console)
124 */
125interface Console {
126 "assert"(condition?: boolean, ...data: any[]): void;
127 /**
128 * The **`console.clear()`** static method clears the console if possible.
129 *
130 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static)
131 */
132 clear(): void;
133 /**
134 * The **`console.count()`** static method logs the number of times that this particular call to count() has been called.
135 *
136 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static)
137 */
138 count(label?: string): void;
139 /**
140 * The **`console.countReset()`** static method resets counter used with console.count().
141 *
142 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static)
143 */
144 countReset(label?: string): void;
145 /**
146 * 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.
147 *
148 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static)
149 */
150 debug(...data: any[]): void;
151 /**
152 * 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.
153 *
154 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static)
155 */
156 dir(item?: any, options?: any): void;
157 /**
158 * 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.
159 *
160 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static)
161 */
162 dirxml(...data: any[]): void;
163 /**
164 * 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.
165 *
166 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static)
167 */
168 error(...data: any[]): void;
169 /**
170 * 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.
171 *
172 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static)
173 */
174 group(...data: any[]): void;
175 /**
176 * 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.
177 *
178 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static)
179 */
180 groupCollapsed(...data: any[]): void;
181 /**
182 * 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.
183 *
184 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static)
185 */
186 groupEnd(): void;
187 /**
188 * 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.
189 *
190 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static)
191 */
192 info(...data: any[]): void;
193 /**
194 * The **`console.log()`** static method outputs a message to the console.
195 *
196 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
197 */
198 log(...data: any[]): void;
199 /**
200 * The **`console.table()`** static method displays tabular data as a table.
201 *
202 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static)
203 */
204 table(tabularData?: any, properties?: string[]): void;
205 /**
206 * 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.
207 *
208 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static)
209 */
210 time(label?: string): void;
211 /**
212 * The **`console.timeEnd()`** static method stops a timer that was previously started by calling console.time().
213 *
214 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static)
215 */
216 timeEnd(label?: string): void;
217 /**
218 * The **`console.timeLog()`** static method logs the current value of a timer that was previously started by calling console.time().
219 *
220 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static)
221 */
222 timeLog(label?: string, ...data: any[]): void;
223 /* 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. */
224 timeStamp(label?: string): void;
225 /**
226 * The **`console.trace()`** static method outputs a stack trace to the console.
227 *
228 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static)
229 */
230 trace(...data: any[]): void;
231 /**
232 * 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.
233 *
234 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static)
235 */
236 warn(...data: any[]): void;
237}
238declare const console: Console;
239type BufferSource = ArrayBufferView | ArrayBuffer;
240type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;
241declare namespace WebAssembly {
242 class CompileError extends Error {
243 constructor(message?: string);
244 }
245 class RuntimeError extends Error {
246 constructor(message?: string);
247 }
248 type ValueType = "anyfunc" | "externref" | "f32" | "f64" | "i32" | "i64" | "v128";
249 interface GlobalDescriptor {
250 value: ValueType;
251 mutable?: boolean;
252 }
253 class Global {
254 constructor(descriptor: GlobalDescriptor, value?: any);
255 value: any;
256 valueOf(): any;
257 }
258 type ImportValue = ExportValue | number;
259 type ModuleImports = Record<string, ImportValue>;
260 type Imports = Record<string, ModuleImports>;
261 type ExportValue = Function | Global | Memory | Table;
262 type Exports = Record<string, ExportValue>;
263 class Instance {
264 constructor(module: Module, imports?: Imports);
265 readonly exports: Exports;
266 }
267 interface MemoryDescriptor {
268 initial: number;
269 maximum?: number;
270 shared?: boolean;
271 }
272 class Memory {
273 constructor(descriptor: MemoryDescriptor);
274 readonly buffer: ArrayBuffer;
275 grow(delta: number): number;
276 }
277 type ImportExportKind = "function" | "global" | "memory" | "table";
278 interface ModuleExportDescriptor {
279 kind: ImportExportKind;
280 name: string;
281 }
282 interface ModuleImportDescriptor {
283 kind: ImportExportKind;
284 module: string;
285 name: string;
286 }
287 abstract class Module {
288 static customSections(module: Module, sectionName: string): ArrayBuffer[];
289 static exports(module: Module): ModuleExportDescriptor[];
290 static imports(module: Module): ModuleImportDescriptor[];
291 }
292 type TableKind = "anyfunc" | "externref";
293 interface TableDescriptor {
294 element: TableKind;
295 initial: number;
296 maximum?: number;
297 }
298 class Table {
299 constructor(descriptor: TableDescriptor, value?: any);
300 readonly length: number;
301 get(index: number): any;
302 grow(delta: number, value?: any): number;
303 set(index: number, value?: any): void;
304 }
305 function instantiate(module: Module, imports?: Imports): Promise<Instance>;
306 function validate(bytes: BufferSource): boolean;
307}
308/**
309 * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker.
310 * Available only in secure contexts.
311 *
312 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope)
313 */
314interface ServiceWorkerGlobalScope extends WorkerGlobalScope {
315 DOMException: typeof DOMException;
316 WorkerGlobalScope: typeof WorkerGlobalScope;
317 btoa(data: string): string;
318 atob(data: string): string;
319 setTimeout(callback: (...args: any[]) => void, msDelay?: number): number;
320 setTimeout<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;
321 clearTimeout(timeoutId: number | null): void;
322 setInterval(callback: (...args: any[]) => void, msDelay?: number): number;
323 setInterval<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;
324 clearInterval(timeoutId: number | null): void;
325 queueMicrotask(task: Function): void;
326 structuredClone<T>(value: T, options?: StructuredSerializeOptions): T;
327 reportError(error: any): void;
328 fetch(input: RequestInfo | URL, init?: RequestInit<RequestInitCfProperties>): Promise<Response>;
329 self: ServiceWorkerGlobalScope;
330 crypto: Crypto;
331 caches: CacheStorage;
332 scheduler: Scheduler;
333 performance: Performance;
334 Cloudflare: Cloudflare;
335 readonly origin: string;
336 Event: typeof Event;
337 ExtendableEvent: typeof ExtendableEvent;
338 CustomEvent: typeof CustomEvent;
339 PromiseRejectionEvent: typeof PromiseRejectionEvent;
340 FetchEvent: typeof FetchEvent;
341 TailEvent: typeof TailEvent;
342 TraceEvent: typeof TailEvent;
343 ScheduledEvent: typeof ScheduledEvent;
344 MessageEvent: typeof MessageEvent;
345 CloseEvent: typeof CloseEvent;
346 ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader;
347 ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader;
348 ReadableStream: typeof ReadableStream;
349 WritableStream: typeof WritableStream;
350 WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter;
351 TransformStream: typeof TransformStream;
352 ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy;
353 CountQueuingStrategy: typeof CountQueuingStrategy;
354 ErrorEvent: typeof ErrorEvent;
355 MessageChannel: typeof MessageChannel;
356 MessagePort: typeof MessagePort;
357 EventSource: typeof EventSource;
358 ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest;
359 ReadableStreamDefaultController: typeof ReadableStreamDefaultController;
360 ReadableByteStreamController: typeof ReadableByteStreamController;
361 WritableStreamDefaultController: typeof WritableStreamDefaultController;
362 TransformStreamDefaultController: typeof TransformStreamDefaultController;
363 CompressionStream: typeof CompressionStream;
364 DecompressionStream: typeof DecompressionStream;
365 TextEncoderStream: typeof TextEncoderStream;
366 TextDecoderStream: typeof TextDecoderStream;
367 Headers: typeof Headers;
368 Body: typeof Body;
369 Request: typeof Request;
370 Response: typeof Response;
371 WebSocket: typeof WebSocket;
372 WebSocketPair: typeof WebSocketPair;
373 WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair;
374 AbortController: typeof AbortController;
375 AbortSignal: typeof AbortSignal;
376 TextDecoder: typeof TextDecoder;
377 TextEncoder: typeof TextEncoder;
378 navigator: Navigator;
379 Navigator: typeof Navigator;
380 URL: typeof URL;
381 URLSearchParams: typeof URLSearchParams;
382 URLPattern: typeof URLPattern;
383 Blob: typeof Blob;
384 File: typeof File;
385 FormData: typeof FormData;
386 Crypto: typeof Crypto;
387 SubtleCrypto: typeof SubtleCrypto;
388 CryptoKey: typeof CryptoKey;
389 CacheStorage: typeof CacheStorage;
390 Cache: typeof Cache;
391 FixedLengthStream: typeof FixedLengthStream;
392 IdentityTransformStream: typeof IdentityTransformStream;
393 HTMLRewriter: typeof HTMLRewriter;
394}
395declare function addEventListener<Type extends keyof WorkerGlobalScopeEventMap>(type: Type, handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, options?: EventTargetAddEventListenerOptions | boolean): void;
396declare function removeEventListener<Type extends keyof WorkerGlobalScopeEventMap>(type: Type, handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, options?: EventTargetEventListenerOptions | boolean): void;
397/**
398 * 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().
399 *
400 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent)
401 */
402declare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean;
403/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */
404declare function btoa(data: string): string;
405/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */
406declare function atob(data: string): string;
407/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */
408declare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number;
409/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */
410declare function setTimeout<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;
411/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */
412declare function clearTimeout(timeoutId: number | null): void;
413/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */
414declare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number;
415/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */
416declare function setInterval<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;
417/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */
418declare function clearInterval(timeoutId: number | null): void;
419/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */
420declare function queueMicrotask(task: Function): void;
421/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */
422declare function structuredClone<T>(value: T, options?: StructuredSerializeOptions): T;
423/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */
424declare function reportError(error: any): void;
425/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */
426declare function fetch(input: RequestInfo | URL, init?: RequestInit<RequestInitCfProperties>): Promise<Response>;
427declare const self: ServiceWorkerGlobalScope;
428/**
429* The Web Crypto API provides a set of low-level functions for common cryptographic tasks.
430* The Workers runtime implements the full surface of this API, but with some differences in
431* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms)
432* compared to those implemented in most browsers.
433*
434* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/)
435*/
436declare const crypto: Crypto;
437/**
438* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.
439*
440* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)
441*/
442declare const caches: CacheStorage;
443/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/scheduler) */
444declare const scheduler: Scheduler;
445/**
446* The Workers runtime supports a subset of the Performance API, used to measure timing and performance,
447* as well as timing of subrequests and other operations.
448*
449* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/)
450*/
451declare const performance: Performance;
452declare const Cloudflare: Cloudflare;
453declare const origin: string;
454declare const navigator: Navigator;
455interface TestController {
456}
457interface ExecutionContext<Props = unknown> {
458 waitUntil(promise: Promise<any>): void;
459 passThroughOnException(): void;
460 readonly exports: Cloudflare.Exports;
461 readonly props: Props;
462 cache?: CacheContext;
463 readonly access?: CloudflareAccessContext;
464 tracing: Tracing;
465 abort(reason?: any): void;
466}
467type ExportedHandlerFetchHandler<Env = unknown, CfHostMetadata = unknown, Props = unknown> = (request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, env: Env, ctx: ExecutionContext<Props>) => Response | Promise<Response>;
468type ExportedHandlerConnectHandler<Env = unknown, Props = unknown> = (socket: Socket, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
469type ExportedHandlerTailHandler<Env = unknown, Props = unknown> = (events: TraceItem[], env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
470type ExportedHandlerTraceHandler<Env = unknown, Props = unknown> = (traces: TraceItem[], env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
471type ExportedHandlerTailStreamHandler<Env = unknown, Props = unknown> = (event: TailStream.TailEvent<TailStream.Onset>, env: Env, ctx: ExecutionContext<Props>) => TailStream.TailEventHandlerType | undefined | Promise<TailStream.TailEventHandlerType | undefined>;
472type ExportedHandlerScheduledHandler<Env = unknown, Props = unknown> = (controller: ScheduledController, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
473type ExportedHandlerQueueHandler<Env = unknown, Message = unknown, Props = unknown> = (batch: MessageBatch<Message>, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
474type ExportedHandlerTestHandler<Env = unknown, Props = unknown> = (controller: TestController, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
475interface ExportedHandler<Env = unknown, QueueHandlerMessage = unknown, CfHostMetadata = unknown, Props = unknown> {
476 fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata, Props>;
477 connect?: ExportedHandlerConnectHandler<Env, Props>;
478 tail?: ExportedHandlerTailHandler<Env, Props>;
479 trace?: ExportedHandlerTraceHandler<Env, Props>;
480 tailStream?: ExportedHandlerTailStreamHandler<Env, Props>;
481 scheduled?: ExportedHandlerScheduledHandler<Env, Props>;
482 test?: ExportedHandlerTestHandler<Env, Props>;
483 email?: EmailExportedHandler<Env, Props>;
484 queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage, Props>;
485}
486interface StructuredSerializeOptions {
487 transfer?: any[];
488}
489declare abstract class Navigator {
490 sendBeacon(url: string, body?: BodyInit): boolean;
491 readonly userAgent: string;
492 readonly hardwareConcurrency: number;
493 readonly platform: string;
494 readonly language: string;
495 readonly languages: string[];
496}
497interface AlarmInvocationInfo {
498 readonly isRetry: boolean;
499 readonly retryCount: number;
500 readonly scheduledTime: number;
501}
502interface Cloudflare {
503 readonly compatibilityFlags: Record<string, boolean>;
504}
505interface CachePurgeError {
506 code: number;
507 message: string;
508}
509interface CachePurgeResult {
510 success: boolean;
511 errors: CachePurgeError[];
512}
513interface CachePurgeOptions {
514 tags?: string[];
515 pathPrefixes?: string[];
516 purgeEverything?: boolean;
517}
518interface CacheContext {
519 purge(options: CachePurgeOptions): Promise<CachePurgeResult>;
520}
521interface CloudflareAccessContext {
522 readonly aud: string;
523 getIdentity(): Promise<CloudflareAccessIdentity | undefined>;
524}
525declare abstract class ColoLocalActorNamespace {
526 get(actorId: string): Fetcher;
527}
528interface DurableObject {
529 fetch(request: Request): Response | Promise<Response>;
530 connect?(socket: Socket): void | Promise<void>;
531 alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise<void>;
532 webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise<void>;
533 webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise<void>;
534 webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>;
535}
536type DurableObjectStub<T extends Rpc.DurableObjectBranded | undefined = undefined> = Fetcher<T, "alarm" | "connect" | "webSocketMessage" | "webSocketClose" | "webSocketError"> & {
537 readonly id: DurableObjectId;
538 readonly name?: string;
539};
540interface DurableObjectId {
541 toString(): string;
542 equals(other: DurableObjectId): boolean;
543 readonly name?: string;
544 readonly jurisdiction?: string;
545}
546declare abstract class DurableObjectNamespace<T extends Rpc.DurableObjectBranded | undefined = undefined> {
547 newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId;
548 idFromName(name: string): DurableObjectId;
549 idFromString(id: string): DurableObjectId;
550 get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub<T>;
551 getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub<T>;
552 jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace<T>;
553}
554type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high" | "us";
555interface DurableObjectNamespaceNewUniqueIdOptions {
556 jurisdiction?: DurableObjectJurisdiction;
557}
558type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "apac-ne" | "apac-se" | "oc" | "afr" | "me";
559type DurableObjectRoutingMode = "primary-only";
560interface DurableObjectNamespaceGetDurableObjectOptions {
561 locationHint?: DurableObjectLocationHint;
562 routingMode?: DurableObjectRoutingMode;
563}
564interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> {
565}
566interface DurableObjectState<Props = unknown> {
567 waitUntil(promise: Promise<any>): void;
568 readonly exports: Cloudflare.Exports;
569 readonly props: Props;
570 readonly id: DurableObjectId;
571 readonly storage: DurableObjectStorage;
572 container?: Container;
573 facets: DurableObjectFacets;
574 blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>;
575 acceptWebSocket(ws: WebSocket, tags?: string[]): void;
576 getWebSockets(tag?: string): WebSocket[];
577 setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void;
578 getWebSocketAutoResponse(): WebSocketRequestResponsePair | null;
579 getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null;
580 setHibernatableWebSocketEventTimeout(timeoutMs?: number): void;
581 getHibernatableWebSocketEventTimeout(): number | null;
582 getTags(ws: WebSocket): string[];
583 abort(reason?: string, options?: DurableObjectAbortOptions): void;
584}
585interface DurableObjectTransaction {
586 get<T = unknown>(key: string, options?: DurableObjectGetOptions): Promise<T | undefined>;
587 get<T = unknown>(keys: string[], options?: DurableObjectGetOptions): Promise<Map<string, T>>;
588 list<T = unknown>(options?: DurableObjectListOptions): Promise<Map<string, T>>;
589 put<T>(key: string, value: T, options?: DurableObjectPutOptions): Promise<void>;
590 put<T>(entries: Record<string, T>, options?: DurableObjectPutOptions): Promise<void>;
591 delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>;
592 delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>;
593 rollback(): void;
594 getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>;
595 setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise<void>;
596 deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>;
597}
598interface DurableObjectStorage {
599 get<T = unknown>(key: string, options?: DurableObjectGetOptions): Promise<T | undefined>;
600 get<T = unknown>(keys: string[], options?: DurableObjectGetOptions): Promise<Map<string, T>>;
601 list<T = unknown>(options?: DurableObjectListOptions): Promise<Map<string, T>>;
602 put<T>(key: string, value: T, options?: DurableObjectPutOptions): Promise<void>;
603 put<T>(entries: Record<string, T>, options?: DurableObjectPutOptions): Promise<void>;
604 delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>;
605 delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>;
606 deleteAll(options?: DurableObjectPutOptions): Promise<void>;
607 transaction<T>(closure: (txn: DurableObjectTransaction) => Promise<T>): Promise<T>;
608 getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>;
609 setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise<void>;
610 deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>;
611 sync(): Promise<void>;
612 sql: SqlStorage;
613 kv: SyncKvStorage;
614 transactionSync<T>(closure: () => T): T;
615 getCurrentBookmark(): Promise<string>;
616 getBookmarkForTime(timestamp: number | Date): Promise<string>;
617 onNextSessionRestoreBookmark(bookmark: string): Promise<string>;
618}
619interface DurableObjectAbortOptions {
620 retryAlarm?: boolean;
621}
622interface DurableObjectListOptions {
623 start?: string;
624 startAfter?: string;
625 end?: string;
626 prefix?: string;
627 reverse?: boolean;
628 limit?: number;
629 allowConcurrency?: boolean;
630 noCache?: boolean;
631}
632interface DurableObjectGetOptions {
633 allowConcurrency?: boolean;
634 noCache?: boolean;
635}
636interface DurableObjectGetAlarmOptions {
637 allowConcurrency?: boolean;
638}
639interface DurableObjectPutOptions {
640 allowConcurrency?: boolean;
641 allowUnconfirmed?: boolean;
642 noCache?: boolean;
643}
644interface DurableObjectSetAlarmOptions {
645 allowConcurrency?: boolean;
646 allowUnconfirmed?: boolean;
647}
648declare class WebSocketRequestResponsePair {
649 constructor(request: string, response: string);
650 get request(): string;
651 get response(): string;
652}
653interface DurableObjectFacets {
654 get<T extends Rpc.DurableObjectBranded | undefined = undefined>(name: string, getStartupOptions: () => FacetStartupOptions<T> | Promise<FacetStartupOptions<T>>): Fetcher<T>;
655 abort(name: string, reason: any): void;
656 delete(name: string): void;
657 clone(src: string, dst: string): void;
658}
659interface FacetStartupOptions<T extends Rpc.DurableObjectBranded | undefined = undefined> {
660 id?: DurableObjectId | string;
661 class: DurableObjectClass<T>;
662}
663interface AnalyticsEngineDataset {
664 writeDataPoint(event?: AnalyticsEngineDataPoint): void;
665}
666interface AnalyticsEngineDataPoint {
667 indexes?: ((ArrayBuffer | string) | null)[];
668 doubles?: number[];
669 blobs?: ((ArrayBuffer | string) | null)[];
670}
671/**
672 * The **`Event`** interface represents an event which takes place on an EventTarget.
673 *
674 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event)
675 */
676declare class Event {
677 constructor(type: string, init?: EventInit);
678 /**
679 * 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.
680 *
681 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type)
682 */
683 get type(): string;
684 /**
685 * The **`eventPhase`** read-only property of the Event interface indicates which phase of the event flow is currently being evaluated.
686 *
687 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase)
688 */
689 get eventPhase(): number;
690 /**
691 * 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.
692 *
693 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed)
694 */
695 get composed(): boolean;
696 /**
697 * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not.
698 *
699 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles)
700 */
701 get bubbles(): boolean;
702 /**
703 * 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.
704 *
705 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable)
706 */
707 get cancelable(): boolean;
708 /**
709 * 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.
710 *
711 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented)
712 */
713 get defaultPrevented(): boolean;
714 /**
715 * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not.
716 * @deprecated
717 *
718 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue)
719 */
720 get returnValue(): boolean;
721 /**
722 * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached.
723 *
724 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget)
725 */
726 get currentTarget(): EventTarget | undefined;
727 /**
728 * 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.
729 *
730 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target)
731 */
732 get target(): EventTarget | undefined;
733 /**
734 * The deprecated **`Event.srcElement`** is an alias for the Event.target property. Use Event.target instead.
735 * @deprecated
736 *
737 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement)
738 */
739 get srcElement(): EventTarget | undefined;
740 /**
741 * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created.
742 *
743 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp)
744 */
745 get timeStamp(): number;
746 /**
747 * 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.
748 *
749 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted)
750 */
751 get isTrusted(): boolean;
752 /**
753 * 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.
754 * @deprecated
755 *
756 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble)
757 */
758 get cancelBubble(): boolean;
759 /**
760 * 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.
761 * @deprecated
762 *
763 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble)
764 */
765 set cancelBubble(value: boolean);
766 /**
767 * The **`stopImmediatePropagation()`** method of the Event interface prevents other listeners of the same event from being called.
768 *
769 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation)
770 */
771 stopImmediatePropagation(): void;
772 /**
773 * 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.
774 *
775 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault)
776 */
777 preventDefault(): void;
778 /**
779 * 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().
780 *
781 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation)
782 */
783 stopPropagation(): void;
784 /**
785 * 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.
786 *
787 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath)
788 */
789 composedPath(): EventTarget[];
790 static readonly NONE: number;
791 static readonly CAPTURING_PHASE: number;
792 static readonly AT_TARGET: number;
793 static readonly BUBBLING_PHASE: number;
794}
795interface EventInit {
796 bubbles?: boolean;
797 cancelable?: boolean;
798 composed?: boolean;
799}
800type EventListener<EventType extends Event = Event> = (event: EventType) => void;
801interface EventListenerObject<EventType extends Event = Event> {
802 handleEvent(event: EventType): void;
803}
804type EventListenerOrEventListenerObject<EventType extends Event = Event> = EventListener<EventType> | EventListenerObject<EventType>;
805/**
806 * 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.
807 *
808 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget)
809 */
810declare class EventTarget<EventMap extends Record<string, Event> = Record<string, Event>> {
811 constructor();
812 /**
813 * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.
814 *
815 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener)
816 */
817 addEventListener<Type extends keyof EventMap>(type: Type, handler: EventListenerOrEventListenerObject<EventMap[Type]>, options?: EventTargetAddEventListenerOptions | boolean): void;
818 /**
819 * 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.
820 *
821 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener)
822 */
823 removeEventListener<Type extends keyof EventMap>(type: Type, handler: EventListenerOrEventListenerObject<EventMap[Type]>, options?: EventTargetEventListenerOptions | boolean): void;
824 /**
825 * 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().
826 *
827 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent)
828 */
829 dispatchEvent(event: EventMap[keyof EventMap]): boolean;
830}
831interface EventTargetEventListenerOptions {
832 capture?: boolean;
833}
834interface EventTargetAddEventListenerOptions {
835 capture?: boolean;
836 passive?: boolean;
837 once?: boolean;
838 signal?: AbortSignal;
839}
840interface EventTargetHandlerObject {
841 handleEvent: (event: Event) => any | undefined;
842}
843/**
844 * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired.
845 *
846 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController)
847 */
848declare class AbortController {
849 constructor();
850 /**
851 * 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.
852 *
853 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal)
854 */
855 get signal(): AbortSignal;
856 /**
857 * 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.
858 *
859 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort)
860 */
861 abort(reason?: any): void;
862}
863/**
864 * 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.
865 *
866 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal)
867 */
868declare abstract class AbortSignal extends EventTarget {
869 /**
870 * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an abort event).
871 *
872 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static)
873 */
874 static abort(reason?: any): AbortSignal;
875 /**
876 * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time.
877 *
878 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static)
879 */
880 static timeout(delay: number): AbortSignal;
881 /**
882 * 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.
883 *
884 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static)
885 */
886 static any(signals: AbortSignal[]): AbortSignal;
887 /**
888 * 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).
889 *
890 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted)
891 */
892 get aborted(): boolean;
893 /**
894 * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason.
895 *
896 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason)
897 */
898 get reason(): any;
899 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */
900 get onabort(): any | null;
901 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */
902 set onabort(value: any | null);
903 /**
904 * The **`throwIfAborted()`** method throws the signal's abort reason if the signal has been aborted; otherwise it does nothing.
905 *
906 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted)
907 */
908 throwIfAborted(): void;
909}
910/**
911 * The **`Scheduler`** interface of the Prioritized Task Scheduling API provides methods for scheduling prioritized tasks.
912 *
913 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Scheduler)
914 */
915interface Scheduler {
916 wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>;
917}
918interface SchedulerWaitOptions {
919 signal?: AbortSignal;
920}
921/**
922 * 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.
923 *
924 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent)
925 */
926declare abstract class ExtendableEvent extends Event {
927 /**
928 * 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.
929 *
930 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil)
931 */
932 waitUntil(promise: Promise<any>): void;
933}
934/**
935 * The **`CustomEvent`** interface can be used to attach custom data to an event generated by an application.
936 *
937 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent)
938 */
939declare class CustomEvent<T = any> extends Event {
940 constructor(type: string, init?: CustomEventCustomEventInit);
941 /**
942 * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event.
943 *
944 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail)
945 */
946 get detail(): T;
947}
948interface CustomEventCustomEventInit {
949 bubbles?: boolean;
950 cancelable?: boolean;
951 composed?: boolean;
952 detail?: any;
953}
954/**
955 * 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.
956 *
957 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob)
958 */
959declare class Blob {
960 constructor(bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions);
961 /**
962 * The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes.
963 *
964 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size)
965 */
966 get size(): number;
967 /**
968 * The **`type`** read-only property of the Blob interface returns the MIME type of the file.
969 *
970 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type)
971 */
972 get type(): string;
973 /**
974 * 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.
975 *
976 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice)
977 */
978 slice(start?: number, end?: number, type?: string): Blob;
979 /**
980 * 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.
981 *
982 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer)
983 */
984 arrayBuffer(): Promise<ArrayBuffer>;
985 /**
986 * 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.
987 *
988 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes)
989 */
990 bytes(): Promise<Uint8Array>;
991 /**
992 * 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.
993 *
994 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text)
995 */
996 text(): Promise<string>;
997 /**
998 * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the Blob.
999 *
1000 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream)
1001 */
1002 stream(): ReadableStream;
1003}
1004interface BlobOptions {
1005 type?: string;
1006}
1007/**
1008 * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content.
1009 *
1010 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File)
1011 */
1012declare class File extends Blob {
1013 constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions);
1014 /**
1015 * 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.
1016 *
1017 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name)
1018 */
1019 get name(): string;
1020 /**
1021 * 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.
1022 *
1023 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified)
1024 */
1025 get lastModified(): number;
1026}
1027interface FileOptions {
1028 type?: string;
1029 lastModified?: number;
1030}
1031/**
1032* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.
1033*
1034* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)
1035*/
1036declare abstract class CacheStorage {
1037 /**
1038 * The **`open()`** method of the CacheStorage interface returns a Promise that resolves to the Cache object matching the cacheName.
1039 *
1040 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open)
1041 */
1042 open(cacheName: string): Promise<Cache>;
1043 readonly default: Cache;
1044}
1045/**
1046* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.
1047*
1048* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)
1049*/
1050declare abstract class Cache {
1051 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */
1052 delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<boolean>;
1053 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */
1054 match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<Response | undefined>;
1055 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */
1056 put(request: RequestInfo | URL, response: Response): Promise<void>;
1057}
1058interface CacheQueryOptions {
1059 ignoreMethod?: boolean;
1060}
1061/**
1062* The Web Crypto API provides a set of low-level functions for common cryptographic tasks.
1063* The Workers runtime implements the full surface of this API, but with some differences in
1064* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms)
1065* compared to those implemented in most browsers.
1066*
1067* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/)
1068*/
1069declare abstract class Crypto {
1070 /**
1071 * The **`Crypto.subtle`** read-only property returns a SubtleCrypto which can then be used to perform low-level cryptographic operations.
1072 * Available only in secure contexts.
1073 *
1074 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle)
1075 */
1076 get subtle(): SubtleCrypto;
1077 /**
1078 * 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).
1079 *
1080 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues)
1081 */
1082 getRandomValues<T extends Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | BigInt64Array | BigUint64Array>(buffer: T): T;
1083 /**
1084 * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator.
1085 * Available only in secure contexts.
1086 *
1087 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID)
1088 */
1089 randomUUID(): string;
1090 DigestStream: typeof DigestStream;
1091}
1092/**
1093 * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions.
1094 * Available only in secure contexts.
1095 *
1096 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto)
1097 */
1098declare abstract class SubtleCrypto {
1099 /**
1100 * The **`encrypt()`** method of the SubtleCrypto interface encrypts data.
1101 *
1102 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt)
1103 */
1104 encrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;
1105 /**
1106 * 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").
1107 *
1108 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt)
1109 */
1110 decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;
1111 /**
1112 * The **`sign()`** method of the SubtleCrypto interface generates a digital signature.
1113 *
1114 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign)
1115 */
1116 sign(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;
1117 /**
1118 * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature.
1119 *
1120 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify)
1121 */
1122 verify(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView): Promise<boolean>;
1123 /**
1124 * 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.
1125 *
1126 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest)
1127 */
1128 digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;
1129 /**
1130 * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms).
1131 *
1132 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey)
1133 */
1134 generateKey(algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey | CryptoKeyPair>;
1135 /**
1136 * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key.
1137 *
1138 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey)
1139 */
1140 deriveKey(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;
1141 /**
1142 * The **`deriveBits()`** method of the SubtleCrypto interface can be used to derive an array of bits from a base key.
1143 *
1144 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits)
1145 */
1146 deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise<ArrayBuffer>;
1147 /**
1148 * 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.
1149 *
1150 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey)
1151 */
1152 importKey(format: string, keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;
1153 /**
1154 * 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.
1155 *
1156 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey)
1157 */
1158 exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>;
1159 /**
1160 * 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.
1161 *
1162 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey)
1163 */
1164 wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise<ArrayBuffer>;
1165 /**
1166 * 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.
1167 *
1168 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey)
1169 */
1170 unwrapKey(format: string, wrappedKey: ArrayBuffer | ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;
1171 timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean;
1172}
1173/**
1174 * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods generateKey(), deriveKey(), importKey(), or unwrapKey().
1175 * Available only in secure contexts.
1176 *
1177 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey)
1178 */
1179declare abstract class CryptoKey {
1180 /**
1181 * 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:
1182 *
1183 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type)
1184 */
1185 readonly type: string;
1186 /**
1187 * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using SubtleCrypto.exportKey() or SubtleCrypto.wrapKey().
1188 *
1189 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable)
1190 */
1191 readonly extractable: boolean;
1192 /**
1193 * 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.
1194 *
1195 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm)
1196 */
1197 readonly algorithm: CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm;
1198 /**
1199 * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key.
1200 *
1201 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages)
1202 */
1203 readonly usages: string[];
1204}
1205interface CryptoKeyPair {
1206 publicKey: CryptoKey;
1207 privateKey: CryptoKey;
1208}
1209interface JsonWebKey {
1210 kty: string;
1211 use?: string;
1212 key_ops?: string[];
1213 alg?: string;
1214 ext?: boolean;
1215 crv?: string;
1216 x?: string;
1217 y?: string;
1218 d?: string;
1219 n?: string;
1220 e?: string;
1221 p?: string;
1222 q?: string;
1223 dp?: string;
1224 dq?: string;
1225 qi?: string;
1226 oth?: RsaOtherPrimesInfo[];
1227 k?: string;
1228 pub?: string;
1229 priv?: string;
1230}
1231interface RsaOtherPrimesInfo {
1232 r?: string;
1233 d?: string;
1234 t?: string;
1235}
1236interface SubtleCryptoDeriveKeyAlgorithm {
1237 name: string;
1238 salt?: (ArrayBuffer | ArrayBufferView);
1239 iterations?: number;
1240 hash?: (string | SubtleCryptoHashAlgorithm);
1241 $public?: CryptoKey;
1242 info?: (ArrayBuffer | ArrayBufferView);
1243}
1244interface SubtleCryptoEncryptAlgorithm {
1245 name: string;
1246 iv?: (ArrayBuffer | ArrayBufferView);
1247 additionalData?: (ArrayBuffer | ArrayBufferView);
1248 tagLength?: number;
1249 counter?: (ArrayBuffer | ArrayBufferView);
1250 length?: number;
1251 label?: (ArrayBuffer | ArrayBufferView);
1252}
1253interface SubtleCryptoGenerateKeyAlgorithm {
1254 name: string;
1255 hash?: (string | SubtleCryptoHashAlgorithm);
1256 modulusLength?: number;
1257 publicExponent?: (ArrayBuffer | ArrayBufferView);
1258 length?: number;
1259 namedCurve?: string;
1260}
1261interface SubtleCryptoHashAlgorithm {
1262 name: string;
1263}
1264interface SubtleCryptoImportKeyAlgorithm {
1265 name: string;
1266 hash?: (string | SubtleCryptoHashAlgorithm);
1267 length?: number;
1268 namedCurve?: string;
1269 compressed?: boolean;
1270}
1271interface SubtleCryptoSignAlgorithm {
1272 name: string;
1273 hash?: (string | SubtleCryptoHashAlgorithm);
1274 dataLength?: number;
1275 saltLength?: number;
1276 context?: ArrayBuffer | ArrayBufferView;
1277}
1278interface CryptoKeyKeyAlgorithm {
1279 name: string;
1280}
1281interface CryptoKeyAesKeyAlgorithm {
1282 name: string;
1283 length: number;
1284}
1285interface CryptoKeyHmacKeyAlgorithm {
1286 name: string;
1287 hash: CryptoKeyKeyAlgorithm;
1288 length: number;
1289}
1290interface CryptoKeyRsaKeyAlgorithm {
1291 name: string;
1292 modulusLength: number;
1293 publicExponent: ArrayBuffer | ArrayBufferView;
1294 hash?: CryptoKeyKeyAlgorithm;
1295}
1296interface CryptoKeyEllipticKeyAlgorithm {
1297 name: string;
1298 namedCurve: string;
1299}
1300interface CryptoKeyArbitraryKeyAlgorithm {
1301 name: string;
1302 hash?: CryptoKeyKeyAlgorithm;
1303 namedCurve?: string;
1304 length?: number;
1305}
1306declare class DigestStream extends WritableStream<ArrayBuffer | ArrayBufferView> {
1307 constructor(algorithm: string | SubtleCryptoHashAlgorithm, options?: DigestStreamOptions);
1308 readonly digest: Promise<ArrayBuffer>;
1309 get bytesWritten(): number | bigint;
1310}
1311interface DigestStreamOptions {
1312 toWellFormed?: boolean;
1313}
1314/**
1315 * 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.
1316 *
1317 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder)
1318 */
1319declare class TextDecoder {
1320 constructor(label?: string, options?: TextDecoderConstructorOptions);
1321 /**
1322 * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter.
1323 *
1324 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode)
1325 */
1326 decode(input?: (ArrayBuffer | ArrayBufferView), options?: TextDecoderDecodeOptions): string;
1327 get encoding(): string;
1328 get fatal(): boolean;
1329 get ignoreBOM(): boolean;
1330}
1331/**
1332 * The **`TextEncoder`** interface enables you to encode a JavaScript string using UTF-8.
1333 *
1334 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder)
1335 */
1336declare class TextEncoder {
1337 constructor();
1338 /**
1339 * The **`TextEncoder.encode()`** method takes a string as input, and returns a Uint8Array containing the string encoded using UTF-8.
1340 *
1341 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode)
1342 */
1343 encode(input?: string): Uint8Array;
1344 /**
1345 * 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.
1346 *
1347 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto)
1348 */
1349 encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult;
1350 get encoding(): string;
1351}
1352interface TextDecoderConstructorOptions {
1353 fatal: boolean;
1354 ignoreBOM: boolean;
1355}
1356interface TextDecoderDecodeOptions {
1357 stream: boolean;
1358}
1359interface TextEncoderEncodeIntoResult {
1360 read: number;
1361 written: number;
1362}
1363/**
1364 * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files.
1365 *
1366 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent)
1367 */
1368declare class ErrorEvent extends Event {
1369 constructor(type: string, init?: ErrorEventErrorEventInit);
1370 /**
1371 * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred.
1372 *
1373 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename)
1374 */
1375 get filename(): string;
1376 /**
1377 * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem.
1378 *
1379 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message)
1380 */
1381 get message(): string;
1382 /**
1383 * 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.
1384 *
1385 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno)
1386 */
1387 get lineno(): number;
1388 /**
1389 * 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.
1390 *
1391 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno)
1392 */
1393 get colno(): number;
1394 /**
1395 * 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.
1396 *
1397 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error)
1398 */
1399 get error(): any;
1400}
1401interface ErrorEventErrorEventInit {
1402 bubbles?: boolean;
1403 cancelable?: boolean;
1404 composed?: boolean;
1405 message?: string;
1406 filename?: string;
1407 lineno?: number;
1408 colno?: number;
1409 error?: any;
1410}
1411/**
1412 * The **`MessageEvent`** interface represents a message received by a target object.
1413 *
1414 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent)
1415 */
1416declare class MessageEvent extends Event {
1417 constructor(type: string, initializer?: MessageEventInit);
1418 /**
1419 * The **`data`** read-only property of the MessageEvent interface represents the data sent by the message emitter.
1420 *
1421 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data)
1422 */
1423 readonly data: any;
1424 /**
1425 * The **`origin`** read-only property of the MessageEvent interface is a string representing the origin of the message emitter.
1426 *
1427 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin)
1428 */
1429 readonly origin: string | null;
1430 /**
1431 * The **`lastEventId`** read-only property of the MessageEvent interface is a string representing a unique ID for the event.
1432 *
1433 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId)
1434 */
1435 readonly lastEventId: string;
1436 /**
1437 * 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.
1438 *
1439 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source)
1440 */
1441 readonly source: MessagePort | null;
1442 /**
1443 * 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.
1444 *
1445 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports)
1446 */
1447 readonly ports: MessagePort[];
1448}
1449interface MessageEventInit {
1450 bubbles?: boolean;
1451 cancelable?: boolean;
1452 composed?: boolean;
1453 data?: any;
1454 origin?: string;
1455 lastEventId?: string;
1456 source?: (MessagePort | null);
1457 ports?: MessagePort[];
1458}
1459/**
1460 * 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.
1461 *
1462 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent)
1463 */
1464declare abstract class PromiseRejectionEvent extends Event {
1465 /**
1466 * 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.
1467 *
1468 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise)
1469 */
1470 readonly promise: Promise<any>;
1471 /**
1472 * 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.
1473 *
1474 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason)
1475 */
1476 readonly reason: any;
1477}
1478/**
1479 * 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".
1480 *
1481 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData)
1482 */
1483declare class FormData {
1484 constructor();
1485 /**
1486 * 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.
1487 *
1488 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append)
1489 */
1490 append(name: string, value: string | Blob): void;
1491 /**
1492 * 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.
1493 *
1494 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append)
1495 */
1496 append(name: string, value: string): void;
1497 /**
1498 * 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.
1499 *
1500 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append)
1501 */
1502 append(name: string, value: Blob, filename?: string): void;
1503 /**
1504 * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a FormData object.
1505 *
1506 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete)
1507 */
1508 delete(name: string): void;
1509 /**
1510 * 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.
1511 *
1512 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get)
1513 */
1514 get(name: string): (File | string) | null;
1515 /**
1516 * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a FormData object.
1517 *
1518 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll)
1519 */
1520 getAll(name: string): (File | string)[];
1521 /**
1522 * The **`has()`** method of the FormData interface returns whether a FormData object contains a certain key.
1523 *
1524 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has)
1525 */
1526 has(name: string): boolean;
1527 /**
1528 * 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.
1529 *
1530 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set)
1531 */
1532 set(name: string, value: string | Blob): void;
1533 /**
1534 * 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.
1535 *
1536 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set)
1537 */
1538 set(name: string, value: string): void;
1539 /**
1540 * 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.
1541 *
1542 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set)
1543 */
1544 set(name: string, value: Blob, filename?: string): void;
1545 entries(): IterableIterator<[
1546 key: string,
1547 value: File | string
1548 ]>;
1549 keys(): IterableIterator<string>;
1550 values(): IterableIterator<(File | string)>;
1551 forEach<This = unknown>(callback: (this: This, value: File | string, key: string, parent: FormData) => void, thisArg?: This): void;
1552 [Symbol.iterator](): IterableIterator<[
1553 key: string,
1554 value: File | string
1555 ]>;
1556}
1557interface ContentOptions {
1558 html?: boolean;
1559}
1560declare class HTMLRewriter {
1561 constructor();
1562 on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter;
1563 onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter;
1564 transform(response: Response): Response;
1565}
1566interface HTMLRewriterElementContentHandlers {
1567 element?(element: Element): void | Promise<void>;
1568 comments?(comment: Comment): void | Promise<void>;
1569 text?(element: Text): void | Promise<void>;
1570}
1571interface HTMLRewriterDocumentContentHandlers {
1572 doctype?(doctype: Doctype): void | Promise<void>;
1573 comments?(comment: Comment): void | Promise<void>;
1574 text?(text: Text): void | Promise<void>;
1575 end?(end: DocumentEnd): void | Promise<void>;
1576}
1577interface Doctype {
1578 readonly name: string | null;
1579 readonly publicId: string | null;
1580 readonly systemId: string | null;
1581}
1582interface Element {
1583 tagName: string;
1584 readonly attributes: IterableIterator<string[]>;
1585 readonly removed: boolean;
1586 readonly namespaceURI: string;
1587 getAttribute(name: string): string | null;
1588 hasAttribute(name: string): boolean;
1589 setAttribute(name: string, value: string): Element;
1590 removeAttribute(name: string): Element;
1591 before(content: string | ReadableStream | Response, options?: ContentOptions): Element;
1592 after(content: string | ReadableStream | Response, options?: ContentOptions): Element;
1593 prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element;
1594 append(content: string | ReadableStream | Response, options?: ContentOptions): Element;
1595 replace(content: string | ReadableStream | Response, options?: ContentOptions): Element;
1596 remove(): Element;
1597 removeAndKeepContent(): Element;
1598 setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element;
1599 onEndTag(handler: (tag: EndTag) => void | Promise<void>): void;
1600}
1601interface EndTag {
1602 name: string;
1603 before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag;
1604 after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag;
1605 remove(): EndTag;
1606}
1607interface Comment {
1608 text: string;
1609 readonly removed: boolean;
1610 before(content: string, options?: ContentOptions): Comment;
1611 after(content: string, options?: ContentOptions): Comment;
1612 replace(content: string, options?: ContentOptions): Comment;
1613 remove(): Comment;
1614}
1615interface Text {
1616 readonly text: string;
1617 readonly lastInTextNode: boolean;
1618 readonly removed: boolean;
1619 before(content: string | ReadableStream | Response, options?: ContentOptions): Text;
1620 after(content: string | ReadableStream | Response, options?: ContentOptions): Text;
1621 replace(content: string | ReadableStream | Response, options?: ContentOptions): Text;
1622 remove(): Text;
1623}
1624interface DocumentEnd {
1625 append(content: string, options?: ContentOptions): DocumentEnd;
1626}
1627/**
1628 * 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.
1629 *
1630 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent)
1631 */
1632declare abstract class FetchEvent extends ExtendableEvent {
1633 /**
1634 * The **`request`** read-only property of the FetchEvent interface returns the Request that triggered the event handler.
1635 *
1636 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request)
1637 */
1638 readonly request: Request;
1639 /**
1640 * The **`respondWith()`** method of FetchEvent prevents the browser's default fetch handling, and allows you to provide a promise for a Response yourself.
1641 *
1642 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith)
1643 */
1644 respondWith(promise: Response | Promise<Response>): void;
1645 passThroughOnException(): void;
1646}
1647type HeadersInit = Headers | Iterable<Iterable<string>> | Record<string, string>;
1648/**
1649 * 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.
1650 *
1651 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers)
1652 */
1653declare class Headers {
1654 constructor(init?: HeadersInit);
1655 /**
1656 * 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.
1657 *
1658 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get)
1659 */
1660 get(name: string): string | null;
1661 getAll(name: string): string[];
1662 /**
1663 * 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.
1664 *
1665 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie)
1666 */
1667 getSetCookie(): string[];
1668 /**
1669 * The **`has()`** method of the Headers interface returns a boolean stating whether a Headers object contains a certain header.
1670 *
1671 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has)
1672 */
1673 has(name: string): boolean;
1674 /**
1675 * 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.
1676 *
1677 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set)
1678 */
1679 set(name: string, value: string): void;
1680 /**
1681 * 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.
1682 *
1683 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append)
1684 */
1685 append(name: string, value: string): void;
1686 /**
1687 * The **`delete()`** method of the Headers interface deletes a header from the current Headers object.
1688 *
1689 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete)
1690 */
1691 delete(name: string): void;
1692 forEach<This = unknown>(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void;
1693 entries(): IterableIterator<[
1694 key: string,
1695 value: string
1696 ]>;
1697 keys(): IterableIterator<string>;
1698 values(): IterableIterator<string>;
1699 [Symbol.iterator](): IterableIterator<[
1700 key: string,
1701 value: string
1702 ]>;
1703}
1704type BodyInit = ReadableStream<Uint8Array> | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData | Iterable<ArrayBuffer | ArrayBufferView> | AsyncIterable<ArrayBuffer | ArrayBufferView>;
1705declare abstract class Body {
1706 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */
1707 get body(): ReadableStream | null;
1708 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */
1709 get bodyUsed(): boolean;
1710 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */
1711 arrayBuffer(): Promise<ArrayBuffer>;
1712 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */
1713 bytes(): Promise<Uint8Array>;
1714 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */
1715 text(): Promise<string>;
1716 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */
1717 json<T>(): Promise<T>;
1718 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */
1719 formData(): Promise<FormData>;
1720 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */
1721 blob(): Promise<Blob>;
1722}
1723/**
1724 * The **`Response`** interface of the Fetch API represents the response to a request.
1725 *
1726 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)
1727 */
1728declare var Response: {
1729 prototype: Response;
1730 new (body?: BodyInit | null, init?: ResponseInit): Response;
1731 error(): Response;
1732 redirect(url: string, status?: number): Response;
1733 json(any: any, maybeInit?: (ResponseInit | Response)): Response;
1734};
1735/**
1736 * The **`Response`** interface of the Fetch API represents the response to a request.
1737 *
1738 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)
1739 */
1740interface Response extends Body {
1741 /**
1742 * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable.
1743 *
1744 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone)
1745 */
1746 clone(): Response;
1747 /**
1748 * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response.
1749 *
1750 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status)
1751 */
1752 status: number;
1753 /**
1754 * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status.
1755 *
1756 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText)
1757 */
1758 statusText: string;
1759 /**
1760 * The **`headers`** read-only property of the Response interface contains the Headers object associated with the response.
1761 *
1762 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers)
1763 */
1764 headers: Headers;
1765 /**
1766 * 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.
1767 *
1768 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok)
1769 */
1770 ok: boolean;
1771 /**
1772 * 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.
1773 *
1774 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected)
1775 */
1776 redirected: boolean;
1777 /**
1778 * 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.
1779 *
1780 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url)
1781 */
1782 url: string;
1783 webSocket: WebSocket | null;
1784 cf: any | undefined;
1785 /**
1786 * 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.
1787 *
1788 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type)
1789 */
1790 type: "default" | "error";
1791}
1792interface ResponseInit {
1793 status?: number;
1794 statusText?: string;
1795 headers?: HeadersInit;
1796 cf?: any;
1797 webSocket?: (WebSocket | null);
1798 encodeBody?: "automatic" | "manual";
1799}
1800type RequestInfo<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>> = Request<CfHostMetadata, Cf> | string;
1801/**
1802 * The **`Request`** interface of the Fetch API represents a resource request.
1803 *
1804 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request)
1805 */
1806declare var Request: {
1807 prototype: Request;
1808 new <CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>>(input: RequestInfo<CfProperties> | URL, init?: RequestInit<Cf>): Request<CfHostMetadata, Cf>;
1809};
1810/**
1811 * The **`Request`** interface of the Fetch API represents a resource request.
1812 *
1813 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request)
1814 */
1815interface Request<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>> extends Body {
1816 /**
1817 * The **`clone()`** method of the Request interface creates a copy of the current Request object.
1818 *
1819 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone)
1820 */
1821 clone(): Request<CfHostMetadata, Cf>;
1822 /**
1823 * The **`method`** read-only property of the Request interface contains the request's method (GET, POST, etc.)
1824 *
1825 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method)
1826 */
1827 method: string;
1828 /**
1829 * The **`url`** read-only property of the Request interface contains the URL of the request.
1830 *
1831 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url)
1832 */
1833 url: string;
1834 /**
1835 * The **`headers`** read-only property of the Request interface contains the Headers object associated with the request.
1836 *
1837 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers)
1838 */
1839 headers: Headers;
1840 /**
1841 * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled.
1842 *
1843 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect)
1844 */
1845 redirect: string;
1846 fetcher: Fetcher | null;
1847 /**
1848 * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request.
1849 *
1850 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal)
1851 */
1852 signal: AbortSignal;
1853 cf?: Cf;
1854 /**
1855 * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request.
1856 *
1857 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity)
1858 */
1859 integrity: string;
1860 /**
1861 * 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.
1862 *
1863 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive)
1864 */
1865 keepalive: boolean;
1866 /**
1867 * 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.
1868 *
1869 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache)
1870 */
1871 cache?: "no-store" | "no-cache";
1872}
1873interface RequestInit<Cf = CfProperties> {
1874 /* A string to set request's method. */
1875 method?: string;
1876 /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */
1877 headers?: HeadersInit;
1878 /* A BodyInit object or null to set request's body. */
1879 body?: BodyInit | null;
1880 /* 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. */
1881 redirect?: string;
1882 fetcher?: (Fetcher | null);
1883 cf?: Cf;
1884 /* A string indicating how the request will interact with the browser's cache to set request's cache. */
1885 cache?: "no-store" | "no-cache";
1886 /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */
1887 integrity?: string;
1888 /* An AbortSignal to set request's signal. */
1889 signal?: (AbortSignal | null);
1890 encodeResponseBody?: "automatic" | "manual";
1891}
1892type 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>;
1893type Fetcher<T extends Rpc.EntrypointBranded | undefined = undefined, Reserved extends string = never> = (T extends Rpc.EntrypointBranded ? Rpc.Provider<T, Reserved | "fetch" | "connect"> : unknown) & {
1894 fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
1895 connect(address: SocketAddress | string, options?: SocketOptions): Socket;
1896};
1897interface KVNamespaceListKey<Metadata, Key extends string = string> {
1898 name: Key;
1899 expiration?: number;
1900 metadata?: Metadata;
1901}
1902type KVNamespaceListResult<Metadata, Key extends string = string> = {
1903 list_complete: false;
1904 keys: KVNamespaceListKey<Metadata, Key>[];
1905 cursor: string;
1906 cacheStatus: string | null;
1907} | {
1908 list_complete: true;
1909 keys: KVNamespaceListKey<Metadata, Key>[];
1910 cacheStatus: string | null;
1911};
1912interface KVNamespace<Key extends string = string> {
1913 get(key: Key, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<string | null>;
1914 get(key: Key, type: "text"): Promise<string | null>;
1915 get<ExpectedValue = unknown>(key: Key, type: "json"): Promise<ExpectedValue | null>;
1916 get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>;
1917 get(key: Key, type: "stream"): Promise<ReadableStream | null>;
1918 get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise<string | null>;
1919 get<ExpectedValue = unknown>(key: Key, options?: KVNamespaceGetOptions<"json">): Promise<ExpectedValue | null>;
1920 get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise<ArrayBuffer | null>;
1921 get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise<ReadableStream | null>;
1922 get(key: Array<Key>, type: "text"): Promise<Map<string, string | null>>;
1923 get<ExpectedValue = unknown>(key: Array<Key>, type: "json"): Promise<Map<string, ExpectedValue | null>>;
1924 get(key: Array<Key>, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<Map<string, string | null>>;
1925 get(key: Array<Key>, options?: KVNamespaceGetOptions<"text">): Promise<Map<string, string | null>>;
1926 get<ExpectedValue = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<"json">): Promise<Map<string, ExpectedValue | null>>;
1927 list<Metadata = unknown>(options?: KVNamespaceListOptions): Promise<KVNamespaceListResult<Metadata, Key>>;
1928 put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise<void>;
1929 getWithMetadata<Metadata = unknown>(key: Key, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;
1930 getWithMetadata<Metadata = unknown>(key: Key, type: "text"): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;
1931 getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Key, type: "json"): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>;
1932 getWithMetadata<Metadata = unknown>(key: Key, type: "arrayBuffer"): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>;
1933 getWithMetadata<Metadata = unknown>(key: Key, type: "stream"): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>;
1934 getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"text">): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;
1935 getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"json">): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>;
1936 getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"arrayBuffer">): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>;
1937 getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"stream">): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>;
1938 getWithMetadata<Metadata = unknown>(key: Array<Key>, type: "text"): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;
1939 getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Array<Key>, type: "json"): Promise<Map<string, KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>>;
1940 getWithMetadata<Metadata = unknown>(key: Array<Key>, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;
1941 getWithMetadata<Metadata = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<"text">): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;
1942 getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<"json">): Promise<Map<string, KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>>;
1943 delete(key: Key): Promise<void>;
1944}
1945interface KVNamespaceListOptions {
1946 limit?: number;
1947 prefix?: (string | null);
1948 cursor?: (string | null);
1949}
1950interface KVNamespaceGetOptions<Type> {
1951 type: Type;
1952 cacheTtl?: number;
1953}
1954interface KVNamespacePutOptions {
1955 expiration?: number;
1956 expirationTtl?: number;
1957 metadata?: (any | null);
1958}
1959interface KVNamespaceGetWithMetadataResult<Value, Metadata> {
1960 value: Value | null;
1961 metadata: Metadata | null;
1962 cacheStatus: string | null;
1963}
1964type QueueContentType = "text" | "bytes" | "json" | "v8";
1965interface Queue<Body = unknown> {
1966 metrics(): Promise<QueueMetrics>;
1967 send(message: Body, options?: QueueSendOptions): Promise<QueueSendResponse>;
1968 sendBatch(messages: Iterable<MessageSendRequest<Body>>, options?: QueueSendBatchOptions): Promise<QueueSendBatchResponse>;
1969}
1970interface QueueSendMetrics {
1971 backlogCount: number;
1972 backlogBytes: number;
1973 oldestMessageTimestamp?: Date;
1974}
1975interface QueueSendMetadata {
1976 metrics: QueueSendMetrics;
1977}
1978interface QueueSendResponse {
1979 metadata: QueueSendMetadata;
1980}
1981interface QueueSendBatchMetrics {
1982 backlogCount: number;
1983 backlogBytes: number;
1984 oldestMessageTimestamp?: Date;
1985}
1986interface QueueSendBatchMetadata {
1987 metrics: QueueSendBatchMetrics;
1988}
1989interface QueueSendBatchResponse {
1990 metadata: QueueSendBatchMetadata;
1991}
1992interface QueueSendOptions {
1993 contentType?: QueueContentType;
1994 delaySeconds?: number;
1995}
1996interface QueueSendBatchOptions {
1997 delaySeconds?: number;
1998}
1999interface MessageSendRequest<Body = unknown> {
2000 body: Body;
2001 contentType?: QueueContentType;
2002 delaySeconds?: number;
2003}
2004interface QueueMetrics {
2005 backlogCount: number;
2006 backlogBytes: number;
2007 oldestMessageTimestamp?: Date;
2008}
2009interface MessageBatchMetrics {
2010 backlogCount: number;
2011 backlogBytes: number;
2012 oldestMessageTimestamp?: Date;
2013}
2014interface MessageBatchMetadata {
2015 metrics: MessageBatchMetrics;
2016}
2017interface QueueRetryOptions {
2018 delaySeconds?: number;
2019}
2020interface Message<Body = unknown> {
2021 readonly id: string;
2022 readonly timestamp: Date;
2023 readonly body: Body;
2024 readonly attempts: number;
2025 retry(options?: QueueRetryOptions): void;
2026 ack(): void;
2027}
2028interface QueueEvent<Body = unknown> extends ExtendableEvent {
2029 readonly messages: readonly Message<Body>[];
2030 readonly queue: string;
2031 readonly metadata: MessageBatchMetadata;
2032 retryAll(options?: QueueRetryOptions): void;
2033 ackAll(): void;
2034}
2035interface MessageBatch<Body = unknown> {
2036 readonly messages: readonly Message<Body>[];
2037 readonly queue: string;
2038 readonly metadata: MessageBatchMetadata;
2039 retryAll(options?: QueueRetryOptions): void;
2040 ackAll(): void;
2041}
2042interface R2Error extends Error {
2043 readonly name: string;
2044 readonly code: number;
2045 readonly message: string;
2046 readonly action: string;
2047 readonly stack: any;
2048}
2049interface R2ListOptions {
2050 limit?: number;
2051 prefix?: string;
2052 cursor?: string;
2053 delimiter?: string;
2054 startAfter?: string;
2055 include?: ("httpMetadata" | "customMetadata")[];
2056}
2057interface R2Bucket {
2058 head(key: string): Promise<R2Object | null>;
2059 get(key: string, options: R2GetOptions & {
2060 onlyIf: R2Conditional | Headers;
2061 }): Promise<R2ObjectBody | R2Object | null>;
2062 get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>;
2063 put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & {
2064 onlyIf: R2Conditional | Headers;
2065 }): Promise<R2Object | null>;
2066 put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise<R2Object>;
2067 createMultipartUpload(key: string, options?: R2MultipartOptions): Promise<R2MultipartUpload>;
2068 resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload;
2069 delete(keys: string | string[]): Promise<void>;
2070 list(options?: R2ListOptions): Promise<R2Objects>;
2071}
2072interface R2MultipartUpload {
2073 readonly key: string;
2074 readonly uploadId: string;
2075 uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise<R2UploadedPart>;
2076 abort(): Promise<void>;
2077 complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>;
2078}
2079interface R2UploadedPart {
2080 partNumber: number;
2081 etag: string;
2082}
2083declare abstract class R2Object {
2084 readonly key: string;
2085 readonly version: string;
2086 readonly size: number;
2087 readonly etag: string;
2088 readonly httpEtag: string;
2089 readonly checksums: R2Checksums;
2090 readonly uploaded: Date;
2091 readonly httpMetadata?: R2HTTPMetadata;
2092 readonly customMetadata?: Record<string, string>;
2093 readonly range?: R2Range;
2094 readonly storageClass: string;
2095 readonly ssecKeyMd5?: string;
2096 writeHttpMetadata(headers: Headers): void;
2097}
2098interface R2ObjectBody extends R2Object {
2099 get body(): ReadableStream;
2100 get bodyUsed(): boolean;
2101 arrayBuffer(): Promise<ArrayBuffer>;
2102 bytes(): Promise<Uint8Array>;
2103 text(): Promise<string>;
2104 json<T>(): Promise<T>;
2105 blob(): Promise<Blob>;
2106}
2107type R2Range = {
2108 offset: number;
2109 length?: number;
2110} | {
2111 offset?: number;
2112 length: number;
2113} | {
2114 suffix: number;
2115};
2116interface R2Conditional {
2117 etagMatches?: string;
2118 etagDoesNotMatch?: string;
2119 uploadedBefore?: Date;
2120 uploadedAfter?: Date;
2121 secondsGranularity?: boolean;
2122}
2123interface R2GetOptions {
2124 onlyIf?: (R2Conditional | Headers);
2125 range?: (R2Range | Headers);
2126 ssecKey?: (ArrayBuffer | string);
2127}
2128interface R2PutOptions {
2129 onlyIf?: (R2Conditional | Headers);
2130 httpMetadata?: (R2HTTPMetadata | Headers);
2131 customMetadata?: Record<string, string>;
2132 md5?: ((ArrayBuffer | ArrayBufferView) | string);
2133 sha1?: ((ArrayBuffer | ArrayBufferView) | string);
2134 sha256?: ((ArrayBuffer | ArrayBufferView) | string);
2135 sha384?: ((ArrayBuffer | ArrayBufferView) | string);
2136 sha512?: ((ArrayBuffer | ArrayBufferView) | string);
2137 storageClass?: string;
2138 ssecKey?: (ArrayBuffer | string);
2139}
2140interface R2MultipartOptions {
2141 httpMetadata?: (R2HTTPMetadata | Headers);
2142 customMetadata?: Record<string, string>;
2143 storageClass?: string;
2144 ssecKey?: (ArrayBuffer | string);
2145}
2146interface R2Checksums {
2147 readonly md5?: ArrayBuffer;
2148 readonly sha1?: ArrayBuffer;
2149 readonly sha256?: ArrayBuffer;
2150 readonly sha384?: ArrayBuffer;
2151 readonly sha512?: ArrayBuffer;
2152 toJSON(): R2StringChecksums;
2153}
2154interface R2StringChecksums {
2155 md5?: string;
2156 sha1?: string;
2157 sha256?: string;
2158 sha384?: string;
2159 sha512?: string;
2160}
2161interface R2HTTPMetadata {
2162 contentType?: string;
2163 contentLanguage?: string;
2164 contentDisposition?: string;
2165 contentEncoding?: string;
2166 cacheControl?: string;
2167 cacheExpiry?: Date;
2168}
2169type R2Objects = {
2170 objects: R2Object[];
2171 delimitedPrefixes: string[];
2172} & ({
2173 truncated: true;
2174 cursor: string;
2175} | {
2176 truncated: false;
2177});
2178interface R2UploadPartOptions {
2179 ssecKey?: (ArrayBuffer | string);
2180}
2181declare abstract class ScheduledEvent extends ExtendableEvent {
2182 readonly scheduledTime: number;
2183 readonly cron: string;
2184 noRetry(): void;
2185}
2186interface ScheduledController {
2187 readonly scheduledTime: number;
2188 readonly cron: string;
2189 noRetry(): void;
2190}
2191interface QueuingStrategy<T = any> {
2192 highWaterMark?: (number | bigint);
2193 size?: (chunk: T) => number | bigint;
2194}
2195interface UnderlyingSink<W = any> {
2196 type?: string;
2197 start?: (controller: WritableStreamDefaultController) => void | Promise<void>;
2198 write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise<void>;
2199 abort?: (reason: any) => void | Promise<void>;
2200 close?: () => void | Promise<void>;
2201}
2202interface UnderlyingByteSource {
2203 type: "bytes";
2204 autoAllocateChunkSize?: number;
2205 start?: (controller: ReadableByteStreamController) => void | Promise<void>;
2206 pull?: (controller: ReadableByteStreamController) => void | Promise<void>;
2207 cancel?: (reason: any) => void | Promise<void>;
2208}
2209interface UnderlyingSource<R = any> {
2210 type?: "" | undefined;
2211 start?: (controller: ReadableStreamDefaultController<R>) => void | Promise<void>;
2212 pull?: (controller: ReadableStreamDefaultController<R>) => void | Promise<void>;
2213 cancel?: (reason: any) => void | Promise<void>;
2214 expectedLength?: (number | bigint);
2215}
2216interface Transformer<I = any, O = any> {
2217 readableType?: string;
2218 writableType?: string;
2219 start?: (controller: TransformStreamDefaultController<O>) => void | Promise<void>;
2220 transform?: (chunk: I, controller: TransformStreamDefaultController<O>) => void | Promise<void>;
2221 flush?: (controller: TransformStreamDefaultController<O>) => void | Promise<void>;
2222 cancel?: (reason: any) => void | Promise<void>;
2223 expectedLength?: number;
2224}
2225interface StreamPipeOptions {
2226 preventAbort?: boolean;
2227 preventCancel?: boolean;
2228 /**
2229 * 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.
2230 *
2231 * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
2232 *
2233 * Errors and closures of the source and destination streams propagate as follows:
2234 *
2235 * 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.
2236 *
2237 * 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.
2238 *
2239 * 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.
2240 *
2241 * 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.
2242 *
2243 * 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.
2244 */
2245 preventClose?: boolean;
2246 signal?: AbortSignal;
2247}
2248type ReadableStreamReadResult<R = any> = {
2249 done: false;
2250 value: R;
2251} | {
2252 done: true;
2253 value?: undefined;
2254};
2255/**
2256 * 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.
2257 *
2258 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream)
2259 */
2260interface ReadableStream<R = any> {
2261 /**
2262 * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader.
2263 *
2264 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked)
2265 */
2266 get locked(): boolean;
2267 /**
2268 * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled.
2269 *
2270 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel)
2271 */
2272 cancel(reason?: any): Promise<void>;
2273 /**
2274 * 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.
2275 *
2276 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader)
2277 */
2278 getReader(): ReadableStreamDefaultReader<R>;
2279 /**
2280 * 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.
2281 *
2282 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader)
2283 */
2284 getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader;
2285 /**
2286 * 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.
2287 *
2288 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough)
2289 */
2290 pipeThrough<T>(transform: ReadableWritablePair<T, R>, options?: StreamPipeOptions): ReadableStream<T>;
2291 /**
2292 * 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.
2293 *
2294 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo)
2295 */
2296 pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>;
2297 /**
2298 * 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.
2299 *
2300 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee)
2301 */
2302 tee(): [
2303 ReadableStream<R>,
2304 ReadableStream<R>
2305 ];
2306 values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>;
2307 [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>;
2308}
2309/**
2310 * 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.
2311 *
2312 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream)
2313 */
2314declare const ReadableStream: {
2315 prototype: ReadableStream;
2316 new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy<Uint8Array>): ReadableStream<Uint8Array>;
2317 new <R = any>(underlyingSource?: UnderlyingSource<R>, strategy?: QueuingStrategy<R>): ReadableStream<R>;
2318};
2319/**
2320 * 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).
2321 *
2322 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader)
2323 */
2324declare class ReadableStreamDefaultReader<R = any> {
2325 constructor(stream: ReadableStream);
2326 get closed(): Promise<void>;
2327 cancel(reason?: any): Promise<void>;
2328 /**
2329 * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue.
2330 *
2331 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read)
2332 */
2333 read(): Promise<ReadableStreamReadResult<R>>;
2334 /**
2335 * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream.
2336 *
2337 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock)
2338 */
2339 releaseLock(): void;
2340}
2341/**
2342 * 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.
2343 *
2344 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader)
2345 */
2346declare class ReadableStreamBYOBReader {
2347 constructor(stream: ReadableStream);
2348 get closed(): Promise<void>;
2349 cancel(reason?: any): Promise<void>;
2350 /**
2351 * 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.
2352 *
2353 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read)
2354 */
2355 read<T extends ArrayBufferView>(view: T): Promise<ReadableStreamReadResult<T>>;
2356 /**
2357 * 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.
2358 *
2359 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock)
2360 */
2361 releaseLock(): void;
2362 readAtLeast<T extends ArrayBufferView>(minElements: number, view: T): Promise<ReadableStreamReadResult<T>>;
2363}
2364interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions {
2365 min?: number;
2366}
2367interface ReadableStreamGetReaderOptions {
2368 /**
2369 * Creates a ReadableStreamBYOBReader and locks the stream to the new reader.
2370 *
2371 * 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.
2372 */
2373 mode: "byob";
2374}
2375/**
2376 * 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).
2377 *
2378 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest)
2379 */
2380declare abstract class ReadableStreamBYOBRequest {
2381 /**
2382 * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view.
2383 *
2384 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view)
2385 */
2386 get view(): Uint8Array | null;
2387 /**
2388 * 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.
2389 *
2390 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond)
2391 */
2392 respond(bytesWritten: number): void;
2393 /**
2394 * 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.
2395 *
2396 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView)
2397 */
2398 respondWithNewView(view: ArrayBuffer | ArrayBufferView): void;
2399 get atLeast(): number | null;
2400}
2401/**
2402 * 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.
2403 *
2404 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController)
2405 */
2406declare abstract class ReadableStreamDefaultController<R = any> {
2407 /**
2408 * The **`desiredSize`** read-only property of the ReadableStreamDefaultController interface returns the desired size required to fill the stream's internal queue.
2409 *
2410 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize)
2411 */
2412 get desiredSize(): number | null;
2413 /**
2414 * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream.
2415 *
2416 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close)
2417 */
2418 close(): void;
2419 /**
2420 * The **`enqueue()`** method of the ReadableStreamDefaultController interface enqueues a given chunk in the associated stream.
2421 *
2422 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue)
2423 */
2424 enqueue(chunk?: R): void;
2425 /**
2426 * The **`error()`** method of the ReadableStreamDefaultController interface causes any future interactions with the associated stream to error.
2427 *
2428 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error)
2429 */
2430 error(reason: any): void;
2431}
2432/**
2433 * 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.
2434 *
2435 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController)
2436 */
2437declare abstract class ReadableByteStreamController {
2438 /**
2439 * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or null if there are no pending requests.
2440 *
2441 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest)
2442 */
2443 get byobRequest(): ReadableStreamBYOBRequest | null;
2444 /**
2445 * 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".
2446 *
2447 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize)
2448 */
2449 get desiredSize(): number | null;
2450 /**
2451 * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream.
2452 *
2453 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close)
2454 */
2455 close(): void;
2456 /**
2457 * 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).
2458 *
2459 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue)
2460 */
2461 enqueue(chunk: ArrayBuffer | ArrayBufferView): void;
2462 /**
2463 * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason.
2464 *
2465 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error)
2466 */
2467 error(reason: any): void;
2468}
2469/**
2470 * 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.
2471 *
2472 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController)
2473 */
2474declare abstract class WritableStreamDefaultController {
2475 /**
2476 * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller.
2477 *
2478 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal)
2479 */
2480 get signal(): AbortSignal;
2481 /**
2482 * The **`error()`** method of the WritableStreamDefaultController interface causes any future interactions with the associated stream to error.
2483 *
2484 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error)
2485 */
2486 error(reason?: any): void;
2487}
2488/**
2489 * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream.
2490 *
2491 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController)
2492 */
2493declare abstract class TransformStreamDefaultController<O = any> {
2494 /**
2495 * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream.
2496 *
2497 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize)
2498 */
2499 get desiredSize(): number | null;
2500 /**
2501 * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream.
2502 *
2503 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue)
2504 */
2505 enqueue(chunk?: O): void;
2506 /**
2507 * 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.
2508 *
2509 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error)
2510 */
2511 error(reason: any): void;
2512 /**
2513 * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream.
2514 *
2515 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate)
2516 */
2517 terminate(): void;
2518}
2519interface ReadableWritablePair<R = any, W = any> {
2520 readable: ReadableStream<R>;
2521 /**
2522 * 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.
2523 *
2524 * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
2525 */
2526 writable: WritableStream<W>;
2527}
2528/**
2529 * 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.
2530 *
2531 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream)
2532 */
2533declare class WritableStream<W = any> {
2534 constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy);
2535 /**
2536 * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the WritableStream is locked to a writer.
2537 *
2538 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked)
2539 */
2540 get locked(): boolean;
2541 /**
2542 * 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.
2543 *
2544 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort)
2545 */
2546 abort(reason?: any): Promise<void>;
2547 /**
2548 * 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.
2549 *
2550 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close)
2551 */
2552 close(): Promise<void>;
2553 /**
2554 * 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.
2555 *
2556 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter)
2557 */
2558 getWriter(): WritableStreamDefaultWriter<W>;
2559}
2560/**
2561 * 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.
2562 *
2563 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter)
2564 */
2565declare class WritableStreamDefaultWriter<W = any> {
2566 constructor(stream: WritableStream);
2567 /**
2568 * 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.
2569 *
2570 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed)
2571 */
2572 get closed(): Promise<void>;
2573 /**
2574 * 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.
2575 *
2576 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready)
2577 */
2578 get ready(): Promise<void>;
2579 /**
2580 * The **`desiredSize`** read-only property of the WritableStreamDefaultWriter interface returns the desired size required to fill the stream's internal queue.
2581 *
2582 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize)
2583 */
2584 get desiredSize(): number | null;
2585 /**
2586 * 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.
2587 *
2588 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort)
2589 */
2590 abort(reason?: any): Promise<void>;
2591 /**
2592 * The **`close()`** method of the WritableStreamDefaultWriter interface closes the associated writable stream.
2593 *
2594 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close)
2595 */
2596 close(): Promise<void>;
2597 /**
2598 * 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.
2599 *
2600 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write)
2601 */
2602 write(chunk?: W): Promise<void>;
2603 /**
2604 * 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.
2605 *
2606 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock)
2607 */
2608 releaseLock(): void;
2609}
2610/**
2611 * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain transform stream concept.
2612 *
2613 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream)
2614 */
2615declare class TransformStream<I = any, O = any> {
2616 constructor(transformer?: Transformer<I, O>, writableStrategy?: QueuingStrategy<I>, readableStrategy?: QueuingStrategy<O>);
2617 /**
2618 * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this TransformStream. This stream emits the transformed output data.
2619 *
2620 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable)
2621 */
2622 get readable(): ReadableStream<O>;
2623 /**
2624 * 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.
2625 *
2626 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable)
2627 */
2628 get writable(): WritableStream<I>;
2629}
2630declare class FixedLengthStream extends IdentityTransformStream {
2631 constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy);
2632}
2633declare class IdentityTransformStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {
2634 constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy);
2635}
2636interface IdentityTransformStreamQueuingStrategy {
2637 highWaterMark?: (number | bigint);
2638}
2639interface ReadableStreamValuesOptions {
2640 preventCancel?: boolean;
2641}
2642/**
2643 * 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.
2644 *
2645 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream)
2646 */
2647declare class CompressionStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {
2648 constructor(format: "gzip" | "deflate" | "deflate-raw");
2649}
2650/**
2651 * 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.
2652 *
2653 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream)
2654 */
2655declare class DecompressionStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {
2656 constructor(format: "gzip" | "deflate" | "deflate-raw");
2657}
2658/**
2659 * 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.
2660 *
2661 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream)
2662 */
2663declare class TextEncoderStream extends TransformStream<string, Uint8Array> {
2664 constructor();
2665 get encoding(): string;
2666}
2667/**
2668 * 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.
2669 *
2670 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream)
2671 */
2672declare class TextDecoderStream extends TransformStream<ArrayBuffer | ArrayBufferView, string> {
2673 constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit);
2674 get encoding(): string;
2675 get fatal(): boolean;
2676 get ignoreBOM(): boolean;
2677}
2678interface TextDecoderStreamTextDecoderStreamInit {
2679 fatal?: boolean;
2680 ignoreBOM?: boolean;
2681}
2682/**
2683 * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams.
2684 *
2685 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy)
2686 */
2687declare class ByteLengthQueuingStrategy implements QueuingStrategy<ArrayBufferView> {
2688 constructor(init: QueuingStrategyInit);
2689 /**
2690 * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied.
2691 *
2692 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark)
2693 */
2694 get highWaterMark(): number;
2695 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */
2696 get size(): (chunk?: any) => number;
2697}
2698/**
2699 * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams.
2700 *
2701 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy)
2702 */
2703declare class CountQueuingStrategy implements QueuingStrategy {
2704 constructor(init: QueuingStrategyInit);
2705 /**
2706 * The read-only **`CountQueuingStrategy.highWaterMark`** property returns the total number of chunks that can be contained in the internal queue before backpressure is applied.
2707 *
2708 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark)
2709 */
2710 get highWaterMark(): number;
2711 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */
2712 get size(): (chunk?: any) => number;
2713}
2714interface QueuingStrategyInit {
2715 /**
2716 * Creates a new ByteLengthQueuingStrategy with the provided high water mark.
2717 *
2718 * 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.
2719 */
2720 highWaterMark: number;
2721}
2722interface TracePreviewInfo {
2723 id: string;
2724 slug: string;
2725 name: string;
2726}
2727interface ScriptVersion {
2728 id?: string;
2729 tag?: string;
2730 message?: string;
2731}
2732declare abstract class TailEvent extends ExtendableEvent {
2733 readonly events: TraceItem[];
2734 readonly traces: TraceItem[];
2735}
2736interface TraceItem {
2737 readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemConnectEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null;
2738 readonly eventTimestamp: number | null;
2739 readonly logs: TraceLog[];
2740 readonly exceptions: TraceException[];
2741 readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[];
2742 readonly scriptName: string | null;
2743 readonly entrypoint?: string;
2744 readonly scriptVersion?: ScriptVersion;
2745 readonly dispatchNamespace?: string;
2746 readonly scriptTags?: string[];
2747 readonly tailAttributes?: Record<string, boolean | number | string>;
2748 readonly preview?: TracePreviewInfo;
2749 readonly durableObjectId?: string;
2750 readonly outcome: string;
2751 readonly executionModel: string;
2752 readonly truncated: boolean;
2753 readonly cpuTime: number;
2754 readonly wallTime: number;
2755}
2756interface TraceItemAlarmEventInfo {
2757 readonly scheduledTime: Date;
2758}
2759interface TraceItemConnectEventInfo {
2760}
2761interface TraceItemCustomEventInfo {
2762}
2763interface TraceItemScheduledEventInfo {
2764 readonly scheduledTime: number;
2765 readonly cron: string;
2766}
2767interface TraceItemQueueEventInfo {
2768 readonly queue: string;
2769 readonly batchSize: number;
2770}
2771interface TraceItemEmailEventInfo {
2772 readonly mailFrom: string;
2773 readonly rcptTo: string;
2774 readonly rawSize: number;
2775}
2776interface TraceItemTailEventInfo {
2777 readonly consumedEvents: TraceItemTailEventInfoTailItem[];
2778}
2779interface TraceItemTailEventInfoTailItem {
2780 readonly scriptName: string | null;
2781}
2782interface TraceItemFetchEventInfo {
2783 readonly response?: TraceItemFetchEventInfoResponse;
2784 readonly request: TraceItemFetchEventInfoRequest;
2785}
2786interface TraceItemFetchEventInfoRequest {
2787 readonly cf?: any;
2788 readonly headers: Record<string, string>;
2789 readonly method: string;
2790 readonly url: string;
2791 getUnredacted(): TraceItemFetchEventInfoRequest;
2792}
2793interface TraceItemFetchEventInfoResponse {
2794 readonly status: number;
2795}
2796interface TraceItemJsRpcEventInfo {
2797 readonly rpcMethod: string;
2798}
2799interface TraceItemHibernatableWebSocketEventInfo {
2800 readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError;
2801}
2802interface TraceItemHibernatableWebSocketEventInfoMessage {
2803 readonly webSocketEventType: string;
2804}
2805interface TraceItemHibernatableWebSocketEventInfoClose {
2806 readonly webSocketEventType: string;
2807 readonly code: number;
2808 readonly wasClean: boolean;
2809}
2810interface TraceItemHibernatableWebSocketEventInfoError {
2811 readonly webSocketEventType: string;
2812}
2813interface TraceLog {
2814 readonly timestamp: number;
2815 readonly level: string;
2816 readonly message: any;
2817 readonly errorInfo?: (TraceLogErrorInfo | null)[];
2818}
2819interface TraceLogErrorInfo {
2820 name: string;
2821 message: string;
2822 stack?: string;
2823}
2824interface TraceException {
2825 readonly timestamp: number;
2826 readonly message: string;
2827 readonly name: string;
2828 readonly stack?: string;
2829}
2830interface TraceDiagnosticChannelEvent {
2831 readonly timestamp: number;
2832 readonly channel: string;
2833 readonly message: any;
2834}
2835interface TraceMetrics {
2836 readonly cpuTime: number;
2837 readonly wallTime: number;
2838}
2839interface UnsafeTraceMetrics {
2840 fromTrace(item: TraceItem): TraceMetrics;
2841}
2842/**
2843 * 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.
2844 *
2845 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL)
2846 */
2847declare class URL {
2848 constructor(url: string | URL, base?: string | URL);
2849 /**
2850 * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL.
2851 *
2852 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin)
2853 */
2854 get origin(): string;
2855 /**
2856 * The **`href`** property of the URL interface is a string containing the whole URL.
2857 *
2858 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href)
2859 */
2860 get href(): string;
2861 /**
2862 * The **`href`** property of the URL interface is a string containing the whole URL.
2863 *
2864 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href)
2865 */
2866 set href(value: string);
2867 /**
2868 * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final ":".
2869 *
2870 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol)
2871 */
2872 get protocol(): string;
2873 /**
2874 * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final ":".
2875 *
2876 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol)
2877 */
2878 set protocol(value: string);
2879 /**
2880 * 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, "".
2881 *
2882 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username)
2883 */
2884 get username(): string;
2885 /**
2886 * 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, "".
2887 *
2888 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username)
2889 */
2890 set username(value: string);
2891 /**
2892 * 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, "".
2893 *
2894 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password)
2895 */
2896 get password(): string;
2897 /**
2898 * 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, "".
2899 *
2900 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password)
2901 */
2902 set password(value: string);
2903 /**
2904 * 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, "".
2905 *
2906 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host)
2907 */
2908 get host(): string;
2909 /**
2910 * 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, "".
2911 *
2912 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host)
2913 */
2914 set host(value: string);
2915 /**
2916 * 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.
2917 *
2918 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname)
2919 */
2920 get hostname(): string;
2921 /**
2922 * 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.
2923 *
2924 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname)
2925 */
2926 set hostname(value: string);
2927 /**
2928 * 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, "".
2929 *
2930 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port)
2931 */
2932 get port(): string;
2933 /**
2934 * 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, "".
2935 *
2936 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port)
2937 */
2938 set port(value: string);
2939 /**
2940 * 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.
2941 *
2942 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname)
2943 */
2944 get pathname(): string;
2945 /**
2946 * 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.
2947 *
2948 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname)
2949 */
2950 set pathname(value: string);
2951 /**
2952 * 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, "".
2953 *
2954 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search)
2955 */
2956 get search(): string;
2957 /**
2958 * 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, "".
2959 *
2960 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search)
2961 */
2962 set search(value: string);
2963 /**
2964 * 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, "".
2965 *
2966 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash)
2967 */
2968 get hash(): string;
2969 /**
2970 * 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, "".
2971 *
2972 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash)
2973 */
2974 set hash(value: string);
2975 /**
2976 * 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.
2977 *
2978 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams)
2979 */
2980 get searchParams(): URLSearchParams;
2981 /**
2982 * 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().
2983 *
2984 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON)
2985 */
2986 toJSON(): string;
2987 /*function toString() { [native code] }*/
2988 toString(): string;
2989 /**
2990 * 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.
2991 *
2992 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static)
2993 */
2994 static canParse(url: string, base?: string): boolean;
2995 /**
2996 * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters.
2997 *
2998 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static)
2999 */
3000 static parse(url: string, base?: string): URL | null;
3001 /**
3002 * The **`createObjectURL()`** static method of the URL interface creates a string containing a blob URL pointing to the object given in the parameter.
3003 *
3004 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static)
3005 */
3006 static createObjectURL(object: File | Blob): string;
3007 /**
3008 * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling URL.createObjectURL().
3009 *
3010 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static)
3011 */
3012 static revokeObjectURL(object_url: string): void;
3013}
3014/**
3015 * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL.
3016 *
3017 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams)
3018 */
3019declare class URLSearchParams {
3020 constructor(init?: (Iterable<Iterable<string>> | Record<string, string> | string));
3021 /**
3022 * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries.
3023 *
3024 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size)
3025 */
3026 get size(): number;
3027 /**
3028 * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter.
3029 *
3030 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append)
3031 */
3032 append(name: string, value: string): void;
3033 /**
3034 * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters.
3035 *
3036 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete)
3037 */
3038 delete(name: string, value?: string): void;
3039 /**
3040 * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter.
3041 *
3042 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get)
3043 */
3044 get(name: string): string | null;
3045 /**
3046 * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array.
3047 *
3048 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll)
3049 */
3050 getAll(name: string): string[];
3051 /**
3052 * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters.
3053 *
3054 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has)
3055 */
3056 has(name: string, value?: string): boolean;
3057 /**
3058 * 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.
3059 *
3060 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set)
3061 */
3062 set(name: string, value: string): void;
3063 /**
3064 * 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).
3065 *
3066 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort)
3067 */
3068 sort(): void;
3069 entries(): IterableIterator<[
3070 key: string,
3071 value: string
3072 ]>;
3073 keys(): IterableIterator<string>;
3074 values(): IterableIterator<string>;
3075 forEach<This = unknown>(callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This): void;
3076 /*function toString() { [native code] }*/
3077 toString(): string;
3078 [Symbol.iterator](): IterableIterator<[
3079 key: string,
3080 value: string
3081 ]>;
3082}
3083/**
3084 * 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.
3085 *
3086 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern)
3087 */
3088declare class URLPattern {
3089 constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions);
3090 /**
3091 * The **`protocol`** read-only property of the URLPattern interface is a string containing the pattern used to match the protocol part of a URL.
3092 *
3093 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/protocol)
3094 */
3095 get protocol(): string;
3096 /**
3097 * The **`username`** read-only property of the URLPattern interface is a string containing the pattern used to match the username part of a URL.
3098 *
3099 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/username)
3100 */
3101 get username(): string;
3102 /**
3103 * The **`password`** read-only property of the URLPattern interface is a string containing the pattern used to match the password part of a URL.
3104 *
3105 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/password)
3106 */
3107 get password(): string;
3108 /**
3109 * The **`hostname`** read-only property of the URLPattern interface is a string containing the pattern used to match the hostname part of a URL.
3110 *
3111 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hostname)
3112 */
3113 get hostname(): string;
3114 /**
3115 * The **`port`** read-only property of the URLPattern interface is a string containing the pattern used to match the port part of a URL.
3116 *
3117 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/port)
3118 */
3119 get port(): string;
3120 /**
3121 * The **`pathname`** read-only property of the URLPattern interface is a string containing the pattern used to match the pathname part of a URL.
3122 *
3123 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/pathname)
3124 */
3125 get pathname(): string;
3126 /**
3127 * The **`search`** read-only property of the URLPattern interface is a string containing the pattern used to match the search part of a URL.
3128 *
3129 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/search)
3130 */
3131 get search(): string;
3132 /**
3133 * The **`hash`** read-only property of the URLPattern interface is a string containing the pattern used to match the fragment part of a URL.
3134 *
3135 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hash)
3136 */
3137 get hash(): string;
3138 /**
3139 * 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.
3140 *
3141 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hasRegExpGroups)
3142 */
3143 get hasRegExpGroups(): boolean;
3144 /**
3145 * 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.
3146 *
3147 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/test)
3148 */
3149 test(input?: (string | URLPatternInit), baseURL?: string): boolean;
3150 /**
3151 * 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.
3152 *
3153 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/exec)
3154 */
3155 exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null;
3156}
3157interface URLPatternInit {
3158 protocol?: string;
3159 username?: string;
3160 password?: string;
3161 hostname?: string;
3162 port?: string;
3163 pathname?: string;
3164 search?: string;
3165 hash?: string;
3166 baseURL?: string;
3167}
3168interface URLPatternComponentResult {
3169 input: string;
3170 groups: Record<string, string>;
3171}
3172interface URLPatternResult {
3173 inputs: (string | URLPatternInit)[];
3174 protocol: URLPatternComponentResult;
3175 username: URLPatternComponentResult;
3176 password: URLPatternComponentResult;
3177 hostname: URLPatternComponentResult;
3178 port: URLPatternComponentResult;
3179 pathname: URLPatternComponentResult;
3180 search: URLPatternComponentResult;
3181 hash: URLPatternComponentResult;
3182}
3183interface URLPatternOptions {
3184 ignoreCase?: boolean;
3185}
3186/**
3187 * 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.
3188 *
3189 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent)
3190 */
3191declare class CloseEvent extends Event {
3192 constructor(type: string, initializer?: CloseEventInit);
3193 /**
3194 * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed.
3195 *
3196 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code)
3197 */
3198 readonly code: number;
3199 /**
3200 * 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.
3201 *
3202 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason)
3203 */
3204 readonly reason: string;
3205 /**
3206 * The **`wasClean`** read-only property of the CloseEvent interface returns true if the connection closed cleanly.
3207 *
3208 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean)
3209 */
3210 readonly wasClean: boolean;
3211}
3212interface CloseEventInit {
3213 bubbles?: boolean;
3214 cancelable?: boolean;
3215 composed?: boolean;
3216 code?: number;
3217 reason?: string;
3218 wasClean?: boolean;
3219}
3220type WebSocketEventMap = {
3221 close: CloseEvent;
3222 message: MessageEvent;
3223 open: Event;
3224 error: ErrorEvent;
3225};
3226/**
3227 * 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.
3228 *
3229 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket)
3230 */
3231declare var WebSocket: {
3232 prototype: WebSocket;
3233 new (url: string, protocols?: (string[] | string)): WebSocket;
3234 readonly READY_STATE_CONNECTING: number;
3235 readonly CONNECTING: number;
3236 readonly READY_STATE_OPEN: number;
3237 readonly OPEN: number;
3238 readonly READY_STATE_CLOSING: number;
3239 readonly CLOSING: number;
3240 readonly READY_STATE_CLOSED: number;
3241 readonly CLOSED: number;
3242};
3243/**
3244 * 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.
3245 *
3246 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket)
3247 */
3248interface WebSocket extends EventTarget<WebSocketEventMap> {
3249 accept(options?: WebSocketAcceptOptions): void;
3250 /**
3251 * 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.
3252 *
3253 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send)
3254 */
3255 send(message: (ArrayBuffer | ArrayBufferView) | string): void;
3256 /**
3257 * The **`WebSocket.close()`** method closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED, this method does nothing.
3258 *
3259 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close)
3260 */
3261 close(code?: number, reason?: string): void;
3262 serializeAttachment(attachment: any): void;
3263 deserializeAttachment(): any | null;
3264 /**
3265 * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection.
3266 *
3267 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState)
3268 */
3269 readyState: number;
3270 /**
3271 * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor.
3272 *
3273 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url)
3274 */
3275 url: string | null;
3276 /**
3277 * 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.
3278 *
3279 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol)
3280 */
3281 protocol: string | null;
3282 /**
3283 * 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.
3284 *
3285 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions)
3286 */
3287 extensions: string | null;
3288 /**
3289 * The **`WebSocket.binaryType`** property controls the type of binary data being received over the WebSocket connection.
3290 *
3291 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType)
3292 */
3293 binaryType: "blob" | "arraybuffer";
3294}
3295interface WebSocketAcceptOptions {
3296 /**
3297 * When set to `true`, receiving a server-initiated WebSocket Close frame will not
3298 * automatically send a reciprocal Close frame, leaving the connection in a half-open
3299 * state. This is useful for proxying scenarios where you need to coordinate closing
3300 * both sides independently. Defaults to `false` when the
3301 * `no_web_socket_half_open_by_default` compatibility flag is enabled.
3302 */
3303 allowHalfOpen?: boolean;
3304}
3305declare const WebSocketPair: {
3306 new (): {
3307 0: WebSocket;
3308 1: WebSocket;
3309 };
3310};
3311interface SqlStorage {
3312 exec<T extends Record<string, SqlStorageValue>>(query: string, ...bindings: any[]): SqlStorageCursor<T>;
3313 get databaseSize(): number;
3314 Cursor: typeof SqlStorageCursor;
3315 Statement: typeof SqlStorageStatement;
3316}
3317declare abstract class SqlStorageStatement {
3318}
3319type SqlStorageValue = ArrayBuffer | string | number | null;
3320declare abstract class SqlStorageCursor<T extends Record<string, SqlStorageValue>> {
3321 next(): {
3322 done?: false;
3323 value: T;
3324 } | {
3325 done: true;
3326 value?: never;
3327 };
3328 toArray(): T[];
3329 one(): T;
3330 raw<U extends SqlStorageValue[]>(): IterableIterator<U>;
3331 columnNames: string[];
3332 get rowsRead(): number;
3333 get rowsWritten(): number;
3334 [Symbol.iterator](): IterableIterator<T>;
3335}
3336interface Socket {
3337 get readable(): ReadableStream;
3338 get writable(): WritableStream;
3339 get closed(): Promise<void>;
3340 get opened(): Promise<SocketInfo>;
3341 get upgraded(): boolean;
3342 get secureTransport(): "on" | "off" | "starttls";
3343 close(): Promise<void>;
3344 startTls(options?: TlsOptions): Socket;
3345}
3346interface SocketOptions {
3347 secureTransport?: string;
3348 allowHalfOpen: boolean;
3349 highWaterMark?: (number | bigint);
3350}
3351interface SocketAddress {
3352 hostname: string;
3353 port: number;
3354}
3355interface TlsOptions {
3356 expectedServerHostname?: string;
3357}
3358interface SocketInfo {
3359 remoteAddress?: string;
3360 localAddress?: string;
3361}
3362/**
3363 * The **`EventSource`** interface is web content's interface to server-sent events.
3364 *
3365 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource)
3366 */
3367declare class EventSource extends EventTarget {
3368 constructor(url: string, init?: EventSourceEventSourceInit);
3369 /**
3370 * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the EventSource.readyState attribute to 2 (closed).
3371 *
3372 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
3373 */
3374 close(): void;
3375 /**
3376 * The **`url`** read-only property of the EventSource interface returns a string representing the URL of the source.
3377 *
3378 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
3379 */
3380 get url(): string;
3381 /**
3382 * The **`withCredentials`** read-only property of the EventSource interface returns a boolean value indicating whether the EventSource object was instantiated with CORS credentials set.
3383 *
3384 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
3385 */
3386 get withCredentials(): boolean;
3387 /**
3388 * The **`readyState`** read-only property of the EventSource interface returns a number representing the state of the connection.
3389 *
3390 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
3391 */
3392 get readyState(): number;
3393 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
3394 get onopen(): any | null;
3395 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
3396 set onopen(value: any | null);
3397 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
3398 get onmessage(): any | null;
3399 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
3400 set onmessage(value: any | null);
3401 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
3402 get onerror(): any | null;
3403 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
3404 set onerror(value: any | null);
3405 static readonly CONNECTING: number;
3406 static readonly OPEN: number;
3407 static readonly CLOSED: number;
3408 static from(stream: ReadableStream): EventSource;
3409}
3410interface EventSourceEventSourceInit {
3411 withCredentials?: boolean;
3412 fetcher?: Fetcher;
3413}
3414interface ExecOutput {
3415 readonly stdout: ArrayBuffer;
3416 readonly stderr: ArrayBuffer;
3417 readonly exitCode: number;
3418}
3419interface ContainerExecOptions {
3420 cwd?: string;
3421 env?: Record<string, string>;
3422 user?: string;
3423 signal?: AbortSignal;
3424 pty?: boolean | ContainerExecPtyOptions;
3425 stdin?: ReadableStream | "pipe";
3426 stdout?: "pipe" | "ignore";
3427 stderr?: "pipe" | "ignore" | "combined";
3428}
3429interface ContainerExecPtyOptions {
3430 cols?: number;
3431 rows?: number;
3432}
3433interface ExecProcess {
3434 readonly stdin: WritableStream | null;
3435 readonly stdout: ReadableStream | null;
3436 readonly stderr: ReadableStream | null;
3437 readonly pid: number;
3438 readonly isPty: boolean;
3439 readonly exitCode: Promise<number>;
3440 output(): Promise<ExecOutput>;
3441 kill(signal?: number): void;
3442 resize(cols: number, rows: number): void;
3443}
3444interface Container {
3445 get running(): boolean;
3446 get images(): Record<string, string>;
3447 start(options?: ContainerStartupOptions): void;
3448 monitor(): Promise<void>;
3449 destroy(error?: any): Promise<void>;
3450 signal(signo: number): void;
3451 getTcpPort(port: number): Fetcher;
3452 setInactivityTimeout(durationMs: number | bigint): Promise<void>;
3453 interceptOutboundHttp(addr: string, binding: Fetcher): Promise<void>;
3454 interceptAllOutboundHttp(binding: Fetcher): Promise<void>;
3455 snapshotContainer(options?: ContainerSnapshotOptions): Promise<ContainerSnapshot>;
3456 interceptOutboundHttps(addr: string, binding: Fetcher): Promise<void>;
3457 exec(cmd: string[], options?: ContainerExecOptions): Promise<ExecProcess>;
3458 inspect(): Promise<ContainerInfo | null>;
3459}
3460interface ContainerDirectorySnapshot {
3461 id: string;
3462 size: number;
3463 dir: string;
3464 name?: string;
3465}
3466type ContainerDirectorySnapshotRestoreParams = {
3467 snapshot: ContainerDirectorySnapshot;
3468 mountPoint?: string;
3469} | {
3470 snapshot?: undefined;
3471 mountPoint: string;
3472};
3473interface ContainerSnapshot {
3474 id: string;
3475 size: number;
3476 name?: string;
3477}
3478interface ContainerSnapshotRestoreParams {
3479 id: string;
3480}
3481interface ContainerSnapshotOptions {
3482 name?: string;
3483}
3484type ContainerStartupOptions = {
3485 entrypoint?: string[];
3486 enableInternet: boolean;
3487 env?: Record<string, string>;
3488 instance?: "lite" | "standard-1" | "standard-2" | "standard-3" | "standard-4" | ContainerStartResources;
3489 labels?: Record<string, string>;
3490 directorySnapshots?: ContainerDirectorySnapshotRestoreParams[];
3491} & ({
3492 image: string;
3493 containerSnapshot?: never;
3494} | {
3495 image?: never;
3496 containerSnapshot?: ContainerSnapshotRestoreParams;
3497});
3498interface ContainerInfo {
3499 labels: Record<string, string>;
3500 image: string;
3501}
3502interface ContainerStartResources {
3503 vcpu: number;
3504 memoryMib: number;
3505 diskMb: number;
3506}
3507/**
3508 * 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.
3509 *
3510 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort)
3511 */
3512declare abstract class MessagePort extends EventTarget {
3513 /**
3514 * The **`postMessage()`** method of the MessagePort interface sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts.
3515 *
3516 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage)
3517 */
3518 postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void;
3519 /**
3520 * 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.
3521 *
3522 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close)
3523 */
3524 close(): void;
3525 /**
3526 * 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.
3527 *
3528 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start)
3529 */
3530 start(): void;
3531 get onmessage(): any | null;
3532 set onmessage(value: any | null);
3533}
3534/**
3535 * 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.
3536 *
3537 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel)
3538 */
3539declare class MessageChannel {
3540 constructor();
3541 /**
3542 * 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.
3543 *
3544 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1)
3545 */
3546 readonly port1: MessagePort;
3547 /**
3548 * 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.
3549 *
3550 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2)
3551 */
3552 readonly port2: MessagePort;
3553}
3554interface MessagePortPostMessageOptions {
3555 transfer?: any[];
3556}
3557type 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 new (...args: any[]) => CloudflareWorkersModule.WorkflowEntrypoint<any, infer Params> ? Workflow<Params> : T extends ExportedHandler<any, any, any> ? LoopbackServiceStub<undefined> : undefined;
3558type LoopbackServiceStub<T extends Rpc.WorkerEntrypointBranded | undefined = undefined> = Fetcher<T> & (T extends CloudflareWorkersModule.WorkerEntrypoint<any, infer Props> ? (opts: {
3559 props?: Props;
3560}) => Fetcher<T> : (opts: {
3561 props?: any;
3562}) => Fetcher<T>);
3563type LoopbackDurableObjectClass<T extends Rpc.DurableObjectBranded | undefined = undefined> = DurableObjectClass<T> & (T extends CloudflareWorkersModule.DurableObject<any, infer Props> ? (opts: {
3564 props?: Props;
3565}) => DurableObjectClass<T> : (opts: {
3566 props?: any;
3567}) => DurableObjectClass<T>);
3568interface LoopbackDurableObjectNamespace extends DurableObjectNamespace {
3569}
3570interface LoopbackColoLocalActorNamespace extends ColoLocalActorNamespace {
3571}
3572interface SyncKvStorage {
3573 get<T = unknown>(key: string): T | undefined;
3574 list<T = unknown>(options?: SyncKvListOptions): Iterable<[
3575 string,
3576 T
3577 ]>;
3578 put<T>(key: string, value: T): void;
3579 delete(key: string): boolean;
3580}
3581interface SyncKvListOptions {
3582 start?: string;
3583 startAfter?: string;
3584 end?: string;
3585 prefix?: string;
3586 reverse?: boolean;
3587 limit?: number;
3588}
3589interface WorkerStub {
3590 getEntrypoint<T extends Rpc.WorkerEntrypointBranded | undefined>(name?: string, options?: WorkerStubEntrypointOptions): Fetcher<T>;
3591 getDurableObjectClass<T extends Rpc.DurableObjectBranded | undefined>(name?: string, options?: WorkerStubEntrypointOptions): DurableObjectClass<T>;
3592}
3593interface WorkerStubEntrypointOptions {
3594 props?: any;
3595 limits?: workerdResourceLimits;
3596}
3597interface WorkerLoader {
3598 get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise<WorkerLoaderWorkerCode>): WorkerStub;
3599 load(code: WorkerLoaderWorkerCode): WorkerStub;
3600}
3601interface WorkerLoaderModule {
3602 js?: string;
3603 cjs?: string;
3604 text?: string;
3605 data?: ArrayBuffer;
3606 json?: any;
3607 py?: string;
3608 wasm?: ArrayBuffer | ArrayBufferView | WebAssembly.Module;
3609}
3610interface WorkerLoaderWorkerCode {
3611 compatibilityDate: string;
3612 compatibilityFlags?: string[];
3613 allowExperimental?: boolean;
3614 limits?: workerdResourceLimits;
3615 mainModule: string;
3616 modules: Record<string, string | WebAssembly.Module | WorkerLoaderModule>;
3617 env?: any;
3618 globalOutbound?: (Fetcher | null);
3619 tails?: Fetcher[];
3620 streamingTails?: Fetcher[];
3621}
3622interface workerdResourceLimits {
3623 cpuMs?: number;
3624 subRequests?: number;
3625}
3626/**
3627* The Workers runtime supports a subset of the Performance API, used to measure timing and performance,
3628* as well as timing of subrequests and other operations.
3629*
3630* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/)
3631*/
3632declare abstract class Performance {
3633 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */
3634 get timeOrigin(): number;
3635 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */
3636 now(): number;
3637 /**
3638 * The **`toJSON()`** method of the Performance interface is a serializer; it returns a JSON representation of the Performance object.
3639 *
3640 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/toJSON)
3641 */
3642 toJSON(): object;
3643}
3644interface Tracing {
3645 enterSpan<T, A extends unknown[]>(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T;
3646 startActiveSpan<T, A extends unknown[]>(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T;
3647 startSpan(name: string): Span;
3648 getActiveSpan(): Span | undefined;
3649 Span: typeof Span;
3650}
3651declare abstract class Span {
3652 get isTraced(): boolean;
3653 setAttribute(key: string, value: boolean | number | string): this;
3654 setAttributes(attributes: Record<string, boolean | number | string | undefined>): this;
3655 recordException(exception: string | {
3656 code: string | number;
3657 name?: string;
3658 message?: string;
3659 stack?: string;
3660 } | {
3661 code?: string | number;
3662 name: string;
3663 message?: string;
3664 stack?: string;
3665 } | {
3666 code?: string | number;
3667 name?: string;
3668 message: string;
3669 stack?: string;
3670 }): void;
3671 updateName(name: string): this;
3672 setStatus(status: TracingSpanStatus): this;
3673 end(): void;
3674}
3675type TracingSpanStatusCode = "unset" | "ok" | "error";
3676interface TracingSpanStatus {
3677 code: TracingSpanStatusCode;
3678 message?: string;
3679}
3680/**
3681 * Represents the identity of a user authenticated via Cloudflare Access.
3682 * This matches the result of calling /cdn-cgi/access/get-identity.
3683 *
3684 * The exact structure of the returned object depends on the identity provider
3685 * configuration for the Access application. The fields below represent commonly
3686 * available properties, but additional provider-specific fields may be present.
3687 */
3688interface CloudflareAccessIdentity extends Record<string, unknown> {
3689 /** The user's email address, if available from the identity provider. */
3690 email?: string;
3691 /** The user's display name. */
3692 name?: string;
3693 /** The user's unique identifier. */
3694 user_uuid?: string;
3695 /** The Cloudflare account ID. */
3696 account_id?: string;
3697 /** Login timestamp (Unix epoch seconds). */
3698 iat?: number;
3699 /** The user's IP address at authentication time. */
3700 ip?: string;
3701 /** Authentication methods used (e.g., "pwd"). */
3702 amr?: string[];
3703 /** Identity provider information. */
3704 idp?: {
3705 id: string;
3706 type: string;
3707 };
3708 /** Geographic information about where the user authenticated. */
3709 geo?: {
3710 country: string;
3711 };
3712 /** Group memberships from the identity provider. */
3713 groups?: Array<{
3714 id: string;
3715 name: string;
3716 email?: string;
3717 }>;
3718 /** Device posture check results, keyed by check ID. */
3719 devicePosture?: Record<string, unknown>;
3720 /** True if the user connected via Cloudflare WARP. */
3721 is_warp?: boolean;
3722 /** True if the user is authenticated via Cloudflare Gateway. */
3723 is_gateway?: boolean;
3724}
3725// ============================================================================
3726// Agent Memory
3727//
3728// Public type surface for user Workers binding to an Agent Memory namespace.
3729// ============================================================================
3730/** Memory type — every memory is classified into exactly one. */
3731type AgentMemoryMemoryType = "fact" | "event" | "instruction" | "task";
3732/** Search intensity for recall. */
3733type AgentMemoryThinkingLevel = "low" | "medium" | "high";
3734/** Response verbosity for recall. */
3735type AgentMemoryResponseLength = "short" | "medium" | "long";
3736/** A conversation message passed to ingest(). */
3737interface AgentMemoryMessage {
3738 role: "system" | "user" | "assistant";
3739 content: string;
3740 /** Optional message timestamp. */
3741 timestamp?: Date;
3742}
3743/** Raw memory content passed to remember(). */
3744interface AgentMemoryIncomingMemory {
3745 /** Raw memory content. The service classifies and summarizes automatically. */
3746 content: string;
3747 /** Optional session identifier to associate with this memory. */
3748 sessionId?: string | null | undefined;
3749}
3750/** A stored memory returned from remember(), get(), and delete(). */
3751interface AgentMemoryMemory {
3752 /** Memory ID. */
3753 id: string;
3754 /** Memory type. */
3755 type: AgentMemoryMemoryType;
3756 /** Text summary. */
3757 summary: string;
3758 /** Memory text. */
3759 content: string;
3760 /** Session that created this memory. */
3761 sessionId: string | null;
3762 /** Memory creation time. */
3763 createdAt: Date;
3764 /** Memory last-update time. */
3765 updatedAt: Date;
3766}
3767/** Single entry in a list() response. Same shape as Memory minus full content. */
3768type AgentMemoryMemoryListEntry = Omit<AgentMemoryMemory, "content">;
3769/** A scored memory candidate in a recall result. */
3770interface AgentMemoryScoredCandidate {
3771 /** Candidate ID. */
3772 id: string;
3773 /** Text summary. */
3774 summary: string;
3775 /** Session that created this candidate, when known. */
3776 sessionId: string | null;
3777 /** Relevance score (higher is better). Comparable only within a single query. */
3778 score: number;
3779}
3780/** Options for the ingest() method. */
3781interface AgentMemoryIngestOptions {
3782 /** Session identifier to associate with memories created during ingestion. */
3783 sessionId?: string | null | undefined;
3784}
3785/** Options for the getSummary() method. */
3786interface AgentMemoryGetSummaryOptions {
3787 /** Session identifier to retrieve session summary for. */
3788 sessionId?: string | null | undefined;
3789}
3790/** Response from the getSummary() method. */
3791interface AgentMemoryGetSummaryResponse {
3792 /** Markdown summary. */
3793 summary: string;
3794}
3795/**
3796 * Options for the recall() method.
3797 *
3798 * `referenceDate` accepts a Date object, an ISO-8601 date string
3799 * (YYYY-MM-DD), or a full ISO-8601 datetime string. When provided, this
3800 * date is used as "today" for resolving relative time references
3801 * ("how many days ago", "last week") instead of the server's wall-clock time.
3802 */
3803interface AgentMemoryRecallOptions {
3804 /** Recall intensity: "low" (default), "medium", or "high". */
3805 thinkingLevel?: AgentMemoryThinkingLevel;
3806 /** Response verbosity: "short", "medium" (default), or "long". */
3807 responseLength?: AgentMemoryResponseLength;
3808 /** Temporal anchor for date arithmetic. */
3809 referenceDate?: Date | string;
3810}
3811/** Response from the recall() method. */
3812interface AgentMemoryRecallResult {
3813 /** Number of memories retrieved. */
3814 count: number;
3815 /** LLM-generated answer synthesizing the matching memories. */
3816 answer: string;
3817 /** Matching memories ranked by relevance. */
3818 candidates: AgentMemoryScoredCandidate[];
3819}
3820/**
3821 * Options for the list() method.
3822 *
3823 * `cursor` is the opaque continuation token returned by the previous page;
3824 * pass it back unchanged to fetch the next page. `sessionId` and `type`
3825 * are exact-match filters; combining them is allowed.
3826 */
3827interface AgentMemoryListMemoriesOptions {
3828 /** Maximum number of memories to return. Default 20, max 500. */
3829 limit?: number;
3830 /** Opaque cursor from a previous page. */
3831 cursor?: string;
3832 /** Exact-match session filter. */
3833 sessionId?: string;
3834 /** Exact-match memory-type filter. */
3835 type?: AgentMemoryMemoryType;
3836}
3837/** Response from the list() method. */
3838interface AgentMemoryListMemoriesResult {
3839 memories: AgentMemoryMemoryListEntry[];
3840 /** Continuation cursor; absent when this page exhausted the result set. */
3841 cursor?: string;
3842}
3843/**
3844 * A single Agent Memory profile, scoped to a profile name.
3845 *
3846 * Returned by {@link AgentMemoryNamespace.getProfile}.
3847 */
3848declare abstract class AgentMemoryProfile {
3849 /**
3850 * Retrieve a memory by ID.
3851 *
3852 * @param memoryId - ULID of the memory to retrieve.
3853 * @throws if the memory does not exist.
3854 */
3855 get(memoryId: string): Promise<AgentMemoryMemory>;
3856 /**
3857 * Delete a memory by ID.
3858 *
3859 * Removes the memory and any source messages linked by the memory's
3860 * source message IDs.
3861 *
3862 * @param memoryId - ULID of the memory to delete.
3863 * @throws if the memory does not exist.
3864 */
3865 delete(memoryId: string): Promise<AgentMemoryMemory>;
3866 /**
3867 * Store a memory in this profile. The content is automatically classified,
3868 * summarized, and indexed.
3869 *
3870 * @param memory - Raw memory content to persist.
3871 */
3872 remember(memory: AgentMemoryIncomingMemory): Promise<AgentMemoryMemory>;
3873 /**
3874 * Extract memories from a conversation.
3875 *
3876 * @param messages - Conversation messages to extract memories from.
3877 * @param options - Optional ingest options.
3878 */
3879 ingest(messages: Iterable<AgentMemoryMessage>, options?: AgentMemoryIngestOptions): Promise<void>;
3880 /**
3881 * Get a profile summary.
3882 *
3883 * @param options - Optional getSummary options.
3884 */
3885 getSummary(options?: AgentMemoryGetSummaryOptions): Promise<AgentMemoryGetSummaryResponse>;
3886 /**
3887 * Recall memories in this profile.
3888 *
3889 * @param query - Recall query matched against memory content and keywords.
3890 * @param options - Optional recall parameters.
3891 * @returns Matching memories with relevance scores and a synthesized answer.
3892 */
3893 recall(query: string, options?: AgentMemoryRecallOptions): Promise<AgentMemoryRecallResult>;
3894 /**
3895 * List active memories in this profile.
3896 *
3897 * Returns a paginated, filterable view of stored memories. Superseded
3898 * versions are excluded. Use the returned `cursor` (when present) to
3899 * fetch the next page.
3900 *
3901 * @param options - Optional pagination and filter options.
3902 */
3903 list(options?: AgentMemoryListMemoriesOptions): Promise<AgentMemoryListMemoriesResult>;
3904 /**
3905 * Soft-delete every memory and message in this profile that is tagged
3906 * with `sessionId`.
3907 *
3908 * Idempotent: deleting a sessionId that has no rows is a no-op.
3909 *
3910 * @param sessionId - Session to delete.
3911 */
3912 deleteSession(sessionId: string): Promise<void>;
3913}
3914/**
3915 * Namespace-level Agent Memory binding.
3916 *
3917 * Used as the type of an `env.MEMORY`-style binding backed by the Agent
3918 * Memory product.
3919 *
3920 * @example
3921 * ```ts
3922 * export default {
3923 * async fetch(_request: Request, env: Env): Promise<Response> {
3924 * const profile = await env.MEMORY.getProfile("wrangler-e2e");
3925 * const summary = await profile.getSummary();
3926 * return Response.json(summary);
3927 * },
3928 * };
3929 * ```
3930 */
3931declare abstract class AgentMemoryNamespace {
3932 /**
3933 * Get a memory profile by name. Profiles are isolated by namespace and
3934 * addressed by a compound key (namespaceId:profileName).
3935 *
3936 * @param profileName - Profile name (validated against naming rules).
3937 * @returns RPC target for interacting with the profile.
3938 */
3939 getProfile(profileName: string): Promise<AgentMemoryProfile>;
3940 /**
3941 * Soft-delete a profile and schedule deferred purge. Marks all
3942 * memories and messages as deleted.
3943 *
3944 * @param profileName - Name of the profile to delete.
3945 */
3946 deleteProfile(profileName: string): Promise<void>;
3947}
3948// ============ AI Search Error Interfaces ============
3949interface AiSearchInternalError extends Error {
3950}
3951interface AiSearchNotFoundError extends Error {
3952}
3953// ============ AI Search Common Types ============
3954/** A single message in a conversation-style search or chat request. */
3955type AiSearchMessage = {
3956 role: 'system' | 'developer' | 'user' | 'assistant' | 'tool';
3957 content: string | null;
3958};
3959/**
3960 * Common shape for `ai_search_options` used by both single-instance and multi-instance requests.
3961 * Contains retrieval, query rewrite, reranking, and cache sub-options.
3962 */
3963type AiSearchOptions = {
3964 retrieval?: {
3965 /** Which retrieval backend to use. Defaults to the instance's configured index_method. */
3966 retrieval_type?: 'vector' | 'keyword' | 'hybrid';
3967 /** Fusion method for combining vector + keyword results. */
3968 fusion_method?: 'max' | 'rrf';
3969 /** How keyword terms are combined: "and" = all terms must match, "or" = any term matches. */
3970 keyword_match_mode?: 'and' | 'or';
3971 /** Minimum similarity score (0-1) for a result to be included. Default 0.4. */
3972 match_threshold?: number;
3973 /** Maximum number of results to return (1-50). Default 10. */
3974 max_num_results?: number;
3975 /** Vectorize metadata filters applied to the search. */
3976 filters?: VectorizeVectorMetadataFilter;
3977 /** Number of surrounding chunks to include for context (0-3). Default 0. */
3978 context_expansion?: number;
3979 /** If true, return only item metadata without chunk text. */
3980 metadata_only?: boolean;
3981 /** If true (default), return empty results on retrieval failure instead of throwing. */
3982 return_on_failure?: boolean;
3983 /** Boost results by metadata field values. Max 3 entries. */
3984 boost_by?: Array<{
3985 field: string;
3986 direction?: 'asc' | 'desc' | 'exists' | 'not_exists';
3987 }>;
3988 [key: string]: unknown;
3989 };
3990 query_rewrite?: {
3991 enabled?: boolean;
3992 model?: string;
3993 rewrite_prompt?: string;
3994 [key: string]: unknown;
3995 };
3996 reranking?: {
3997 enabled?: boolean;
3998 model?: string;
3999 /** Match threshold (0-1, default 0.4) */
4000 match_threshold?: number;
4001 [key: string]: unknown;
4002 };
4003 cache?: {
4004 enabled?: boolean;
4005 cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes';
4006 };
4007 [key: string]: unknown;
4008};
4009// ============ AI Search Request Types ============
4010/**
4011 * Request body for single-instance search.
4012 * Exactly one of `query` or `messages` must be provided.
4013 */
4014type AiSearchSearchRequest = {
4015 /** Simple query string. */
4016 query: string;
4017 messages?: never;
4018 ai_search_options?: AiSearchOptions;
4019} | {
4020 query?: never;
4021 /** Conversation-style input. At least one user message with non-empty content is required. */
4022 messages: AiSearchMessage[];
4023 ai_search_options?: AiSearchOptions;
4024};
4025type AiSearchChatCompletionsRequest = {
4026 messages: AiSearchMessage[];
4027 model?: string;
4028 stream?: boolean;
4029 ai_search_options?: AiSearchOptions;
4030 [key: string]: unknown;
4031};
4032// ============ AI Search Multi-Instance Types (Namespace-Scoped) ============
4033/** `ai_search_options` shape for multi-instance requests — requires `instance_ids`. */
4034type AiSearchMultiSearchOptions = AiSearchOptions & {
4035 /** Instance IDs to search across (1-10). */
4036 instance_ids: string[];
4037};
4038/**
4039 * Request for searching across multiple instances within a namespace.
4040 * `ai_search_options` is required and must include `instance_ids`.
4041 * Exactly one of `query` or `messages` must be provided.
4042 */
4043type AiSearchMultiSearchRequest = {
4044 /** Simple query string. */
4045 query: string;
4046 messages?: never;
4047 ai_search_options: AiSearchMultiSearchOptions;
4048} | {
4049 query?: never;
4050 /** Conversation-style input. */
4051 messages: AiSearchMessage[];
4052 ai_search_options: AiSearchMultiSearchOptions;
4053};
4054/** A search result chunk tagged with the instance it originated from. */
4055type AiSearchMultiSearchChunk = AiSearchSearchResponse['chunks'][number] & {
4056 instance_id: string;
4057};
4058/** Describes a per-instance error during a multi-instance operation. */
4059type AiSearchMultiSearchError = {
4060 instance_id: string;
4061 message: string;
4062};
4063/** Response from a multi-instance search, with chunks tagged by instance and optional partial-failure errors. */
4064type AiSearchMultiSearchResponse = {
4065 search_query: string;
4066 chunks: AiSearchMultiSearchChunk[];
4067 errors?: AiSearchMultiSearchError[];
4068};
4069/** Request for chat completions across multiple instances within a namespace. `ai_search_options` is required and must include `instance_ids`. */
4070type AiSearchMultiChatCompletionsRequest = Omit<AiSearchChatCompletionsRequest, 'ai_search_options'> & {
4071 ai_search_options: AiSearchMultiSearchOptions;
4072};
4073/** Response from multi-instance chat completions, with chunks tagged by instance and optional partial-failure errors. */
4074type AiSearchMultiChatCompletionsResponse = Omit<AiSearchChatCompletionsResponse, 'chunks'> & {
4075 chunks: AiSearchMultiSearchChunk[];
4076 errors?: AiSearchMultiSearchError[];
4077};
4078// ============ AI Search Response Types ============
4079type AiSearchSearchResponse = {
4080 search_query: string;
4081 chunks: Array<{
4082 id: string;
4083 type: string;
4084 /** Match score (0-1) */
4085 score: number;
4086 text: string;
4087 item: {
4088 timestamp?: number;
4089 key: string;
4090 metadata?: Record<string, unknown>;
4091 };
4092 scoring_details?: {
4093 /** Keyword match score (0-1) */
4094 keyword_score?: number;
4095 /** Vector similarity score (0-1) */
4096 vector_score?: number;
4097 /** Keyword rank position */
4098 keyword_rank?: number;
4099 /** Vector rank position */
4100 vector_rank?: number;
4101 /** Reranking model score */
4102 reranking_score?: number;
4103 /** Fusion method used to combine results */
4104 fusion_method?: 'rrf' | 'max';
4105 [key: string]: unknown;
4106 };
4107 }>;
4108};
4109type AiSearchChatCompletionsResponse = {
4110 id?: string;
4111 object?: string;
4112 model?: string;
4113 choices: Array<{
4114 index?: number;
4115 message: {
4116 role: 'system' | 'developer' | 'user' | 'assistant' | 'tool';
4117 content: string | null;
4118 [key: string]: unknown;
4119 };
4120 [key: string]: unknown;
4121 }>;
4122 chunks: AiSearchSearchResponse['chunks'];
4123 [key: string]: unknown;
4124};
4125type AiSearchStatsResponse = {
4126 queued?: number;
4127 running?: number;
4128 completed?: number;
4129 error?: number;
4130 skipped?: number;
4131 outdated?: number;
4132 last_activity?: string;
4133 /** Storage engine statistics. */
4134 engine?: {
4135 vectorize?: {
4136 vectorsCount: number;
4137 dimensions: number;
4138 };
4139 r2?: {
4140 payloadSizeBytes: number;
4141 metadataSizeBytes: number;
4142 objectCount: number;
4143 };
4144 };
4145};
4146// ============ AI Search Instance Info Types ============
4147type AiSearchInstanceInfo = {
4148 id: string;
4149 type?: 'r2' | 'web-crawler' | string;
4150 source?: string;
4151 source_params?: unknown;
4152 paused?: boolean;
4153 status?: string;
4154 namespace?: string;
4155 created_at?: string;
4156 modified_at?: string;
4157 token_id?: string;
4158 ai_gateway_id?: string;
4159 rewrite_query?: boolean;
4160 reranking?: boolean;
4161 embedding_model?: string;
4162 ai_search_model?: string;
4163 rewrite_model?: string;
4164 reranking_model?: string;
4165 /** @deprecated Use index_method instead. */
4166 hybrid_search_enabled?: boolean;
4167 /** Controls which storage backends are active. */
4168 index_method?: {
4169 vector?: boolean;
4170 keyword?: boolean;
4171 };
4172 /** Fusion method for combining vector and keyword results. */
4173 fusion_method?: 'max' | 'rrf';
4174 indexing_options?: {
4175 keyword_tokenizer?: 'porter' | 'trigram';
4176 } | null;
4177 retrieval_options?: {
4178 keyword_match_mode?: 'and' | 'or';
4179 boost_by?: Array<{
4180 field: string;
4181 direction?: 'asc' | 'desc' | 'exists' | 'not_exists';
4182 }>;
4183 } | null;
4184 chunk?: boolean;
4185 chunk_size?: number;
4186 chunk_overlap?: number;
4187 score_threshold?: number;
4188 max_num_results?: number;
4189 cache?: boolean;
4190 cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes';
4191 custom_metadata?: Array<{
4192 field_name: string;
4193 data_type: 'text' | 'number' | 'boolean' | 'datetime';
4194 }>;
4195 /** Sync interval in seconds. */
4196 sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400;
4197 metadata?: Record<string, unknown>;
4198 [key: string]: unknown;
4199};
4200/** Pagination, search, and ordering parameters for listing instances within a namespace. */
4201type AiSearchListInstancesParams = {
4202 page?: number;
4203 per_page?: number;
4204 /** Search instances by ID. */
4205 search?: string;
4206 /** Field to sort by. */
4207 order_by?: 'created_at';
4208 /** Sort direction. */
4209 order_by_direction?: 'asc' | 'desc';
4210};
4211type AiSearchListResponse = {
4212 result: AiSearchInstanceInfo[];
4213 result_info?: {
4214 count: number;
4215 page: number;
4216 per_page: number;
4217 total_count: number;
4218 };
4219};
4220// ============ AI Search Config Types ============
4221type AiSearchConfig = {
4222 /** Instance ID (1-32 chars, pattern: ^[a-z0-9_]+(?:-[a-z0-9_]+)*$) */
4223 id: string;
4224 /** Instance type. Omit to create with built-in storage. */
4225 type?: 'r2' | 'web-crawler' | string;
4226 /** Source URL (required for web-crawler type). */
4227 source?: string;
4228 source_params?: unknown;
4229 /** Token ID (UUID format) */
4230 token_id?: string;
4231 ai_gateway_id?: string;
4232 /** Enable query rewriting (default false) */
4233 rewrite_query?: boolean;
4234 /** Enable reranking (default false) */
4235 reranking?: boolean;
4236 embedding_model?: string;
4237 ai_search_model?: string;
4238 rewrite_model?: string;
4239 reranking_model?: string;
4240 /** @deprecated Use index_method instead. */
4241 hybrid_search_enabled?: boolean;
4242 /** Controls which storage backends are used during indexing. Defaults to vector-only. */
4243 index_method?: {
4244 vector?: boolean;
4245 keyword?: boolean;
4246 };
4247 /** Fusion method for combining vector and keyword results. "rrf" = reciprocal rank fusion (default), "max" = maximum score. */
4248 fusion_method?: 'max' | 'rrf';
4249 indexing_options?: {
4250 keyword_tokenizer?: 'porter' | 'trigram';
4251 } | null;
4252 retrieval_options?: {
4253 keyword_match_mode?: 'and' | 'or';
4254 boost_by?: Array<{
4255 field: string;
4256 direction?: 'asc' | 'desc' | 'exists' | 'not_exists';
4257 }>;
4258 } | null;
4259 chunk?: boolean;
4260 chunk_size?: number;
4261 chunk_overlap?: number;
4262 /** Minimum similarity score (0-1) for a result to be included. */
4263 score_threshold?: number;
4264 max_num_results?: number;
4265 cache?: boolean;
4266 /** Similarity threshold for cache hits. Stricter = fewer cache hits but higher relevance. */
4267 cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes';
4268 custom_metadata?: Array<{
4269 field_name: string;
4270 data_type: 'text' | 'number' | 'boolean' | 'datetime';
4271 }>;
4272 namespace?: string;
4273 /** Sync interval in seconds. 3600=1h, 7200=2h, 14400=4h, 21600=6h, 43200=12h, 86400=24h. */
4274 sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400;
4275 metadata?: Record<string, unknown>;
4276 [key: string]: unknown;
4277};
4278// ============ AI Search Item Types ============
4279type AiSearchItemInfo = {
4280 id: string;
4281 key: string;
4282 status: 'completed' | 'error' | 'skipped' | 'queued' | 'running' | 'outdated';
4283 next_action?: 'INDEX' | 'DELETE' | null;
4284 error?: string;
4285 checksum?: string;
4286 namespace?: string;
4287 chunks_count?: number | null;
4288 file_size?: number | null;
4289 source_id?: string | null;
4290 last_seen_at?: string;
4291 created_at?: string;
4292 metadata?: Record<string, unknown>;
4293 [key: string]: unknown;
4294};
4295type AiSearchItemContentResult = {
4296 body: ReadableStream;
4297 contentType: string;
4298 filename: string;
4299 size: number;
4300};
4301type AiSearchUploadItemOptions = {
4302 metadata?: Record<string, unknown>;
4303};
4304type AiSearchListItemsParams = {
4305 page?: number;
4306 per_page?: number;
4307 /** Search items by key name. */
4308 search?: string;
4309 /** Sort order for results. */
4310 sort_by?: 'status' | 'modified_at';
4311 /** Filter items by processing status. */
4312 status?: 'queued' | 'running' | 'completed' | 'error' | 'skipped' | 'outdated';
4313 /** Filter items by source (e.g. "builtin" or "web-crawler:https://example.com"). */
4314 source?: string;
4315 /** JSON-encoded Vectorize filter for metadata filtering. */
4316 metadata_filter?: string;
4317 /** Filter items by their unique ID. Returns at most one item. */
4318 item_id?: string;
4319 /**
4320 * Filter items by their exact key (object key / filename). Keys are unique
4321 * per source, so combine with `source` to disambiguate across data sources.
4322 */
4323 key?: string;
4324};
4325type AiSearchListItemsResponse = {
4326 result: AiSearchItemInfo[];
4327 result_info?: {
4328 count: number;
4329 page: number;
4330 per_page: number;
4331 total_count: number;
4332 };
4333};
4334// ============ AI Search Item Logs Types ============
4335type AiSearchItemLogsParams = {
4336 /** Maximum number of log entries to return (1-100, default 50). */
4337 limit?: number;
4338 /** Opaque cursor for pagination. Pass the `cursor` value from a previous response. */
4339 cursor?: string;
4340};
4341type AiSearchItemLog = {
4342 timestamp: string;
4343 action: string;
4344 message: string;
4345 fileKey?: string;
4346 chunkCount?: number;
4347 processingTimeMs?: number;
4348 errorType?: string;
4349};
4350/** Paginated response for item processing logs (cursor-based). */
4351type AiSearchItemLogsResponse = {
4352 result: AiSearchItemLog[];
4353 result_info: {
4354 count: number;
4355 per_page: number;
4356 cursor: string | null;
4357 truncated: boolean;
4358 };
4359};
4360// ============ AI Search Item Chunks Types ============
4361type AiSearchItemChunksParams = {
4362 /** Maximum number of chunks to return (1-100, default 20). */
4363 limit?: number;
4364 /** Offset into the chunks list (default 0). */
4365 offset?: number;
4366};
4367/** A single indexed chunk belonging to an item, including its text content and byte range. */
4368type AiSearchItemChunk = {
4369 id: string;
4370 text: string;
4371 start_byte: number;
4372 end_byte: number;
4373 item?: {
4374 timestamp?: number;
4375 key: string;
4376 metadata?: Record<string, unknown>;
4377 };
4378};
4379/** Paginated response for item chunks (offset-based). */
4380type AiSearchItemChunksResponse = {
4381 result: AiSearchItemChunk[];
4382 result_info: {
4383 count: number;
4384 total: number;
4385 limit: number;
4386 offset: number;
4387 };
4388};
4389// ============ AI Search Job Types ============
4390type AiSearchJobInfo = {
4391 id: string;
4392 source: 'user' | 'schedule';
4393 description?: string;
4394 last_seen_at?: string;
4395 started_at?: string;
4396 ended_at?: string;
4397 end_reason?: string;
4398};
4399type AiSearchJobLog = {
4400 id: number;
4401 message: string;
4402 message_type: number;
4403 created_at: number;
4404};
4405type AiSearchCreateJobParams = {
4406 description?: string;
4407};
4408type AiSearchListJobsParams = {
4409 page?: number;
4410 per_page?: number;
4411};
4412type AiSearchListJobsResponse = {
4413 result: AiSearchJobInfo[];
4414 result_info?: {
4415 count: number;
4416 page: number;
4417 per_page: number;
4418 total_count: number;
4419 };
4420};
4421type AiSearchJobLogsParams = {
4422 page?: number;
4423 per_page?: number;
4424};
4425type AiSearchJobLogsResponse = {
4426 result: AiSearchJobLog[];
4427 result_info?: {
4428 count: number;
4429 page: number;
4430 per_page: number;
4431 total_count: number;
4432 };
4433};
4434// ============ AI Search Sub-Service Classes ============
4435/**
4436 * Single item service for an AI Search instance.
4437 * Provides info, download, sync, logs, and chunks operations on a specific item.
4438 */
4439declare abstract class AiSearchItem {
4440 /** Get metadata about this item. */
4441 info(): Promise<AiSearchItemInfo>;
4442 /**
4443 * Download the item's content.
4444 * @returns Object with body stream, content type, filename, and size.
4445 */
4446 download(): Promise<AiSearchItemContentResult>;
4447 /**
4448 * Trigger re-indexing of this item.
4449 * @returns The updated item info.
4450 */
4451 sync(): Promise<AiSearchItemInfo>;
4452 /**
4453 * Retrieve processing logs for this item (cursor-based pagination).
4454 * @param params Optional pagination parameters (limit, cursor).
4455 * @returns Paginated log entries for this item.
4456 */
4457 logs(params?: AiSearchItemLogsParams): Promise<AiSearchItemLogsResponse>;
4458 /**
4459 * List indexed chunks for this item (offset-based pagination).
4460 * @param params Optional pagination parameters (limit, offset).
4461 * @returns Paginated chunk entries for this item.
4462 */
4463 chunks(params?: AiSearchItemChunksParams): Promise<AiSearchItemChunksResponse>;
4464}
4465/**
4466 * Items collection service for an AI Search instance.
4467 * Provides list, upload, and access to individual items.
4468 */
4469declare abstract class AiSearchItems {
4470 /** List items in this instance. */
4471 list(params?: AiSearchListItemsParams): Promise<AiSearchListItemsResponse>;
4472 /**
4473 * Upload a file as an item. Behaves as an upsert: if an item with the same
4474 * filename already exists, it is overwritten and re-indexed.
4475 * @param name Filename for the uploaded item.
4476 * @param content File content as a ReadableStream, Blob, or string.
4477 * @param options Optional metadata to attach to the item.
4478 * @returns The created item info.
4479 */
4480 upload(name: string, content: ReadableStream | Blob | string, options?: AiSearchUploadItemOptions): Promise<AiSearchItemInfo>;
4481 /**
4482 * Upload a file and poll until processing completes.
4483 * Behaves as an upsert: if an item with the same filename already exists,
4484 * it is overwritten and re-indexed.
4485 * @param name Filename for the uploaded item.
4486 * @param content File content as a ReadableStream, Blob, or string.
4487 * @param options Optional metadata and polling configuration.
4488 * @returns The item info after processing completes (or timeout).
4489 */
4490 uploadAndPoll(name: string, content: ReadableStream | Blob | string, options?: AiSearchUploadItemOptions & {
4491 /** Polling interval in milliseconds (default 1000). */
4492 pollIntervalMs?: number;
4493 /** Maximum time to wait in milliseconds (default 30000). */
4494 timeoutMs?: number;
4495 }): Promise<AiSearchItemInfo>;
4496 /**
4497 * Get an item by ID.
4498 * @param itemId The item identifier.
4499 * @returns Item service for info, download, sync, logs, and chunks operations.
4500 */
4501 get(itemId: string): AiSearchItem;
4502 /**
4503 * Delete an item from the instance.
4504 * @param itemId The item identifier.
4505 */
4506 delete(itemId: string): Promise<void>;
4507}
4508/**
4509 * Single job service for an AI Search instance.
4510 * Provides info, logs, and cancel operations for a specific job.
4511 */
4512declare abstract class AiSearchJob {
4513 /** Get metadata about this job. */
4514 info(): Promise<AiSearchJobInfo>;
4515 /** Get logs for this job. */
4516 logs(params?: AiSearchJobLogsParams): Promise<AiSearchJobLogsResponse>;
4517 /**
4518 * Cancel a running job.
4519 * @returns The updated job info.
4520 * @throws AiSearchNotFoundError if the job does not exist.
4521 */
4522 cancel(): Promise<AiSearchJobInfo>;
4523}
4524/**
4525 * Jobs collection service for an AI Search instance.
4526 * Provides list, create, and access to individual jobs.
4527 */
4528declare abstract class AiSearchJobs {
4529 /** List jobs for this instance. */
4530 list(params?: AiSearchListJobsParams): Promise<AiSearchListJobsResponse>;
4531 /**
4532 * Create a new indexing job.
4533 * @param params Optional job parameters.
4534 * @returns The created job info.
4535 */
4536 create(params?: AiSearchCreateJobParams): Promise<AiSearchJobInfo>;
4537 /**
4538 * Get a job by ID.
4539 * @param jobId The job identifier.
4540 * @returns Job service for info, logs, and cancel operations.
4541 */
4542 get(jobId: string): AiSearchJob;
4543}
4544// ============ AI Search Binding Classes ============
4545/**
4546 * Instance-level AI Search service.
4547 *
4548 * Used as:
4549 * - The return type of `AiSearchNamespace.get(name)` (namespace binding)
4550 * - The type of `env.BLOG_SEARCH` (single instance binding via `ai_search`)
4551 *
4552 * Provides search, chat, update, stats, items, and jobs operations.
4553 *
4554 * @example
4555 * ```ts
4556 * // Via namespace binding
4557 * const instance = env.AI_SEARCH.get("blog");
4558 * const results = await instance.search({
4559 * query: "How does caching work?",
4560 * });
4561 *
4562 * // Via single instance binding
4563 * const results = await env.BLOG_SEARCH.search({
4564 * messages: [{ role: "user", content: "How does caching work?" }],
4565 * });
4566 * ```
4567 */
4568declare abstract class AiSearchInstance {
4569 /**
4570 * Search the AI Search instance for relevant chunks.
4571 * @param params Search request with query or messages and optional AI search options.
4572 * @returns Search response with matching chunks and search query.
4573 */
4574 search(params: AiSearchSearchRequest): Promise<AiSearchSearchResponse>;
4575 /**
4576 * Generate chat completions with AI Search context (streaming).
4577 * @param params Chat completions request with stream: true.
4578 * @returns ReadableStream of server-sent events.
4579 */
4580 chatCompletions(params: AiSearchChatCompletionsRequest & {
4581 stream: true;
4582 }): Promise<ReadableStream>;
4583 /**
4584 * Generate chat completions with AI Search context.
4585 * @param params Chat completions request.
4586 * @returns Chat completion response with choices and RAG chunks.
4587 */
4588 chatCompletions(params: AiSearchChatCompletionsRequest): Promise<AiSearchChatCompletionsResponse>;
4589 /**
4590 * Update the instance configuration.
4591 * @param config Partial configuration to update.
4592 * @returns Updated instance info.
4593 */
4594 update(config: Partial<AiSearchConfig>): Promise<AiSearchInstanceInfo>;
4595 /** Get metadata about this instance. */
4596 info(): Promise<AiSearchInstanceInfo>;
4597 /**
4598 * Get instance statistics (item count, indexing status, etc.).
4599 * @returns Statistics with counts per status, last activity time, and engine details.
4600 */
4601 stats(): Promise<AiSearchStatsResponse>;
4602 /** Items collection — list, upload, and manage items in this instance. */
4603 get items(): AiSearchItems;
4604 /** Jobs collection — list, create, and inspect indexing jobs. */
4605 get jobs(): AiSearchJobs;
4606}
4607/**
4608 * Namespace-level AI Search service.
4609 *
4610 * Used as the type of `env.AI_SEARCH` (namespace binding via `ai_search_namespaces`).
4611 * Scoped to a single namespace. Provides dynamic instance access, creation, deletion,
4612 * and multi-instance search/chat operations.
4613 *
4614 * @example
4615 * ```ts
4616 * // Access an instance within the namespace
4617 * const blog = env.AI_SEARCH.get("blog");
4618 * const results = await blog.search({ query: "How does caching work?" });
4619 *
4620 * // List all instances in the namespace
4621 * const instances = await env.AI_SEARCH.list();
4622 *
4623 * // Create a new instance with built-in storage
4624 * const tenant = await env.AI_SEARCH.create({ id: "tenant-123" });
4625 *
4626 * // Upload items into the instance
4627 * await tenant.items.upload("doc.pdf", fileContent);
4628 *
4629 * // Search across multiple instances
4630 * const multi = await env.AI_SEARCH.search({
4631 * query: "caching",
4632 * ai_search_options: { instance_ids: ["blog", "docs"] },
4633 * });
4634 *
4635 * // Delete an instance
4636 * await env.AI_SEARCH.delete("tenant-123");
4637 * ```
4638 */
4639declare abstract class AiSearchNamespace {
4640 /**
4641 * Get an instance by name within the bound namespace.
4642 * @param name Instance name.
4643 * @returns Instance service for search, chat, update, stats, items, and jobs.
4644 */
4645 get(name: string): AiSearchInstance;
4646 /**
4647 * List instances in the bound namespace.
4648 * @param params Optional pagination, search, and ordering parameters.
4649 * @returns Array of instance metadata with pagination info.
4650 */
4651 list(params?: AiSearchListInstancesParams): Promise<AiSearchListResponse>;
4652 /**
4653 * Create a new instance within the bound namespace.
4654 * @param config Instance configuration. Only `id` is required — omit `type` and `source` to create with built-in storage.
4655 * @returns Instance service for the newly created instance.
4656 *
4657 * @example
4658 * ```ts
4659 * // Create with built-in storage (upload items manually)
4660 * const instance = await env.AI_SEARCH.create({ id: "my-search" });
4661 *
4662 * // Create with web crawler source
4663 * const instance = await env.AI_SEARCH.create({
4664 * id: "docs-search",
4665 * type: "web-crawler",
4666 * source: "https://developers.cloudflare.com",
4667 * });
4668 * ```
4669 */
4670 create(config: AiSearchConfig): Promise<AiSearchInstance>;
4671 /**
4672 * Delete an instance from the bound namespace.
4673 * @param name Instance name to delete.
4674 */
4675 delete(name: string): Promise<void>;
4676 /**
4677 * Search across multiple instances within the bound namespace.
4678 * Fans out to the specified instance_ids and merges results.
4679 * @param params Search request with required `ai_search_options.instance_ids`.
4680 * @returns Search response with chunks tagged by instance_id and optional partial-failure errors.
4681 */
4682 search(params: AiSearchMultiSearchRequest): Promise<AiSearchMultiSearchResponse>;
4683 /**
4684 * Generate chat completions across multiple instances within the bound namespace (streaming).
4685 * Fans out to the specified instance_ids, merges context, and generates a response.
4686 * @param params Chat completions request with stream: true and required `ai_search_options.instance_ids`.
4687 * @returns ReadableStream of server-sent events.
4688 */
4689 chatCompletions(params: AiSearchMultiChatCompletionsRequest & {
4690 stream: true;
4691 }): Promise<ReadableStream>;
4692 /**
4693 * Generate chat completions across multiple instances within the bound namespace.
4694 * Fans out to the specified instance_ids, merges context, and generates a response.
4695 * @param params Chat completions request with required `ai_search_options.instance_ids`.
4696 * @returns Chat completion response with choices, chunks tagged by instance_id, and optional partial-failure errors.
4697 */
4698 chatCompletions(params: AiSearchMultiChatCompletionsRequest): Promise<AiSearchMultiChatCompletionsResponse>;
4699}
4700type AiImageClassificationInput = {
4701 image: number[];
4702};
4703type AiImageClassificationOutput = {
4704 score?: number;
4705 label?: string;
4706}[];
4707declare abstract class BaseAiImageClassification {
4708 inputs: AiImageClassificationInput;
4709 postProcessedOutputs: AiImageClassificationOutput;
4710}
4711type AiImageToTextInput = {
4712 image: number[];
4713 prompt?: string;
4714 max_tokens?: number;
4715 temperature?: number;
4716 top_p?: number;
4717 top_k?: number;
4718 seed?: number;
4719 repetition_penalty?: number;
4720 frequency_penalty?: number;
4721 presence_penalty?: number;
4722 raw?: boolean;
4723 messages?: RoleScopedChatInput[];
4724};
4725type AiImageToTextOutput = {
4726 description: string;
4727};
4728declare abstract class BaseAiImageToText {
4729 inputs: AiImageToTextInput;
4730 postProcessedOutputs: AiImageToTextOutput;
4731}
4732type AiImageTextToTextInput = {
4733 image: string;
4734 prompt?: string;
4735 max_tokens?: number;
4736 temperature?: number;
4737 ignore_eos?: boolean;
4738 top_p?: number;
4739 top_k?: number;
4740 seed?: number;
4741 repetition_penalty?: number;
4742 frequency_penalty?: number;
4743 presence_penalty?: number;
4744 raw?: boolean;
4745 messages?: RoleScopedChatInput[];
4746};
4747type AiImageTextToTextOutput = {
4748 description: string;
4749};
4750declare abstract class BaseAiImageTextToText {
4751 inputs: AiImageTextToTextInput;
4752 postProcessedOutputs: AiImageTextToTextOutput;
4753}
4754type AiMultimodalEmbeddingsInput = {
4755 image: string;
4756 text: string[];
4757};
4758type AiIMultimodalEmbeddingsOutput = {
4759 data: number[][];
4760 shape: number[];
4761};
4762declare abstract class BaseAiMultimodalEmbeddings {
4763 inputs: AiImageTextToTextInput;
4764 postProcessedOutputs: AiImageTextToTextOutput;
4765}
4766type AiObjectDetectionInput = {
4767 image: number[];
4768};
4769type AiObjectDetectionOutput = {
4770 score?: number;
4771 label?: string;
4772}[];
4773declare abstract class BaseAiObjectDetection {
4774 inputs: AiObjectDetectionInput;
4775 postProcessedOutputs: AiObjectDetectionOutput;
4776}
4777type AiSentenceSimilarityInput = {
4778 source: string;
4779 sentences: string[];
4780};
4781type AiSentenceSimilarityOutput = number[];
4782declare abstract class BaseAiSentenceSimilarity {
4783 inputs: AiSentenceSimilarityInput;
4784 postProcessedOutputs: AiSentenceSimilarityOutput;
4785}
4786type AiAutomaticSpeechRecognitionInput = {
4787 audio: number[];
4788};
4789type AiAutomaticSpeechRecognitionOutput = {
4790 text?: string;
4791 words?: {
4792 word: string;
4793 start: number;
4794 end: number;
4795 }[];
4796 vtt?: string;
4797};
4798declare abstract class BaseAiAutomaticSpeechRecognition {
4799 inputs: AiAutomaticSpeechRecognitionInput;
4800 postProcessedOutputs: AiAutomaticSpeechRecognitionOutput;
4801}
4802type AiSummarizationInput = {
4803 input_text: string;
4804 max_length?: number;
4805};
4806type AiSummarizationOutput = {
4807 summary: string;
4808};
4809declare abstract class BaseAiSummarization {
4810 inputs: AiSummarizationInput;
4811 postProcessedOutputs: AiSummarizationOutput;
4812}
4813type AiTextClassificationInput = {
4814 text: string;
4815};
4816type AiTextClassificationOutput = {
4817 score?: number;
4818 label?: string;
4819}[];
4820declare abstract class BaseAiTextClassification {
4821 inputs: AiTextClassificationInput;
4822 postProcessedOutputs: AiTextClassificationOutput;
4823}
4824type AiTextEmbeddingsInput = {
4825 text: string | string[];
4826};
4827type AiTextEmbeddingsOutput = {
4828 shape: number[];
4829 data: number[][];
4830};
4831declare abstract class BaseAiTextEmbeddings {
4832 inputs: AiTextEmbeddingsInput;
4833 postProcessedOutputs: AiTextEmbeddingsOutput;
4834}
4835type RoleScopedChatInput = {
4836 role: "user" | "assistant" | "system" | "tool" | (string & NonNullable<unknown>);
4837 content: string;
4838 name?: string;
4839};
4840type AiTextGenerationToolLegacyInput = {
4841 name: string;
4842 description: string;
4843 parameters?: {
4844 type: "object" | (string & NonNullable<unknown>);
4845 properties: {
4846 [key: string]: {
4847 type: string;
4848 description?: string;
4849 };
4850 };
4851 required: string[];
4852 };
4853};
4854type AiTextGenerationToolInput = {
4855 type: "function" | (string & NonNullable<unknown>);
4856 function: {
4857 name: string;
4858 description: string;
4859 parameters?: {
4860 type: "object" | (string & NonNullable<unknown>);
4861 properties: {
4862 [key: string]: {
4863 type: string;
4864 description?: string;
4865 };
4866 };
4867 required: string[];
4868 };
4869 };
4870};
4871type AiTextGenerationFunctionsInput = {
4872 name: string;
4873 code: string;
4874};
4875type AiTextGenerationResponseFormat = {
4876 type: string;
4877 json_schema?: any;
4878};
4879type AiTextGenerationInput = {
4880 prompt?: string;
4881 raw?: boolean;
4882 stream?: boolean;
4883 max_tokens?: number;
4884 temperature?: number;
4885 top_p?: number;
4886 top_k?: number;
4887 seed?: number;
4888 repetition_penalty?: number;
4889 frequency_penalty?: number;
4890 presence_penalty?: number;
4891 messages?: RoleScopedChatInput[];
4892 response_format?: AiTextGenerationResponseFormat;
4893 tools?: AiTextGenerationToolInput[] | AiTextGenerationToolLegacyInput[] | (object & NonNullable<unknown>);
4894 functions?: AiTextGenerationFunctionsInput[];
4895};
4896type AiTextGenerationToolLegacyOutput = {
4897 name: string;
4898 arguments: unknown;
4899};
4900type AiTextGenerationToolOutput = {
4901 id: string;
4902 type: "function";
4903 function: {
4904 name: string;
4905 arguments: string;
4906 };
4907};
4908type UsageTags = {
4909 prompt_tokens: number;
4910 completion_tokens: number;
4911 total_tokens: number;
4912};
4913type AiTextGenerationOutput = {
4914 response?: string;
4915 tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[];
4916 usage?: UsageTags;
4917};
4918declare abstract class BaseAiTextGeneration {
4919 inputs: AiTextGenerationInput;
4920 postProcessedOutputs: AiTextGenerationOutput;
4921}
4922type AiTextToSpeechInput = {
4923 prompt: string;
4924 lang?: string;
4925};
4926type AiTextToSpeechOutput = Uint8Array | {
4927 audio: string;
4928};
4929declare abstract class BaseAiTextToSpeech {
4930 inputs: AiTextToSpeechInput;
4931 postProcessedOutputs: AiTextToSpeechOutput;
4932}
4933type AiTextToImageInput = {
4934 prompt: string;
4935 negative_prompt?: string;
4936 height?: number;
4937 width?: number;
4938 image?: number[];
4939 image_b64?: string;
4940 mask?: number[];
4941 num_steps?: number;
4942 strength?: number;
4943 guidance?: number;
4944 seed?: number;
4945};
4946type AiTextToImageOutput = ReadableStream<Uint8Array>;
4947declare abstract class BaseAiTextToImage {
4948 inputs: AiTextToImageInput;
4949 postProcessedOutputs: AiTextToImageOutput;
4950}
4951type AiTranslationInput = {
4952 text: string;
4953 target_lang: string;
4954 source_lang?: string;
4955};
4956type AiTranslationOutput = {
4957 translated_text?: string;
4958};
4959declare abstract class BaseAiTranslation {
4960 inputs: AiTranslationInput;
4961 postProcessedOutputs: AiTranslationOutput;
4962}
4963/**
4964 * Workers AI support for OpenAI's Chat Completions API
4965 */
4966type ChatCompletionContentPartText = {
4967 type: "text";
4968 text: string;
4969};
4970type ChatCompletionContentPartImage = {
4971 type: "image_url";
4972 image_url: {
4973 url: string;
4974 detail?: "auto" | "low" | "high";
4975 };
4976};
4977type ChatCompletionContentPartInputAudio = {
4978 type: "input_audio";
4979 input_audio: {
4980 /** Base64 encoded audio data. */
4981 data: string;
4982 format: "wav" | "mp3";
4983 };
4984};
4985type ChatCompletionContentPartFile = {
4986 type: "file";
4987 file: {
4988 /** Base64 encoded file data. */
4989 file_data?: string;
4990 /** The ID of an uploaded file. */
4991 file_id?: string;
4992 filename?: string;
4993 };
4994};
4995type ChatCompletionContentPartRefusal = {
4996 type: "refusal";
4997 refusal: string;
4998};
4999type ChatCompletionContentPart = ChatCompletionContentPartText | ChatCompletionContentPartImage | ChatCompletionContentPartInputAudio | ChatCompletionContentPartFile;
5000type FunctionDefinition = {
5001 name: string;
5002 description?: string;
5003 parameters?: Record<string, unknown>;
5004 strict?: boolean | null;
5005};
5006type ChatCompletionFunctionTool = {
5007 type: "function";
5008 function: FunctionDefinition;
5009};
5010type ChatCompletionCustomToolGrammarFormat = {
5011 type: "grammar";
5012 grammar: {
5013 definition: string;
5014 syntax: "lark" | "regex";
5015 };
5016};
5017type ChatCompletionCustomToolTextFormat = {
5018 type: "text";
5019};
5020type ChatCompletionCustomToolFormat = ChatCompletionCustomToolTextFormat | ChatCompletionCustomToolGrammarFormat;
5021type ChatCompletionCustomTool = {
5022 type: "custom";
5023 custom: {
5024 name: string;
5025 description?: string;
5026 format?: ChatCompletionCustomToolFormat;
5027 };
5028};
5029type ChatCompletionTool = ChatCompletionFunctionTool | ChatCompletionCustomTool;
5030type ChatCompletionMessageFunctionToolCall = {
5031 id: string;
5032 type: "function";
5033 function: {
5034 name: string;
5035 /** JSON-encoded arguments string. */
5036 arguments: string;
5037 };
5038};
5039type ChatCompletionMessageCustomToolCall = {
5040 id: string;
5041 type: "custom";
5042 custom: {
5043 name: string;
5044 input: string;
5045 };
5046};
5047type ChatCompletionMessageToolCall = ChatCompletionMessageFunctionToolCall | ChatCompletionMessageCustomToolCall;
5048type ChatCompletionToolChoiceFunction = {
5049 type: "function";
5050 function: {
5051 name: string;
5052 };
5053};
5054type ChatCompletionToolChoiceCustom = {
5055 type: "custom";
5056 custom: {
5057 name: string;
5058 };
5059};
5060type ChatCompletionToolChoiceAllowedTools = {
5061 type: "allowed_tools";
5062 allowed_tools: {
5063 mode: "auto" | "required";
5064 tools: Array<Record<string, unknown>>;
5065 };
5066};
5067type ChatCompletionToolChoiceOption = "none" | "auto" | "required" | ChatCompletionToolChoiceFunction | ChatCompletionToolChoiceCustom | ChatCompletionToolChoiceAllowedTools;
5068type DeveloperMessage = {
5069 role: "developer";
5070 content: string | Array<{
5071 type: "text";
5072 text: string;
5073 }>;
5074 name?: string;
5075};
5076type SystemMessage = {
5077 role: "system";
5078 content: string | Array<{
5079 type: "text";
5080 text: string;
5081 }>;
5082 name?: string;
5083};
5084/**
5085 * Permissive merged content part used inside UserMessage arrays.
5086 *
5087 * Cabidela has a limitation where anyOf/oneOf with enum-based discrimination
5088 * inside nested array items does not correctly match different branches for
5089 * different array elements, so the schema uses a single merged object.
5090 */
5091type UserMessageContentPart = {
5092 type: "text" | "image_url" | "input_audio" | "file";
5093 text?: string;
5094 image_url?: {
5095 url?: string;
5096 detail?: "auto" | "low" | "high";
5097 };
5098 input_audio?: {
5099 data?: string;
5100 format?: "wav" | "mp3";
5101 };
5102 file?: {
5103 file_data?: string;
5104 file_id?: string;
5105 filename?: string;
5106 };
5107};
5108type UserMessage = {
5109 role: "user";
5110 content: string | Array<UserMessageContentPart>;
5111 name?: string;
5112};
5113type AssistantMessageContentPart = {
5114 type: "text" | "refusal";
5115 text?: string;
5116 refusal?: string;
5117};
5118type AssistantMessage = {
5119 role: "assistant";
5120 content?: string | null | Array<AssistantMessageContentPart>;
5121 refusal?: string | null;
5122 name?: string;
5123 audio?: {
5124 id: string;
5125 };
5126 tool_calls?: Array<ChatCompletionMessageToolCall>;
5127 function_call?: {
5128 name: string;
5129 arguments: string;
5130 };
5131};
5132type ToolMessage = {
5133 role: "tool";
5134 content: string | Array<{
5135 type: "text";
5136 text: string;
5137 }>;
5138 tool_call_id: string;
5139};
5140type FunctionMessage = {
5141 role: "function";
5142 content: string;
5143 name: string;
5144};
5145type ChatCompletionMessageParam = DeveloperMessage | SystemMessage | UserMessage | AssistantMessage | ToolMessage | FunctionMessage;
5146type ChatCompletionsResponseFormatText = {
5147 type: "text";
5148};
5149type ChatCompletionsResponseFormatJSONObject = {
5150 type: "json_object";
5151};
5152type ResponseFormatJSONSchema = {
5153 type: "json_schema";
5154 json_schema: {
5155 name: string;
5156 description?: string;
5157 schema?: Record<string, unknown>;
5158 strict?: boolean | null;
5159 };
5160};
5161type ResponseFormat = ChatCompletionsResponseFormatText | ChatCompletionsResponseFormatJSONObject | ResponseFormatJSONSchema;
5162type ChatCompletionsStreamOptions = {
5163 include_usage?: boolean;
5164 include_obfuscation?: boolean;
5165};
5166type PredictionContent = {
5167 type: "content";
5168 content: string | Array<{
5169 type: "text";
5170 text: string;
5171 }>;
5172};
5173type AudioParams = {
5174 voice: string | {
5175 id: string;
5176 };
5177 format: "wav" | "aac" | "mp3" | "flac" | "opus" | "pcm16";
5178};
5179type WebSearchUserLocation = {
5180 type: "approximate";
5181 approximate: {
5182 city?: string;
5183 country?: string;
5184 region?: string;
5185 timezone?: string;
5186 };
5187};
5188type WebSearchOptions = {
5189 search_context_size?: "low" | "medium" | "high";
5190 user_location?: WebSearchUserLocation;
5191};
5192// Source of truth for per-model reasoning types: each model's `reasoning_effort` metadata
5193// in Workers AI ConfigAPI (supported efforts, aliases, defaults, and whether reasoning can
5194// be turned off). The Workers AI SDK type generator (cloudflare/ai/sdk,
5195// apps/worker-constellation-entry/scripts/build-types) turns it into the per-model
5196// `inputs` types below; the developer docs model schemas come from the same metadata.
5197type ChatTemplateKwargs = {
5198 /** Whether to enable reasoning. Support and defaults depend on the model. */
5199 enable_thinking?: boolean;
5200 /** If false, preserves reasoning context between turns. */
5201 clear_thinking?: boolean;
5202};
5203/** Shared optional properties used by both Prompt and Messages input branches. */
5204type ChatCompletionsCommonOptions = {
5205 model?: string;
5206 audio?: AudioParams;
5207 frequency_penalty?: number | null;
5208 logit_bias?: Record<string, unknown> | null;
5209 logprobs?: boolean | null;
5210 top_logprobs?: number | null;
5211 max_tokens?: number | null;
5212 max_completion_tokens?: number | null;
5213 metadata?: Record<string, unknown> | null;
5214 modalities?: Array<"text" | "audio"> | null;
5215 n?: number | null;
5216 parallel_tool_calls?: boolean;
5217 prediction?: PredictionContent;
5218 presence_penalty?: number | null;
5219 /** Reasoning effort. Supported levels depend on the model. */
5220 reasoning_effort?: "low" | "medium" | "high" | null;
5221 chat_template_kwargs?: ChatTemplateKwargs;
5222 response_format?: ResponseFormat;
5223 seed?: number | null;
5224 service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;
5225 stop?: string | Array<string> | null;
5226 store?: boolean | null;
5227 stream?: boolean | null;
5228 stream_options?: ChatCompletionsStreamOptions;
5229 temperature?: number | null;
5230 tool_choice?: ChatCompletionToolChoiceOption;
5231 tools?: Array<ChatCompletionTool>;
5232 top_p?: number | null;
5233 user?: string;
5234 web_search_options?: WebSearchOptions;
5235 function_call?: "none" | "auto" | {
5236 name: string;
5237 };
5238 functions?: Array<FunctionDefinition>;
5239};
5240type PromptTokensDetails = {
5241 cached_tokens?: number;
5242 audio_tokens?: number;
5243};
5244type CompletionTokensDetails = {
5245 reasoning_tokens?: number;
5246 audio_tokens?: number;
5247 accepted_prediction_tokens?: number;
5248 rejected_prediction_tokens?: number;
5249};
5250type CompletionUsage = {
5251 prompt_tokens: number;
5252 completion_tokens: number;
5253 total_tokens: number;
5254 prompt_tokens_details?: PromptTokensDetails;
5255 completion_tokens_details?: CompletionTokensDetails;
5256};
5257type ChatCompletionTopLogprob = {
5258 token: string;
5259 logprob: number;
5260 bytes: Array<number> | null;
5261};
5262type ChatCompletionTokenLogprob = {
5263 token: string;
5264 logprob: number;
5265 bytes: Array<number> | null;
5266 top_logprobs: Array<ChatCompletionTopLogprob>;
5267};
5268type ChatCompletionAudio = {
5269 id: string;
5270 /** Base64 encoded audio bytes. */
5271 data: string;
5272 expires_at: number;
5273 transcript: string;
5274};
5275type ChatCompletionUrlCitation = {
5276 type: "url_citation";
5277 url_citation: {
5278 url: string;
5279 title: string;
5280 start_index: number;
5281 end_index: number;
5282 };
5283};
5284type ChatCompletionResponseMessage = {
5285 role: "assistant";
5286 content: string | null;
5287 refusal: string | null;
5288 annotations?: Array<ChatCompletionUrlCitation>;
5289 audio?: ChatCompletionAudio;
5290 tool_calls?: Array<ChatCompletionMessageToolCall>;
5291 function_call?: {
5292 name: string;
5293 arguments: string;
5294 } | null;
5295};
5296type ChatCompletionLogprobs = {
5297 content: Array<ChatCompletionTokenLogprob> | null;
5298 refusal?: Array<ChatCompletionTokenLogprob> | null;
5299};
5300type ChatCompletionChoice = {
5301 index: number;
5302 message: ChatCompletionResponseMessage;
5303 finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | "function_call";
5304 logprobs: ChatCompletionLogprobs | null;
5305};
5306type ChatCompletionsMessagesInput = {
5307 messages: Array<ChatCompletionMessageParam>;
5308} & ChatCompletionsCommonOptions;
5309type ChatCompletionsOutput = {
5310 id: string;
5311 object: string;
5312 created: number;
5313 model: string;
5314 choices: Array<ChatCompletionChoice>;
5315 usage?: CompletionUsage;
5316 system_fingerprint?: string | null;
5317 service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;
5318};
5319/**
5320 * Workers AI support for OpenAI's Responses API
5321 * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts
5322 *
5323 * It's a stripped down version from its source.
5324 * It currently supports basic function calling, json mode and accepts images as input.
5325 *
5326 * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools.
5327 * We plan to add those incrementally as model + platform capabilities evolve.
5328 */
5329type ResponsesInput = {
5330 background?: boolean | null;
5331 conversation?: string | ResponseConversationParam | null;
5332 include?: Array<ResponseIncludable> | null;
5333 input?: string | ResponseInput;
5334 instructions?: string | null;
5335 max_output_tokens?: number | null;
5336 parallel_tool_calls?: boolean | null;
5337 previous_response_id?: string | null;
5338 prompt_cache_key?: string;
5339 reasoning?: Reasoning | null;
5340 safety_identifier?: string;
5341 service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;
5342 stream?: boolean | null;
5343 stream_options?: StreamOptions | null;
5344 temperature?: number | null;
5345 text?: ResponseTextConfig;
5346 tool_choice?: ToolChoiceOptions | ToolChoiceFunction;
5347 tools?: Array<Tool>;
5348 top_p?: number | null;
5349 truncation?: "auto" | "disabled" | null;
5350};
5351type ResponsesOutput = {
5352 id?: string;
5353 created_at?: number;
5354 output_text?: string;
5355 error?: ResponseError | null;
5356 incomplete_details?: ResponseIncompleteDetails | null;
5357 instructions?: string | Array<ResponseInputItem> | null;
5358 object?: "response";
5359 output?: Array<ResponseOutputItem>;
5360 parallel_tool_calls?: boolean;
5361 temperature?: number | null;
5362 tool_choice?: ToolChoiceOptions | ToolChoiceFunction;
5363 tools?: Array<Tool>;
5364 top_p?: number | null;
5365 max_output_tokens?: number | null;
5366 previous_response_id?: string | null;
5367 prompt?: ResponsePrompt | null;
5368 reasoning?: Reasoning | null;
5369 safety_identifier?: string;
5370 service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;
5371 status?: ResponseStatus;
5372 text?: ResponseTextConfig;
5373 truncation?: "auto" | "disabled" | null;
5374 usage?: ResponseUsage;
5375};
5376type EasyInputMessage = {
5377 content: string | ResponseInputMessageContentList;
5378 role: "user" | "assistant" | "system" | "developer";
5379 type?: "message";
5380};
5381type ResponsesFunctionTool = {
5382 name: string;
5383 parameters: {
5384 [key: string]: unknown;
5385 } | null;
5386 strict: boolean | null;
5387 type: "function";
5388 description?: string | null;
5389};
5390type ResponseIncompleteDetails = {
5391 reason?: "max_output_tokens" | "content_filter";
5392};
5393type ResponsePrompt = {
5394 id: string;
5395 variables?: {
5396 [key: string]: string | ResponseInputText | ResponseInputImage;
5397 } | null;
5398 version?: string | null;
5399};
5400type Reasoning = {
5401 effort?: ReasoningEffort | null;
5402 generate_summary?: "auto" | "concise" | "detailed" | null;
5403 summary?: "auto" | "concise" | "detailed" | null;
5404};
5405type ResponseContent = ResponseInputText | ResponseInputImage | ResponseOutputText | ResponseOutputRefusal | ResponseContentReasoningText;
5406type ResponseContentReasoningText = {
5407 text: string;
5408 type: "reasoning_text";
5409};
5410type ResponseConversationParam = {
5411 id: string;
5412};
5413type ResponseCreatedEvent = {
5414 response: Response;
5415 sequence_number: number;
5416 type: "response.created";
5417};
5418type ResponseCustomToolCallOutput = {
5419 call_id: string;
5420 output: string | Array<ResponseInputText | ResponseInputImage>;
5421 type: "custom_tool_call_output";
5422 id?: string;
5423};
5424type ResponseError = {
5425 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";
5426 message: string;
5427};
5428type ResponseErrorEvent = {
5429 code: string | null;
5430 message: string;
5431 param: string | null;
5432 sequence_number: number;
5433 type: "error";
5434};
5435type ResponseFailedEvent = {
5436 response: Response;
5437 sequence_number: number;
5438 type: "response.failed";
5439};
5440type ResponseFormatText = {
5441 type: "text";
5442};
5443type ResponseFormatJSONObject = {
5444 type: "json_object";
5445};
5446type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject;
5447type ResponseFormatTextJSONSchemaConfig = {
5448 name: string;
5449 schema: {
5450 [key: string]: unknown;
5451 };
5452 type: "json_schema";
5453 description?: string;
5454 strict?: boolean | null;
5455};
5456type ResponseFunctionCallArgumentsDeltaEvent = {
5457 delta: string;
5458 item_id: string;
5459 output_index: number;
5460 sequence_number: number;
5461 type: "response.function_call_arguments.delta";
5462};
5463type ResponseFunctionCallArgumentsDoneEvent = {
5464 arguments: string;
5465 item_id: string;
5466 name: string;
5467 output_index: number;
5468 sequence_number: number;
5469 type: "response.function_call_arguments.done";
5470};
5471type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent;
5472type ResponseFunctionCallOutputItemList = Array<ResponseFunctionCallOutputItem>;
5473type ResponseFunctionToolCall = {
5474 arguments: string;
5475 call_id: string;
5476 name: string;
5477 type: "function_call";
5478 id?: string;
5479 status?: "in_progress" | "completed" | "incomplete";
5480};
5481interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall {
5482 id: string;
5483}
5484type ResponseFunctionToolCallOutputItem = {
5485 id: string;
5486 call_id: string;
5487 output: string | Array<ResponseInputText | ResponseInputImage>;
5488 type: "function_call_output";
5489 status?: "in_progress" | "completed" | "incomplete";
5490};
5491type ResponseIncludable = "message.input_image.image_url" | "message.output_text.logprobs";
5492type ResponseIncompleteEvent = {
5493 response: Response;
5494 sequence_number: number;
5495 type: "response.incomplete";
5496};
5497type ResponseInput = Array<ResponseInputItem>;
5498type ResponseInputContent = ResponseInputText | ResponseInputImage;
5499type ResponseInputImage = {
5500 detail: "low" | "high" | "auto";
5501 type: "input_image";
5502 /**
5503 * Base64 encoded image
5504 */
5505 image_url?: string | null;
5506};
5507type ResponseInputImageContent = {
5508 type: "input_image";
5509 detail?: "low" | "high" | "auto" | null;
5510 /**
5511 * Base64 encoded image
5512 */
5513 image_url?: string | null;
5514};
5515type ResponseInputItem = EasyInputMessage | ResponseInputItemMessage | ResponseOutputMessage | ResponseFunctionToolCall | ResponseInputItemFunctionCallOutput | ResponseReasoningItem;
5516type ResponseInputItemFunctionCallOutput = {
5517 call_id: string;
5518 output: string | ResponseFunctionCallOutputItemList;
5519 type: "function_call_output";
5520 id?: string | null;
5521 status?: "in_progress" | "completed" | "incomplete" | null;
5522};
5523type ResponseInputItemMessage = {
5524 content: ResponseInputMessageContentList;
5525 role: "user" | "system" | "developer";
5526 status?: "in_progress" | "completed" | "incomplete";
5527 type?: "message";
5528};
5529type ResponseInputMessageContentList = Array<ResponseInputContent>;
5530type ResponseInputMessageItem = {
5531 id: string;
5532 content: ResponseInputMessageContentList;
5533 role: "user" | "system" | "developer";
5534 status?: "in_progress" | "completed" | "incomplete";
5535 type?: "message";
5536};
5537type ResponseInputText = {
5538 text: string;
5539 type: "input_text";
5540};
5541type ResponseInputTextContent = {
5542 text: string;
5543 type: "input_text";
5544};
5545type ResponseItem = ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem;
5546type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem;
5547type ResponseOutputItemAddedEvent = {
5548 item: ResponseOutputItem;
5549 output_index: number;
5550 sequence_number: number;
5551 type: "response.output_item.added";
5552};
5553type ResponseOutputItemDoneEvent = {
5554 item: ResponseOutputItem;
5555 output_index: number;
5556 sequence_number: number;
5557 type: "response.output_item.done";
5558};
5559type ResponseOutputMessage = {
5560 id: string;
5561 content: Array<ResponseOutputText | ResponseOutputRefusal>;
5562 role: "assistant";
5563 status: "in_progress" | "completed" | "incomplete";
5564 type: "message";
5565};
5566type ResponseOutputRefusal = {
5567 refusal: string;
5568 type: "refusal";
5569};
5570type ResponseOutputText = {
5571 text: string;
5572 type: "output_text";
5573 logprobs?: Array<Logprob>;
5574};
5575type ResponseReasoningItem = {
5576 id: string;
5577 summary: Array<ResponseReasoningSummaryItem>;
5578 type: "reasoning";
5579 content?: Array<ResponseReasoningContentItem>;
5580 encrypted_content?: string | null;
5581 status?: "in_progress" | "completed" | "incomplete";
5582};
5583type ResponseReasoningSummaryItem = {
5584 text: string;
5585 type: "summary_text";
5586};
5587type ResponseReasoningContentItem = {
5588 text: string;
5589 type: "reasoning_text";
5590};
5591type ResponseReasoningTextDeltaEvent = {
5592 content_index: number;
5593 delta: string;
5594 item_id: string;
5595 output_index: number;
5596 sequence_number: number;
5597 type: "response.reasoning_text.delta";
5598};
5599type ResponseReasoningTextDoneEvent = {
5600 content_index: number;
5601 item_id: string;
5602 output_index: number;
5603 sequence_number: number;
5604 text: string;
5605 type: "response.reasoning_text.done";
5606};
5607type ResponseRefusalDeltaEvent = {
5608 content_index: number;
5609 delta: string;
5610 item_id: string;
5611 output_index: number;
5612 sequence_number: number;
5613 type: "response.refusal.delta";
5614};
5615type ResponseRefusalDoneEvent = {
5616 content_index: number;
5617 item_id: string;
5618 output_index: number;
5619 refusal: string;
5620 sequence_number: number;
5621 type: "response.refusal.done";
5622};
5623type ResponseStatus = "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete";
5624type ResponseStreamEvent = ResponseCompletedEvent | ResponseCreatedEvent | ResponseErrorEvent | ResponseFunctionCallArgumentsDeltaEvent | ResponseFunctionCallArgumentsDoneEvent | ResponseFailedEvent | ResponseIncompleteEvent | ResponseOutputItemAddedEvent | ResponseOutputItemDoneEvent | ResponseReasoningTextDeltaEvent | ResponseReasoningTextDoneEvent | ResponseRefusalDeltaEvent | ResponseRefusalDoneEvent | ResponseTextDeltaEvent | ResponseTextDoneEvent;
5625type ResponseCompletedEvent = {
5626 response: Response;
5627 sequence_number: number;
5628 type: "response.completed";
5629};
5630type ResponseTextConfig = {
5631 format?: ResponseFormatTextConfig;
5632 verbosity?: "low" | "medium" | "high" | null;
5633};
5634type ResponseTextDeltaEvent = {
5635 content_index: number;
5636 delta: string;
5637 item_id: string;
5638 logprobs: Array<Logprob>;
5639 output_index: number;
5640 sequence_number: number;
5641 type: "response.output_text.delta";
5642};
5643type ResponseTextDoneEvent = {
5644 content_index: number;
5645 item_id: string;
5646 logprobs: Array<Logprob>;
5647 output_index: number;
5648 sequence_number: number;
5649 text: string;
5650 type: "response.output_text.done";
5651};
5652type Logprob = {
5653 token: string;
5654 logprob: number;
5655 top_logprobs?: Array<TopLogprob>;
5656};
5657type TopLogprob = {
5658 token?: string;
5659 logprob?: number;
5660};
5661type ResponseUsage = {
5662 input_tokens: number;
5663 output_tokens: number;
5664 total_tokens: number;
5665};
5666type Tool = ResponsesFunctionTool;
5667type ToolChoiceFunction = {
5668 name: string;
5669 type: "function";
5670};
5671type ToolChoiceOptions = "none";
5672type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null;
5673type StreamOptions = {
5674 include_obfuscation?: boolean;
5675};
5676/** Marks keys from T that aren't in U as optional never */
5677type Without<T, U> = {
5678 [P in Exclude<keyof T, keyof U>]?: never;
5679};
5680/** Either T or U, but not both (mutually exclusive) */
5681type XOR<T, U> = (T & Without<U, T>) | (U & Without<T, U>);
5682type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = {
5683 text: string | string[];
5684 /**
5685 * 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.
5686 */
5687 pooling?: "mean" | "cls";
5688} | {
5689 /**
5690 * Batch of the embeddings requests to run using async-queue
5691 */
5692 requests: {
5693 text: string | string[];
5694 /**
5695 * 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.
5696 */
5697 pooling?: "mean" | "cls";
5698 }[];
5699};
5700type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = {
5701 shape?: number[];
5702 /**
5703 * Embeddings of the requested text values
5704 */
5705 data?: number[][];
5706 /**
5707 * The pooling method used in the embedding process.
5708 */
5709 pooling?: "mean" | "cls";
5710} | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse;
5711interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse {
5712 /**
5713 * The async request id that can be used to obtain the results.
5714 */
5715 request_id?: string;
5716}
5717declare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 {
5718 inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input;
5719 postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output;
5720}
5721type Ai_Cf_Openai_Whisper_Input = string | {
5722 /**
5723 * An array of integers that represent the audio data constrained to 8-bit unsigned integer values
5724 */
5725 audio: number[];
5726};
5727interface Ai_Cf_Openai_Whisper_Output {
5728 /**
5729 * The transcription
5730 */
5731 text: string;
5732 word_count?: number;
5733 words?: {
5734 word?: string;
5735 /**
5736 * The second this word begins in the recording
5737 */
5738 start?: number;
5739 /**
5740 * The ending second when the word completes
5741 */
5742 end?: number;
5743 }[];
5744 vtt?: string;
5745}
5746declare abstract class Base_Ai_Cf_Openai_Whisper {
5747 inputs: Ai_Cf_Openai_Whisper_Input;
5748 postProcessedOutputs: Ai_Cf_Openai_Whisper_Output;
5749}
5750type Ai_Cf_Meta_M2M100_1_2B_Input = {
5751 /**
5752 * The text to be translated
5753 */
5754 text: string;
5755 /**
5756 * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified
5757 */
5758 source_lang?: string;
5759 /**
5760 * The language code to translate the text into (e.g., 'es' for Spanish)
5761 */
5762 target_lang: string;
5763} | {
5764 /**
5765 * Batch of the embeddings requests to run using async-queue
5766 */
5767 requests: {
5768 /**
5769 * The text to be translated
5770 */
5771 text: string;
5772 /**
5773 * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified
5774 */
5775 source_lang?: string;
5776 /**
5777 * The language code to translate the text into (e.g., 'es' for Spanish)
5778 */
5779 target_lang: string;
5780 }[];
5781};
5782type Ai_Cf_Meta_M2M100_1_2B_Output = {
5783 /**
5784 * The translated text in the target language
5785 */
5786 translated_text?: string;
5787} | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse;
5788interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse {
5789 /**
5790 * The async request id that can be used to obtain the results.
5791 */
5792 request_id?: string;
5793}
5794declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B {
5795 inputs: Ai_Cf_Meta_M2M100_1_2B_Input;
5796 postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output;
5797}
5798type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = {
5799 text: string | string[];
5800 /**
5801 * 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.
5802 */
5803 pooling?: "mean" | "cls";
5804} | {
5805 /**
5806 * Batch of the embeddings requests to run using async-queue
5807 */
5808 requests: {
5809 text: string | string[];
5810 /**
5811 * 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.
5812 */
5813 pooling?: "mean" | "cls";
5814 }[];
5815};
5816type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = {
5817 shape?: number[];
5818 /**
5819 * Embeddings of the requested text values
5820 */
5821 data?: number[][];
5822 /**
5823 * The pooling method used in the embedding process.
5824 */
5825 pooling?: "mean" | "cls";
5826} | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse;
5827interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse {
5828 /**
5829 * The async request id that can be used to obtain the results.
5830 */
5831 request_id?: string;
5832}
5833declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 {
5834 inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input;
5835 postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output;
5836}
5837type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = {
5838 text: string | string[];
5839 /**
5840 * 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.
5841 */
5842 pooling?: "mean" | "cls";
5843} | {
5844 /**
5845 * Batch of the embeddings requests to run using async-queue
5846 */
5847 requests: {
5848 text: string | string[];
5849 /**
5850 * 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.
5851 */
5852 pooling?: "mean" | "cls";
5853 }[];
5854};
5855type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = {
5856 shape?: number[];
5857 /**
5858 * Embeddings of the requested text values
5859 */
5860 data?: number[][];
5861 /**
5862 * The pooling method used in the embedding process.
5863 */
5864 pooling?: "mean" | "cls";
5865} | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse;
5866interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse {
5867 /**
5868 * The async request id that can be used to obtain the results.
5869 */
5870 request_id?: string;
5871}
5872declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 {
5873 inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input;
5874 postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output;
5875}
5876type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = string | {
5877 /**
5878 * The input text prompt for the model to generate a response.
5879 */
5880 prompt?: string;
5881 /**
5882 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
5883 */
5884 raw?: boolean;
5885 /**
5886 * 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.
5887 */
5888 top_p?: number;
5889 /**
5890 * 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.
5891 */
5892 top_k?: number;
5893 /**
5894 * Random seed for reproducibility of the generation.
5895 */
5896 seed?: number;
5897 /**
5898 * Penalty for repeated tokens; higher values discourage repetition.
5899 */
5900 repetition_penalty?: number;
5901 /**
5902 * Decreases the likelihood of the model repeating the same lines verbatim.
5903 */
5904 frequency_penalty?: number;
5905 /**
5906 * Increases the likelihood of the model introducing new topics.
5907 */
5908 presence_penalty?: number;
5909 image: number[] | (string & NonNullable<unknown>);
5910 /**
5911 * The maximum number of tokens to generate in the response.
5912 */
5913 max_tokens?: number;
5914};
5915interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output {
5916 description?: string;
5917}
5918declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M {
5919 inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input;
5920 postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output;
5921}
5922type Ai_Cf_Openai_Whisper_Tiny_En_Input = string | {
5923 /**
5924 * An array of integers that represent the audio data constrained to 8-bit unsigned integer values
5925 */
5926 audio: number[];
5927};
5928interface Ai_Cf_Openai_Whisper_Tiny_En_Output {
5929 /**
5930 * The transcription
5931 */
5932 text: string;
5933 word_count?: number;
5934 words?: {
5935 word?: string;
5936 /**
5937 * The second this word begins in the recording
5938 */
5939 start?: number;
5940 /**
5941 * The ending second when the word completes
5942 */
5943 end?: number;
5944 }[];
5945 vtt?: string;
5946}
5947declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En {
5948 inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input;
5949 postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output;
5950}
5951interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input {
5952 audio: string | {
5953 body?: object;
5954 contentType?: string;
5955 };
5956 /**
5957 * Supported tasks are 'translate' or 'transcribe'.
5958 */
5959 task?: string;
5960 /**
5961 * The language of the audio being transcribed or translated.
5962 */
5963 language?: string;
5964 /**
5965 * Preprocess the audio with a voice activity detection model.
5966 */
5967 vad_filter?: boolean;
5968 /**
5969 * A text prompt to help provide context to the model on the contents of the audio.
5970 */
5971 initial_prompt?: string;
5972 /**
5973 * The prefix appended to the beginning of the output of the transcription and can guide the transcription result.
5974 */
5975 prefix?: string;
5976 /**
5977 * The number of beams to use in beam search decoding. Higher values may improve accuracy at the cost of speed.
5978 */
5979 beam_size?: number;
5980 /**
5981 * Whether to condition on previous text during transcription. Setting to false may help prevent hallucination loops.
5982 */
5983 condition_on_previous_text?: boolean;
5984 /**
5985 * Threshold for detecting no-speech segments. Segments with no-speech probability above this value are skipped.
5986 */
5987 no_speech_threshold?: number;
5988 /**
5989 * Threshold for filtering out segments with high compression ratio, which often indicate repetitive or hallucinated text.
5990 */
5991 compression_ratio_threshold?: number;
5992 /**
5993 * Threshold for filtering out segments with low average log probability, indicating low confidence.
5994 */
5995 log_prob_threshold?: number;
5996 /**
5997 * Optional threshold (in seconds) to skip silent periods that may cause hallucinations.
5998 */
5999 hallucination_silence_threshold?: number;
6000}
6001interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output {
6002 transcription_info?: {
6003 /**
6004 * The language of the audio being transcribed or translated.
6005 */
6006 language?: string;
6007 /**
6008 * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1.
6009 */
6010 language_probability?: number;
6011 /**
6012 * The total duration of the original audio file, in seconds.
6013 */
6014 duration?: number;
6015 /**
6016 * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds.
6017 */
6018 duration_after_vad?: number;
6019 };
6020 /**
6021 * The complete transcription of the audio.
6022 */
6023 text: string;
6024 /**
6025 * The total number of words in the transcription.
6026 */
6027 word_count?: number;
6028 segments?: {
6029 /**
6030 * The starting time of the segment within the audio, in seconds.
6031 */
6032 start?: number;
6033 /**
6034 * The ending time of the segment within the audio, in seconds.
6035 */
6036 end?: number;
6037 /**
6038 * The transcription of the segment.
6039 */
6040 text?: string;
6041 /**
6042 * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs.
6043 */
6044 temperature?: number;
6045 /**
6046 * The average log probability of the predictions for the words in this segment, indicating overall confidence.
6047 */
6048 avg_logprob?: number;
6049 /**
6050 * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process.
6051 */
6052 compression_ratio?: number;
6053 /**
6054 * The probability that the segment contains no speech, represented as a decimal between 0 and 1.
6055 */
6056 no_speech_prob?: number;
6057 words?: {
6058 /**
6059 * The individual word transcribed from the audio.
6060 */
6061 word?: string;
6062 /**
6063 * The starting time of the word within the audio, in seconds.
6064 */
6065 start?: number;
6066 /**
6067 * The ending time of the word within the audio, in seconds.
6068 */
6069 end?: number;
6070 }[];
6071 }[];
6072 /**
6073 * The transcription in WebVTT format, which includes timing and text information for use in subtitles.
6074 */
6075 vtt?: string;
6076}
6077declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo {
6078 inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input;
6079 postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output;
6080}
6081type Ai_Cf_Baai_Bge_M3_Input = Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts | Ai_Cf_Baai_Bge_M3_Input_Embedding | {
6082 /**
6083 * Batch of the embeddings requests to run using async-queue
6084 */
6085 requests: (Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 | Ai_Cf_Baai_Bge_M3_Input_Embedding_1)[];
6086};
6087interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts {
6088 /**
6089 * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts
6090 */
6091 query?: string;
6092 /**
6093 * List of provided contexts. Note that the index in this array is important, as the response will refer to it.
6094 */
6095 contexts: {
6096 /**
6097 * One of the provided context content
6098 */
6099 text?: string;
6100 }[];
6101 /**
6102 * When provided with too long context should the model error out or truncate the context to fit?
6103 */
6104 truncate_inputs?: boolean;
6105}
6106interface Ai_Cf_Baai_Bge_M3_Input_Embedding {
6107 text: string | string[];
6108 /**
6109 * When provided with too long context should the model error out or truncate the context to fit?
6110 */
6111 truncate_inputs?: boolean;
6112}
6113interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 {
6114 /**
6115 * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts
6116 */
6117 query?: string;
6118 /**
6119 * List of provided contexts. Note that the index in this array is important, as the response will refer to it.
6120 */
6121 contexts: {
6122 /**
6123 * One of the provided context content
6124 */
6125 text?: string;
6126 }[];
6127 /**
6128 * When provided with too long context should the model error out or truncate the context to fit?
6129 */
6130 truncate_inputs?: boolean;
6131}
6132interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 {
6133 text: string | string[];
6134 /**
6135 * When provided with too long context should the model error out or truncate the context to fit?
6136 */
6137 truncate_inputs?: boolean;
6138}
6139type 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;
6140interface Ai_Cf_Baai_Bge_M3_Output_Query {
6141 response?: {
6142 /**
6143 * Index of the context in the request
6144 */
6145 id?: number;
6146 /**
6147 * Score of the context under the index.
6148 */
6149 score?: number;
6150 }[];
6151}
6152interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts {
6153 response?: number[][];
6154 shape?: number[];
6155 /**
6156 * The pooling method used in the embedding process.
6157 */
6158 pooling?: "mean" | "cls";
6159}
6160interface Ai_Cf_Baai_Bge_M3_Output_Embedding {
6161 shape?: number[];
6162 /**
6163 * Embeddings of the requested text values
6164 */
6165 data?: number[][];
6166 /**
6167 * The pooling method used in the embedding process.
6168 */
6169 pooling?: "mean" | "cls";
6170}
6171interface Ai_Cf_Baai_Bge_M3_AsyncResponse {
6172 /**
6173 * The async request id that can be used to obtain the results.
6174 */
6175 request_id?: string;
6176}
6177declare abstract class Base_Ai_Cf_Baai_Bge_M3 {
6178 inputs: Ai_Cf_Baai_Bge_M3_Input;
6179 postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output;
6180}
6181interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input {
6182 /**
6183 * A text description of the image you want to generate.
6184 */
6185 prompt: string;
6186 /**
6187 * The number of diffusion steps; higher values can improve quality but take longer.
6188 */
6189 steps?: number;
6190}
6191interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output {
6192 /**
6193 * The generated image in Base64 format.
6194 */
6195 image?: string;
6196}
6197declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell {
6198 inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input;
6199 postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output;
6200}
6201type 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;
6202interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt {
6203 /**
6204 * The input text prompt for the model to generate a response.
6205 */
6206 prompt: string;
6207 image?: number[] | (string & NonNullable<unknown>);
6208 /**
6209 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
6210 */
6211 raw?: boolean;
6212 /**
6213 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
6214 */
6215 stream?: boolean;
6216 /**
6217 * The maximum number of tokens to generate in the response.
6218 */
6219 max_tokens?: number;
6220 /**
6221 * Controls the randomness of the output; higher values produce more random results.
6222 */
6223 temperature?: number;
6224 /**
6225 * 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.
6226 */
6227 top_p?: number;
6228 /**
6229 * 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.
6230 */
6231 top_k?: number;
6232 /**
6233 * Random seed for reproducibility of the generation.
6234 */
6235 seed?: number;
6236 /**
6237 * Penalty for repeated tokens; higher values discourage repetition.
6238 */
6239 repetition_penalty?: number;
6240 /**
6241 * Decreases the likelihood of the model repeating the same lines verbatim.
6242 */
6243 frequency_penalty?: number;
6244 /**
6245 * Increases the likelihood of the model introducing new topics.
6246 */
6247 presence_penalty?: number;
6248 /**
6249 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
6250 */
6251 lora?: string;
6252}
6253interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages {
6254 /**
6255 * An array of message objects representing the conversation history.
6256 */
6257 messages: {
6258 /**
6259 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
6260 */
6261 role?: string;
6262 /**
6263 * The tool call id. If you don't know what to put here you can fall back to 000000001
6264 */
6265 tool_call_id?: string;
6266 content?: string | {
6267 /**
6268 * Type of the content provided
6269 */
6270 type?: string;
6271 text?: string;
6272 image_url?: {
6273 /**
6274 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
6275 */
6276 url?: string;
6277 };
6278 }[] | {
6279 /**
6280 * Type of the content provided
6281 */
6282 type?: string;
6283 text?: string;
6284 image_url?: {
6285 /**
6286 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
6287 */
6288 url?: string;
6289 };
6290 };
6291 }[];
6292 image?: number[] | (string & NonNullable<unknown>);
6293 functions?: {
6294 name: string;
6295 code: string;
6296 }[];
6297 /**
6298 * A list of tools available for the assistant to use.
6299 */
6300 tools?: ({
6301 /**
6302 * The name of the tool. More descriptive the better.
6303 */
6304 name: string;
6305 /**
6306 * A brief description of what the tool does.
6307 */
6308 description: string;
6309 /**
6310 * Schema defining the parameters accepted by the tool.
6311 */
6312 parameters: {
6313 /**
6314 * The type of the parameters object (usually 'object').
6315 */
6316 type: string;
6317 /**
6318 * List of required parameter names.
6319 */
6320 required?: string[];
6321 /**
6322 * Definitions of each parameter.
6323 */
6324 properties: {
6325 [k: string]: {
6326 /**
6327 * The data type of the parameter.
6328 */
6329 type: string;
6330 /**
6331 * A description of the expected parameter.
6332 */
6333 description: string;
6334 };
6335 };
6336 };
6337 } | {
6338 /**
6339 * Specifies the type of tool (e.g., 'function').
6340 */
6341 type: string;
6342 /**
6343 * Details of the function tool.
6344 */
6345 function: {
6346 /**
6347 * The name of the function.
6348 */
6349 name: string;
6350 /**
6351 * A brief description of what the function does.
6352 */
6353 description: string;
6354 /**
6355 * Schema defining the parameters accepted by the function.
6356 */
6357 parameters: {
6358 /**
6359 * The type of the parameters object (usually 'object').
6360 */
6361 type: string;
6362 /**
6363 * List of required parameter names.
6364 */
6365 required?: string[];
6366 /**
6367 * Definitions of each parameter.
6368 */
6369 properties: {
6370 [k: string]: {
6371 /**
6372 * The data type of the parameter.
6373 */
6374 type: string;
6375 /**
6376 * A description of the expected parameter.
6377 */
6378 description: string;
6379 };
6380 };
6381 };
6382 };
6383 })[];
6384 /**
6385 * If true, the response will be streamed back incrementally.
6386 */
6387 stream?: boolean;
6388 /**
6389 * The maximum number of tokens to generate in the response.
6390 */
6391 max_tokens?: number;
6392 /**
6393 * Controls the randomness of the output; higher values produce more random results.
6394 */
6395 temperature?: number;
6396 /**
6397 * 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.
6398 */
6399 top_p?: number;
6400 /**
6401 * 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.
6402 */
6403 top_k?: number;
6404 /**
6405 * Random seed for reproducibility of the generation.
6406 */
6407 seed?: number;
6408 /**
6409 * Penalty for repeated tokens; higher values discourage repetition.
6410 */
6411 repetition_penalty?: number;
6412 /**
6413 * Decreases the likelihood of the model repeating the same lines verbatim.
6414 */
6415 frequency_penalty?: number;
6416 /**
6417 * Increases the likelihood of the model introducing new topics.
6418 */
6419 presence_penalty?: number;
6420}
6421type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = {
6422 /**
6423 * The generated text response from the model
6424 */
6425 response?: string;
6426 /**
6427 * An array of tool calls requests made during the response generation
6428 */
6429 tool_calls?: {
6430 /**
6431 * The arguments passed to be passed to the tool call request
6432 */
6433 arguments?: object;
6434 /**
6435 * The name of the tool to be called
6436 */
6437 name?: string;
6438 }[];
6439};
6440declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct {
6441 inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input;
6442 postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output;
6443}
6444type 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;
6445interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt {
6446 /**
6447 * The input text prompt for the model to generate a response.
6448 */
6449 prompt: string;
6450 /**
6451 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
6452 */
6453 lora?: string;
6454 response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode;
6455 /**
6456 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
6457 */
6458 raw?: boolean;
6459 /**
6460 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
6461 */
6462 stream?: boolean;
6463 /**
6464 * The maximum number of tokens to generate in the response.
6465 */
6466 max_tokens?: number;
6467 /**
6468 * Controls the randomness of the output; higher values produce more random results.
6469 */
6470 temperature?: number;
6471 /**
6472 * 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.
6473 */
6474 top_p?: number;
6475 /**
6476 * 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.
6477 */
6478 top_k?: number;
6479 /**
6480 * Random seed for reproducibility of the generation.
6481 */
6482 seed?: number;
6483 /**
6484 * Penalty for repeated tokens; higher values discourage repetition.
6485 */
6486 repetition_penalty?: number;
6487 /**
6488 * Decreases the likelihood of the model repeating the same lines verbatim.
6489 */
6490 frequency_penalty?: number;
6491 /**
6492 * Increases the likelihood of the model introducing new topics.
6493 */
6494 presence_penalty?: number;
6495}
6496interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode {
6497 type?: "json_object" | "json_schema";
6498 json_schema?: unknown;
6499}
6500interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages {
6501 /**
6502 * An array of message objects representing the conversation history.
6503 */
6504 messages: {
6505 /**
6506 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
6507 */
6508 role: string;
6509 content: string | {
6510 /**
6511 * Type of the content (text)
6512 */
6513 type?: string;
6514 /**
6515 * Text content
6516 */
6517 text?: string;
6518 }[];
6519 }[];
6520 functions?: {
6521 name: string;
6522 code: string;
6523 }[];
6524 /**
6525 * A list of tools available for the assistant to use.
6526 */
6527 tools?: ({
6528 /**
6529 * The name of the tool. More descriptive the better.
6530 */
6531 name: string;
6532 /**
6533 * A brief description of what the tool does.
6534 */
6535 description: string;
6536 /**
6537 * Schema defining the parameters accepted by the tool.
6538 */
6539 parameters: {
6540 /**
6541 * The type of the parameters object (usually 'object').
6542 */
6543 type: string;
6544 /**
6545 * List of required parameter names.
6546 */
6547 required?: string[];
6548 /**
6549 * Definitions of each parameter.
6550 */
6551 properties: {
6552 [k: string]: {
6553 /**
6554 * The data type of the parameter.
6555 */
6556 type: string;
6557 /**
6558 * A description of the expected parameter.
6559 */
6560 description: string;
6561 };
6562 };
6563 };
6564 } | {
6565 /**
6566 * Specifies the type of tool (e.g., 'function').
6567 */
6568 type: string;
6569 /**
6570 * Details of the function tool.
6571 */
6572 function: {
6573 /**
6574 * The name of the function.
6575 */
6576 name: string;
6577 /**
6578 * A brief description of what the function does.
6579 */
6580 description: string;
6581 /**
6582 * Schema defining the parameters accepted by the function.
6583 */
6584 parameters: {
6585 /**
6586 * The type of the parameters object (usually 'object').
6587 */
6588 type: string;
6589 /**
6590 * List of required parameter names.
6591 */
6592 required?: string[];
6593 /**
6594 * Definitions of each parameter.
6595 */
6596 properties: {
6597 [k: string]: {
6598 /**
6599 * The data type of the parameter.
6600 */
6601 type: string;
6602 /**
6603 * A description of the expected parameter.
6604 */
6605 description: string;
6606 };
6607 };
6608 };
6609 };
6610 })[];
6611 response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1;
6612 /**
6613 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
6614 */
6615 raw?: boolean;
6616 /**
6617 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
6618 */
6619 stream?: boolean;
6620 /**
6621 * The maximum number of tokens to generate in the response.
6622 */
6623 max_tokens?: number;
6624 /**
6625 * Controls the randomness of the output; higher values produce more random results.
6626 */
6627 temperature?: number;
6628 /**
6629 * 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.
6630 */
6631 top_p?: number;
6632 /**
6633 * 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.
6634 */
6635 top_k?: number;
6636 /**
6637 * Random seed for reproducibility of the generation.
6638 */
6639 seed?: number;
6640 /**
6641 * Penalty for repeated tokens; higher values discourage repetition.
6642 */
6643 repetition_penalty?: number;
6644 /**
6645 * Decreases the likelihood of the model repeating the same lines verbatim.
6646 */
6647 frequency_penalty?: number;
6648 /**
6649 * Increases the likelihood of the model introducing new topics.
6650 */
6651 presence_penalty?: number;
6652}
6653interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 {
6654 type?: "json_object" | "json_schema";
6655 json_schema?: unknown;
6656}
6657interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch {
6658 requests?: {
6659 /**
6660 * 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.
6661 */
6662 external_reference?: string;
6663 /**
6664 * Prompt for the text generation model
6665 */
6666 prompt?: string;
6667 /**
6668 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
6669 */
6670 stream?: boolean;
6671 /**
6672 * The maximum number of tokens to generate in the response.
6673 */
6674 max_tokens?: number;
6675 /**
6676 * Controls the randomness of the output; higher values produce more random results.
6677 */
6678 temperature?: number;
6679 /**
6680 * 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.
6681 */
6682 top_p?: number;
6683 /**
6684 * Random seed for reproducibility of the generation.
6685 */
6686 seed?: number;
6687 /**
6688 * Penalty for repeated tokens; higher values discourage repetition.
6689 */
6690 repetition_penalty?: number;
6691 /**
6692 * Decreases the likelihood of the model repeating the same lines verbatim.
6693 */
6694 frequency_penalty?: number;
6695 /**
6696 * Increases the likelihood of the model introducing new topics.
6697 */
6698 presence_penalty?: number;
6699 response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2;
6700 }[];
6701}
6702interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 {
6703 type?: "json_object" | "json_schema";
6704 json_schema?: unknown;
6705}
6706type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = {
6707 /**
6708 * The generated text response from the model
6709 */
6710 response: string;
6711 /**
6712 * Usage statistics for the inference request
6713 */
6714 usage?: {
6715 /**
6716 * Total number of tokens in input
6717 */
6718 prompt_tokens?: number;
6719 /**
6720 * Total number of tokens in output
6721 */
6722 completion_tokens?: number;
6723 /**
6724 * Total number of input and output tokens
6725 */
6726 total_tokens?: number;
6727 };
6728 /**
6729 * An array of tool calls requests made during the response generation
6730 */
6731 tool_calls?: {
6732 /**
6733 * The arguments passed to be passed to the tool call request
6734 */
6735 arguments?: object;
6736 /**
6737 * The name of the tool to be called
6738 */
6739 name?: string;
6740 }[];
6741} | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse;
6742interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse {
6743 /**
6744 * The async request id that can be used to obtain the results.
6745 */
6746 request_id?: string;
6747}
6748declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast {
6749 inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input;
6750 postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output;
6751}
6752interface Ai_Cf_Meta_Llama_Guard_3_8B_Input {
6753 /**
6754 * An array of message objects representing the conversation history.
6755 */
6756 messages: {
6757 /**
6758 * The role of the message sender must alternate between 'user' and 'assistant'.
6759 */
6760 role: "user" | "assistant";
6761 /**
6762 * The content of the message as a string.
6763 */
6764 content: string;
6765 }[];
6766 /**
6767 * The maximum number of tokens to generate in the response.
6768 */
6769 max_tokens?: number;
6770 /**
6771 * Controls the randomness of the output; higher values produce more random results.
6772 */
6773 temperature?: number;
6774 /**
6775 * Dictate the output format of the generated response.
6776 */
6777 response_format?: {
6778 /**
6779 * Set to json_object to process and output generated text as JSON.
6780 */
6781 type?: string;
6782 };
6783}
6784interface Ai_Cf_Meta_Llama_Guard_3_8B_Output {
6785 response?: string | {
6786 /**
6787 * Whether the conversation is safe or not.
6788 */
6789 safe?: boolean;
6790 /**
6791 * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe.
6792 */
6793 categories?: string[];
6794 };
6795 /**
6796 * Usage statistics for the inference request
6797 */
6798 usage?: {
6799 /**
6800 * Total number of tokens in input
6801 */
6802 prompt_tokens?: number;
6803 /**
6804 * Total number of tokens in output
6805 */
6806 completion_tokens?: number;
6807 /**
6808 * Total number of input and output tokens
6809 */
6810 total_tokens?: number;
6811 };
6812}
6813declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B {
6814 inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input;
6815 postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output;
6816}
6817interface Ai_Cf_Baai_Bge_Reranker_Base_Input {
6818 /**
6819 * A query you wish to perform against the provided contexts.
6820 */
6821 /**
6822 * Number of returned results starting with the best score.
6823 */
6824 top_k?: number;
6825 /**
6826 * List of provided contexts. Note that the index in this array is important, as the response will refer to it.
6827 */
6828 contexts: {
6829 /**
6830 * One of the provided context content
6831 */
6832 text?: string;
6833 }[];
6834}
6835interface Ai_Cf_Baai_Bge_Reranker_Base_Output {
6836 response?: {
6837 /**
6838 * Index of the context in the request
6839 */
6840 id?: number;
6841 /**
6842 * Score of the context under the index.
6843 */
6844 score?: number;
6845 }[];
6846}
6847declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base {
6848 inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input;
6849 postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output;
6850}
6851type 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;
6852interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt {
6853 /**
6854 * The input text prompt for the model to generate a response.
6855 */
6856 prompt: string;
6857 /**
6858 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
6859 */
6860 lora?: string;
6861 response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode;
6862 /**
6863 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
6864 */
6865 raw?: boolean;
6866 /**
6867 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
6868 */
6869 stream?: boolean;
6870 /**
6871 * The maximum number of tokens to generate in the response.
6872 */
6873 max_tokens?: number;
6874 /**
6875 * Controls the randomness of the output; higher values produce more random results.
6876 */
6877 temperature?: number;
6878 /**
6879 * 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.
6880 */
6881 top_p?: number;
6882 /**
6883 * 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.
6884 */
6885 top_k?: number;
6886 /**
6887 * Random seed for reproducibility of the generation.
6888 */
6889 seed?: number;
6890 /**
6891 * Penalty for repeated tokens; higher values discourage repetition.
6892 */
6893 repetition_penalty?: number;
6894 /**
6895 * Decreases the likelihood of the model repeating the same lines verbatim.
6896 */
6897 frequency_penalty?: number;
6898 /**
6899 * Increases the likelihood of the model introducing new topics.
6900 */
6901 presence_penalty?: number;
6902}
6903interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode {
6904 type?: "json_object" | "json_schema";
6905 json_schema?: unknown;
6906}
6907interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages {
6908 /**
6909 * An array of message objects representing the conversation history.
6910 */
6911 messages: {
6912 /**
6913 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
6914 */
6915 role: string;
6916 /**
6917 * The content of the message as a string.
6918 */
6919 content: string;
6920 }[];
6921 functions?: {
6922 name: string;
6923 code: string;
6924 }[];
6925 /**
6926 * A list of tools available for the assistant to use.
6927 */
6928 tools?: ({
6929 /**
6930 * The name of the tool. More descriptive the better.
6931 */
6932 name: string;
6933 /**
6934 * A brief description of what the tool does.
6935 */
6936 description: string;
6937 /**
6938 * Schema defining the parameters accepted by the tool.
6939 */
6940 parameters: {
6941 /**
6942 * The type of the parameters object (usually 'object').
6943 */
6944 type: string;
6945 /**
6946 * List of required parameter names.
6947 */
6948 required?: string[];
6949 /**
6950 * Definitions of each parameter.
6951 */
6952 properties: {
6953 [k: string]: {
6954 /**
6955 * The data type of the parameter.
6956 */
6957 type: string;
6958 /**
6959 * A description of the expected parameter.
6960 */
6961 description: string;
6962 };
6963 };
6964 };
6965 } | {
6966 /**
6967 * Specifies the type of tool (e.g., 'function').
6968 */
6969 type: string;
6970 /**
6971 * Details of the function tool.
6972 */
6973 function: {
6974 /**
6975 * The name of the function.
6976 */
6977 name: string;
6978 /**
6979 * A brief description of what the function does.
6980 */
6981 description: string;
6982 /**
6983 * Schema defining the parameters accepted by the function.
6984 */
6985 parameters: {
6986 /**
6987 * The type of the parameters object (usually 'object').
6988 */
6989 type: string;
6990 /**
6991 * List of required parameter names.
6992 */
6993 required?: string[];
6994 /**
6995 * Definitions of each parameter.
6996 */
6997 properties: {
6998 [k: string]: {
6999 /**
7000 * The data type of the parameter.
7001 */
7002 type: string;
7003 /**
7004 * A description of the expected parameter.
7005 */
7006 description: string;
7007 };
7008 };
7009 };
7010 };
7011 })[];
7012 response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1;
7013 /**
7014 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7015 */
7016 raw?: boolean;
7017 /**
7018 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7019 */
7020 stream?: boolean;
7021 /**
7022 * The maximum number of tokens to generate in the response.
7023 */
7024 max_tokens?: number;
7025 /**
7026 * Controls the randomness of the output; higher values produce more random results.
7027 */
7028 temperature?: number;
7029 /**
7030 * 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.
7031 */
7032 top_p?: number;
7033 /**
7034 * 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.
7035 */
7036 top_k?: number;
7037 /**
7038 * Random seed for reproducibility of the generation.
7039 */
7040 seed?: number;
7041 /**
7042 * Penalty for repeated tokens; higher values discourage repetition.
7043 */
7044 repetition_penalty?: number;
7045 /**
7046 * Decreases the likelihood of the model repeating the same lines verbatim.
7047 */
7048 frequency_penalty?: number;
7049 /**
7050 * Increases the likelihood of the model introducing new topics.
7051 */
7052 presence_penalty?: number;
7053}
7054interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 {
7055 type?: "json_object" | "json_schema";
7056 json_schema?: unknown;
7057}
7058type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = {
7059 /**
7060 * The generated text response from the model
7061 */
7062 response: string;
7063 /**
7064 * Usage statistics for the inference request
7065 */
7066 usage?: {
7067 /**
7068 * Total number of tokens in input
7069 */
7070 prompt_tokens?: number;
7071 /**
7072 * Total number of tokens in output
7073 */
7074 completion_tokens?: number;
7075 /**
7076 * Total number of input and output tokens
7077 */
7078 total_tokens?: number;
7079 };
7080 /**
7081 * An array of tool calls requests made during the response generation
7082 */
7083 tool_calls?: {
7084 /**
7085 * The arguments passed to be passed to the tool call request
7086 */
7087 arguments?: object;
7088 /**
7089 * The name of the tool to be called
7090 */
7091 name?: string;
7092 }[];
7093};
7094declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct {
7095 inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input;
7096 postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output;
7097}
7098type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages;
7099interface Ai_Cf_Qwen_Qwq_32B_Prompt {
7100 /**
7101 * The input text prompt for the model to generate a response.
7102 */
7103 prompt: string;
7104 /**
7105 * JSON schema that should be fulfilled for the response.
7106 */
7107 guided_json?: object;
7108 /**
7109 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7110 */
7111 raw?: boolean;
7112 /**
7113 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7114 */
7115 stream?: boolean;
7116 /**
7117 * The maximum number of tokens to generate in the response.
7118 */
7119 max_tokens?: number;
7120 /**
7121 * Controls the randomness of the output; higher values produce more random results.
7122 */
7123 temperature?: number;
7124 /**
7125 * 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.
7126 */
7127 top_p?: number;
7128 /**
7129 * 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.
7130 */
7131 top_k?: number;
7132 /**
7133 * Random seed for reproducibility of the generation.
7134 */
7135 seed?: number;
7136 /**
7137 * Penalty for repeated tokens; higher values discourage repetition.
7138 */
7139 repetition_penalty?: number;
7140 /**
7141 * Decreases the likelihood of the model repeating the same lines verbatim.
7142 */
7143 frequency_penalty?: number;
7144 /**
7145 * Increases the likelihood of the model introducing new topics.
7146 */
7147 presence_penalty?: number;
7148}
7149interface Ai_Cf_Qwen_Qwq_32B_Messages {
7150 /**
7151 * An array of message objects representing the conversation history.
7152 */
7153 messages: {
7154 /**
7155 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
7156 */
7157 role?: string;
7158 /**
7159 * The tool call id. If you don't know what to put here you can fall back to 000000001
7160 */
7161 tool_call_id?: string;
7162 content?: string | {
7163 /**
7164 * Type of the content provided
7165 */
7166 type?: string;
7167 text?: string;
7168 image_url?: {
7169 /**
7170 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7171 */
7172 url?: string;
7173 };
7174 }[] | {
7175 /**
7176 * Type of the content provided
7177 */
7178 type?: string;
7179 text?: string;
7180 image_url?: {
7181 /**
7182 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7183 */
7184 url?: string;
7185 };
7186 };
7187 }[];
7188 functions?: {
7189 name: string;
7190 code: string;
7191 }[];
7192 /**
7193 * A list of tools available for the assistant to use.
7194 */
7195 tools?: ({
7196 /**
7197 * The name of the tool. More descriptive the better.
7198 */
7199 name: string;
7200 /**
7201 * A brief description of what the tool does.
7202 */
7203 description: string;
7204 /**
7205 * Schema defining the parameters accepted by the tool.
7206 */
7207 parameters: {
7208 /**
7209 * The type of the parameters object (usually 'object').
7210 */
7211 type: string;
7212 /**
7213 * List of required parameter names.
7214 */
7215 required?: string[];
7216 /**
7217 * Definitions of each parameter.
7218 */
7219 properties: {
7220 [k: string]: {
7221 /**
7222 * The data type of the parameter.
7223 */
7224 type: string;
7225 /**
7226 * A description of the expected parameter.
7227 */
7228 description: string;
7229 };
7230 };
7231 };
7232 } | {
7233 /**
7234 * Specifies the type of tool (e.g., 'function').
7235 */
7236 type: string;
7237 /**
7238 * Details of the function tool.
7239 */
7240 function: {
7241 /**
7242 * The name of the function.
7243 */
7244 name: string;
7245 /**
7246 * A brief description of what the function does.
7247 */
7248 description: string;
7249 /**
7250 * Schema defining the parameters accepted by the function.
7251 */
7252 parameters: {
7253 /**
7254 * The type of the parameters object (usually 'object').
7255 */
7256 type: string;
7257 /**
7258 * List of required parameter names.
7259 */
7260 required?: string[];
7261 /**
7262 * Definitions of each parameter.
7263 */
7264 properties: {
7265 [k: string]: {
7266 /**
7267 * The data type of the parameter.
7268 */
7269 type: string;
7270 /**
7271 * A description of the expected parameter.
7272 */
7273 description: string;
7274 };
7275 };
7276 };
7277 };
7278 })[];
7279 /**
7280 * JSON schema that should be fufilled for the response.
7281 */
7282 guided_json?: object;
7283 /**
7284 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7285 */
7286 raw?: boolean;
7287 /**
7288 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7289 */
7290 stream?: boolean;
7291 /**
7292 * The maximum number of tokens to generate in the response.
7293 */
7294 max_tokens?: number;
7295 /**
7296 * Controls the randomness of the output; higher values produce more random results.
7297 */
7298 temperature?: number;
7299 /**
7300 * 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.
7301 */
7302 top_p?: number;
7303 /**
7304 * 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.
7305 */
7306 top_k?: number;
7307 /**
7308 * Random seed for reproducibility of the generation.
7309 */
7310 seed?: number;
7311 /**
7312 * Penalty for repeated tokens; higher values discourage repetition.
7313 */
7314 repetition_penalty?: number;
7315 /**
7316 * Decreases the likelihood of the model repeating the same lines verbatim.
7317 */
7318 frequency_penalty?: number;
7319 /**
7320 * Increases the likelihood of the model introducing new topics.
7321 */
7322 presence_penalty?: number;
7323}
7324type Ai_Cf_Qwen_Qwq_32B_Output = {
7325 /**
7326 * The generated text response from the model
7327 */
7328 response: string;
7329 /**
7330 * Usage statistics for the inference request
7331 */
7332 usage?: {
7333 /**
7334 * Total number of tokens in input
7335 */
7336 prompt_tokens?: number;
7337 /**
7338 * Total number of tokens in output
7339 */
7340 completion_tokens?: number;
7341 /**
7342 * Total number of input and output tokens
7343 */
7344 total_tokens?: number;
7345 };
7346 /**
7347 * An array of tool calls requests made during the response generation
7348 */
7349 tool_calls?: {
7350 /**
7351 * The arguments passed to be passed to the tool call request
7352 */
7353 arguments?: object;
7354 /**
7355 * The name of the tool to be called
7356 */
7357 name?: string;
7358 }[];
7359};
7360declare abstract class Base_Ai_Cf_Qwen_Qwq_32B {
7361 inputs: Ai_Cf_Qwen_Qwq_32B_Input;
7362 postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output;
7363}
7364type 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;
7365interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt {
7366 /**
7367 * The input text prompt for the model to generate a response.
7368 */
7369 prompt: string;
7370 /**
7371 * JSON schema that should be fulfilled for the response.
7372 */
7373 guided_json?: object;
7374 /**
7375 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7376 */
7377 raw?: boolean;
7378 /**
7379 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7380 */
7381 stream?: boolean;
7382 /**
7383 * The maximum number of tokens to generate in the response.
7384 */
7385 max_tokens?: number;
7386 /**
7387 * Controls the randomness of the output; higher values produce more random results.
7388 */
7389 temperature?: number;
7390 /**
7391 * 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.
7392 */
7393 top_p?: number;
7394 /**
7395 * 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.
7396 */
7397 top_k?: number;
7398 /**
7399 * Random seed for reproducibility of the generation.
7400 */
7401 seed?: number;
7402 /**
7403 * Penalty for repeated tokens; higher values discourage repetition.
7404 */
7405 repetition_penalty?: number;
7406 /**
7407 * Decreases the likelihood of the model repeating the same lines verbatim.
7408 */
7409 frequency_penalty?: number;
7410 /**
7411 * Increases the likelihood of the model introducing new topics.
7412 */
7413 presence_penalty?: number;
7414}
7415interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages {
7416 /**
7417 * An array of message objects representing the conversation history.
7418 */
7419 messages: {
7420 /**
7421 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
7422 */
7423 role?: string;
7424 /**
7425 * 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 000000001
7426 */
7427 tool_call_id?: string;
7428 content?: string | {
7429 /**
7430 * Type of the content provided
7431 */
7432 type?: string;
7433 text?: string;
7434 image_url?: {
7435 /**
7436 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7437 */
7438 url?: string;
7439 };
7440 }[] | {
7441 /**
7442 * Type of the content provided
7443 */
7444 type?: string;
7445 text?: string;
7446 image_url?: {
7447 /**
7448 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7449 */
7450 url?: string;
7451 };
7452 };
7453 }[];
7454 functions?: {
7455 name: string;
7456 code: string;
7457 }[];
7458 /**
7459 * A list of tools available for the assistant to use.
7460 */
7461 tools?: ({
7462 /**
7463 * The name of the tool. More descriptive the better.
7464 */
7465 name: string;
7466 /**
7467 * A brief description of what the tool does.
7468 */
7469 description: string;
7470 /**
7471 * Schema defining the parameters accepted by the tool.
7472 */
7473 parameters: {
7474 /**
7475 * The type of the parameters object (usually 'object').
7476 */
7477 type: string;
7478 /**
7479 * List of required parameter names.
7480 */
7481 required?: string[];
7482 /**
7483 * Definitions of each parameter.
7484 */
7485 properties: {
7486 [k: string]: {
7487 /**
7488 * The data type of the parameter.
7489 */
7490 type: string;
7491 /**
7492 * A description of the expected parameter.
7493 */
7494 description: string;
7495 };
7496 };
7497 };
7498 } | {
7499 /**
7500 * Specifies the type of tool (e.g., 'function').
7501 */
7502 type: string;
7503 /**
7504 * Details of the function tool.
7505 */
7506 function: {
7507 /**
7508 * The name of the function.
7509 */
7510 name: string;
7511 /**
7512 * A brief description of what the function does.
7513 */
7514 description: string;
7515 /**
7516 * Schema defining the parameters accepted by the function.
7517 */
7518 parameters: {
7519 /**
7520 * The type of the parameters object (usually 'object').
7521 */
7522 type: string;
7523 /**
7524 * List of required parameter names.
7525 */
7526 required?: string[];
7527 /**
7528 * Definitions of each parameter.
7529 */
7530 properties: {
7531 [k: string]: {
7532 /**
7533 * The data type of the parameter.
7534 */
7535 type: string;
7536 /**
7537 * A description of the expected parameter.
7538 */
7539 description: string;
7540 };
7541 };
7542 };
7543 };
7544 })[];
7545 /**
7546 * JSON schema that should be fufilled for the response.
7547 */
7548 guided_json?: object;
7549 /**
7550 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7551 */
7552 raw?: boolean;
7553 /**
7554 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7555 */
7556 stream?: boolean;
7557 /**
7558 * The maximum number of tokens to generate in the response.
7559 */
7560 max_tokens?: number;
7561 /**
7562 * Controls the randomness of the output; higher values produce more random results.
7563 */
7564 temperature?: number;
7565 /**
7566 * 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.
7567 */
7568 top_p?: number;
7569 /**
7570 * 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.
7571 */
7572 top_k?: number;
7573 /**
7574 * Random seed for reproducibility of the generation.
7575 */
7576 seed?: number;
7577 /**
7578 * Penalty for repeated tokens; higher values discourage repetition.
7579 */
7580 repetition_penalty?: number;
7581 /**
7582 * Decreases the likelihood of the model repeating the same lines verbatim.
7583 */
7584 frequency_penalty?: number;
7585 /**
7586 * Increases the likelihood of the model introducing new topics.
7587 */
7588 presence_penalty?: number;
7589}
7590type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = {
7591 /**
7592 * The generated text response from the model
7593 */
7594 response: string;
7595 /**
7596 * Usage statistics for the inference request
7597 */
7598 usage?: {
7599 /**
7600 * Total number of tokens in input
7601 */
7602 prompt_tokens?: number;
7603 /**
7604 * Total number of tokens in output
7605 */
7606 completion_tokens?: number;
7607 /**
7608 * Total number of input and output tokens
7609 */
7610 total_tokens?: number;
7611 };
7612 /**
7613 * An array of tool calls requests made during the response generation
7614 */
7615 tool_calls?: {
7616 /**
7617 * The arguments passed to be passed to the tool call request
7618 */
7619 arguments?: object;
7620 /**
7621 * The name of the tool to be called
7622 */
7623 name?: string;
7624 }[];
7625};
7626declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct {
7627 inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input;
7628 postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output;
7629}
7630type Ai_Cf_Google_Gemma_3_12B_It_Input = Ai_Cf_Google_Gemma_3_12B_It_Prompt | Ai_Cf_Google_Gemma_3_12B_It_Messages;
7631interface Ai_Cf_Google_Gemma_3_12B_It_Prompt {
7632 /**
7633 * The input text prompt for the model to generate a response.
7634 */
7635 prompt: string;
7636 /**
7637 * JSON schema that should be fufilled for the response.
7638 */
7639 guided_json?: object;
7640 /**
7641 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7642 */
7643 raw?: boolean;
7644 /**
7645 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7646 */
7647 stream?: boolean;
7648 /**
7649 * The maximum number of tokens to generate in the response.
7650 */
7651 max_tokens?: number;
7652 /**
7653 * Controls the randomness of the output; higher values produce more random results.
7654 */
7655 temperature?: number;
7656 /**
7657 * 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.
7658 */
7659 top_p?: number;
7660 /**
7661 * 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.
7662 */
7663 top_k?: number;
7664 /**
7665 * Random seed for reproducibility of the generation.
7666 */
7667 seed?: number;
7668 /**
7669 * Penalty for repeated tokens; higher values discourage repetition.
7670 */
7671 repetition_penalty?: number;
7672 /**
7673 * Decreases the likelihood of the model repeating the same lines verbatim.
7674 */
7675 frequency_penalty?: number;
7676 /**
7677 * Increases the likelihood of the model introducing new topics.
7678 */
7679 presence_penalty?: number;
7680}
7681interface Ai_Cf_Google_Gemma_3_12B_It_Messages {
7682 /**
7683 * An array of message objects representing the conversation history.
7684 */
7685 messages: {
7686 /**
7687 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
7688 */
7689 role?: string;
7690 content?: string | {
7691 /**
7692 * Type of the content provided
7693 */
7694 type?: string;
7695 text?: string;
7696 image_url?: {
7697 /**
7698 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7699 */
7700 url?: string;
7701 };
7702 }[];
7703 }[];
7704 functions?: {
7705 name: string;
7706 code: string;
7707 }[];
7708 /**
7709 * A list of tools available for the assistant to use.
7710 */
7711 tools?: ({
7712 /**
7713 * The name of the tool. More descriptive the better.
7714 */
7715 name: string;
7716 /**
7717 * A brief description of what the tool does.
7718 */
7719 description: string;
7720 /**
7721 * Schema defining the parameters accepted by the tool.
7722 */
7723 parameters: {
7724 /**
7725 * The type of the parameters object (usually 'object').
7726 */
7727 type: string;
7728 /**
7729 * List of required parameter names.
7730 */
7731 required?: string[];
7732 /**
7733 * Definitions of each parameter.
7734 */
7735 properties: {
7736 [k: string]: {
7737 /**
7738 * The data type of the parameter.
7739 */
7740 type: string;
7741 /**
7742 * A description of the expected parameter.
7743 */
7744 description: string;
7745 };
7746 };
7747 };
7748 } | {
7749 /**
7750 * Specifies the type of tool (e.g., 'function').
7751 */
7752 type: string;
7753 /**
7754 * Details of the function tool.
7755 */
7756 function: {
7757 /**
7758 * The name of the function.
7759 */
7760 name: string;
7761 /**
7762 * A brief description of what the function does.
7763 */
7764 description: string;
7765 /**
7766 * Schema defining the parameters accepted by the function.
7767 */
7768 parameters: {
7769 /**
7770 * The type of the parameters object (usually 'object').
7771 */
7772 type: string;
7773 /**
7774 * List of required parameter names.
7775 */
7776 required?: string[];
7777 /**
7778 * Definitions of each parameter.
7779 */
7780 properties: {
7781 [k: string]: {
7782 /**
7783 * The data type of the parameter.
7784 */
7785 type: string;
7786 /**
7787 * A description of the expected parameter.
7788 */
7789 description: string;
7790 };
7791 };
7792 };
7793 };
7794 })[];
7795 /**
7796 * JSON schema that should be fufilled for the response.
7797 */
7798 guided_json?: object;
7799 /**
7800 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7801 */
7802 raw?: boolean;
7803 /**
7804 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7805 */
7806 stream?: boolean;
7807 /**
7808 * The maximum number of tokens to generate in the response.
7809 */
7810 max_tokens?: number;
7811 /**
7812 * Controls the randomness of the output; higher values produce more random results.
7813 */
7814 temperature?: number;
7815 /**
7816 * 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.
7817 */
7818 top_p?: number;
7819 /**
7820 * 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.
7821 */
7822 top_k?: number;
7823 /**
7824 * Random seed for reproducibility of the generation.
7825 */
7826 seed?: number;
7827 /**
7828 * Penalty for repeated tokens; higher values discourage repetition.
7829 */
7830 repetition_penalty?: number;
7831 /**
7832 * Decreases the likelihood of the model repeating the same lines verbatim.
7833 */
7834 frequency_penalty?: number;
7835 /**
7836 * Increases the likelihood of the model introducing new topics.
7837 */
7838 presence_penalty?: number;
7839}
7840type Ai_Cf_Google_Gemma_3_12B_It_Output = {
7841 /**
7842 * The generated text response from the model
7843 */
7844 response: string;
7845 /**
7846 * Usage statistics for the inference request
7847 */
7848 usage?: {
7849 /**
7850 * Total number of tokens in input
7851 */
7852 prompt_tokens?: number;
7853 /**
7854 * Total number of tokens in output
7855 */
7856 completion_tokens?: number;
7857 /**
7858 * Total number of input and output tokens
7859 */
7860 total_tokens?: number;
7861 };
7862 /**
7863 * An array of tool calls requests made during the response generation
7864 */
7865 tool_calls?: {
7866 /**
7867 * The arguments passed to be passed to the tool call request
7868 */
7869 arguments?: object;
7870 /**
7871 * The name of the tool to be called
7872 */
7873 name?: string;
7874 }[];
7875};
7876declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It {
7877 inputs: Ai_Cf_Google_Gemma_3_12B_It_Input;
7878 postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output;
7879}
7880type 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;
7881interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt {
7882 /**
7883 * The input text prompt for the model to generate a response.
7884 */
7885 prompt: string;
7886 /**
7887 * JSON schema that should be fulfilled for the response.
7888 */
7889 guided_json?: object;
7890 response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;
7891 /**
7892 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7893 */
7894 raw?: boolean;
7895 /**
7896 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7897 */
7898 stream?: boolean;
7899 /**
7900 * The maximum number of tokens to generate in the response.
7901 */
7902 max_tokens?: number;
7903 /**
7904 * Controls the randomness of the output; higher values produce more random results.
7905 */
7906 temperature?: number;
7907 /**
7908 * 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.
7909 */
7910 top_p?: number;
7911 /**
7912 * 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.
7913 */
7914 top_k?: number;
7915 /**
7916 * Random seed for reproducibility of the generation.
7917 */
7918 seed?: number;
7919 /**
7920 * Penalty for repeated tokens; higher values discourage repetition.
7921 */
7922 repetition_penalty?: number;
7923 /**
7924 * Decreases the likelihood of the model repeating the same lines verbatim.
7925 */
7926 frequency_penalty?: number;
7927 /**
7928 * Increases the likelihood of the model introducing new topics.
7929 */
7930 presence_penalty?: number;
7931}
7932interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode {
7933 type?: "json_object" | "json_schema";
7934 json_schema?: unknown;
7935}
7936interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages {
7937 /**
7938 * An array of message objects representing the conversation history.
7939 */
7940 messages: {
7941 /**
7942 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
7943 */
7944 role?: string;
7945 /**
7946 * The tool call id. If you don't know what to put here you can fall back to 000000001
7947 */
7948 tool_call_id?: string;
7949 content?: string | {
7950 /**
7951 * Type of the content provided
7952 */
7953 type?: string;
7954 text?: string;
7955 image_url?: {
7956 /**
7957 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7958 */
7959 url?: string;
7960 };
7961 }[] | {
7962 /**
7963 * Type of the content provided
7964 */
7965 type?: string;
7966 text?: string;
7967 image_url?: {
7968 /**
7969 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7970 */
7971 url?: string;
7972 };
7973 };
7974 }[];
7975 functions?: {
7976 name: string;
7977 code: string;
7978 }[];
7979 /**
7980 * A list of tools available for the assistant to use.
7981 */
7982 tools?: ({
7983 /**
7984 * The name of the tool. More descriptive the better.
7985 */
7986 name: string;
7987 /**
7988 * A brief description of what the tool does.
7989 */
7990 description: string;
7991 /**
7992 * Schema defining the parameters accepted by the tool.
7993 */
7994 parameters: {
7995 /**
7996 * The type of the parameters object (usually 'object').
7997 */
7998 type: string;
7999 /**
8000 * List of required parameter names.
8001 */
8002 required?: string[];
8003 /**
8004 * Definitions of each parameter.
8005 */
8006 properties: {
8007 [k: string]: {
8008 /**
8009 * The data type of the parameter.
8010 */
8011 type: string;
8012 /**
8013 * A description of the expected parameter.
8014 */
8015 description: string;
8016 };
8017 };
8018 };
8019 } | {
8020 /**
8021 * Specifies the type of tool (e.g., 'function').
8022 */
8023 type: string;
8024 /**
8025 * Details of the function tool.
8026 */
8027 function: {
8028 /**
8029 * The name of the function.
8030 */
8031 name: string;
8032 /**
8033 * A brief description of what the function does.
8034 */
8035 description: string;
8036 /**
8037 * Schema defining the parameters accepted by the function.
8038 */
8039 parameters: {
8040 /**
8041 * The type of the parameters object (usually 'object').
8042 */
8043 type: string;
8044 /**
8045 * List of required parameter names.
8046 */
8047 required?: string[];
8048 /**
8049 * Definitions of each parameter.
8050 */
8051 properties: {
8052 [k: string]: {
8053 /**
8054 * The data type of the parameter.
8055 */
8056 type: string;
8057 /**
8058 * A description of the expected parameter.
8059 */
8060 description: string;
8061 };
8062 };
8063 };
8064 };
8065 })[];
8066 response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;
8067 /**
8068 * JSON schema that should be fufilled for the response.
8069 */
8070 guided_json?: object;
8071 /**
8072 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8073 */
8074 raw?: boolean;
8075 /**
8076 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8077 */
8078 stream?: boolean;
8079 /**
8080 * The maximum number of tokens to generate in the response.
8081 */
8082 max_tokens?: number;
8083 /**
8084 * Controls the randomness of the output; higher values produce more random results.
8085 */
8086 temperature?: number;
8087 /**
8088 * 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.
8089 */
8090 top_p?: number;
8091 /**
8092 * 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.
8093 */
8094 top_k?: number;
8095 /**
8096 * Random seed for reproducibility of the generation.
8097 */
8098 seed?: number;
8099 /**
8100 * Penalty for repeated tokens; higher values discourage repetition.
8101 */
8102 repetition_penalty?: number;
8103 /**
8104 * Decreases the likelihood of the model repeating the same lines verbatim.
8105 */
8106 frequency_penalty?: number;
8107 /**
8108 * Increases the likelihood of the model introducing new topics.
8109 */
8110 presence_penalty?: number;
8111}
8112interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch {
8113 requests: (Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner)[];
8114}
8115interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner {
8116 /**
8117 * The input text prompt for the model to generate a response.
8118 */
8119 prompt: string;
8120 /**
8121 * JSON schema that should be fulfilled for the response.
8122 */
8123 guided_json?: object;
8124 response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;
8125 /**
8126 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8127 */
8128 raw?: boolean;
8129 /**
8130 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8131 */
8132 stream?: boolean;
8133 /**
8134 * The maximum number of tokens to generate in the response.
8135 */
8136 max_tokens?: number;
8137 /**
8138 * Controls the randomness of the output; higher values produce more random results.
8139 */
8140 temperature?: number;
8141 /**
8142 * 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.
8143 */
8144 top_p?: number;
8145 /**
8146 * 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.
8147 */
8148 top_k?: number;
8149 /**
8150 * Random seed for reproducibility of the generation.
8151 */
8152 seed?: number;
8153 /**
8154 * Penalty for repeated tokens; higher values discourage repetition.
8155 */
8156 repetition_penalty?: number;
8157 /**
8158 * Decreases the likelihood of the model repeating the same lines verbatim.
8159 */
8160 frequency_penalty?: number;
8161 /**
8162 * Increases the likelihood of the model introducing new topics.
8163 */
8164 presence_penalty?: number;
8165}
8166interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner {
8167 /**
8168 * An array of message objects representing the conversation history.
8169 */
8170 messages: {
8171 /**
8172 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
8173 */
8174 role?: string;
8175 /**
8176 * The tool call id. If you don't know what to put here you can fall back to 000000001
8177 */
8178 tool_call_id?: string;
8179 content?: string | {
8180 /**
8181 * Type of the content provided
8182 */
8183 type?: string;
8184 text?: string;
8185 image_url?: {
8186 /**
8187 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
8188 */
8189 url?: string;
8190 };
8191 }[] | {
8192 /**
8193 * Type of the content provided
8194 */
8195 type?: string;
8196 text?: string;
8197 image_url?: {
8198 /**
8199 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
8200 */
8201 url?: string;
8202 };
8203 };
8204 }[];
8205 functions?: {
8206 name: string;
8207 code: string;
8208 }[];
8209 /**
8210 * A list of tools available for the assistant to use.
8211 */
8212 tools?: ({
8213 /**
8214 * The name of the tool. More descriptive the better.
8215 */
8216 name: string;
8217 /**
8218 * A brief description of what the tool does.
8219 */
8220 description: string;
8221 /**
8222 * Schema defining the parameters accepted by the tool.
8223 */
8224 parameters: {
8225 /**
8226 * The type of the parameters object (usually 'object').
8227 */
8228 type: string;
8229 /**
8230 * List of required parameter names.
8231 */
8232 required?: string[];
8233 /**
8234 * Definitions of each parameter.
8235 */
8236 properties: {
8237 [k: string]: {
8238 /**
8239 * The data type of the parameter.
8240 */
8241 type: string;
8242 /**
8243 * A description of the expected parameter.
8244 */
8245 description: string;
8246 };
8247 };
8248 };
8249 } | {
8250 /**
8251 * Specifies the type of tool (e.g., 'function').
8252 */
8253 type: string;
8254 /**
8255 * Details of the function tool.
8256 */
8257 function: {
8258 /**
8259 * The name of the function.
8260 */
8261 name: string;
8262 /**
8263 * A brief description of what the function does.
8264 */
8265 description: string;
8266 /**
8267 * Schema defining the parameters accepted by the function.
8268 */
8269 parameters: {
8270 /**
8271 * The type of the parameters object (usually 'object').
8272 */
8273 type: string;
8274 /**
8275 * List of required parameter names.
8276 */
8277 required?: string[];
8278 /**
8279 * Definitions of each parameter.
8280 */
8281 properties: {
8282 [k: string]: {
8283 /**
8284 * The data type of the parameter.
8285 */
8286 type: string;
8287 /**
8288 * A description of the expected parameter.
8289 */
8290 description: string;
8291 };
8292 };
8293 };
8294 };
8295 })[];
8296 response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;
8297 /**
8298 * JSON schema that should be fufilled for the response.
8299 */
8300 guided_json?: object;
8301 /**
8302 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8303 */
8304 raw?: boolean;
8305 /**
8306 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8307 */
8308 stream?: boolean;
8309 /**
8310 * The maximum number of tokens to generate in the response.
8311 */
8312 max_tokens?: number;
8313 /**
8314 * Controls the randomness of the output; higher values produce more random results.
8315 */
8316 temperature?: number;
8317 /**
8318 * 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.
8319 */
8320 top_p?: number;
8321 /**
8322 * 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.
8323 */
8324 top_k?: number;
8325 /**
8326 * Random seed for reproducibility of the generation.
8327 */
8328 seed?: number;
8329 /**
8330 * Penalty for repeated tokens; higher values discourage repetition.
8331 */
8332 repetition_penalty?: number;
8333 /**
8334 * Decreases the likelihood of the model repeating the same lines verbatim.
8335 */
8336 frequency_penalty?: number;
8337 /**
8338 * Increases the likelihood of the model introducing new topics.
8339 */
8340 presence_penalty?: number;
8341}
8342type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = {
8343 /**
8344 * The generated text response from the model
8345 */
8346 response: string;
8347 /**
8348 * Usage statistics for the inference request
8349 */
8350 usage?: {
8351 /**
8352 * Total number of tokens in input
8353 */
8354 prompt_tokens?: number;
8355 /**
8356 * Total number of tokens in output
8357 */
8358 completion_tokens?: number;
8359 /**
8360 * Total number of input and output tokens
8361 */
8362 total_tokens?: number;
8363 };
8364 /**
8365 * An array of tool calls requests made during the response generation
8366 */
8367 tool_calls?: {
8368 /**
8369 * The tool call id.
8370 */
8371 id?: string;
8372 /**
8373 * Specifies the type of tool (e.g., 'function').
8374 */
8375 type?: string;
8376 /**
8377 * Details of the function tool.
8378 */
8379 function?: {
8380 /**
8381 * The name of the tool to be called
8382 */
8383 name?: string;
8384 /**
8385 * The arguments passed to be passed to the tool call request
8386 */
8387 arguments?: object;
8388 };
8389 }[];
8390};
8391declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct {
8392 inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input;
8393 postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output;
8394}
8395type 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;
8396interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt {
8397 /**
8398 * The input text prompt for the model to generate a response.
8399 */
8400 prompt: string;
8401 /**
8402 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
8403 */
8404 lora?: string;
8405 response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode;
8406 /**
8407 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8408 */
8409 raw?: boolean;
8410 /**
8411 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8412 */
8413 stream?: boolean;
8414 /**
8415 * The maximum number of tokens to generate in the response.
8416 */
8417 max_tokens?: number;
8418 /**
8419 * Controls the randomness of the output; higher values produce more random results.
8420 */
8421 temperature?: number;
8422 /**
8423 * 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.
8424 */
8425 top_p?: number;
8426 /**
8427 * 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.
8428 */
8429 top_k?: number;
8430 /**
8431 * Random seed for reproducibility of the generation.
8432 */
8433 seed?: number;
8434 /**
8435 * Penalty for repeated tokens; higher values discourage repetition.
8436 */
8437 repetition_penalty?: number;
8438 /**
8439 * Decreases the likelihood of the model repeating the same lines verbatim.
8440 */
8441 frequency_penalty?: number;
8442 /**
8443 * Increases the likelihood of the model introducing new topics.
8444 */
8445 presence_penalty?: number;
8446}
8447interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode {
8448 type?: "json_object" | "json_schema";
8449 json_schema?: unknown;
8450}
8451interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages {
8452 /**
8453 * An array of message objects representing the conversation history.
8454 */
8455 messages: {
8456 /**
8457 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
8458 */
8459 role: string;
8460 content: string | {
8461 /**
8462 * Type of the content (text)
8463 */
8464 type?: string;
8465 /**
8466 * Text content
8467 */
8468 text?: string;
8469 }[];
8470 }[];
8471 functions?: {
8472 name: string;
8473 code: string;
8474 }[];
8475 /**
8476 * A list of tools available for the assistant to use.
8477 */
8478 tools?: ({
8479 /**
8480 * The name of the tool. More descriptive the better.
8481 */
8482 name: string;
8483 /**
8484 * A brief description of what the tool does.
8485 */
8486 description: string;
8487 /**
8488 * Schema defining the parameters accepted by the tool.
8489 */
8490 parameters: {
8491 /**
8492 * The type of the parameters object (usually 'object').
8493 */
8494 type: string;
8495 /**
8496 * List of required parameter names.
8497 */
8498 required?: string[];
8499 /**
8500 * Definitions of each parameter.
8501 */
8502 properties: {
8503 [k: string]: {
8504 /**
8505 * The data type of the parameter.
8506 */
8507 type: string;
8508 /**
8509 * A description of the expected parameter.
8510 */
8511 description: string;
8512 };
8513 };
8514 };
8515 } | {
8516 /**
8517 * Specifies the type of tool (e.g., 'function').
8518 */
8519 type: string;
8520 /**
8521 * Details of the function tool.
8522 */
8523 function: {
8524 /**
8525 * The name of the function.
8526 */
8527 name: string;
8528 /**
8529 * A brief description of what the function does.
8530 */
8531 description: string;
8532 /**
8533 * Schema defining the parameters accepted by the function.
8534 */
8535 parameters: {
8536 /**
8537 * The type of the parameters object (usually 'object').
8538 */
8539 type: string;
8540 /**
8541 * List of required parameter names.
8542 */
8543 required?: string[];
8544 /**
8545 * Definitions of each parameter.
8546 */
8547 properties: {
8548 [k: string]: {
8549 /**
8550 * The data type of the parameter.
8551 */
8552 type: string;
8553 /**
8554 * A description of the expected parameter.
8555 */
8556 description: string;
8557 };
8558 };
8559 };
8560 };
8561 })[];
8562 response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1;
8563 /**
8564 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8565 */
8566 raw?: boolean;
8567 /**
8568 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8569 */
8570 stream?: boolean;
8571 /**
8572 * The maximum number of tokens to generate in the response.
8573 */
8574 max_tokens?: number;
8575 /**
8576 * Controls the randomness of the output; higher values produce more random results.
8577 */
8578 temperature?: number;
8579 /**
8580 * 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.
8581 */
8582 top_p?: number;
8583 /**
8584 * 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.
8585 */
8586 top_k?: number;
8587 /**
8588 * Random seed for reproducibility of the generation.
8589 */
8590 seed?: number;
8591 /**
8592 * Penalty for repeated tokens; higher values discourage repetition.
8593 */
8594 repetition_penalty?: number;
8595 /**
8596 * Decreases the likelihood of the model repeating the same lines verbatim.
8597 */
8598 frequency_penalty?: number;
8599 /**
8600 * Increases the likelihood of the model introducing new topics.
8601 */
8602 presence_penalty?: number;
8603}
8604interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 {
8605 type?: "json_object" | "json_schema";
8606 json_schema?: unknown;
8607}
8608interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch {
8609 requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[];
8610}
8611interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 {
8612 /**
8613 * The input text prompt for the model to generate a response.
8614 */
8615 prompt: string;
8616 /**
8617 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
8618 */
8619 lora?: string;
8620 response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2;
8621 /**
8622 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8623 */
8624 raw?: boolean;
8625 /**
8626 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8627 */
8628 stream?: boolean;
8629 /**
8630 * The maximum number of tokens to generate in the response.
8631 */
8632 max_tokens?: number;
8633 /**
8634 * Controls the randomness of the output; higher values produce more random results.
8635 */
8636 temperature?: number;
8637 /**
8638 * 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.
8639 */
8640 top_p?: number;
8641 /**
8642 * 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.
8643 */
8644 top_k?: number;
8645 /**
8646 * Random seed for reproducibility of the generation.
8647 */
8648 seed?: number;
8649 /**
8650 * Penalty for repeated tokens; higher values discourage repetition.
8651 */
8652 repetition_penalty?: number;
8653 /**
8654 * Decreases the likelihood of the model repeating the same lines verbatim.
8655 */
8656 frequency_penalty?: number;
8657 /**
8658 * Increases the likelihood of the model introducing new topics.
8659 */
8660 presence_penalty?: number;
8661}
8662interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 {
8663 type?: "json_object" | "json_schema";
8664 json_schema?: unknown;
8665}
8666interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 {
8667 /**
8668 * An array of message objects representing the conversation history.
8669 */
8670 messages: {
8671 /**
8672 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
8673 */
8674 role: string;
8675 content: string | {
8676 /**
8677 * Type of the content (text)
8678 */
8679 type?: string;
8680 /**
8681 * Text content
8682 */
8683 text?: string;
8684 }[];
8685 }[];
8686 functions?: {
8687 name: string;
8688 code: string;
8689 }[];
8690 /**
8691 * A list of tools available for the assistant to use.
8692 */
8693 tools?: ({
8694 /**
8695 * The name of the tool. More descriptive the better.
8696 */
8697 name: string;
8698 /**
8699 * A brief description of what the tool does.
8700 */
8701 description: string;
8702 /**
8703 * Schema defining the parameters accepted by the tool.
8704 */
8705 parameters: {
8706 /**
8707 * The type of the parameters object (usually 'object').
8708 */
8709 type: string;
8710 /**
8711 * List of required parameter names.
8712 */
8713 required?: string[];
8714 /**
8715 * Definitions of each parameter.
8716 */
8717 properties: {
8718 [k: string]: {
8719 /**
8720 * The data type of the parameter.
8721 */
8722 type: string;
8723 /**
8724 * A description of the expected parameter.
8725 */
8726 description: string;
8727 };
8728 };
8729 };
8730 } | {
8731 /**
8732 * Specifies the type of tool (e.g., 'function').
8733 */
8734 type: string;
8735 /**
8736 * Details of the function tool.
8737 */
8738 function: {
8739 /**
8740 * The name of the function.
8741 */
8742 name: string;
8743 /**
8744 * A brief description of what the function does.
8745 */
8746 description: string;
8747 /**
8748 * Schema defining the parameters accepted by the function.
8749 */
8750 parameters: {
8751 /**
8752 * The type of the parameters object (usually 'object').
8753 */
8754 type: string;
8755 /**
8756 * List of required parameter names.
8757 */
8758 required?: string[];
8759 /**
8760 * Definitions of each parameter.
8761 */
8762 properties: {
8763 [k: string]: {
8764 /**
8765 * The data type of the parameter.
8766 */
8767 type: string;
8768 /**
8769 * A description of the expected parameter.
8770 */
8771 description: string;
8772 };
8773 };
8774 };
8775 };
8776 })[];
8777 response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3;
8778 /**
8779 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8780 */
8781 raw?: boolean;
8782 /**
8783 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8784 */
8785 stream?: boolean;
8786 /**
8787 * The maximum number of tokens to generate in the response.
8788 */
8789 max_tokens?: number;
8790 /**
8791 * Controls the randomness of the output; higher values produce more random results.
8792 */
8793 temperature?: number;
8794 /**
8795 * 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.
8796 */
8797 top_p?: number;
8798 /**
8799 * 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.
8800 */
8801 top_k?: number;
8802 /**
8803 * Random seed for reproducibility of the generation.
8804 */
8805 seed?: number;
8806 /**
8807 * Penalty for repeated tokens; higher values discourage repetition.
8808 */
8809 repetition_penalty?: number;
8810 /**
8811 * Decreases the likelihood of the model repeating the same lines verbatim.
8812 */
8813 frequency_penalty?: number;
8814 /**
8815 * Increases the likelihood of the model introducing new topics.
8816 */
8817 presence_penalty?: number;
8818}
8819interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 {
8820 type?: "json_object" | "json_schema";
8821 json_schema?: unknown;
8822}
8823type 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;
8824interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response {
8825 /**
8826 * Unique identifier for the completion
8827 */
8828 id?: string;
8829 /**
8830 * Object type identifier
8831 */
8832 object?: "chat.completion";
8833 /**
8834 * Unix timestamp of when the completion was created
8835 */
8836 created?: number;
8837 /**
8838 * Model used for the completion
8839 */
8840 model?: string;
8841 /**
8842 * List of completion choices
8843 */
8844 choices?: {
8845 /**
8846 * Index of the choice in the list
8847 */
8848 index?: number;
8849 /**
8850 * The message generated by the model
8851 */
8852 message?: {
8853 /**
8854 * Role of the message author
8855 */
8856 role: string;
8857 /**
8858 * The content of the message
8859 */
8860 content: string;
8861 /**
8862 * Internal reasoning content (if available)
8863 */
8864 reasoning_content?: string;
8865 /**
8866 * Tool calls made by the assistant
8867 */
8868 tool_calls?: {
8869 /**
8870 * Unique identifier for the tool call
8871 */
8872 id: string;
8873 /**
8874 * Type of tool call
8875 */
8876 type: "function";
8877 function: {
8878 /**
8879 * Name of the function to call
8880 */
8881 name: string;
8882 /**
8883 * JSON string of arguments for the function
8884 */
8885 arguments: string;
8886 };
8887 }[];
8888 };
8889 /**
8890 * Reason why the model stopped generating
8891 */
8892 finish_reason?: string;
8893 /**
8894 * Stop reason (may be null)
8895 */
8896 stop_reason?: string | null;
8897 /**
8898 * Log probabilities (if requested)
8899 */
8900 logprobs?: {} | null;
8901 }[];
8902 /**
8903 * Usage statistics for the inference request
8904 */
8905 usage?: {
8906 /**
8907 * Total number of tokens in input
8908 */
8909 prompt_tokens?: number;
8910 /**
8911 * Total number of tokens in output
8912 */
8913 completion_tokens?: number;
8914 /**
8915 * Total number of input and output tokens
8916 */
8917 total_tokens?: number;
8918 };
8919 /**
8920 * Log probabilities for the prompt (if requested)
8921 */
8922 prompt_logprobs?: {} | null;
8923}
8924interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response {
8925 /**
8926 * Unique identifier for the completion
8927 */
8928 id?: string;
8929 /**
8930 * Object type identifier
8931 */
8932 object?: "text_completion";
8933 /**
8934 * Unix timestamp of when the completion was created
8935 */
8936 created?: number;
8937 /**
8938 * Model used for the completion
8939 */
8940 model?: string;
8941 /**
8942 * List of completion choices
8943 */
8944 choices?: {
8945 /**
8946 * Index of the choice in the list
8947 */
8948 index: number;
8949 /**
8950 * The generated text completion
8951 */
8952 text: string;
8953 /**
8954 * Reason why the model stopped generating
8955 */
8956 finish_reason: string;
8957 /**
8958 * Stop reason (may be null)
8959 */
8960 stop_reason?: string | null;
8961 /**
8962 * Log probabilities (if requested)
8963 */
8964 logprobs?: {} | null;
8965 /**
8966 * Log probabilities for the prompt (if requested)
8967 */
8968 prompt_logprobs?: {} | null;
8969 }[];
8970 /**
8971 * Usage statistics for the inference request
8972 */
8973 usage?: {
8974 /**
8975 * Total number of tokens in input
8976 */
8977 prompt_tokens?: number;
8978 /**
8979 * Total number of tokens in output
8980 */
8981 completion_tokens?: number;
8982 /**
8983 * Total number of input and output tokens
8984 */
8985 total_tokens?: number;
8986 };
8987}
8988interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse {
8989 /**
8990 * The async request id that can be used to obtain the results.
8991 */
8992 request_id?: string;
8993}
8994declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 {
8995 inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input;
8996 postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output;
8997}
8998interface Ai_Cf_Deepgram_Nova_3_Input {
8999 audio: {
9000 body: object;
9001 contentType: string;
9002 };
9003 /**
9004 * 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.
9005 */
9006 custom_topic_mode?: "extended" | "strict";
9007 /**
9008 * Custom topics you want the model to detect within your input audio or text if present Submit up to 100
9009 */
9010 custom_topic?: string;
9011 /**
9012 * 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 param
9013 */
9014 custom_intent_mode?: "extended" | "strict";
9015 /**
9016 * Custom intents you want the model to detect within your input audio if present
9017 */
9018 custom_intent?: string;
9019 /**
9020 * Identifies and extracts key entities from content in submitted audio
9021 */
9022 detect_entities?: boolean;
9023 /**
9024 * Identifies the dominant language spoken in submitted audio
9025 */
9026 detect_language?: boolean;
9027 /**
9028 * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0
9029 */
9030 diarize?: boolean;
9031 /**
9032 * Identify and extract key entities from content in submitted audio
9033 */
9034 dictation?: boolean;
9035 /**
9036 * Specify the expected encoding of your submitted audio
9037 */
9038 encoding?: "linear16" | "flac" | "mulaw" | "amr-nb" | "amr-wb" | "opus" | "speex" | "g729";
9039 /**
9040 * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing
9041 */
9042 extra?: string;
9043 /**
9044 * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um'
9045 */
9046 filler_words?: boolean;
9047 /**
9048 * Key term prompting can boost or suppress specialized terminology and brands.
9049 */
9050 keyterm?: string;
9051 /**
9052 * Keywords can boost or suppress specialized terminology and brands.
9053 */
9054 keywords?: string;
9055 /**
9056 * 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.
9057 */
9058 language?: string;
9059 /**
9060 * Spoken measurements will be converted to their corresponding abbreviations.
9061 */
9062 measurements?: boolean;
9063 /**
9064 * 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.
9065 */
9066 mip_opt_out?: boolean;
9067 /**
9068 * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio
9069 */
9070 mode?: "general" | "medical" | "finance";
9071 /**
9072 * Transcribe each audio channel independently.
9073 */
9074 multichannel?: boolean;
9075 /**
9076 * Numerals converts numbers from written format to numerical format.
9077 */
9078 numerals?: boolean;
9079 /**
9080 * Splits audio into paragraphs to improve transcript readability.
9081 */
9082 paragraphs?: boolean;
9083 /**
9084 * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely.
9085 */
9086 profanity_filter?: boolean;
9087 /**
9088 * Add punctuation and capitalization to the transcript.
9089 */
9090 punctuate?: boolean;
9091 /**
9092 * Redaction removes sensitive information from your transcripts.
9093 */
9094 redact?: string;
9095 /**
9096 * Search for terms or phrases in submitted audio and replaces them.
9097 */
9098 replace?: string;
9099 /**
9100 * Search for terms or phrases in submitted audio.
9101 */
9102 search?: string;
9103 /**
9104 * Recognizes the sentiment throughout a transcript or text.
9105 */
9106 sentiment?: boolean;
9107 /**
9108 * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability.
9109 */
9110 smart_format?: boolean;
9111 /**
9112 * Detect topics throughout a transcript or text.
9113 */
9114 topics?: boolean;
9115 /**
9116 * Segments speech into meaningful semantic units.
9117 */
9118 utterances?: boolean;
9119 /**
9120 * Seconds to wait before detecting a pause between words in submitted audio.
9121 */
9122 utt_split?: number;
9123 /**
9124 * The number of channels in the submitted audio
9125 */
9126 channels?: number;
9127 /**
9128 * 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.
9129 */
9130 interim_results?: boolean;
9131 /**
9132 * 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 endpointing
9133 */
9134 endpointing?: string;
9135 /**
9136 * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets.
9137 */
9138 vad_events?: boolean;
9139 /**
9140 * 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.
9141 */
9142 utterance_end_ms?: boolean;
9143}
9144interface Ai_Cf_Deepgram_Nova_3_Output {
9145 results?: {
9146 channels?: {
9147 alternatives?: {
9148 confidence?: number;
9149 transcript?: string;
9150 words?: {
9151 confidence?: number;
9152 end?: number;
9153 start?: number;
9154 word?: string;
9155 }[];
9156 }[];
9157 }[];
9158 summary?: {
9159 result?: string;
9160 short?: string;
9161 };
9162 sentiments?: {
9163 segments?: {
9164 text?: string;
9165 start_word?: number;
9166 end_word?: number;
9167 sentiment?: string;
9168 sentiment_score?: number;
9169 }[];
9170 average?: {
9171 sentiment?: string;
9172 sentiment_score?: number;
9173 };
9174 };
9175 };
9176}
9177declare abstract class Base_Ai_Cf_Deepgram_Nova_3 {
9178 inputs: Ai_Cf_Deepgram_Nova_3_Input;
9179 postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output;
9180}
9181interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input {
9182 queries?: string | string[];
9183 /**
9184 * Optional instruction for the task
9185 */
9186 instruction?: string;
9187 documents?: string | string[];
9188 text?: string | string[];
9189}
9190interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output {
9191 data?: number[][];
9192 shape?: number[];
9193}
9194declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B {
9195 inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input;
9196 postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output;
9197}
9198type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = {
9199 /**
9200 * readable stream with audio data and content-type specified for that data
9201 */
9202 audio: {
9203 body: object;
9204 contentType: string;
9205 };
9206 /**
9207 * type of data PCM data that's sent to the inference server as raw array
9208 */
9209 dtype?: "uint8" | "float32" | "float64";
9210} | {
9211 /**
9212 * base64 encoded audio data
9213 */
9214 audio: string;
9215 /**
9216 * type of data PCM data that's sent to the inference server as raw array
9217 */
9218 dtype?: "uint8" | "float32" | "float64";
9219};
9220interface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output {
9221 /**
9222 * if true, end-of-turn was detected
9223 */
9224 is_complete?: boolean;
9225 /**
9226 * probability of the end-of-turn detection
9227 */
9228 probability?: number;
9229}
9230declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 {
9231 inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input;
9232 postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output;
9233}
9234declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B {
9235 inputs: XOR<Omit<ResponsesInput, "reasoning"> & {
9236 reasoning?: (Omit<Reasoning, "effort"> & {
9237 /**
9238 * Reasoning effort. Supported levels: low, medium, high. Reasoning cannot be disabled.
9239 *
9240 * @default "medium"
9241 */
9242 effort?: "low" | "medium" | "high" | null;
9243 }) | null;
9244 }, Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
9245 /**
9246 * Reasoning effort. Supported levels: low, medium, high. Reasoning cannot be disabled.
9247 *
9248 * @default "medium"
9249 */
9250 reasoning_effort?: "low" | "medium" | "high" | null;
9251 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
9252 /**
9253 * Reasoning is always enabled for this model and cannot be disabled.
9254 *
9255 * @default true
9256 */
9257 enable_thinking?: true;
9258 };
9259 }>;
9260 postProcessedOutputs: XOR<ResponsesOutput, ChatCompletionsOutput>;
9261}
9262declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B {
9263 inputs: XOR<Omit<ResponsesInput, "reasoning"> & {
9264 reasoning?: (Omit<Reasoning, "effort"> & {
9265 /**
9266 * Reasoning effort. Supported levels: low, medium, high. Reasoning cannot be disabled.
9267 *
9268 * @default "medium"
9269 */
9270 effort?: "low" | "medium" | "high" | null;
9271 }) | null;
9272 }, Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
9273 /**
9274 * Reasoning effort. Supported levels: low, medium, high. Reasoning cannot be disabled.
9275 *
9276 * @default "medium"
9277 */
9278 reasoning_effort?: "low" | "medium" | "high" | null;
9279 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
9280 /**
9281 * Reasoning is always enabled for this model and cannot be disabled.
9282 *
9283 * @default true
9284 */
9285 enable_thinking?: true;
9286 };
9287 }>;
9288 postProcessedOutputs: XOR<ResponsesOutput, ChatCompletionsOutput>;
9289}
9290interface Ai_Cf_Leonardo_Phoenix_1_0_Input {
9291 /**
9292 * A text description of the image you want to generate.
9293 */
9294 prompt: string;
9295 /**
9296 * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt
9297 */
9298 guidance?: number;
9299 /**
9300 * Random seed for reproducibility of the image generation
9301 */
9302 seed?: number;
9303 /**
9304 * The height of the generated image in pixels
9305 */
9306 height?: number;
9307 /**
9308 * The width of the generated image in pixels
9309 */
9310 width?: number;
9311 /**
9312 * The number of diffusion steps; higher values can improve quality but take longer
9313 */
9314 num_steps?: number;
9315 /**
9316 * Specify what to exclude from the generated images
9317 */
9318 negative_prompt?: string;
9319}
9320/**
9321 * The generated image in JPEG format
9322 */
9323type Ai_Cf_Leonardo_Phoenix_1_0_Output = string;
9324declare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 {
9325 inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input;
9326 postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output;
9327}
9328interface Ai_Cf_Leonardo_Lucid_Origin_Input {
9329 /**
9330 * A text description of the image you want to generate.
9331 */
9332 prompt: string;
9333 /**
9334 * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt
9335 */
9336 guidance?: number;
9337 /**
9338 * Random seed for reproducibility of the image generation
9339 */
9340 seed?: number;
9341 /**
9342 * The height of the generated image in pixels
9343 */
9344 height?: number;
9345 /**
9346 * The width of the generated image in pixels
9347 */
9348 width?: number;
9349 /**
9350 * The number of diffusion steps; higher values can improve quality but take longer
9351 */
9352 num_steps?: number;
9353 /**
9354 * The number of diffusion steps; higher values can improve quality but take longer
9355 */
9356 steps?: number;
9357}
9358interface Ai_Cf_Leonardo_Lucid_Origin_Output {
9359 /**
9360 * The generated image in Base64 format.
9361 */
9362 image?: string;
9363}
9364declare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin {
9365 inputs: Ai_Cf_Leonardo_Lucid_Origin_Input;
9366 postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output;
9367}
9368interface Ai_Cf_Deepgram_Aura_1_Input {
9369 /**
9370 * Speaker used to produce the audio.
9371 */
9372 speaker?: "angus" | "asteria" | "arcas" | "orion" | "orpheus" | "athena" | "luna" | "zeus" | "perseus" | "helios" | "hera" | "stella";
9373 /**
9374 * Encoding of the output audio.
9375 */
9376 encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac";
9377 /**
9378 * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type..
9379 */
9380 container?: "none" | "wav" | "ogg";
9381 /**
9382 * The text content to be converted to speech
9383 */
9384 text: string;
9385 /**
9386 * 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 configurable
9387 */
9388 sample_rate?: number;
9389 /**
9390 * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type.
9391 */
9392 bit_rate?: number;
9393}
9394/**
9395 * The generated audio in MP3 format
9396 */
9397type Ai_Cf_Deepgram_Aura_1_Output = string;
9398declare abstract class Base_Ai_Cf_Deepgram_Aura_1 {
9399 inputs: Ai_Cf_Deepgram_Aura_1_Input;
9400 postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output;
9401}
9402interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input {
9403 /**
9404 * Input text to translate. Can be a single string or a list of strings.
9405 */
9406 text: string | string[];
9407 /**
9408 * Target langauge to translate to
9409 */
9410 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";
9411}
9412interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output {
9413 /**
9414 * Translated texts
9415 */
9416 translations: string[];
9417}
9418declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B {
9419 inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input;
9420 postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output;
9421}
9422type 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;
9423interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt {
9424 /**
9425 * The input text prompt for the model to generate a response.
9426 */
9427 prompt: string;
9428 /**
9429 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
9430 */
9431 lora?: string;
9432 response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode;
9433 /**
9434 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
9435 */
9436 raw?: boolean;
9437 /**
9438 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
9439 */
9440 stream?: boolean;
9441 /**
9442 * The maximum number of tokens to generate in the response.
9443 */
9444 max_tokens?: number;
9445 /**
9446 * Controls the randomness of the output; higher values produce more random results.
9447 */
9448 temperature?: number;
9449 /**
9450 * 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.
9451 */
9452 top_p?: number;
9453 /**
9454 * 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.
9455 */
9456 top_k?: number;
9457 /**
9458 * Random seed for reproducibility of the generation.
9459 */
9460 seed?: number;
9461 /**
9462 * Penalty for repeated tokens; higher values discourage repetition.
9463 */
9464 repetition_penalty?: number;
9465 /**
9466 * Decreases the likelihood of the model repeating the same lines verbatim.
9467 */
9468 frequency_penalty?: number;
9469 /**
9470 * Increases the likelihood of the model introducing new topics.
9471 */
9472 presence_penalty?: number;
9473}
9474interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode {
9475 type?: "json_object" | "json_schema";
9476 json_schema?: unknown;
9477}
9478interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages {
9479 /**
9480 * An array of message objects representing the conversation history.
9481 */
9482 messages: {
9483 /**
9484 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
9485 */
9486 role: string;
9487 content: string | {
9488 /**
9489 * Type of the content (text)
9490 */
9491 type?: string;
9492 /**
9493 * Text content
9494 */
9495 text?: string;
9496 }[];
9497 }[];
9498 functions?: {
9499 name: string;
9500 code: string;
9501 }[];
9502 /**
9503 * A list of tools available for the assistant to use.
9504 */
9505 tools?: ({
9506 /**
9507 * The name of the tool. More descriptive the better.
9508 */
9509 name: string;
9510 /**
9511 * A brief description of what the tool does.
9512 */
9513 description: string;
9514 /**
9515 * Schema defining the parameters accepted by the tool.
9516 */
9517 parameters: {
9518 /**
9519 * The type of the parameters object (usually 'object').
9520 */
9521 type: string;
9522 /**
9523 * List of required parameter names.
9524 */
9525 required?: string[];
9526 /**
9527 * Definitions of each parameter.
9528 */
9529 properties: {
9530 [k: string]: {
9531 /**
9532 * The data type of the parameter.
9533 */
9534 type: string;
9535 /**
9536 * A description of the expected parameter.
9537 */
9538 description: string;
9539 };
9540 };
9541 };
9542 } | {
9543 /**
9544 * Specifies the type of tool (e.g., 'function').
9545 */
9546 type: string;
9547 /**
9548 * Details of the function tool.
9549 */
9550 function: {
9551 /**
9552 * The name of the function.
9553 */
9554 name: string;
9555 /**
9556 * A brief description of what the function does.
9557 */
9558 description: string;
9559 /**
9560 * Schema defining the parameters accepted by the function.
9561 */
9562 parameters: {
9563 /**
9564 * The type of the parameters object (usually 'object').
9565 */
9566 type: string;
9567 /**
9568 * List of required parameter names.
9569 */
9570 required?: string[];
9571 /**
9572 * Definitions of each parameter.
9573 */
9574 properties: {
9575 [k: string]: {
9576 /**
9577 * The data type of the parameter.
9578 */
9579 type: string;
9580 /**
9581 * A description of the expected parameter.
9582 */
9583 description: string;
9584 };
9585 };
9586 };
9587 };
9588 })[];
9589 response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1;
9590 /**
9591 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
9592 */
9593 raw?: boolean;
9594 /**
9595 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
9596 */
9597 stream?: boolean;
9598 /**
9599 * The maximum number of tokens to generate in the response.
9600 */
9601 max_tokens?: number;
9602 /**
9603 * Controls the randomness of the output; higher values produce more random results.
9604 */
9605 temperature?: number;
9606 /**
9607 * 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.
9608 */
9609 top_p?: number;
9610 /**
9611 * 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.
9612 */
9613 top_k?: number;
9614 /**
9615 * Random seed for reproducibility of the generation.
9616 */
9617 seed?: number;
9618 /**
9619 * Penalty for repeated tokens; higher values discourage repetition.
9620 */
9621 repetition_penalty?: number;
9622 /**
9623 * Decreases the likelihood of the model repeating the same lines verbatim.
9624 */
9625 frequency_penalty?: number;
9626 /**
9627 * Increases the likelihood of the model introducing new topics.
9628 */
9629 presence_penalty?: number;
9630}
9631interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 {
9632 type?: "json_object" | "json_schema";
9633 json_schema?: unknown;
9634}
9635interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch {
9636 requests: (Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1)[];
9637}
9638interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 {
9639 /**
9640 * The input text prompt for the model to generate a response.
9641 */
9642 prompt: string;
9643 /**
9644 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
9645 */
9646 lora?: string;
9647 response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2;
9648 /**
9649 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
9650 */
9651 raw?: boolean;
9652 /**
9653 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
9654 */
9655 stream?: boolean;
9656 /**
9657 * The maximum number of tokens to generate in the response.
9658 */
9659 max_tokens?: number;
9660 /**
9661 * Controls the randomness of the output; higher values produce more random results.
9662 */
9663 temperature?: number;
9664 /**
9665 * 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.
9666 */
9667 top_p?: number;
9668 /**
9669 * 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.
9670 */
9671 top_k?: number;
9672 /**
9673 * Random seed for reproducibility of the generation.
9674 */
9675 seed?: number;
9676 /**
9677 * Penalty for repeated tokens; higher values discourage repetition.
9678 */
9679 repetition_penalty?: number;
9680 /**
9681 * Decreases the likelihood of the model repeating the same lines verbatim.
9682 */
9683 frequency_penalty?: number;
9684 /**
9685 * Increases the likelihood of the model introducing new topics.
9686 */
9687 presence_penalty?: number;
9688}
9689interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 {
9690 type?: "json_object" | "json_schema";
9691 json_schema?: unknown;
9692}
9693interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 {
9694 /**
9695 * An array of message objects representing the conversation history.
9696 */
9697 messages: {
9698 /**
9699 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
9700 */
9701 role: string;
9702 content: string | {
9703 /**
9704 * Type of the content (text)
9705 */
9706 type?: string;
9707 /**
9708 * Text content
9709 */
9710 text?: string;
9711 }[];
9712 }[];
9713 functions?: {
9714 name: string;
9715 code: string;
9716 }[];
9717 /**
9718 * A list of tools available for the assistant to use.
9719 */
9720 tools?: ({
9721 /**
9722 * The name of the tool. More descriptive the better.
9723 */
9724 name: string;
9725 /**
9726 * A brief description of what the tool does.
9727 */
9728 description: string;
9729 /**
9730 * Schema defining the parameters accepted by the tool.
9731 */
9732 parameters: {
9733 /**
9734 * The type of the parameters object (usually 'object').
9735 */
9736 type: string;
9737 /**
9738 * List of required parameter names.
9739 */
9740 required?: string[];
9741 /**
9742 * Definitions of each parameter.
9743 */
9744 properties: {
9745 [k: string]: {
9746 /**
9747 * The data type of the parameter.
9748 */
9749 type: string;
9750 /**
9751 * A description of the expected parameter.
9752 */
9753 description: string;
9754 };
9755 };
9756 };
9757 } | {
9758 /**
9759 * Specifies the type of tool (e.g., 'function').
9760 */
9761 type: string;
9762 /**
9763 * Details of the function tool.
9764 */
9765 function: {
9766 /**
9767 * The name of the function.
9768 */
9769 name: string;
9770 /**
9771 * A brief description of what the function does.
9772 */
9773 description: string;
9774 /**
9775 * Schema defining the parameters accepted by the function.
9776 */
9777 parameters: {
9778 /**
9779 * The type of the parameters object (usually 'object').
9780 */
9781 type: string;
9782 /**
9783 * List of required parameter names.
9784 */
9785 required?: string[];
9786 /**
9787 * Definitions of each parameter.
9788 */
9789 properties: {
9790 [k: string]: {
9791 /**
9792 * The data type of the parameter.
9793 */
9794 type: string;
9795 /**
9796 * A description of the expected parameter.
9797 */
9798 description: string;
9799 };
9800 };
9801 };
9802 };
9803 })[];
9804 response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3;
9805 /**
9806 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
9807 */
9808 raw?: boolean;
9809 /**
9810 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
9811 */
9812 stream?: boolean;
9813 /**
9814 * The maximum number of tokens to generate in the response.
9815 */
9816 max_tokens?: number;
9817 /**
9818 * Controls the randomness of the output; higher values produce more random results.
9819 */
9820 temperature?: number;
9821 /**
9822 * 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.
9823 */
9824 top_p?: number;
9825 /**
9826 * 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.
9827 */
9828 top_k?: number;
9829 /**
9830 * Random seed for reproducibility of the generation.
9831 */
9832 seed?: number;
9833 /**
9834 * Penalty for repeated tokens; higher values discourage repetition.
9835 */
9836 repetition_penalty?: number;
9837 /**
9838 * Decreases the likelihood of the model repeating the same lines verbatim.
9839 */
9840 frequency_penalty?: number;
9841 /**
9842 * Increases the likelihood of the model introducing new topics.
9843 */
9844 presence_penalty?: number;
9845}
9846interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 {
9847 type?: "json_object" | "json_schema";
9848 json_schema?: unknown;
9849}
9850type 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;
9851interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response {
9852 /**
9853 * Unique identifier for the completion
9854 */
9855 id?: string;
9856 /**
9857 * Object type identifier
9858 */
9859 object?: "chat.completion";
9860 /**
9861 * Unix timestamp of when the completion was created
9862 */
9863 created?: number;
9864 /**
9865 * Model used for the completion
9866 */
9867 model?: string;
9868 /**
9869 * List of completion choices
9870 */
9871 choices?: {
9872 /**
9873 * Index of the choice in the list
9874 */
9875 index?: number;
9876 /**
9877 * The message generated by the model
9878 */
9879 message?: {
9880 /**
9881 * Role of the message author
9882 */
9883 role: string;
9884 /**
9885 * The content of the message
9886 */
9887 content: string;
9888 /**
9889 * Internal reasoning content (if available)
9890 */
9891 reasoning_content?: string;
9892 /**
9893 * Tool calls made by the assistant
9894 */
9895 tool_calls?: {
9896 /**
9897 * Unique identifier for the tool call
9898 */
9899 id: string;
9900 /**
9901 * Type of tool call
9902 */
9903 type: "function";
9904 function: {
9905 /**
9906 * Name of the function to call
9907 */
9908 name: string;
9909 /**
9910 * JSON string of arguments for the function
9911 */
9912 arguments: string;
9913 };
9914 }[];
9915 };
9916 /**
9917 * Reason why the model stopped generating
9918 */
9919 finish_reason?: string;
9920 /**
9921 * Stop reason (may be null)
9922 */
9923 stop_reason?: string | null;
9924 /**
9925 * Log probabilities (if requested)
9926 */
9927 logprobs?: {} | null;
9928 }[];
9929 /**
9930 * Usage statistics for the inference request
9931 */
9932 usage?: {
9933 /**
9934 * Total number of tokens in input
9935 */
9936 prompt_tokens?: number;
9937 /**
9938 * Total number of tokens in output
9939 */
9940 completion_tokens?: number;
9941 /**
9942 * Total number of input and output tokens
9943 */
9944 total_tokens?: number;
9945 };
9946 /**
9947 * Log probabilities for the prompt (if requested)
9948 */
9949 prompt_logprobs?: {} | null;
9950}
9951interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response {
9952 /**
9953 * Unique identifier for the completion
9954 */
9955 id?: string;
9956 /**
9957 * Object type identifier
9958 */
9959 object?: "text_completion";
9960 /**
9961 * Unix timestamp of when the completion was created
9962 */
9963 created?: number;
9964 /**
9965 * Model used for the completion
9966 */
9967 model?: string;
9968 /**
9969 * List of completion choices
9970 */
9971 choices?: {
9972 /**
9973 * Index of the choice in the list
9974 */
9975 index: number;
9976 /**
9977 * The generated text completion
9978 */
9979 text: string;
9980 /**
9981 * Reason why the model stopped generating
9982 */
9983 finish_reason: string;
9984 /**
9985 * Stop reason (may be null)
9986 */
9987 stop_reason?: string | null;
9988 /**
9989 * Log probabilities (if requested)
9990 */
9991 logprobs?: {} | null;
9992 /**
9993 * Log probabilities for the prompt (if requested)
9994 */
9995 prompt_logprobs?: {} | null;
9996 }[];
9997 /**
9998 * Usage statistics for the inference request
9999 */
10000 usage?: {
10001 /**
10002 * Total number of tokens in input
10003 */
10004 prompt_tokens?: number;
10005 /**
10006 * Total number of tokens in output
10007 */
10008 completion_tokens?: number;
10009 /**
10010 * Total number of input and output tokens
10011 */
10012 total_tokens?: number;
10013 };
10014}
10015interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse {
10016 /**
10017 * The async request id that can be used to obtain the results.
10018 */
10019 request_id?: string;
10020}
10021declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It {
10022 inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input;
10023 postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output;
10024}
10025interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input {
10026 /**
10027 * Input text to embed. Can be a single string or a list of strings.
10028 */
10029 text: string | string[];
10030}
10031interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output {
10032 /**
10033 * Embedding vectors, where each vector is a list of floats.
10034 */
10035 data: number[][];
10036 /**
10037 * Shape of the embedding data as [number_of_embeddings, embedding_dimension].
10038 *
10039 * @minItems 2
10040 * @maxItems 2
10041 */
10042 shape: [
10043 number,
10044 number
10045 ];
10046}
10047declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B {
10048 inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input;
10049 postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output;
10050}
10051interface Ai_Cf_Deepgram_Flux_Input {
10052 /**
10053 * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM.
10054 */
10055 encoding: "linear16";
10056 /**
10057 * Sample rate of the audio stream in Hz.
10058 */
10059 sample_rate: string;
10060 /**
10061 * 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.
10062 */
10063 eager_eot_threshold?: string;
10064 /**
10065 * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9.
10066 */
10067 eot_threshold?: string;
10068 /**
10069 * A turn will be finished when this much time has passed after speech, regardless of EOT confidence.
10070 */
10071 eot_timeout_ms?: string;
10072 /**
10073 * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms.
10074 */
10075 keyterm?: string;
10076 /**
10077 * 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-mip
10078 */
10079 mip_opt_out?: "true" | "false";
10080 /**
10081 * Label your requests for the purpose of identification during usage reporting
10082 */
10083 tag?: string;
10084}
10085/**
10086 * Output will be returned as websocket messages.
10087 */
10088interface Ai_Cf_Deepgram_Flux_Output {
10089 /**
10090 * The unique identifier of the request (uuid)
10091 */
10092 request_id?: string;
10093 /**
10094 * Starts at 0 and increments for each message the server sends to the client.
10095 */
10096 sequence_id?: number;
10097 /**
10098 * The type of event being reported.
10099 */
10100 event?: "Update" | "StartOfTurn" | "EagerEndOfTurn" | "TurnResumed" | "EndOfTurn";
10101 /**
10102 * The index of the current turn
10103 */
10104 turn_index?: number;
10105 /**
10106 * Start time in seconds of the audio range that was transcribed
10107 */
10108 audio_window_start?: number;
10109 /**
10110 * End time in seconds of the audio range that was transcribed
10111 */
10112 audio_window_end?: number;
10113 /**
10114 * Text that was said over the course of the current turn
10115 */
10116 transcript?: string;
10117 /**
10118 * The words in the transcript
10119 */
10120 words?: {
10121 /**
10122 * The individual punctuated, properly-cased word from the transcript
10123 */
10124 word: string;
10125 /**
10126 * Confidence that this word was transcribed correctly
10127 */
10128 confidence: number;
10129 }[];
10130 /**
10131 * Confidence that no more speech is coming in this turn
10132 */
10133 end_of_turn_confidence?: number;
10134}
10135declare abstract class Base_Ai_Cf_Deepgram_Flux {
10136 inputs: Ai_Cf_Deepgram_Flux_Input;
10137 postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output;
10138}
10139interface Ai_Cf_Deepgram_Aura_2_En_Input {
10140 /**
10141 * Speaker used to produce the audio.
10142 */
10143 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";
10144 /**
10145 * Encoding of the output audio.
10146 */
10147 encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac";
10148 /**
10149 * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type..
10150 */
10151 container?: "none" | "wav" | "ogg";
10152 /**
10153 * The text content to be converted to speech
10154 */
10155 text: string;
10156 /**
10157 * 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 configurable
10158 */
10159 sample_rate?: number;
10160 /**
10161 * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type.
10162 */
10163 bit_rate?: number;
10164}
10165/**
10166 * The generated audio in MP3 format
10167 */
10168type Ai_Cf_Deepgram_Aura_2_En_Output = string;
10169declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En {
10170 inputs: Ai_Cf_Deepgram_Aura_2_En_Input;
10171 postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output;
10172}
10173interface Ai_Cf_Deepgram_Aura_2_Es_Input {
10174 /**
10175 * Speaker used to produce the audio.
10176 */
10177 speaker?: "sirio" | "nestor" | "carina" | "celeste" | "alvaro" | "diana" | "aquila" | "selena" | "estrella" | "javier";
10178 /**
10179 * Encoding of the output audio.
10180 */
10181 encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac";
10182 /**
10183 * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type..
10184 */
10185 container?: "none" | "wav" | "ogg";
10186 /**
10187 * The text content to be converted to speech
10188 */
10189 text: string;
10190 /**
10191 * 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 configurable
10192 */
10193 sample_rate?: number;
10194 /**
10195 * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type.
10196 */
10197 bit_rate?: number;
10198}
10199/**
10200 * The generated audio in MP3 format
10201 */
10202type Ai_Cf_Deepgram_Aura_2_Es_Output = string;
10203declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es {
10204 inputs: Ai_Cf_Deepgram_Aura_2_Es_Input;
10205 postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output;
10206}
10207interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input {
10208 multipart: {
10209 body?: object;
10210 contentType?: string;
10211 };
10212}
10213interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output {
10214 /**
10215 * Generated image as Base64 string.
10216 */
10217 image?: string;
10218}
10219declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev {
10220 inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input;
10221 postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output;
10222}
10223interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input {
10224 multipart: {
10225 body?: object;
10226 contentType?: string;
10227 };
10228}
10229interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output {
10230 /**
10231 * Generated image as Base64 string.
10232 */
10233 image?: string;
10234}
10235declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B {
10236 inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input;
10237 postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output;
10238}
10239interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input {
10240 multipart: {
10241 body?: object;
10242 contentType?: string;
10243 };
10244}
10245interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output {
10246 /**
10247 * Generated image as Base64 string.
10248 */
10249 image?: string;
10250}
10251declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B {
10252 inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input;
10253 postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output;
10254}
10255declare abstract class Base_Ai_Cf_Zai_Org_Glm_4_7_Flash {
10256 inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10257 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10258 /**
10259 * Whether to enable reasoning for this model. This model has no reasoning effort levels.
10260 *
10261 * @default true
10262 */
10263 enable_thinking?: boolean;
10264 };
10265 };
10266 postProcessedOutputs: ChatCompletionsOutput;
10267}
10268declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_5 {
10269 inputs: ChatCompletionsInput;
10270 postProcessedOutputs: ChatCompletionsOutput;
10271}
10272declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_6 {
10273 inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10274 /**
10275 * Reasoning effort. Supported levels: high, none. Compatibility aliases (accepted by the API, not by these types): low maps to high; medium maps to high; max maps to high.
10276 *
10277 * @default "high"
10278 */
10279 reasoning_effort?: "high" | "none" | null;
10280 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10281 /**
10282 * Whether to enable reasoning for this model.
10283 *
10284 * @default true
10285 */
10286 enable_thinking?: boolean;
10287 };
10288 };
10289 postProcessedOutputs: ChatCompletionsOutput;
10290}
10291type Ai_Cf_Nvidia_Nemotron_3_120B_A12B_Input = Omit<ChatCompletionsInput, "model" | "max_tokens" | "metadata" | "modalities" | "chat_template_kwargs" | "store" | "reasoning_effort"> & {
10292 /**
10293 * ID of the model to use (for example, '@cf/nvidia/nemotron-3-120b-a12b').
10294 */
10295 model?: ChatCompletionsInput["model"];
10296 /**
10297 * The maximum number of tokens to generate.
10298 */
10299 max_tokens?: ChatCompletionsInput["max_tokens"];
10300 /**
10301 * Set of key-value pairs that can be attached to the object.
10302 */
10303 metadata?: ChatCompletionsInput["metadata"];
10304 /**
10305 * Output types requested from the model.
10306 */
10307 modalities?: ChatCompletionsInput["modalities"];
10308 /**
10309 * Nemotron chat-template controls for normal reasoning, low-effort reasoning, and non-reasoning responses.
10310 */
10311 chat_template_kwargs?: {
10312 /**
10313 * Whether to enable reasoning. Reasoning is enabled by default.
10314 */
10315 enable_thinking?: boolean;
10316 /**
10317 * When reasoning is enabled, use Nemotron's low-effort reasoning mode, which uses significantly fewer reasoning tokens.
10318 */
10319 low_effort?: boolean;
10320 /**
10321 * For coding agent use, Nvidia suggests setting force_nonempty_content=true
10322 */
10323 force_nonempty_content?: boolean;
10324 };
10325 /**
10326 * Whether to store the output for model distillation or evaluation.
10327 *
10328 * @default false
10329 */
10330 store?: ChatCompletionsInput["store"];
10331};
10332declare abstract class Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B {
10333 inputs: Ai_Cf_Nvidia_Nemotron_3_120B_A12B_Input;
10334 postProcessedOutputs: ChatCompletionsOutput;
10335}
10336type Ai_Cf_Google_Gemma_4_26B_A4B_It_Input = Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10337 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10338 /**
10339 * Whether to enable reasoning for this model. This model has no reasoning effort levels.
10340 *
10341 * @default true
10342 */
10343 enable_thinking?: boolean;
10344 };
10345} & {
10346 /**
10347 * @default false
10348 */
10349 skip_special_tokens?: boolean;
10350};
10351declare abstract class Base_Ai_Cf_Google_Gemma_4_26B_A4B_It {
10352 inputs: Ai_Cf_Google_Gemma_4_26B_A4B_It_Input;
10353 postProcessedOutputs: ChatCompletionsOutput;
10354}
10355/** @deprecated Use Base_Ai_Cf_Google_Gemma_4_26B_A4B_It. */
10356declare abstract class Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT extends Base_Ai_Cf_Google_Gemma_4_26B_A4B_It {
10357}
10358type Ai_Cf_Nvidia_Nemotron_Speech_Streaming_En_0_6B_Input = {
10359 /**
10360 * readable stream with audio data and content-type specified for that data
10361 */
10362 audio: {
10363 body: object;
10364 contentType: string;
10365 };
10366} | {
10367 /**
10368 * base64 encoded audio data
10369 */
10370 audio: string;
10371 encoding?: "wav" | "flac" | "ogg" | "linear16";
10372 sample_rate?: number;
10373 channels?: number;
10374};
10375interface Ai_Cf_Nvidia_Nemotron_Speech_Streaming_En_0_6B_Output {
10376 text?: string;
10377 duration?: number;
10378}
10379declare abstract class Base_Ai_Cf_Nvidia_Nemotron_Speech_Streaming_En_0_6B {
10380 inputs: Ai_Cf_Nvidia_Nemotron_Speech_Streaming_En_0_6B_Input;
10381 postProcessedOutputs: Ai_Cf_Nvidia_Nemotron_Speech_Streaming_En_0_6B_Output;
10382}
10383declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_7_Code {
10384 inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10385 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10386 /**
10387 * Reasoning is always enabled for this model and cannot be disabled. This model has no reasoning effort levels.
10388 *
10389 * @default true
10390 */
10391 enable_thinking?: true;
10392 };
10393 };
10394 postProcessedOutputs: ChatCompletionsOutput;
10395}
10396declare abstract class Base_Ai_Cf_Zai_Org_Glm_5_2 {
10397 inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10398 /**
10399 * Reasoning effort. Supported levels: max, high, none. Compatibility aliases (accepted by the API, not by these types): low maps to high; medium maps to high; xhigh maps to max; minimal maps to none.
10400 *
10401 * @default "max"
10402 */
10403 reasoning_effort?: "max" | "high" | "none" | null;
10404 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10405 /**
10406 * Whether to enable reasoning for this model.
10407 *
10408 * @default true
10409 */
10410 enable_thinking?: boolean;
10411 };
10412 };
10413 postProcessedOutputs: ChatCompletionsOutput;
10414}
10415interface Ai_Cf_Moondream_Moondream3_1_9B_A2B_Input {
10416 /**
10417 * Which Moondream skill to run.
10418 */
10419 task?: "query" | "caption" | "point" | "detect";
10420 /**
10421 * Input image as a public HTTPS URL or base64 data URI. Optional for `query`; required for `caption`, `point`, and `detect`.
10422 */
10423 image?: string;
10424 /**
10425 * Question for the `query` task.
10426 */
10427 question?: string;
10428 /**
10429 * Caption length for the `caption` task.
10430 */
10431 caption_length?: "short" | "normal" | "long";
10432 /**
10433 * Object phrase to locate for `point` and `detect` tasks (e.g. 'person wearing a red shirt').
10434 */
10435 target?: string;
10436 /**
10437 * Enable reasoning trace for the `query` task.
10438 */
10439 reasoning?: boolean;
10440 /**
10441 * Sampling temperature.
10442 */
10443 temperature?: number;
10444 /**
10445 * Top-p (nucleus) sampling.
10446 */
10447 top_p?: number;
10448 /**
10449 * Max tokens to generate for `query` and `caption`.
10450 */
10451 max_tokens?: number;
10452 /**
10453 * Max objects to return for `point` and `detect`.
10454 */
10455 max_objects?: number;
10456 /**
10457 * Return incremental tokens for `query` and `caption`. `point` and `detect` do not support streaming.
10458 */
10459 stream?: boolean;
10460}
10461interface Ai_Cf_Moondream_Moondream3_1_9B_A2B_Output {
10462 /**
10463 * Reason the generation finished.
10464 */
10465 finish_reason: string;
10466 metrics: {
10467 /**
10468 * Number of input tokens consumed.
10469 */
10470 input_tokens: number;
10471 /**
10472 * Number of output tokens generated.
10473 */
10474 output_tokens: number;
10475 /**
10476 * Prefill time in milliseconds.
10477 */
10478 prefill_time_ms: number;
10479 /**
10480 * Decode time in milliseconds.
10481 */
10482 decode_time_ms: number;
10483 /**
10484 * Time to first token in milliseconds.
10485 */
10486 ttft_ms: number;
10487 };
10488 /**
10489 * Answer text for the `query` task. Null for other tasks.
10490 */
10491 answer?: string;
10492 /**
10493 * Caption text for the `caption` task. Null for other tasks.
10494 */
10495 caption?: string;
10496 /**
10497 * Located points for the `point` task. Null for other tasks.
10498 */
10499 points?: {
10500 /**
10501 * X coordinate.
10502 */
10503 x: number;
10504 /**
10505 * Y coordinate.
10506 */
10507 y: number;
10508 }[];
10509 /**
10510 * Detected bounding boxes for the `detect` task. Null for other tasks.
10511 */
10512 objects?: {
10513 /**
10514 * Minimum X coordinate.
10515 */
10516 x_min: number;
10517 /**
10518 * Minimum Y coordinate.
10519 */
10520 y_min: number;
10521 /**
10522 * Maximum X coordinate.
10523 */
10524 x_max: number;
10525 /**
10526 * Maximum Y coordinate.
10527 */
10528 y_max: number;
10529 }[];
10530 /**
10531 * Reasoning trace for the `query` task when reasoning=true. Null otherwise.
10532 */
10533 reasoning?: {
10534 /**
10535 * Reasoning text.
10536 */
10537 text: string;
10538 /**
10539 * Grounding information.
10540 */
10541 grounding?: {}[];
10542 };
10543}
10544declare abstract class Base_Ai_Cf_Moondream_Moondream3_1_9B_A2B {
10545 inputs: Ai_Cf_Moondream_Moondream3_1_9B_A2B_Input;
10546 postProcessedOutputs: Ai_Cf_Moondream_Moondream3_1_9B_A2B_Output;
10547}
10548declare abstract class Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Flash_0731 {
10549 inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10550 /**
10551 * Reasoning effort. Supported levels: max, high, low, none. Compatibility aliases (accepted by the API, not by these types): minimal maps to low; medium maps to high; xhigh maps to high.
10552 *
10553 * @default "high"
10554 */
10555 reasoning_effort?: "max" | "high" | "low" | "none" | null;
10556 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10557 /**
10558 * Whether to enable reasoning for this model.
10559 *
10560 * @default true
10561 */
10562 enable_thinking?: boolean;
10563 };
10564 };
10565 postProcessedOutputs: ChatCompletionsOutput;
10566}
10567declare abstract class Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Pro_0813 {
10568 inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10569 /**
10570 * Reasoning effort. Supported levels: max, high, low, none. Compatibility aliases (accepted by the API, not by these types): minimal maps to low; medium maps to high; xhigh maps to high.
10571 *
10572 * @default "high"
10573 */
10574 reasoning_effort?: "max" | "high" | "low" | "none" | null;
10575 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10576 /**
10577 * Whether to enable reasoning for this model.
10578 *
10579 * @default true
10580 */
10581 enable_thinking?: boolean;
10582 };
10583 };
10584 postProcessedOutputs: ChatCompletionsOutput;
10585}
10586declare abstract class Base_Ai_Cf_Qwen_Qwen3_8_27B {
10587 inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10588 /**
10589 * Reasoning effort. Supported levels: low, medium, xhigh.
10590 *
10591 * @default "xhigh"
10592 */
10593 reasoning_effort?: "low" | "medium" | "xhigh" | null;
10594 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10595 /**
10596 * Whether to enable reasoning for this model.
10597 *
10598 * @default true
10599 */
10600 enable_thinking?: boolean;
10601 };
10602 };
10603 postProcessedOutputs: ChatCompletionsOutput;
10604}
10605declare abstract class Base_Ai_Cf_Zai_Org_Glm_5_3 {
10606 inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10607 /**
10608 * Reasoning effort. Supported levels: max, high, low. Reasoning cannot be disabled. Compatibility aliases (accepted by the API, not by these types): none maps to max; minimal maps to max; medium maps to max; xhigh maps to max.
10609 *
10610 * @default "max"
10611 */
10612 reasoning_effort?: "max" | "high" | "low" | null;
10613 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10614 /**
10615 * Reasoning is always enabled for this model and cannot be disabled.
10616 *
10617 * @default true
10618 */
10619 enable_thinking?: true;
10620 };
10621 };
10622 postProcessedOutputs: ChatCompletionsOutput;
10623}
10624declare abstract class Base_Ai_Cf_Zai_Org_Glm_5_3_Flash {
10625 inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10626 /**
10627 * Reasoning effort. Supported levels: max, high, low. Reasoning cannot be disabled. Compatibility aliases (accepted by the API, not by these types): none maps to max; minimal maps to max; medium maps to max; xhigh maps to max.
10628 *
10629 * @default "max"
10630 */
10631 reasoning_effort?: "max" | "high" | "low" | null;
10632 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10633 /**
10634 * Reasoning is always enabled for this model and cannot be disabled.
10635 *
10636 * @default true
10637 */
10638 enable_thinking?: true;
10639 };
10640 };
10641 postProcessedOutputs: ChatCompletionsOutput;
10642}
10643interface AiModels {
10644 "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification;
10645 "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage;
10646 "@cf/runwayml/stable-diffusion-v1-5-inpainting": BaseAiTextToImage;
10647 "@cf/lykon/dreamshaper-8-lcm": BaseAiTextToImage;
10648 "@cf/bytedance/stable-diffusion-xl-lightning": BaseAiTextToImage;
10649 "@cf/myshell-ai/melotts": BaseAiTextToSpeech;
10650 "@cf/google/embeddinggemma-300m": BaseAiTextEmbeddings;
10651 "@cf/microsoft/resnet-50": BaseAiImageClassification;
10652 "@cf/meta/llama-2-7b-chat-int8": BaseAiTextGeneration;
10653 "@cf/mistral/mistral-7b-instruct-v0.1": BaseAiTextGeneration;
10654 "@cf/meta/llama-2-7b-chat-fp16": BaseAiTextGeneration;
10655 "@hf/thebloke/llama-2-13b-chat-awq": BaseAiTextGeneration;
10656 "@hf/thebloke/mistral-7b-instruct-v0.1-awq": BaseAiTextGeneration;
10657 "@hf/thebloke/zephyr-7b-beta-awq": BaseAiTextGeneration;
10658 "@hf/thebloke/openhermes-2.5-mistral-7b-awq": BaseAiTextGeneration;
10659 "@hf/thebloke/neural-chat-7b-v3-1-awq": BaseAiTextGeneration;
10660 "@hf/thebloke/deepseek-coder-6.7b-base-awq": BaseAiTextGeneration;
10661 "@hf/thebloke/deepseek-coder-6.7b-instruct-awq": BaseAiTextGeneration;
10662 "@cf/deepseek-ai/deepseek-math-7b-instruct": BaseAiTextGeneration;
10663 "@cf/defog/sqlcoder-7b-2": BaseAiTextGeneration;
10664 "@cf/openchat/openchat-3.5-0106": BaseAiTextGeneration;
10665 "@cf/tiiuae/falcon-7b-instruct": BaseAiTextGeneration;
10666 "@cf/thebloke/discolm-german-7b-v1-awq": BaseAiTextGeneration;
10667 "@cf/qwen/qwen1.5-0.5b-chat": BaseAiTextGeneration;
10668 "@cf/qwen/qwen1.5-7b-chat-awq": BaseAiTextGeneration;
10669 "@cf/qwen/qwen1.5-14b-chat-awq": BaseAiTextGeneration;
10670 "@cf/tinyllama/tinyllama-1.1b-chat-v1.0": BaseAiTextGeneration;
10671 "@cf/microsoft/phi-2": BaseAiTextGeneration;
10672 "@cf/qwen/qwen1.5-1.8b-chat": BaseAiTextGeneration;
10673 "@cf/mistral/mistral-7b-instruct-v0.2-lora": BaseAiTextGeneration;
10674 "@hf/nousresearch/hermes-2-pro-mistral-7b": BaseAiTextGeneration;
10675 "@hf/nexusflow/starling-lm-7b-beta": BaseAiTextGeneration;
10676 "@hf/google/gemma-7b-it": BaseAiTextGeneration;
10677 "@cf/meta-llama/llama-2-7b-chat-hf-lora": BaseAiTextGeneration;
10678 "@cf/google/gemma-2b-it-lora": BaseAiTextGeneration;
10679 "@cf/google/gemma-7b-it-lora": BaseAiTextGeneration;
10680 "@hf/mistral/mistral-7b-instruct-v0.2": BaseAiTextGeneration;
10681 "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration;
10682 "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration;
10683 "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration;
10684 "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration;
10685 "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration;
10686 "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration;
10687 "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration;
10688 "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration;
10689 "@cf/ibm-granite/granite-4.0-h-micro": BaseAiTextGeneration;
10690 "@cf/facebook/bart-large-cnn": BaseAiSummarization;
10691 "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText;
10692 "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5;
10693 "@cf/openai/whisper": Base_Ai_Cf_Openai_Whisper;
10694 "@cf/meta/m2m100-1.2b": Base_Ai_Cf_Meta_M2M100_1_2B;
10695 "@cf/baai/bge-small-en-v1.5": Base_Ai_Cf_Baai_Bge_Small_En_V1_5;
10696 "@cf/baai/bge-large-en-v1.5": Base_Ai_Cf_Baai_Bge_Large_En_V1_5;
10697 "@cf/unum/uform-gen2-qwen-500m": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M;
10698 "@cf/openai/whisper-tiny-en": Base_Ai_Cf_Openai_Whisper_Tiny_En;
10699 "@cf/openai/whisper-large-v3-turbo": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo;
10700 "@cf/baai/bge-m3": Base_Ai_Cf_Baai_Bge_M3;
10701 "@cf/black-forest-labs/flux-1-schnell": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell;
10702 "@cf/meta/llama-3.2-11b-vision-instruct": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct;
10703 "@cf/meta/llama-3.3-70b-instruct-fp8-fast": Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast;
10704 "@cf/meta/llama-guard-3-8b": Base_Ai_Cf_Meta_Llama_Guard_3_8B;
10705 "@cf/baai/bge-reranker-base": Base_Ai_Cf_Baai_Bge_Reranker_Base;
10706 "@cf/qwen/qwen2.5-coder-32b-instruct": Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct;
10707 "@cf/qwen/qwq-32b": Base_Ai_Cf_Qwen_Qwq_32B;
10708 "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct;
10709 "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It;
10710 "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct;
10711 "@cf/qwen/qwen3-30b-a3b-fp8": Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8;
10712 "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3;
10713 "@cf/qwen/qwen3-embedding-0.6b": Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B;
10714 "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2;
10715 "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B;
10716 "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B;
10717 "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0;
10718 "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin;
10719 "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1;
10720 "@cf/ai4bharat/indictrans2-en-indic-1B": Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B;
10721 "@cf/aisingapore/gemma-sea-lion-v4-27b-it": Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It;
10722 "@cf/pfnet/plamo-embedding-1b": Base_Ai_Cf_Pfnet_Plamo_Embedding_1B;
10723 "@cf/deepgram/flux": Base_Ai_Cf_Deepgram_Flux;
10724 "@cf/deepgram/aura-2-en": Base_Ai_Cf_Deepgram_Aura_2_En;
10725 "@cf/deepgram/aura-2-es": Base_Ai_Cf_Deepgram_Aura_2_Es;
10726 "@cf/black-forest-labs/flux-2-dev": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev;
10727 "@cf/black-forest-labs/flux-2-klein-4b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B;
10728 "@cf/black-forest-labs/flux-2-klein-9b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B;
10729 "@cf/zai-org/glm-4.7-flash": Base_Ai_Cf_Zai_Org_Glm_4_7_Flash;
10730 "@cf/moonshotai/kimi-k2.5": Base_Ai_Cf_Moonshotai_Kimi_K2_5;
10731 "@cf/moonshotai/kimi-k2.6": Base_Ai_Cf_Moonshotai_Kimi_K2_6;
10732 "@cf/nvidia/nemotron-3-120b-a12b": Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B;
10733 "@cf/google/gemma-4-26b-a4b-it": Base_Ai_Cf_Google_Gemma_4_26B_A4B_It;
10734 "@cf/nvidia/nemotron-speech-streaming-en-0.6b": Base_Ai_Cf_Nvidia_Nemotron_Speech_Streaming_En_0_6B;
10735 "@cf/moonshotai/kimi-k2.7-code": Base_Ai_Cf_Moonshotai_Kimi_K2_7_Code;
10736 "@cf/zai-org/glm-5.2": Base_Ai_Cf_Zai_Org_Glm_5_2;
10737 "@cf/moondream/moondream3.1-9B-A2B": Base_Ai_Cf_Moondream_Moondream3_1_9B_A2B;
10738 "@cf/deepseek-ai/deepseek-v4-flash-0731": Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Flash_0731;
10739 "@cf/deepseek-ai/deepseek-v4-pro-0813": Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Pro_0813;
10740 "@cf/qwen/qwen3.8-27b": Base_Ai_Cf_Qwen_Qwen3_8_27B;
10741 "@cf/zai-org/glm-5.3": Base_Ai_Cf_Zai_Org_Glm_5_3;
10742 "@cf/zai-org/glm-5.3-flash": Base_Ai_Cf_Zai_Org_Glm_5_3_Flash;
10743}
10744type AiOptions = {
10745 /**
10746 * Send requests as an asynchronous batch job, only works for supported models
10747 * https://developers.cloudflare.com/workers-ai/features/batch-api
10748 */
10749 queueRequest?: boolean;
10750 /**
10751 * Establish websocket connections, only works for supported models
10752 */
10753 websocket?: boolean;
10754 /**
10755 * Tag your requests to group and view them in Cloudflare dashboard.
10756 *
10757 * Rules:
10758 * Tags must only contain letters, numbers, and the symbols: : - . / @
10759 * Each tag can have maximum 50 characters.
10760 * Maximum 5 tags are allowed each request.
10761 * Duplicate tags will removed.
10762 */
10763 tags?: string[];
10764 gateway?: GatewayOptions;
10765 returnRawResponse?: boolean;
10766 prefix?: string;
10767 extraHeaders?: object;
10768 signal?: AbortSignal;
10769};
10770type AiModelsSearchParams = {
10771 author?: string;
10772 hide_experimental?: boolean;
10773 page?: number;
10774 per_page?: number;
10775 search?: string;
10776 source?: number;
10777 task?: string;
10778};
10779type AiModelsSearchObject = {
10780 id: string;
10781 source: number;
10782 name: string;
10783 description: string;
10784 task: {
10785 id: string;
10786 name: string;
10787 description: string;
10788 };
10789 tags: string[];
10790 properties: {
10791 property_id: string;
10792 value: string;
10793 }[];
10794};
10795type ChatCompletionsBase = ChatCompletionsMessagesInput;
10796type ChatCompletionsInput = ChatCompletionsMessagesInput;
10797interface InferenceUpstreamError extends Error {
10798}
10799interface AiInternalError extends Error {
10800}
10801type AiModelListType = Record<string, any>;
10802type AiAsyncBatchResponse = {
10803 request_id: string;
10804};
10805type AiWebSearchRequest = {
10806 /** AI Gateway configuration used for this request. */
10807 gatewayId: string;
10808 /** Search query. */
10809 query: string;
10810 /** Maximum number of results. Defaults to 10 and is capped at 20. */
10811 limit?: number;
10812 /** Optional BYOK web-search provider configured on the gateway. */
10813 provider?: string;
10814 /** Optional BYOK key alias. Defaults to `default`. */
10815 byokAlias?: string;
10816};
10817declare abstract class Ai<AiModelList extends AiModelListType = AiModels> {
10818 aiGatewayLogId: string | null;
10819 gateway(gatewayId: string): AiGateway;
10820 websearch(request: AiWebSearchRequest): Promise<Response>;
10821 /**
10822 * @deprecated Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead.
10823 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
10824 */
10825 aiSearch(): AiSearchNamespace;
10826 /**
10827 * @deprecated AutoRAG has been replaced by AI Search.
10828 * Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead.
10829 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
10830 *
10831 * @param autoragId Instance ID
10832 */
10833 autorag(autoragId: string): AutoRAG;
10834 // Batch request
10835 run<Name extends keyof AiModelList>(model: Name, inputs: {
10836 requests: AiModelList[Name]['inputs'][];
10837 }, options: AiOptions & {
10838 queueRequest: true;
10839 }): Promise<AiAsyncBatchResponse>;
10840 // Raw response
10841 run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & {
10842 returnRawResponse: true;
10843 }): Promise<Response>;
10844 // WebSocket
10845 run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & {
10846 websocket: true;
10847 }): Promise<Response>;
10848 // Streaming
10849 run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'] & {
10850 stream: true;
10851 }, options?: AiOptions): Promise<ReadableStream>;
10852 // Normal (default) - known model
10853 run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'], options?: AiOptions): Promise<AiModelList[Name]['postProcessedOutputs']>;
10854 // Unknown model (fallback).
10855 //
10856 // The `Exclude<..., keyof AiModelList>` constraint forces TypeScript to
10857 // route any model name that is a literal key of `AiModelList` to one of
10858 // the known-model overloads above (so input/output mismatches surface as
10859 // type errors rather than silently falling back to `Record<string, unknown>`).
10860 // Names that aren't in `AiModelList` — e.g. third-party gateway models
10861 // like `"google/nano-banana"` — still hit this overload.
10862 run<Model extends string>(model: Model extends keyof AiModelList ? never : Model, inputs: Record<string, unknown>, options?: AiOptions): Promise<Record<string, unknown>>;
10863 models(params?: AiModelsSearchParams): Promise<AiModelsSearchObject[]>;
10864 toMarkdown(): ToMarkdownService;
10865 toMarkdown(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise<ConversionResponse[]>;
10866 toMarkdown(files: MarkdownDocument, options?: ConversionRequestOptions): Promise<ConversionResponse>;
10867}
10868type GatewayRetries = {
10869 maxAttempts?: 1 | 2 | 3 | 4 | 5;
10870 retryDelayMs?: number;
10871 backoff?: 'constant' | 'linear' | 'exponential';
10872};
10873type GatewayOptions = {
10874 id: string;
10875 cacheKey?: string;
10876 cacheTtl?: number;
10877 skipCache?: boolean;
10878 metadata?: Record<string, number | string | boolean | null | bigint>;
10879 collectLog?: boolean;
10880 eventId?: string;
10881 requestTimeoutMs?: number;
10882 retries?: GatewayRetries;
10883};
10884type UniversalGatewayOptions = Exclude<GatewayOptions, 'id'> & {
10885 /**
10886 ** @deprecated
10887 */
10888 id?: string;
10889};
10890type AiGatewayPatchLog = {
10891 score?: number | null;
10892 feedback?: -1 | 1 | null;
10893 metadata?: Record<string, number | string | boolean | null | bigint> | null;
10894};
10895type AiGatewayLog = {
10896 id: string;
10897 provider: string;
10898 model: string;
10899 model_type?: string;
10900 path: string;
10901 duration: number;
10902 request_type?: string;
10903 request_content_type?: string;
10904 status_code: number;
10905 response_content_type?: string;
10906 success: boolean;
10907 cached: boolean;
10908 tokens_in?: number;
10909 tokens_out?: number;
10910 metadata?: Record<string, number | string | boolean | null | bigint>;
10911 step?: number;
10912 cost?: number;
10913 custom_cost?: boolean;
10914 request_size: number;
10915 request_head?: string;
10916 request_head_complete: boolean;
10917 response_size: number;
10918 response_head?: string;
10919 response_head_complete: boolean;
10920 created_at: Date;
10921};
10922type 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';
10923type AIGatewayHeaders = {
10924 'cf-aig-metadata': Record<string, number | string | boolean | null | bigint> | string;
10925 'cf-aig-custom-cost': {
10926 per_token_in?: number;
10927 per_token_out?: number;
10928 } | {
10929 total_cost?: number;
10930 } | string;
10931 'cf-aig-cache-ttl': number | string;
10932 'cf-aig-skip-cache': boolean | string;
10933 'cf-aig-cache-key': string;
10934 'cf-aig-event-id': string;
10935 'cf-aig-request-timeout': number | string;
10936 'cf-aig-max-attempts': number | string;
10937 'cf-aig-retry-delay': number | string;
10938 'cf-aig-backoff': string;
10939 'cf-aig-collect-log': boolean | string;
10940 Authorization: string;
10941 'Content-Type': string;
10942 [key: string]: string | number | boolean | object;
10943};
10944type AIGatewayUniversalRequest = {
10945 provider: AIGatewayProviders | string; // eslint-disable-line
10946 endpoint: string;
10947 headers: Partial<AIGatewayHeaders>;
10948 query: unknown;
10949};
10950interface AiGatewayInternalError extends Error {
10951}
10952interface AiGatewayLogNotFound extends Error {
10953}
10954declare abstract class AiGateway {
10955 patchLog(logId: string, data: AiGatewayPatchLog): Promise<void>;
10956 getLog(logId: string): Promise<AiGatewayLog>;
10957 run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: {
10958 gateway?: UniversalGatewayOptions;
10959 extraHeaders?: object;
10960 signal?: AbortSignal;
10961 }): Promise<Response>;
10962 getUrl(provider?: AIGatewayProviders | string): Promise<string>; // eslint-disable-line
10963}
10964/** A parameter accepted by an Analytics SQL query. */
10965type AnalyticsSQLParameter = string | number | boolean | null;
10966/** An Analytics SQL query and its optional positional or named parameters. */
10967interface AnalyticsSQLQuery {
10968 query: string;
10969 params?: readonly AnalyticsSQLParameter[] | Readonly<Record<string, AnalyticsSQLParameter>>;
10970}
10971/** Execution statistics returned by Analytics SQL. */
10972interface AnalyticsSQLStatistics {
10973 elapsed_ms: number;
10974 rows_read: number;
10975 bytes_read: number;
10976}
10977/** The rows and execution statistics returned by an Analytics SQL query. */
10978interface AnalyticsSQLResult<T extends Record<string, unknown> = Record<string, unknown>> {
10979 data: T[];
10980 rows: number;
10981 statistics: AnalyticsSQLStatistics;
10982}
10983/** An Analytics SQL binding. */
10984interface AnalyticsSQLBinding {
10985 query<T extends Record<string, unknown> = Record<string, unknown>>(request: AnalyticsSQLQuery): Promise<AnalyticsSQLResult<T>>;
10986}
10987// Copyright (c) 2022-2025 Cloudflare, Inc.
10988// Licensed under the Apache 2.0 license found in the LICENSE file or at:
10989// https://opensource.org/licenses/Apache-2.0
10990/**
10991 * Artifacts — Git-compatible file storage on Cloudflare Workers.
10992 *
10993 * Provides programmatic access to create, manage, and fork repositories,
10994 * and to issue and revoke scoped access tokens.
10995 */
10996/** Information about a repository. */
10997interface ArtifactsRepoInfo {
10998 /** Unique repository ID. */
10999 id: string;
11000 /** Repository name. */
11001 name: string;
11002 /** Repository description, or null if not set. */
11003 description: string | null;
11004 /** Default branch name (e.g. "main"). */
11005 defaultBranch: string;
11006 /** ISO 8601 creation timestamp. */
11007 createdAt: string;
11008 /** ISO 8601 last-updated timestamp. */
11009 updatedAt: string;
11010 /** ISO 8601 timestamp of the last push, or null if never pushed. */
11011 lastPushAt: string | null;
11012 /** Fork source (e.g. "github:owner/repo", "artifacts:namespace/repo"), or null if not a fork. */
11013 source: string | null;
11014 /** Whether the repository is read-only. */
11015 readOnly: boolean;
11016 /** HTTPS git remote URL. */
11017 remote: string;
11018}
11019/** Result of creating a repository — includes the initial access token. */
11020interface ArtifactsCreateRepoResult {
11021 /** Unique repository ID. */
11022 id: string;
11023 /** Repository name. */
11024 name: string;
11025 /** Repository description, or null if not set. */
11026 description: string | null;
11027 /** Default branch name. */
11028 defaultBranch: string;
11029 /** HTTPS git remote URL. */
11030 remote: string;
11031 /** Plaintext access token (only returned at creation time). */
11032 token: string;
11033}
11034/** Paginated list of repositories. */
11035interface ArtifactsRepoListResult {
11036 /** Repositories in this page (without the `remote` field). */
11037 repos: Omit<ArtifactsRepoInfo, 'remote'>[];
11038 /** Total number of repositories in the namespace. */
11039 total: number;
11040 /** Cursor for the next page, if there are more results. */
11041 cursor?: string;
11042}
11043/** Result of creating an access token. */
11044interface ArtifactsCreateTokenResult {
11045 /** Unique token ID. */
11046 id: string;
11047 /** Plaintext token (only returned at creation time). */
11048 plaintext: string;
11049 /** Token scope: "read" or "write". */
11050 scope: 'read' | 'write';
11051 /** ISO 8601 token expiry timestamp. */
11052 expiresAt: string;
11053}
11054/** Token metadata (no plaintext). */
11055interface ArtifactsTokenInfo {
11056 /** Unique token ID. */
11057 id: string;
11058 /** Token scope: "read" or "write". */
11059 scope: 'read' | 'write';
11060 /** Token state: "active", "expired", or "revoked". */
11061 state: 'active' | 'expired' | 'revoked';
11062 /** ISO 8601 creation timestamp. */
11063 createdAt: string;
11064 /** ISO 8601 expiry timestamp. */
11065 expiresAt: string;
11066}
11067/** Paginated list of tokens for a repository. */
11068interface ArtifactsTokenListResult {
11069 /** Tokens in this page. */
11070 tokens: ArtifactsTokenInfo[];
11071 /** Total number of tokens for the repository. */
11072 total: number;
11073}
11074/**
11075 * Classification of a Git tree entry derived from its mode.
11076 *
11077 * `tree` is a directory, `blob` is a regular file, `symlink` is a symbolic link,
11078 * `gitlink` is a submodule reference, and `exec` is an executable file.
11079 */
11080type ArtifactsTreeEntryType = 'tree' | 'blob' | 'symlink' | 'gitlink' | 'exec';
11081/** An immediate child of a Git tree returned by {@link ArtifactsRepo.readTree}. */
11082interface ArtifactsTreeEntry {
11083 /** Name relative to the tree being read. */
11084 name: string;
11085 /** Canonical Git mode, such as `100644` for a file or `40000` for a tree. */
11086 mode: string;
11087 /** Lowercase, 40-character SHA-1 object ID. */
11088 hash: string;
11089 /** Classification derived from `mode`. */
11090 type: ArtifactsTreeEntryType;
11091}
11092/** Decoded metadata returned by {@link ArtifactsRepo.readCommit} and {@link ArtifactsRepo.log}. */
11093interface ArtifactsCommitMetadata {
11094 /** Lowercase, 40-character SHA-1 commit ID. */
11095 hash: string;
11096 /** Lowercase, 40-character SHA-1 ID of the commit's root tree. */
11097 treeHash: string;
11098 /** Commit message with one trailing newline removed, if present. */
11099 message: string;
11100 /** Author identity from the commit. */
11101 author: {
11102 /** Author name. */
11103 name: string;
11104 /** Author email address. */
11105 email: string;
11106 };
11107 /** Committer identity from the commit. */
11108 committer: {
11109 /** Committer name. */
11110 name: string;
11111 /** Committer email address. */
11112 email: string;
11113 };
11114 /** Parent commit IDs in Git order; empty for a root commit. */
11115 parents: string[];
11116 /** Author timestamp in Unix seconds. */
11117 authoredAt: number;
11118 /** Committer timestamp in Unix seconds. */
11119 committedAt: number;
11120}
11121/**
11122 * Repository capability returned by {@link Artifacts.get}.
11123 *
11124 * Metadata is available through {@link info}, not as properties on the capability.
11125 * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs.
11126 *
11127 * The capability is an RPC stub. Dispose of it when finished, for example with
11128 * `using repo = await env.ARTIFACTS.get(name);`, to release it before the request ends.
11129 */
11130interface ArtifactsRepo extends Disposable {
11131 /**
11132 * Create an access token for this repo.
11133 * @param scope Token scope: "write" (default) or "read".
11134 * @param ttl Time-to-live in seconds (default 86400, min 60, max 31536000).
11135 * @throws {ArtifactsError} with code `INVALID_TTL` if ttl is out of range.
11136 */
11137 createToken(scope?: 'write' | 'read', ttl?: number): Promise<ArtifactsCreateTokenResult>;
11138 /** List tokens for this repo (metadata only, no plaintext). */
11139 listTokens(): Promise<ArtifactsTokenListResult>;
11140 /**
11141 * Revoke a token by plaintext or ID.
11142 * @param tokenOrId Plaintext token or token ID.
11143 * @returns true if revoked, false if not found.
11144 * @throws {ArtifactsError} with code `INVALID_INPUT` if tokenOrId is empty.
11145 */
11146 revokeToken(tokenOrId: string): Promise<boolean>;
11147 /**
11148 * Retrieve current repository metadata. Each call performs a fresh lookup.
11149 * @returns Current public repository metadata.
11150 * @throws {ArtifactsError} `NOT_FOUND` if the repository was deleted, or `INTERNAL_ERROR` on
11151 * an unexpected lookup failure.
11152 */
11153 info(): Promise<ArtifactsRepoInfo>;
11154 /**
11155 * Read the raw bytes of a Git blob by object ID.
11156 * @param hash Lowercase, 40-character SHA-1 object ID.
11157 * @returns An untyped {@link Blob}, or `null` if the object is missing or is not a Git blob.
11158 * @throws {ArtifactsError} `INVALID_INPUT` for a malformed hash, `MEMORY_LIMIT` if the object
11159 * cannot be buffered safely, or `INTERNAL_ERROR` on an unexpected read failure.
11160 * @see {@link ArtifactsRepo.readFile} to resolve a file by ref and path.
11161 */
11162 readBlob(hash: string): Promise<Blob | null>;
11163 /**
11164 * Read the immediate children of a Git tree by object ID.
11165 * @param hash Lowercase, 40-character SHA-1 tree ID.
11166 * @returns Tree entries, or `null` if the object is missing.
11167 * @throws {ArtifactsError} `INVALID_INPUT` for a malformed hash, or `INTERNAL_ERROR` if the
11168 * object is not a valid tree or the read fails unexpectedly.
11169 * @see {@link ArtifactsTreeEntry}
11170 */
11171 readTree(hash: string): Promise<ArtifactsTreeEntry[] | null>;
11172 /**
11173 * Decode a Git commit by object ID.
11174 * @param hash Lowercase, 40-character SHA-1 commit ID.
11175 * @returns Commit metadata, or `null` if the object is missing.
11176 * @throws {ArtifactsError} `INVALID_INPUT` for a malformed hash, or `INTERNAL_ERROR` if the
11177 * object is not a valid commit or the read fails unexpectedly.
11178 * @see {@link ArtifactsCommitMetadata}
11179 */
11180 readCommit(hash: string): Promise<ArtifactsCommitMetadata | null>;
11181 /**
11182 * Resolve a file from a branch, tag, or commit ID and return its bytes with a browser-safe
11183 * content type in {@link Blob.type}.
11184 * @param args File lookup options.
11185 * @param args.ref Branch, tag, or commit ID to resolve.
11186 * @param args.path Non-empty repository-relative path.
11187 * @returns A MIME-typed {@link Blob}, or `null` if the ref or path cannot resolve to a file.
11188 * @throws {ArtifactsError} `INVALID_INPUT` if either argument is empty, `MEMORY_LIMIT` if the
11189 * file cannot be buffered safely, or `INTERNAL_ERROR` on an unexpected read failure.
11190 */
11191 readFile(args: {
11192 ref: string;
11193 path: string;
11194 }): Promise<Blob | null>;
11195 /**
11196 * List commits along the first-parent chain, newest first.
11197 * @param opts History options. All fields are optional.
11198 * @param opts.ref Branch, tag, or commit ID; defaults to `HEAD`.
11199 * @param opts.limit Maximum results; defaults to `50` and is capped at `1000`.
11200 * @param opts.offset Number of matching commits to skip; defaults to `0`.
11201 * @returns Commit metadata, or an empty array if the ref cannot be resolved.
11202 * @throws {ArtifactsError} `INTERNAL_ERROR` on an unexpected traversal failure.
11203 * @see {@link ArtifactsCommitMetadata}
11204 */
11205 log(opts?: {
11206 ref?: string;
11207 limit?: number;
11208 offset?: number;
11209 }): Promise<ArtifactsCommitMetadata[]>;
11210 // ── Fork ──
11211 /**
11212 * Fork this repo to a new repo.
11213 * @param name Target repository name.
11214 * @param opts Optional: description, readOnly flag, defaultBranchOnly (default true).
11215 * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid.
11216 * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists.
11217 * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if a fork is already running.
11218 */
11219 fork(name: string, opts?: {
11220 description?: string;
11221 readOnly?: boolean;
11222 defaultBranchOnly?: boolean;
11223 }): Promise<ArtifactsCreateRepoResult>;
11224}
11225// ── Error types ──────────────────────────────────────────────────────────────
11226/**
11227 * Error codes returned by Artifacts binding operations.
11228 *
11229 * Each code maps to a numeric code available on `ArtifactsError.numericCode`.
11230 */
11231type ArtifactsErrorCode = 'ALREADY_EXISTS' | 'NOT_FOUND' | 'CREATE_IN_PROGRESS' | 'IMPORT_IN_PROGRESS' | 'FORK_IN_PROGRESS' | 'INVALID_INPUT' | 'INVALID_REPO_NAME' | 'INVALID_TTL' | 'INVALID_URL' | 'REMOTE_AUTH_REQUIRED' | 'UPSTREAM_UNAVAILABLE' | 'MEMORY_LIMIT' | 'INTERNAL_ERROR';
11232/**
11233 * Error thrown by Artifacts binding operations.
11234 *
11235 * Uses a string `.code` discriminator following the Cloudflare platform
11236 * convention (StreamError, ImagesError, etc.). The `.numericCode` matches
11237 * the REST API `errors[].code` values.
11238 */
11239interface ArtifactsError extends Error {
11240 readonly name: 'ArtifactsError';
11241 /** String error code for programmatic matching. */
11242 readonly code: ArtifactsErrorCode;
11243 /** Numeric error code matching the REST API. */
11244 readonly numericCode: number;
11245}
11246// ── Binding ──────────────────────────────────────────────────────────────────
11247/**
11248 * Artifacts binding — namespace-level operations.
11249 *
11250 * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs.
11251 */
11252interface Artifacts {
11253 /**
11254 * Create a new repository with an initial access token.
11255 * @param name Repository name (alphanumeric, dots, hyphens, underscores).
11256 * @param opts Optional: readOnly flag, description, default branch name.
11257 * @returns Repo metadata with initial token.
11258 * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid.
11259 * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the repo already exists.
11260 */
11261 create(name: string, opts?: {
11262 readOnly?: boolean;
11263 description?: string;
11264 setDefaultBranch?: string;
11265 }): Promise<ArtifactsCreateRepoResult>;
11266 /**
11267 * Get a handle to an existing repository.
11268 * @param name Repository name.
11269 * @returns Repo handle.
11270 * @throws {ArtifactsError} with code `NOT_FOUND` if the repo does not exist.
11271 * @throws {ArtifactsError} with code `CREATE_IN_PROGRESS` if the repo is still being created.
11272 * @throws {ArtifactsError} with code `IMPORT_IN_PROGRESS` if the repo is still importing.
11273 * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if the repo is still forking.
11274 */
11275 get(name: string): Promise<ArtifactsRepo>;
11276 /**
11277 * Import a repository from an external git remote.
11278 * @param params Source URL and optional branch/depth, plus target name and options.
11279 * @returns Repo metadata with initial token.
11280 * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if the target name is invalid.
11281 * @throws {ArtifactsError} with code `INVALID_INPUT` if the source URL is not valid HTTPS.
11282 * @throws {ArtifactsError} with code `INVALID_URL` if the source URL does not point to a git repository.
11283 * @throws {ArtifactsError} with code `REMOTE_AUTH_REQUIRED` if the remote requires authentication.
11284 * @throws {ArtifactsError} with code `NOT_FOUND` if the remote repository does not exist.
11285 * @throws {ArtifactsError} with code `UPSTREAM_UNAVAILABLE` if the remote cannot be reached.
11286 * @throws {ArtifactsError} with code `MEMORY_LIMIT` if the import exceeds service memory limits.
11287 * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists.
11288 */
11289 import(params: {
11290 source: {
11291 url: string;
11292 branch?: string;
11293 depth?: number;
11294 };
11295 target: {
11296 name: string;
11297 opts?: {
11298 description?: string;
11299 readOnly?: boolean;
11300 };
11301 };
11302 }): Promise<ArtifactsCreateRepoResult>;
11303 /**
11304 * List repositories with cursor-based pagination.
11305 * @param opts Optional: limit (1–200, default 50), cursor for next page.
11306 */
11307 list(opts?: {
11308 limit?: number;
11309 cursor?: string;
11310 }): Promise<ArtifactsRepoListResult>;
11311 /**
11312 * Delete a repository and all associated tokens.
11313 * @param name Repository name.
11314 * @returns true if deleted, false if not found.
11315 * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid.
11316 */
11317 delete(name: string): Promise<boolean>;
11318}
11319/**
11320 * @deprecated Use the standalone AI Search Workers binding instead.
11321 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11322 */
11323interface AutoRAGInternalError extends Error {
11324}
11325/**
11326 * @deprecated Use the standalone AI Search Workers binding instead.
11327 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11328 */
11329interface AutoRAGNotFoundError extends Error {
11330}
11331/**
11332 * @deprecated Use the standalone AI Search Workers binding instead.
11333 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11334 */
11335interface AutoRAGUnauthorizedError extends Error {
11336}
11337/**
11338 * @deprecated Use the standalone AI Search Workers binding instead.
11339 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11340 */
11341interface AutoRAGNameNotSetError extends Error {
11342}
11343type ComparisonFilter = {
11344 key: string;
11345 type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte';
11346 value: string | number | boolean;
11347};
11348type CompoundFilter = {
11349 type: 'and' | 'or';
11350 filters: ComparisonFilter[];
11351};
11352/**
11353 * @deprecated Use the standalone AI Search Workers binding instead.
11354 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11355 */
11356type AutoRagSearchRequest = {
11357 query: string;
11358 filters?: CompoundFilter | ComparisonFilter;
11359 max_num_results?: number;
11360 ranking_options?: {
11361 ranker?: string;
11362 score_threshold?: number;
11363 };
11364 reranking?: {
11365 enabled?: boolean;
11366 model?: string;
11367 };
11368 rewrite_query?: boolean;
11369};
11370/**
11371 * @deprecated Use the standalone AI Search Workers binding instead.
11372 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11373 */
11374type AutoRagAiSearchRequest = AutoRagSearchRequest & {
11375 stream?: boolean;
11376 system_prompt?: string;
11377};
11378/**
11379 * @deprecated Use the standalone AI Search Workers binding instead.
11380 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11381 */
11382type AutoRagAiSearchRequestStreaming = Omit<AutoRagAiSearchRequest, 'stream'> & {
11383 stream: true;
11384};
11385/**
11386 * @deprecated Use the standalone AI Search Workers binding instead.
11387 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11388 */
11389type AutoRagSearchResponse = {
11390 object: 'vector_store.search_results.page';
11391 search_query: string;
11392 data: {
11393 file_id: string;
11394 filename: string;
11395 score: number;
11396 attributes: Record<string, string | number | boolean | null>;
11397 content: {
11398 type: 'text';
11399 text: string;
11400 }[];
11401 }[];
11402 has_more: boolean;
11403 next_page: string | null;
11404};
11405/**
11406 * @deprecated Use the standalone AI Search Workers binding instead.
11407 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11408 */
11409type AutoRagListResponse = {
11410 id: string;
11411 enable: boolean;
11412 type: string;
11413 source: string;
11414 vectorize_name: string;
11415 paused: boolean;
11416 status: string;
11417}[];
11418/**
11419 * @deprecated Use the standalone AI Search Workers binding instead.
11420 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11421 */
11422type AutoRagAiSearchResponse = AutoRagSearchResponse & {
11423 response: string;
11424};
11425/**
11426 * @deprecated Use the standalone AI Search Workers binding instead.
11427 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11428 */
11429declare abstract class AutoRAG {
11430 /**
11431 * @deprecated Use the standalone AI Search Workers binding instead.
11432 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11433 */
11434 list(): Promise<AutoRagListResponse>;
11435 /**
11436 * @deprecated Use the standalone AI Search Workers binding instead.
11437 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11438 */
11439 search(params: AutoRagSearchRequest): Promise<AutoRagSearchResponse>;
11440 /**
11441 * @deprecated Use the standalone AI Search Workers binding instead.
11442 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11443 */
11444 aiSearch(params: AutoRagAiSearchRequestStreaming): Promise<Response>;
11445 /**
11446 * @deprecated Use the standalone AI Search Workers binding instead.
11447 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11448 */
11449 aiSearch(params: AutoRagAiSearchRequest): Promise<AutoRagAiSearchResponse>;
11450 /**
11451 * @deprecated Use the standalone AI Search Workers binding instead.
11452 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11453 */
11454 aiSearch(params: AutoRagAiSearchRequest): Promise<AutoRagAiSearchResponse | Response>;
11455}
11456type BrowserRunLifecycleEvent = 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2';
11457type BrowserRunResourceType = 'document' | 'stylesheet' | 'image' | 'media' | 'font' | 'script' | 'texttrack' | 'xhr' | 'fetch' | 'prefetch' | 'eventsource' | 'websocket' | 'manifest' | 'signedexchange' | 'ping' | 'cspviolationreport' | 'preflight' | 'other';
11458/** Options fields shared by all quick actions. */
11459interface BrowserRunBaseOptions {
11460 /** Adds `<script>` tags into the page with the desired URL or content.
11461 * @see https://pptr.dev/api/puppeteer.frameaddscripttagoptions
11462 */
11463 addScriptTag?: Array<{
11464 content?: string;
11465 url?: string;
11466 type?: string;
11467 id?: string;
11468 }>;
11469 /** Adds `<link rel="stylesheet">` or `<style>` tags into the page.
11470 * @see https://pptr.dev/api/puppeteer.frameaddstyletagoptions
11471 */
11472 addStyleTag?: Array<{
11473 content?: string;
11474 url?: string;
11475 }>;
11476 /** Provide credentials for HTTP authentication. @see https://pptr.dev/api/puppeteer.credentials */
11477 authenticate?: {
11478 username: string;
11479 password: string;
11480 };
11481 /** Set cookies before navigating. @see https://pptr.dev/api/puppeteer.cookieparam */
11482 cookies?: Array<{
11483 name: string;
11484 value: string;
11485 url?: string;
11486 domain?: string;
11487 path?: string;
11488 secure?: boolean;
11489 httpOnly?: boolean;
11490 sameSite?: 'Strict' | 'Lax' | 'None';
11491 expires?: number;
11492 priority?: 'Low' | 'Medium' | 'High';
11493 sameParty?: boolean;
11494 sourceScheme?: 'Unset' | 'NonSecure' | 'Secure';
11495 sourcePort?: number;
11496 partitionKey?: string;
11497 }>;
11498 /** Emulate a specific CSS media type (e.g. `"screen"`, `"print"`). */
11499 emulateMediaType?: string;
11500 /** Navigation options. @see https://pptr.dev/api/puppeteer.gotooptions */
11501 gotoOptions?: {
11502 /** Navigation timeout in milliseconds (max 60 000). @default 30000 */
11503 timeout?: number;
11504 /** When to consider navigation complete. @default "domcontentloaded" */
11505 waitUntil?: BrowserRunLifecycleEvent | BrowserRunLifecycleEvent[];
11506 referer?: string;
11507 referrerPolicy?: string;
11508 };
11509 /** Block requests matching these regex patterns. Mutually exclusive with `allowRequestPattern`. */
11510 rejectRequestPattern?: string[];
11511 /** Only allow requests matching these regex patterns. Mutually exclusive with `rejectRequestPattern`. */
11512 allowRequestPattern?: string[];
11513 /** Block requests of these resource types. Mutually exclusive with `allowResourceTypes`. */
11514 rejectResourceTypes?: BrowserRunResourceType[];
11515 /** Only allow requests of these resource types. Mutually exclusive with `rejectResourceTypes`. */
11516 allowResourceTypes?: BrowserRunResourceType[];
11517 /** Additional HTTP headers sent with every request. */
11518 setExtraHTTPHeaders?: Record<string, string>;
11519 /** Whether JavaScript is enabled on the page. */
11520 setJavaScriptEnabled?: boolean;
11521 /** Override the default user agent string.
11522 * @default "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"
11523 * */
11524 userAgent?: string;
11525 /** Set the browser viewport size.
11526 * @see https://pptr.dev/api/puppeteer.viewport
11527 * @default {width:1920,height:1080}
11528 * */
11529 viewport?: {
11530 width: number;
11531 height: number;
11532 deviceScaleFactor?: number;
11533 isMobile?: boolean;
11534 isLandscape?: boolean;
11535 hasTouch?: boolean;
11536 };
11537 /** Wait for a CSS selector to appear in the page before proceeding.
11538 * @see https://pptr.dev/api/puppeteer.waitforselectoroptions
11539 */
11540 waitForSelector?: {
11541 selector: string;
11542 hidden?: true;
11543 visible?: true;
11544 /** Timeout in milliseconds. Max 120000 */
11545 timeout?: number;
11546 };
11547 /** Wait for a fixed delay in milliseconds before proceeding. Max 120000 */
11548 waitForTimeout?: number;
11549 /** When true, continue on best-effort when awaited events fail or timeout. */
11550 bestAttempt?: boolean;
11551 /** Maximum duration in milliseconds for the browser action after page load. Max 120000 */
11552 actionTimeout?: number;
11553 /** Cache time to live in seconds (0-86400). Set to 0 to disable.
11554 * @default 5
11555 */
11556 cacheTTL?: number;
11557}
11558/**
11559 * Backend selection, mixed into the options of the quick actions that support it.
11560 * Deliberately not part of `BrowserRunBaseOptions`: `scrape`, `links` and `snapshot`
11561 * reject an alternate backend, so they must not accept the field.
11562 */
11563interface BrowserRunAlternateBackendOptions {
11564 /** Render with an alternate browser backend instead of the default one. */
11565 browser?: 'kitesurf';
11566}
11567/** Common options shared by all quick actions. Exactly one of `url` or `html` must be provided.*/
11568type BrowserRunCommonOptions = (BrowserRunBaseOptions & {
11569 /** URL to navigate to, e.g. `"https://example.com"`. */
11570 url: string;
11571}) | (BrowserRunBaseOptions & {
11572 /** Set the HTML content of the page directly. */
11573 html: string;
11574});
11575type BrowserRunPuppeteerScreenshotOptions = {
11576 /** @default "png" */
11577 type?: 'png' | 'jpeg' | 'webp';
11578 /** @default "binary" */
11579 encoding?: 'binary' | 'base64';
11580 quality?: number;
11581 fullPage?: boolean;
11582 clip?: {
11583 x: number;
11584 y: number;
11585 width: number;
11586 height: number;
11587 scale?: number;
11588 };
11589 omitBackground?: boolean;
11590 optimizeForSpeed?: boolean;
11591 captureBeyondViewport?: boolean;
11592 fromSurface?: boolean;
11593};
11594type BrowserRunScreenshotOptions = BrowserRunCommonOptions & {
11595 /** CSS selector of the element to screenshot. */
11596 selector?: string;
11597 /** When true, scroll the entire page before taking the screenshot. */
11598 scrollPage?: boolean;
11599 /** @see https://pptr.dev/api/puppeteer.screenshotoptions */
11600 screenshotOptions?: BrowserRunPuppeteerScreenshotOptions;
11601} & BrowserRunAlternateBackendOptions;
11602type BrowserRunPDFOptions = BrowserRunCommonOptions & {
11603 /** @see https://pptr.dev/api/puppeteer.pdfoptions */
11604 pdfOptions?: {
11605 /** @default 1 */
11606 scale?: number;
11607 /** @default false */
11608 displayHeaderFooter?: boolean;
11609 headerTemplate?: string;
11610 footerTemplate?: string;
11611 /** @default false */
11612 printBackground?: boolean;
11613 /** @default false */
11614 landscape?: boolean;
11615 pageRanges?: string;
11616 /** @default "letter" */
11617 format?: 'letter' | 'legal' | 'tabloid' | 'ledger' | 'a0' | 'a1' | 'a2' | 'a3' | 'a4' | 'a5' | 'a6';
11618 width?: string | number;
11619 height?: string | number;
11620 /** @default false */
11621 preferCSSPageSize?: boolean;
11622 margin?: {
11623 top?: string | number;
11624 right?: string | number;
11625 bottom?: string | number;
11626 left?: string | number;
11627 };
11628 /** @default false */
11629 omitBackground?: boolean;
11630 /** @default true */
11631 tagged?: boolean;
11632 /** @default false */
11633 outline?: boolean;
11634 /** @default 30000 */
11635 timeout?: number;
11636 };
11637} & BrowserRunAlternateBackendOptions;
11638type BrowserRunScrapeOptions = BrowserRunCommonOptions & {
11639 /** CSS selectors to scrape. At least one element is required. */
11640 elements: Array<{
11641 selector: string;
11642 }>;
11643};
11644type BrowserRunLinksOptions = BrowserRunCommonOptions & {
11645 /** When true, only return links that are visible on the page. @default false */
11646 visibleLinksOnly?: boolean;
11647 /** When true, exclude links pointing to external domains. @default false */
11648 excludeExternalLinks?: boolean;
11649};
11650type BrowserRunSnapshotFormat = 'content' | 'screenshot' | 'markdown' | 'accessibilityTree';
11651type BrowserRunSnapshotOptions = BrowserRunCommonOptions & {
11652 /** Which representations of the page to return. At least two distinct formats
11653 * are required; request a single format from its dedicated action instead.
11654 * @default ["content","screenshot"]
11655 */
11656 formats?: BrowserRunSnapshotFormat[];
11657 /** @see https://pptr.dev/api/puppeteer.screenshotoptions */
11658 screenshotOptions?: Omit<BrowserRunPuppeteerScreenshotOptions, 'encoding'>;
11659};
11660/** Options for the `accessibilityTree` quick action. */
11661type BrowserRunAccessibilityTreeOptions = BrowserRunCommonOptions & {
11662 /** When true, prune nodes that carry no semantic meaning, such as generic
11663 * containers. Defaults to true, or to false when `root` is set so that the
11664 * requested subtree is returned as-is.
11665 */
11666 interestingOnly?: boolean;
11667 /** CSS selector limiting the tree to the matching element's subtree.
11668 * A selector that matches nothing yields `accessibilityTree: null` with
11669 * HTTP 200; a malformed selector is an error.
11670 */
11671 root?: string;
11672} & BrowserRunAlternateBackendOptions;
11673interface BrowserRunJsonBaseOptions {
11674 /** Custom AI models to try in order. Max 3. Falls back to next on error. */
11675 custom_ai?: Array<{
11676 /** Model ID in `<provider>/<model_name>` format, e.g. `"workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast"`. */
11677 model: string;
11678 /** Bearer token. Not needed for workers-ai models. */
11679 authorization?: string;
11680 }>;
11681}
11682/**
11683 * Options for the `json` quick action.
11684 * At least one of `prompt` or `response_format` must be provided.
11685 */
11686type BrowserRunJsonOptions = BrowserRunCommonOptions & BrowserRunAlternateBackendOptions & BrowserRunJsonBaseOptions & ({
11687 /** Natural-language prompt describing what data to extract. */
11688 prompt: string;
11689 /** Structured output schema for the AI model. @see https://developers.cloudflare.com/workers-ai/json-mode/ */
11690 response_format?: AiTextGenerationResponseFormat;
11691} | {
11692 /** Natural-language prompt describing what data to extract. */
11693 prompt?: string;
11694 /** Structured output schema for the AI model. @see https://developers.cloudflare.com/workers-ai/json-mode/ */
11695 response_format: AiTextGenerationResponseFormat;
11696});
11697type BrowserRunContentOptions = BrowserRunCommonOptions & BrowserRunAlternateBackendOptions;
11698type BrowserRunMarkdownOptions = BrowserRunCommonOptions & BrowserRunAlternateBackendOptions;
11699type BrowserRunRedirectHop = {
11700 /** URL that returned the redirect. */
11701 url: string;
11702 /** HTTP status of the redirect. */
11703 status: number;
11704 /** Redirect response headers, including `location`. */
11705 headers: Record<string, string>;
11706};
11707type BrowserRunResponseMeta = {
11708 /** HTTP status code of the rendered page */
11709 status: number;
11710 /** Page title */
11711 title: string;
11712 /** Origin response headers, lowercased. Repeated headers are joined with a newline. Credential and transport-only headers that do not survive rendering are omitted. */
11713 headers?: Record<string, string>;
11714 /** URL that served the response, after any redirects the browser followed. */
11715 finalUrl?: string;
11716 /** HTTP redirects followed to reach `finalUrl`, oldest first. Omitted for direct navigation and for client-side redirects such as meta refresh. An empty array means redirects occurred but their intermediate responses could not be read. */
11717 redirectChain?: BrowserRunRedirectHop[];
11718};
11719/**
11720 * A node in the page's accessibility tree, as exposed to assistive technology.
11721 * `role` is the only field always present; the rest are populated when the
11722 * underlying element defines them.
11723 * @see https://pptr.dev/api/puppeteer.serializedaxnode
11724 */
11725interface BrowserRunSerializedAXNode {
11726 /** The ARIA role, e.g. `"button"`, `"heading"`, `"RootWebArea"`. */
11727 role: string;
11728 /** The `aria-autocomplete` value. */
11729 autocomplete?: string;
11730 /** Checked state of a checkbox, radio, or menu item. */
11731 checked?: boolean | 'mixed';
11732 /** Accessible description, typically from `aria-describedby` or `title`. */
11733 description?: string;
11734 disabled?: boolean;
11735 expanded?: boolean;
11736 /** Whether the element currently holds keyboard focus. */
11737 focused?: boolean;
11738 /** The kind of popup the element triggers, e.g. `"menu"`, `"dialog"`. */
11739 haspopup?: string;
11740 /** The `aria-invalid` value. */
11741 invalid?: string;
11742 /** Keyboard shortcuts bound to the element, from `aria-keyshortcuts`. */
11743 keyshortcuts?: string;
11744 /** Hierarchical level, e.g. the heading level of an `<h2>`. */
11745 level?: number;
11746 /** Whether the element is a modal dialog. */
11747 modal?: boolean;
11748 /** Whether a text input accepts multiple lines. */
11749 multiline?: boolean;
11750 /** Whether more than one option can be selected. */
11751 multiselectable?: boolean;
11752 /** Accessible name, e.g. a button's label or an image's alt text. */
11753 name?: string;
11754 orientation?: string;
11755 /** Pressed state of a toggle button. */
11756 pressed?: boolean | 'mixed';
11757 readonly?: boolean;
11758 required?: boolean;
11759 /** Author-supplied role description, from `aria-roledescription`. */
11760 roledescription?: string;
11761 selected?: boolean;
11762 /** Current value of an input or range element. */
11763 value?: string | number;
11764 valuemax?: number;
11765 valuemin?: number;
11766 /** Human-readable form of `value`, from `aria-valuetext`. */
11767 valuetext?: string;
11768 /** Child nodes. Absent for leaf nodes. */
11769 children?: BrowserRunSerializedAXNode[];
11770}
11771/** Success response for `content` action. */
11772type BrowserRunContentSuccessResponse = {
11773 success: true;
11774 /** Extracted HTML content */
11775 result: string;
11776 meta: BrowserRunResponseMeta;
11777};
11778/** Success response for `links` action. */
11779type BrowserRunLinksSuccessResponse = {
11780 success: true;
11781 /** Extracted links */
11782 result: string[];
11783 meta: BrowserRunResponseMeta;
11784};
11785/** Success response for `scrape` action. */
11786type BrowserRunScrapeSuccessResponse = {
11787 success: true;
11788 result: Array<{
11789 /** The CSS selector used to find elements. */
11790 selector: string;
11791 /** Array of elements matching the selector. */
11792 results: Array<{
11793 /** Outer HTML of the element. */
11794 html: string;
11795 /** Text content of the element. */
11796 text: string;
11797 /** Width of the element in pixels. */
11798 width: number;
11799 /** Height of the element in pixels. */
11800 height: number;
11801 /** Top position of the element relative to the viewport in pixels. */
11802 top: number;
11803 /** Left position of the element relative to the viewport in pixels. */
11804 left: number;
11805 /** Array of HTML attributes on the element. */
11806 attributes: Array<{
11807 /** Attribute name. */
11808 name: string;
11809 /** Attribute value. */
11810 value: string;
11811 }>;
11812 }>;
11813 }>;
11814 meta: BrowserRunResponseMeta;
11815};
11816/** Success response for `snapshot` action. Each field is present only when the
11817 * corresponding entry was requested in `formats`.
11818 */
11819type BrowserRunSnapshotSuccessResponse = {
11820 success: true;
11821 result: {
11822 /** HTML content of the page. */
11823 content?: string;
11824 /** Base64-encoded screenshot image. */
11825 screenshot?: string;
11826 /** Markdown content. Prefixed with YAML frontmatter (e.g. `title`) when the
11827 * page provides that metadata.
11828 */
11829 markdown?: string;
11830 /** Root of the page's accessibility tree. */
11831 accessibilityTree?: BrowserRunSerializedAXNode;
11832 };
11833 meta: BrowserRunResponseMeta;
11834};
11835/** Success response for `accessibilityTree` action. */
11836type BrowserRunAccessibilityTreeSuccessResponse = {
11837 success: true;
11838 result: {
11839 /** Root of the accessibility tree, or `null` when `root` matched no element. */
11840 accessibilityTree: BrowserRunSerializedAXNode | null;
11841 };
11842 meta: BrowserRunResponseMeta;
11843};
11844/** Success response for `json` action. */
11845type BrowserRunJsonSuccessResponse = {
11846 success: true;
11847 /** JSON data extracted from the page using an AI model */
11848 result: Record<string, unknown>;
11849 meta: BrowserRunResponseMeta;
11850};
11851/** Success response for `markdown` action. */
11852type BrowserRunMarkdownSuccessResponse = {
11853 success: true;
11854 /** Extracted markdown content */
11855 result: string;
11856 meta: BrowserRunResponseMeta;
11857};
11858/** Error response for BrowserRun actions. */
11859type BrowserRunErrorResponse = {
11860 success: false;
11861 errors: {
11862 message: string;
11863 code?: number;
11864 detail?: string;
11865 path?: string;
11866 }[];
11867};
11868/** Error response for BrowserRun `json` action. */
11869type BrowserRunJsonErrorResponse = BrowserRunErrorResponse & {
11870 /** Raw AI response text for debugging */
11871 rawAiResponse?: string;
11872};
11873/** Session-scoped guardrails applied when acquiring a browser session. */
11874type BrowserRunAcquireGuardrails = {
11875 /** Domains that the browser may access. An empty list denies all domains. */
11876 allowedDomains?: string[];
11877 /** Named domain sets that the browser may access. */
11878 allowedDomainSets?: string[];
11879};
11880/** Options for acquiring a new browser session. */
11881type BrowserRunAcquireOptions = {
11882 /** Idle session lifetime in milliseconds. */
11883 keepAlive?: number;
11884 /** Record the browser session. */
11885 recording?: boolean;
11886 /** Geoegress hint as an ISO-3166 alpha-2 country code. */
11887 location?: string;
11888 /** Map hostnames to caller-provided Workers that handle outbound requests. */
11889 outboundByHost?: Record<string, Fetcher>;
11890 /** Session-scoped network guardrails. */
11891 guardrails?: BrowserRunAcquireGuardrails;
11892 /** Include the session's DevTools targets in the result. */
11893 targets?: boolean;
11894 /** Lifetime of target live-view URLs in milliseconds. */
11895 liveViewUrlExpiresInMs?: number;
11896};
11897/** Metadata returned when a browser session is acquired. */
11898type BrowserRunAcquireResult = {
11899 sessionId: string;
11900 targets?: BrowserRunDevToolsTarget[];
11901};
11902/** Options for connecting to an already-acquired browser session. */
11903type BrowserRunConnectOptions = {
11904 /** Connect to a specific page target instead of the browser-level CDP endpoint. */
11905 targetId?: string;
11906};
11907/** Connection capability returned by `connectSession()` and `launch()`. */
11908type BrowserRunConnection = {
11909 sessionId: string;
11910 /** A session-pinned Fetcher. Use its `fetch()` method for a WebSocket upgrade. */
11911 webSocket: Fetcher;
11912 targets?: BrowserRunDevToolsTarget[];
11913};
11914/** The UI mode for a live-view link. */
11915type BrowserRunLiveViewMode = 'devtools' | 'tab' | 'full';
11916/** Connection-scoped guardrails applied to a live-view link. */
11917type BrowserRunConnectionGuardrails = {
11918 mode: 'readonly';
11919};
11920/** Options for minting a live-view link. */
11921type BrowserRunLiveViewOptions = {
11922 mode?: BrowserRunLiveViewMode;
11923 targetId?: string;
11924 expiresInMs?: number;
11925 guardrails?: BrowserRunConnectionGuardrails;
11926};
11927/** Live-view link metadata. */
11928type BrowserRunLiveView = {
11929 webSocketDebuggerUrl: string;
11930 devtoolsFrontendUrl: string;
11931 id: string;
11932 options: {
11933 mode: BrowserRunLiveViewMode;
11934 guardrails?: BrowserRunConnectionGuardrails;
11935 };
11936};
11937/** Options for listing active browser sessions. */
11938type BrowserRunListSessionsOptions = {
11939 limit?: number;
11940 offset?: number;
11941};
11942/** Options for listing session history. */
11943type BrowserRunHistoryOptions = {
11944 limit?: number;
11945 offset?: number;
11946};
11947/** A browser session returned by the session-management methods. */
11948type BrowserRunSession = {
11949 sessionId: string;
11950 startTime?: number;
11951 endTime?: number;
11952 closeReason?: number;
11953 closeReasonText?: string;
11954 connectionId?: string;
11955 connectionStartTime?: number;
11956 connectionEndTime?: number;
11957 lastUpdated?: number;
11958 webSocketDebuggerUrl?: string;
11959 devtoolsFrontendUrl?: string;
11960};
11961/** Account browser-session and browser-time limits. */
11962type BrowserRunLimits = {
11963 activeSessions: Array<{
11964 id: string;
11965 }>;
11966 maxConcurrentSessions: number;
11967 allowedBrowserAcquisitions: number;
11968 timeUntilNextAllowedBrowserAcquisition: number;
11969 usedBrowserTimeSeconds?: number;
11970};
11971/** A browser target returned by the DevTools JSON methods. */
11972type BrowserRunDevToolsTarget = {
11973 id: string;
11974 type: string;
11975 url: string;
11976 title?: string;
11977 description?: string;
11978 webSocketDebuggerUrl?: string;
11979 devtoolsFrontendUrl?: string;
11980};
11981/** Browser and protocol version metadata. */
11982type BrowserRunDevToolsVersion = {
11983 Browser: string;
11984 'Protocol-Version': string;
11985 'User-Agent': string;
11986 'V8-Version': string;
11987 'WebKit-Version': string;
11988 webSocketDebuggerUrl: string;
11989};
11990/** A DevTools protocol domain. Protocol definitions may gain additional fields over time. */
11991interface BrowserRunDevToolsProtocolDomain extends Record<string, unknown> {
11992 domain: string;
11993 experimental?: boolean;
11994 dependencies?: string[];
11995 types?: Array<Record<string, any>>;
11996 commands?: Array<Record<string, any>>;
11997 events?: Array<Record<string, any>>;
11998}
11999/** The DevTools protocol definition. Additional protocol fields may be returned by Chrome. */
12000interface BrowserRunDevToolsProtocol extends Record<string, any> {
12001 domains: BrowserRunDevToolsProtocolDomain[];
12002 version?: {
12003 major: string;
12004 minor: string;
12005 };
12006}
12007/** Options shared by DevTools target-listing and target-creation methods. */
12008type BrowserRunTargetOptions = {
12009 liveViewUrlExpiresInMs?: number;
12010};
12011/** Result returned by DevTools target activation and close methods. */
12012type BrowserRunTargetActionResult = {
12013 message: string;
12014};
12015/** Methods exposed by the nested `devtools` binding target. */
12016type BrowserRunDevtools = {
12017 getVersion(sessionId: string): Promise<BrowserRunDevToolsVersion>;
12018 getProtocol(sessionId: string): Promise<BrowserRunDevToolsProtocol>;
12019 listTargets(sessionId: string, options?: BrowserRunTargetOptions): Promise<BrowserRunDevToolsTarget[]>;
12020 getTarget(sessionId: string, targetId: string): Promise<BrowserRunDevToolsTarget>;
12021 newTarget(sessionId: string, url?: string, options?: BrowserRunTargetOptions): Promise<BrowserRunDevToolsTarget>;
12022 activateTarget(sessionId: string, targetId: string): Promise<BrowserRunTargetActionResult>;
12023 closeTarget(sessionId: string, targetId: string): Promise<BrowserRunTargetActionResult>;
12024};
12025/** Result returned when closing a browser session. */
12026type BrowserRunCloseSessionResult = {
12027 status: 'closing' | 'closed';
12028};
12029/**
12030 * Browser Run API binding for automating headless browsers.
12031 * @see https://developers.cloudflare.com/browser-run/
12032 */
12033declare abstract class BrowserRun {
12034 /**
12035 * Send a raw HTTP request to the Browser Run API.
12036 * Used by libraries like `@cloudflare/puppeteer` to acquire and connect to a browser instance.
12037 * @see https://developers.cloudflare.com/browser-run/
12038 */
12039 fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
12040 /**
12041 * Take a screenshot of a web page.
12042 * @param action - Must be `'screenshot'`.
12043 * @param options - Screenshot options including viewport, selectors, and image format.
12044 * @returns A `Response` containing one of:
12045 *
12046 * **Success (HTTP 200):**
12047 * - Binary image data with `Content-Type: image/png`, `image/jpeg`, or `image/webp` (when `encoding: 'binary'`, the default)
12048 * - Data URI string with `Content-Type: text/plain` (when `encoding: 'base64'`)
12049 *
12050 * **Error:**
12051 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
12052 *
12053 * **Headers:**
12054 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
12055 */
12056 quickAction(action: 'screenshot', options: BrowserRunScreenshotOptions): Promise<Response>;
12057 /**
12058 * Generate a PDF of a web page.
12059 * @param action - Must be `'pdf'`.
12060 * @param options - PDF generation options including page size, margins, and headers/footers.
12061 * @returns A `Response` containing one of:
12062 *
12063 * **Success (HTTP 200):**
12064 * - Binary PDF data with `Content-Type: application/pdf`
12065 *
12066 * **Error:**
12067 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
12068 *
12069 * **Headers:**
12070 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
12071 */
12072 quickAction(action: 'pdf', options: BrowserRunPDFOptions): Promise<Response>;
12073 /**
12074 * Get the HTML content of a web page.
12075 * @param action - Must be `'content'`.
12076 * @param options - Navigation and page interaction options.
12077 * @returns A `Response` containing one of:
12078 *
12079 * **Success (HTTP 200):**
12080 * - `BrowserRunContentSuccessResponse` JSON with `Content-Type: application/json`
12081 *
12082 * **Error:**
12083 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
12084 *
12085 * **Headers:**
12086 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
12087 */
12088 quickAction(action: 'content', options: BrowserRunContentOptions): Promise<Response>;
12089 /**
12090 * Scrape elements from a web page by CSS selector.
12091 * @param action - Must be `'scrape'`.
12092 * @param options - Scrape options with CSS selectors for elements to extract.
12093 * @returns A `Response` containing one of:
12094 *
12095 * **Success (HTTP 200):**
12096 * - `BrowserRunScrapeSuccessResponse` JSON with `Content-Type: application/json`
12097 *
12098 * **Error:**
12099 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
12100 *
12101 * **Headers:**
12102 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
12103 */
12104 quickAction(action: 'scrape', options: BrowserRunScrapeOptions): Promise<Response>;
12105 /**
12106 * Extract all links from a web page.
12107 * @param action - Must be `'links'`.
12108 * @param options - Options to filter visible or internal links only.
12109 * @returns A `Response` containing one of:
12110 *
12111 * **Success (HTTP 200):**
12112 * - `BrowserRunLinksSuccessResponse` JSON with `Content-Type: application/json`
12113 *
12114 * **Error:**
12115 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
12116 *
12117 * **Headers:**
12118 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
12119 */
12120 quickAction(action: 'links', options: BrowserRunLinksOptions): Promise<Response>;
12121 /**
12122 * Get several representations of a web page in one request.
12123 * @param action - Must be `'snapshot'`.
12124 * @param options - Snapshot options including the `formats` to return and
12125 * screenshot settings (encoding is always base64).
12126 * @returns A `Response` containing one of:
12127 *
12128 * **Success (HTTP 200):**
12129 * - `BrowserRunSnapshotSuccessResponse` JSON with `Content-Type: application/json`
12130 *
12131 * **Error:**
12132 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
12133 *
12134 * **Headers:**
12135 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
12136 */
12137 quickAction(action: 'snapshot', options: BrowserRunSnapshotOptions): Promise<Response>;
12138 /**
12139 * Extract structured JSON data from a web page using AI.
12140 * @param action - Must be `'json'`.
12141 * @param options - JSON extraction options with prompt or response_format schema.
12142 * @returns A `Response` containing one of:
12143 *
12144 * **Success (HTTP 200):**
12145 * - `BrowserRunJsonSuccessResponse` JSON with `Content-Type: application/json`
12146 *
12147 * **Error:**
12148 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
12149 * - HTTP 422 with code `2012` for HTML-to-markdown conversion failures
12150 * - HTTP 422/500 for AI extraction failures (may include `rawAiResponse` field)
12151 *
12152 * **Headers:**
12153 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
12154 */
12155 quickAction(action: 'json', options: BrowserRunJsonOptions): Promise<Response>;
12156 /**
12157 * Convert a web page to Markdown.
12158 * @param action - Must be `'markdown'`.
12159 * @param options - Navigation and page interaction options.
12160 * @returns A `Response` containing one of:
12161 *
12162 * **Success (HTTP 200):**
12163 * - `BrowserRunMarkdownSuccessResponse` JSON with `Content-Type: application/json`
12164 *
12165 * **Error:**
12166 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
12167 * - HTTP 422 with code `2012` for HTML-to-markdown conversion failures
12168 *
12169 * **Headers:**
12170 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
12171 */
12172 quickAction(action: 'markdown', options: BrowserRunMarkdownOptions): Promise<Response>;
12173 /**
12174 * Get the accessibility tree of a web page.
12175 * @param action - Must be `'accessibilityTree'`.
12176 * @param options - Options to scope the tree to a subtree and to control
12177 * whether semantically uninteresting nodes are pruned.
12178 * @returns A `Response` containing one of:
12179 *
12180 * **Success (HTTP 200):**
12181 * - `BrowserRunAccessibilityTreeSuccessResponse` JSON with `Content-Type: application/json`
12182 * - `result.accessibilityTree` is `null` when `root` matched no element
12183 *
12184 * **Error:**
12185 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
12186 * - HTTP 422 for a malformed `root` selector
12187 * - HTTP 500 with code `2017` or `2018` when the tree could not be built
12188 *
12189 * **Headers:**
12190 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
12191 */
12192 quickAction(action: 'accessibilityTree', options: BrowserRunAccessibilityTreeOptions): Promise<Response>;
12193 /** Acquire a new browser session and return its metadata. */
12194 acquire(options?: BrowserRunAcquireOptions): Promise<BrowserRunAcquireResult>;
12195 /** Acquire a browser session and return a session-pinned WebSocket capability. */
12196 launch(options?: BrowserRunAcquireOptions): Promise<BrowserRunConnection>;
12197 /** Return a session-pinned WebSocket capability for an existing session. */
12198 connectSession(sessionId: string, options?: BrowserRunConnectOptions): Promise<BrowserRunConnection>;
12199 /** Mint an authenticated live-view link for a browser session. */
12200 getLiveView(sessionId: string, options?: BrowserRunLiveViewOptions): Promise<BrowserRunLiveView>;
12201 /** List the caller's active browser sessions. */
12202 listSessions(options?: BrowserRunListSessionsOptions): Promise<BrowserRunSession[]>;
12203 /** List recent active and closed browser sessions. */
12204 history(options?: BrowserRunHistoryOptions): Promise<BrowserRunSession[]>;
12205 /** Return the caller's browser-session and browser-time limits. */
12206 limits(): Promise<BrowserRunLimits>;
12207 /** Return details for one browser session, or `null` when it does not exist. */
12208 getSession(sessionId: string): Promise<BrowserRunSession | null>;
12209 /** Close a browser session. */
12210 closeSession(sessionId: string): Promise<BrowserRunCloseSessionResult>;
12211 /** DevTools JSON methods exposed through one nested binding target. */
12212 get devtools(): BrowserRunDevtools;
12213}
12214/**
12215 * In addition to the properties you can set in the RequestInit dict
12216 * that you pass as an argument to the Request constructor, you can
12217 * set certain properties of a `cf` object to control how Cloudflare
12218 * features are applied to that new Request.
12219 *
12220 * Note: Currently, these properties cannot be tested in the
12221 * playground.
12222 */
12223interface RequestInitCfProperties extends Record<string, unknown> {
12224 cacheEverything?: boolean;
12225 /**
12226 * A request's cache key is what determines if two requests are
12227 * "the same" for caching purposes. If a request has the same cache key
12228 * as some previous request, then we can serve the same cached response for
12229 * both. (e.g. 'some-key')
12230 *
12231 * Only available for Enterprise customers.
12232 */
12233 cacheKey?: string;
12234 /**
12235 * This allows you to append additional Cache-Tag response headers
12236 * to the origin response without modifications to the origin server.
12237 * This will allow for greater control over the Purge by Cache Tag feature
12238 * utilizing changes only in the Workers process.
12239 *
12240 * Only available for Enterprise customers.
12241 */
12242 cacheTags?: string[];
12243 /**
12244 * Force response to be cached for a given number of seconds. (e.g. 300)
12245 */
12246 cacheTtl?: number;
12247 /**
12248 * Force response to be cached for a given number of seconds based on the Origin status code.
12249 * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 })
12250 */
12251 cacheTtlByStatus?: Record<string, number>;
12252 /**
12253 * Controls whether Cloudflare uses range requests when fetching the response
12254 * from the origin.
12255 *
12256 * - `"on"`: enable origin range requests for this request.
12257 * - `"off"`: disable origin range requests for this request.
12258 */
12259 originRangeRequests?: "on" | "off";
12260 /** Controls how responses with a `Vary` header are cached for this request. */
12261 vary?: RequestInitCfPropertiesVary;
12262 /**
12263 * Explicit Cache-Control header value to set on the response stored in cache.
12264 * This gives full control over cache directives (e.g. 'public, max-age=3600, s-maxage=86400').
12265 *
12266 * Cannot be used together with `cacheTtl` or the `cache` request option (`no-store`/`no-cache`),
12267 * as these are mutually exclusive cache control mechanisms. Setting both will throw a TypeError.
12268 *
12269 * Can be used together with `cacheTtlByStatus`.
12270 */
12271 cacheControl?: string;
12272 /**
12273 * Whether the response should be eligible for Cache Reserve storage.
12274 */
12275 cacheReserveEligible?: boolean;
12276 /**
12277 * Whether to respect strong ETags (as opposed to weak ETags) from the origin.
12278 */
12279 respectStrongEtag?: boolean;
12280 /**
12281 * Whether to strip ETag headers from the origin response before caching.
12282 */
12283 stripEtags?: boolean;
12284 /**
12285 * Whether to strip Last-Modified headers from the origin response before caching.
12286 */
12287 stripLastModified?: boolean;
12288 /**
12289 * Whether to enable Cache Deception Armor, which protects against web cache
12290 * deception attacks by verifying the Content-Type matches the URL extension.
12291 */
12292 cacheDeceptionArmor?: boolean;
12293 /**
12294 * Minimum file size in bytes for a response to be eligible for Cache Reserve storage.
12295 */
12296 cacheReserveMinimumFileSize?: number;
12297 scrapeShield?: boolean;
12298 apps?: boolean;
12299 /**
12300 * Controls whether an outbound gRPC-web subrequest from this Worker is
12301 * converted to gRPC at the Cloudflare edge.
12302 *
12303 * - `"passthrough"`: forward the subrequest unchanged as gRPC-web (default).
12304 * - `"convert"`: convert the gRPC-web subrequest to gRPC at the edge.
12305 *
12306 * Provides per-request control over the same edge conversion behavior
12307 * gated by the `auto_grpc_convert` compatibility flag.
12308 */
12309 grpcWeb?: "passthrough" | "convert";
12310 image?: RequestInitCfPropertiesImage;
12311 minify?: RequestInitCfPropertiesImageMinify;
12312 mirage?: boolean;
12313 polish?: "lossy" | "lossless" | "off";
12314 r2?: RequestInitCfPropertiesR2;
12315 /**
12316 * Redirects the request to an alternate origin server. You can use this,
12317 * for example, to implement load balancing across several origins.
12318 * (e.g.us-east.example.com)
12319 *
12320 * Note - For security reasons, the hostname set in resolveOverride must
12321 * be proxied on the same Cloudflare zone of the incoming request.
12322 * Otherwise, the setting is ignored. CNAME hosts are allowed, so to
12323 * resolve to a host under a different domain or a DNS only domain first
12324 * declare a CNAME record within your own zone’s DNS mapping to the
12325 * external hostname, set proxy on Cloudflare, then set resolveOverride
12326 * to point to that CNAME record.
12327 */
12328 resolveOverride?: string;
12329}
12330/**
12331 * Controls how Workers Standard Vary handles a request header listed by an
12332 * origin `Vary` response header:
12333 *
12334 * - `"normalize"`: normalize the request header value before it is used in the
12335 * cache variance key.
12336 * - `"passthrough"`: use the raw request header value in the cache variance
12337 * key.
12338 * - `"bypass"`: bypass cache when the header appears in the origin `Vary`
12339 * response header.
12340 */
12341type RequestInitCfPropertiesVaryAction = "normalize" | "passthrough" | "bypass";
12342/** Configuration for Workers Standard Vary support. */
12343interface RequestInitCfPropertiesVary {
12344 /** The fallback action for varied request headers not listed in `headers`. */
12345 default: RequestInitCfPropertiesVaryHeader;
12346 /**
12347 * Lowercase request header names and their Vary configuration.
12348 *
12349 * The `accept` header can include `media_types`, the `accept-language`
12350 * header can include `languages`, and other headers support only `action`.
12351 */
12352 headers?: RequestInitCfPropertiesVaryHeaders;
12353}
12354/** Common Vary behavior for a single request header. */
12355interface RequestInitCfPropertiesVaryHeader {
12356 /** How this request header contributes to cache variance. */
12357 action: RequestInitCfPropertiesVaryAction;
12358}
12359/** Vary behavior for the `accept` request header. */
12360interface RequestInitCfPropertiesVaryAcceptHeader extends RequestInitCfPropertiesVaryHeader {
12361 /**
12362 * Media types to keep when normalizing the `Accept` request header.
12363 *
12364 * Named `media_types` to match the serialized `cf.vary` configuration.
12365 */
12366 media_types?: string[];
12367}
12368/** Vary behavior for the `accept-language` request header. */
12369interface RequestInitCfPropertiesVaryAcceptLanguageHeader extends RequestInitCfPropertiesVaryHeader {
12370 /**
12371 * Language tags to keep when normalizing the `Accept-Language` request
12372 * header.
12373 */
12374 languages?: string[];
12375}
12376/**
12377 * Lowercase request header names and their Vary behavior.
12378 *
12379 * The index signature allows arbitrary custom request headers beyond the
12380 * well-known `accept` and `accept-language` specializations.
12381 */
12382interface RequestInitCfPropertiesVaryHeaders {
12383 accept?: RequestInitCfPropertiesVaryAcceptHeader;
12384 "accept-language"?: RequestInitCfPropertiesVaryAcceptLanguageHeader;
12385 [header: string]: RequestInitCfPropertiesVaryHeader | RequestInitCfPropertiesVaryAcceptHeader | RequestInitCfPropertiesVaryAcceptLanguageHeader | undefined;
12386}
12387interface BasicImageTransformations {
12388 /**
12389 * Maximum width in image pixels. The value must be an integer.
12390 */
12391 width?: number;
12392 /**
12393 * Maximum height in image pixels. The value must be an integer.
12394 */
12395 height?: number;
12396 /**
12397 * When cropping with fit: "cover", this defines the side or point that should
12398 * be left uncropped. The value is either a string
12399 * "left", "right", "top", "bottom", "auto", or "center" (the default),
12400 * or an object {x, y} containing focal point coordinates in the original
12401 * image expressed as fractions ranging from 0.0 (top or left) to 1.0
12402 * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will
12403 * crop bottom or left and right sides as necessary, but won’t crop anything
12404 * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to
12405 * preserve as much as possible around a point at 20% of the height of the
12406 * source image.
12407 */
12408 gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates;
12409 /**
12410 * Specifies how closely the image is cropped toward detected faces when combined
12411 * with the gravity=face option. Accepts a valid range between 0.0 (includes as much
12412 * of the background as possible) and 1.0 (crops the image as closely to the face as
12413 * possible). The default is 0.
12414 */
12415 zoom?: number;
12416 /**
12417 * Resizing mode as a string. It affects interpretation of width and height
12418 * options:
12419 * - scale-down: Similar to contain, but the image is never enlarged. If
12420 * the image is larger than given width or height, it will be resized.
12421 * Otherwise its original size will be kept.
12422 * - scale-up: Similar to contain, but the image is never shrunk. If the
12423 * image is smaller than the given width or height, it will be resized.
12424 * Otherwise its original size will be kept.
12425 * - contain: Resizes to maximum size that fits within the given width and
12426 * height. If only a single dimension is given (e.g. only width), the
12427 * image will be shrunk or enlarged to exactly match that dimension.
12428 * Aspect ratio is always preserved.
12429 * - cover: Resizes (shrinks or enlarges) to fill the entire area of width
12430 * and height. If the image has an aspect ratio different from the ratio
12431 * of width and height, it will be cropped to fit.
12432 * - crop: The image will be shrunk and cropped to fit within the area
12433 * specified by width and height. The image will not be enlarged. For images
12434 * smaller than the given dimensions it's the same as scale-down. For
12435 * images larger than the given dimensions, it's the same as cover.
12436 * See also trim.
12437 * - pad: Resizes to the maximum size that fits within the given width and
12438 * height, and then fills the remaining area with a background color
12439 * (white by default). Use of this mode is not recommended, as the same
12440 * effect can be more efficiently achieved with the contain mode and the
12441 * CSS object-fit: contain property.
12442 * - squeeze: Stretches and deforms to the width and height given, even if it
12443 * breaks aspect ratio
12444 */
12445 fit?: "scale-down" | "scale-up" | "contain" | "cover" | "crop" | "pad" | "squeeze";
12446 /**
12447 * Allows you to trim your image. Takes dpr into account and is performed before
12448 * resizing or rotation.
12449 *
12450 * It can be used as:
12451 * - left, top, right, bottom - it will specify the number of pixels to cut
12452 * off each side
12453 * - width, height - the width/height you'd like to end up with - can be used
12454 * in combination with the properties above
12455 * - border - this will automatically trim the surroundings of an image based on
12456 * it's color. It consists of three properties:
12457 * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit)
12458 * - tolerance: difference from color to treat as color
12459 * - keep: the number of pixels of border to keep
12460 */
12461 trim?: "border" | {
12462 top?: number;
12463 bottom?: number;
12464 left?: number;
12465 right?: number;
12466 width?: number;
12467 height?: number;
12468 border?: boolean | {
12469 color?: string;
12470 tolerance?: number;
12471 keep?: number;
12472 };
12473 };
12474 /**
12475 * Background color to add underneath the image. Applies only to images with
12476 * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…),
12477 * hsl(…), etc.)
12478 */
12479 background?: string;
12480 /**
12481 * Flips the images horizontally, vertically, or both. Flipping is applied before
12482 * rotation, so if you apply flip=h,rotate=90 then the image will be flipped
12483 * horizontally, then rotated by 90 degrees.
12484 */
12485 flip?: 'h' | 'v' | 'hv';
12486 /**
12487 * Number of degrees (90, 180, 270) to rotate the image by. width and height
12488 * options refer to axes after rotation.
12489 */
12490 rotate?: 0 | 90 | 180 | 270 | 360;
12491 /**
12492 * Strength of sharpening filter to apply to the image. Floating-point
12493 * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a
12494 * recommended value for downscaled images.
12495 */
12496 sharpen?: number;
12497 /**
12498 * Radius of a blur filter (approximate gaussian). Maximum supported radius
12499 * is 250.
12500 */
12501 blur?: number;
12502 /**
12503 * Increase contrast by a factor. A value of 1.0 equals no change, a value of
12504 * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is
12505 * ignored.
12506 */
12507 contrast?: number;
12508 /**
12509 * Increase brightness by a factor. A value of 1.0 equals no change, a value
12510 * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright.
12511 * 0 is ignored.
12512 */
12513 brightness?: number;
12514 /**
12515 * Increase exposure by a factor. A value of 1.0 equals no change, a value of
12516 * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored.
12517 */
12518 gamma?: number;
12519 /**
12520 * Increase contrast by a factor. A value of 1.0 equals no change, a value of
12521 * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is
12522 * ignored.
12523 */
12524 saturation?: number;
12525 /**
12526 * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it
12527 * easier to specify higher-DPI sizes in <img srcset>.
12528 */
12529 dpr?: number;
12530 /**
12531 * Adds a border around the image. The border is added after resizing. Border
12532 * width takes dpr into account, and can be specified either using a single
12533 * width property, or individually for each side.
12534 */
12535 border?: {
12536 color: string;
12537 width: number;
12538 } | {
12539 color: string;
12540 top: number;
12541 right: number;
12542 bottom: number;
12543 left: number;
12544 };
12545 /**
12546 * Image segmentation using artificial intelligence models. Sets pixels not
12547 * within selected segment area to transparent e.g "foreground" sets every
12548 * background pixel as transparent.
12549 */
12550 segment?: "foreground";
12551 /**
12552 * Controls the algorithm used when an image needs to be enlarged. This
12553 * parameter works with any fit mode that upscales, such as `contain`,
12554 * `cover`, and `scale-up`. It has no effect when `fit=scale-down` or when
12555 * the target dimensions are smaller than the source.
12556 * - interpolate: Uses bicubic interpolation, which may reduce image quality.
12557 * This is the default behavior when `upscale` is not specified.
12558 * - generate: Uses AI upscaling to produce sharper, more detailed results
12559 * when enlarging images.
12560 */
12561 upscale?: "interpolate" | "generate";
12562}
12563interface BasicImageTransformationsGravityCoordinates {
12564 x?: number;
12565 y?: number;
12566 mode?: 'remainder' | 'box-center';
12567}
12568interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations {
12569 /**
12570 * Absolute URL of the image file to use for the drawing. It can be any of
12571 * the supported file formats. For drawing of watermarks or non-rectangular
12572 * overlays we recommend using PNG or WebP images.
12573 */
12574 url: string;
12575 /**
12576 * Floating-point number between 0 (transparent) and 1 (opaque).
12577 * For example, opacity: 0.5 makes overlay semitransparent.
12578 */
12579 opacity?: number;
12580 /**
12581 * - If set to true, the overlay image will be tiled to cover the entire
12582 * area. This is useful for stock-photo-like watermarks.
12583 * - If set to "x", the overlay image will be tiled horizontally only
12584 * (form a line).
12585 * - If set to "y", the overlay image will be tiled vertically only
12586 * (form a line).
12587 */
12588 repeat?: true | "x" | "y";
12589 /**
12590 * How to combine the foreground and backdrop pixels to create the result
12591 */
12592 composite?:
12593 /** Foreground drawn on top of backdrop (default) */
12594 'over'
12595 /** Foreground shown only where backdrop is opaque */
12596 | 'in'
12597 /** Foreground drawn on top, but clipped to the backdrop's shape */
12598 | 'atop'
12599 /** Foreground shown only where backdrop is transparent */
12600 | 'out'
12601 /** Foreground and backdrop visible only where the other is not */
12602 | 'xor'
12603 /** Foreground and backdrop channels added (brightening) */
12604 | 'lighter';
12605 /**
12606 * Position of the overlay image relative to a given edge. Each property is
12607 * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10
12608 * positions left side of the overlay 10 pixels from the left edge of the
12609 * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom
12610 * of the background image.
12611 *
12612 * Setting both left & right, or both top & bottom is an error.
12613 *
12614 * If no position is specified, the image will be centered.
12615 */
12616 top?: number;
12617 left?: number;
12618 bottom?: number;
12619 right?: number;
12620}
12621interface RequestInitCfPropertiesImage extends BasicImageTransformations {
12622 /**
12623 * Quality setting from 1-100 (useful values are in 60-90 range). Lower values
12624 * make images look worse, but load faster. The default is 85. It applies only
12625 * to JPEG and WebP images. It doesn’t have any effect on PNG.
12626 */
12627 quality?: number | "low" | "medium-low" | "medium-high" | "high";
12628 /**
12629 * Output format to generate. It can be:
12630 * - avif: generate images in AVIF format.
12631 * - webp: generate images in Google WebP format. Set quality to 100 to get
12632 * the WebP-lossless format.
12633 * - json: instead of generating an image, outputs information about the
12634 * image, in JSON format. The JSON object will contain image size
12635 * (before and after resizing), source image’s MIME type, file size, etc.
12636 * - jpeg: generate images in JPEG format.
12637 * - png: generate images in PNG format.
12638 */
12639 format?: "avif" | "webp" | "json" | "jpeg" | "png" | "baseline-jpeg" | "png-force" | "svg";
12640 /**
12641 * Whether to preserve animation frames from input files. Default is true.
12642 * Setting it to false reduces animations to still images. This setting is
12643 * recommended when enlarging images or processing arbitrary user content,
12644 * because large GIF animations can weigh tens or even hundreds of megabytes.
12645 * It is also useful to set anim:false when using format:"json" to get the
12646 * response quicker without the number of frames.
12647 */
12648 anim?: boolean;
12649 /**
12650 * What EXIF data should be preserved in the output image. Note that EXIF
12651 * rotation and embedded color profiles are always applied ("baked in" into
12652 * the image), and aren't affected by this option. Note that if the Polish
12653 * feature is enabled, all metadata may have been removed already and this
12654 * option may have no effect.
12655 * - keep: Preserve most of EXIF metadata, including GPS location if there's
12656 * any.
12657 * - copyright: Only keep the copyright tag, and discard everything else.
12658 * This is the default behavior for JPEG files.
12659 * - none: Discard all invisible EXIF metadata. Currently WebP and PNG
12660 * output formats always discard metadata.
12661 */
12662 metadata?: "keep" | "copyright" | "none";
12663 /**
12664 * Overlays are drawn in the order they appear in the array (last array
12665 * entry is the topmost layer).
12666 */
12667 draw?: RequestInitCfPropertiesImageDraw[];
12668 /**
12669 * Fetching image from authenticated origin. Setting this property will
12670 * pass authentication headers (Authorization, Cookie, etc.) through to
12671 * the origin.
12672 */
12673 "origin-auth"?: "share-publicly";
12674 /**
12675 * Slightly reduces latency on a cache miss by selecting a
12676 * quickest-to-compress file format, at a cost of increased file size and
12677 * lower image quality. It will usually override the format option and choose
12678 * JPEG over WebP or AVIF. We do not recommend using this option, except in
12679 * unusual circumstances like resizing uncacheable dynamically-generated
12680 * images.
12681 */
12682 compression?: "fast";
12683}
12684interface RequestInitCfPropertiesImageMinify {
12685 javascript?: boolean;
12686 css?: boolean;
12687 html?: boolean;
12688}
12689interface RequestInitCfPropertiesR2 {
12690 /**
12691 * Colo id of bucket that an object is stored in
12692 */
12693 bucketColoId?: number;
12694}
12695/**
12696 * Request metadata provided by Cloudflare's edge.
12697 */
12698type IncomingRequestCfProperties<HostMetadata = unknown> = IncomingRequestCfPropertiesBase & IncomingRequestCfPropertiesBotManagementEnterprise & IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & IncomingRequestCfPropertiesGeographicInformation & IncomingRequestCfPropertiesCloudflareAccessOrApiShield;
12699interface IncomingRequestCfPropertiesBase extends Record<string, unknown> {
12700 /**
12701 * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request.
12702 *
12703 * @example 395747
12704 */
12705 asn?: number;
12706 /**
12707 * The organization which owns the ASN of the incoming request.
12708 *
12709 * @example "Google Cloud"
12710 */
12711 asOrganization?: string;
12712 /**
12713 * The original value of the `Accept-Encoding` header if Cloudflare modified it.
12714 *
12715 * @example "gzip, deflate, br"
12716 */
12717 clientAcceptEncoding?: string;
12718 /**
12719 * The number of milliseconds it took for the request to reach your worker.
12720 *
12721 * @example 22
12722 */
12723 clientTcpRtt?: number;
12724 /**
12725 * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code)
12726 * airport code of the data center that the request hit.
12727 *
12728 * @example "DFW"
12729 */
12730 colo: string;
12731 /**
12732 * Represents the upstream's response to a
12733 * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html)
12734 * from cloudflare.
12735 *
12736 * For workers with no upstream, this will always be `1`.
12737 *
12738 * @example 3
12739 */
12740 edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus;
12741 /**
12742 * The HTTP Protocol the request used.
12743 *
12744 * @example "HTTP/2"
12745 */
12746 httpProtocol: string;
12747 /**
12748 * The browser-requested prioritization information in the request object.
12749 *
12750 * If no information was set, defaults to the empty string `""`
12751 *
12752 * @example "weight=192;exclusive=0;group=3;group-weight=127"
12753 * @default ""
12754 */
12755 requestPriority: string;
12756 /**
12757 * The TLS version of the connection to Cloudflare.
12758 * In requests served over plaintext (without TLS), this property is the empty string `""`.
12759 *
12760 * @example "TLSv1.3"
12761 */
12762 tlsVersion: string;
12763 /**
12764 * The cipher for the connection to Cloudflare.
12765 * In requests served over plaintext (without TLS), this property is the empty string `""`.
12766 *
12767 * @example "AEAD-AES128-GCM-SHA256"
12768 */
12769 tlsCipher: string;
12770 /**
12771 * 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.
12772 *
12773 * If the incoming request was served over plaintext (without TLS) this field is undefined.
12774 */
12775 tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata;
12776}
12777interface IncomingRequestCfPropertiesBotManagementBase {
12778 /**
12779 * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot,
12780 * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human).
12781 *
12782 * @example 54
12783 */
12784 score: number;
12785 /**
12786 * A boolean value that is true if the request comes from a good bot, like Google or Bing.
12787 * 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).
12788 */
12789 verifiedBot: boolean;
12790 /**
12791 * A boolean value that is true if the request originates from a
12792 * Cloudflare-verified proxy service.
12793 */
12794 corporateProxy: boolean;
12795 /**
12796 * 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.
12797 */
12798 staticResource: boolean;
12799 /**
12800 * 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).
12801 */
12802 detectionIds: number[];
12803}
12804interface IncomingRequestCfPropertiesBotManagement {
12805 /**
12806 * Results of Cloudflare's Bot Management analysis
12807 */
12808 botManagement: IncomingRequestCfPropertiesBotManagementBase;
12809 /**
12810 * Duplicate of `botManagement.score`.
12811 *
12812 * @deprecated
12813 */
12814 clientTrustScore: number;
12815}
12816interface IncomingRequestCfPropertiesBotManagementEnterprise extends IncomingRequestCfPropertiesBotManagement {
12817 /**
12818 * Results of Cloudflare's Bot Management analysis
12819 */
12820 botManagement: IncomingRequestCfPropertiesBotManagementBase & {
12821 /**
12822 * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients
12823 * across different destination IPs, Ports, and X509 certificates.
12824 */
12825 ja3Hash: string;
12826 };
12827}
12828interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> {
12829 /**
12830 * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/).
12831 *
12832 * This field is only present if you have Cloudflare for SaaS enabled on your account
12833 * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)).
12834 */
12835 hostMetadata?: HostMetadata;
12836}
12837interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield {
12838 /**
12839 * Information about the client certificate presented to Cloudflare.
12840 *
12841 * This is populated when the incoming request is served over TLS using
12842 * either Cloudflare Access or API Shield (mTLS)
12843 * and the presented SSL certificate has a valid
12844 * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number)
12845 * (i.e., not `null` or `""`).
12846 *
12847 * Otherwise, a set of placeholder values are used.
12848 *
12849 * The property `certPresented` will be set to `"1"` when
12850 * the object is populated (i.e. the above conditions were met).
12851 */
12852 tlsClientAuth: IncomingRequestCfPropertiesTLSClientAuth | IncomingRequestCfPropertiesTLSClientAuthPlaceholder;
12853}
12854/**
12855 * Metadata about the request's TLS handshake
12856 */
12857interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata {
12858 /**
12859 * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal
12860 *
12861 * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d"
12862 */
12863 clientHandshake: string;
12864 /**
12865 * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal
12866 *
12867 * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d"
12868 */
12869 serverHandshake: string;
12870 /**
12871 * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal
12872 *
12873 * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b"
12874 */
12875 clientFinished: string;
12876 /**
12877 * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal
12878 *
12879 * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b"
12880 */
12881 serverFinished: string;
12882}
12883/**
12884 * Geographic data about the request's origin.
12885 */
12886interface IncomingRequestCfPropertiesGeographicInformation {
12887 /**
12888 * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from.
12889 *
12890 * 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.
12891 *
12892 * If Cloudflare is unable to determine where the request originated this property is omitted.
12893 *
12894 * The country code `"T1"` is used for requests originating on TOR.
12895 *
12896 * @example "GB"
12897 */
12898 country?: Iso3166Alpha2Code | "T1";
12899 /**
12900 * If present, this property indicates that the request originated in the EU
12901 *
12902 * @example "1"
12903 */
12904 isEUCountry?: "1";
12905 /**
12906 * A two-letter code indicating the continent the request originated from.
12907 *
12908 * @example "AN"
12909 */
12910 continent?: ContinentCode;
12911 /**
12912 * The city the request originated from
12913 *
12914 * @example "Austin"
12915 */
12916 city?: string;
12917 /**
12918 * Postal code of the incoming request
12919 *
12920 * @example "78701"
12921 */
12922 postalCode?: string;
12923 /**
12924 * Latitude of the incoming request
12925 *
12926 * @example "30.27130"
12927 */
12928 latitude?: string;
12929 /**
12930 * Longitude of the incoming request
12931 *
12932 * @example "-97.74260"
12933 */
12934 longitude?: string;
12935 /**
12936 * Timezone of the incoming request
12937 *
12938 * @example "America/Chicago"
12939 */
12940 timezone?: string;
12941 /**
12942 * If known, the ISO 3166-2 name for the first level region associated with
12943 * the IP address of the incoming request
12944 *
12945 * @example "Texas"
12946 */
12947 region?: string;
12948 /**
12949 * If known, the ISO 3166-2 code for the first-level region associated with
12950 * the IP address of the incoming request
12951 *
12952 * @example "TX"
12953 */
12954 regionCode?: string;
12955 /**
12956 * Metro code (DMA) of the incoming request
12957 *
12958 * @example "635"
12959 */
12960 metroCode?: string;
12961}
12962/** Data about the incoming request's TLS certificate */
12963interface IncomingRequestCfPropertiesTLSClientAuth {
12964 /** Always `"1"`, indicating that the certificate was presented */
12965 certPresented: "1";
12966 /**
12967 * Result of certificate verification.
12968 *
12969 * @example "FAILED:self signed certificate"
12970 */
12971 certVerified: Exclude<CertVerificationStatus, "NONE">;
12972 /** The presented certificate's revokation status.
12973 *
12974 * - A value of `"1"` indicates the certificate has been revoked
12975 * - A value of `"0"` indicates the certificate has not been revoked
12976 */
12977 certRevoked: "1" | "0";
12978 /**
12979 * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html)
12980 *
12981 * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"
12982 */
12983 certIssuerDN: string;
12984 /**
12985 * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html)
12986 *
12987 * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"
12988 */
12989 certSubjectDN: string;
12990 /**
12991 * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted)
12992 *
12993 * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"
12994 */
12995 certIssuerDNRFC2253: string;
12996 /**
12997 * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted)
12998 *
12999 * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"
13000 */
13001 certSubjectDNRFC2253: string;
13002 /** The certificate issuer's distinguished name (legacy policies) */
13003 certIssuerDNLegacy: string;
13004 /** The certificate subject's distinguished name (legacy policies) */
13005 certSubjectDNLegacy: string;
13006 /**
13007 * The certificate's serial number
13008 *
13009 * @example "00936EACBE07F201DF"
13010 */
13011 certSerial: string;
13012 /**
13013 * The certificate issuer's serial number
13014 *
13015 * @example "2489002934BDFEA34"
13016 */
13017 certIssuerSerial: string;
13018 /**
13019 * The certificate's Subject Key Identifier
13020 *
13021 * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4"
13022 */
13023 certSKI: string;
13024 /**
13025 * The certificate issuer's Subject Key Identifier
13026 *
13027 * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4"
13028 */
13029 certIssuerSKI: string;
13030 /**
13031 * The certificate's SHA-1 fingerprint
13032 *
13033 * @example "6b9109f323999e52259cda7373ff0b4d26bd232e"
13034 */
13035 certFingerprintSHA1: string;
13036 /**
13037 * The certificate's SHA-256 fingerprint
13038 *
13039 * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea"
13040 */
13041 certFingerprintSHA256: string;
13042 /**
13043 * The effective starting date of the certificate
13044 *
13045 * @example "Dec 22 19:39:00 2018 GMT"
13046 */
13047 certNotBefore: string;
13048 /**
13049 * The effective expiration date of the certificate
13050 *
13051 * @example "Dec 22 19:39:00 2018 GMT"
13052 */
13053 certNotAfter: string;
13054 /**
13055 * The client leaf certificate in [RFC 9440](https://www.rfc-editor.org/rfc/rfc9440)
13056 * format (`:base64-DER:`). Empty if no client certificate was presented or if
13057 * the leaf certificate exceeded 10 KB (see {@link certRFC9440TooLarge}).
13058 *
13059 * Suitable for forwarding to an origin via the `Client-Cert` HTTP header.
13060 */
13061 certRFC9440: string;
13062 /**
13063 * `true` if the leaf certificate exceeded 10 KB and was omitted from
13064 * {@link certRFC9440}.
13065 */
13066 certRFC9440TooLarge: boolean;
13067 /**
13068 * The intermediate certificate chain in [RFC 9440](https://www.rfc-editor.org/rfc/rfc9440)
13069 * format as a comma-separated list. Empty if no intermediates were sent or
13070 * if the chain exceeded 16 KB (see {@link certChainRFC9440TooLarge}).
13071 *
13072 * Suitable for forwarding to an origin via the `Client-Cert-Chain` HTTP header.
13073 */
13074 certChainRFC9440: string;
13075 /**
13076 * `true` if the intermediate chain exceeded 16 KB and was omitted from
13077 * {@link certChainRFC9440}.
13078 */
13079 certChainRFC9440TooLarge: boolean;
13080}
13081/** Placeholder values for TLS Client Authorization */
13082interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder {
13083 certPresented: "0";
13084 certVerified: "NONE";
13085 certRevoked: "0";
13086 certIssuerDN: "";
13087 certSubjectDN: "";
13088 certIssuerDNRFC2253: "";
13089 certSubjectDNRFC2253: "";
13090 certIssuerDNLegacy: "";
13091 certSubjectDNLegacy: "";
13092 certSerial: "";
13093 certIssuerSerial: "";
13094 certSKI: "";
13095 certIssuerSKI: "";
13096 certFingerprintSHA1: "";
13097 certFingerprintSHA256: "";
13098 certNotBefore: "";
13099 certNotAfter: "";
13100 certRFC9440: "";
13101 certRFC9440TooLarge: false;
13102 certChainRFC9440: "";
13103 certChainRFC9440TooLarge: false;
13104}
13105/** Possible outcomes of TLS verification */
13106declare type CertVerificationStatus =
13107/** Authentication succeeded */
13108"SUCCESS"
13109/** No certificate was presented */
13110 | "NONE"
13111/** Failed because the certificate was self-signed */
13112 | "FAILED:self signed certificate"
13113/** Failed because the certificate failed a trust chain check */
13114 | "FAILED:unable to verify the first certificate"
13115/** Failed because the certificate not yet valid */
13116 | "FAILED:certificate is not yet valid"
13117/** Failed because the certificate is expired */
13118 | "FAILED:certificate has expired"
13119/** Failed for another unspecified reason */
13120 | "FAILED";
13121/**
13122 * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare.
13123 */
13124declare 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 */
13125/** ISO 3166-1 Alpha-2 codes */
13126declare 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";
13127/** The 2-letter continent codes Cloudflare uses */
13128declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA";
13129type CfProperties<HostMetadata = unknown> = IncomingRequestCfProperties<HostMetadata> | RequestInitCfProperties;
13130interface D1Meta {
13131 duration: number;
13132 size_after: number;
13133 rows_read: number;
13134 rows_written: number;
13135 last_row_id: number;
13136 changed_db: boolean;
13137 changes: number;
13138 /**
13139 * The region of the database instance that executed the query.
13140 */
13141 served_by_region?: string;
13142 /**
13143 * The three letters airport code of the colo that executed the query.
13144 */
13145 served_by_colo?: string;
13146 /**
13147 * True if-and-only-if the database instance that executed the query was the primary.
13148 */
13149 served_by_primary?: boolean;
13150 timings?: {
13151 /**
13152 * The duration of the SQL query execution by the database instance. It doesn't include any network time.
13153 */
13154 sql_duration_ms: number;
13155 };
13156 /**
13157 * Number of total attempts to execute the query, due to automatic retries.
13158 * Note: All other fields in the response like `timings` only apply to the last attempt.
13159 */
13160 total_attempts?: number;
13161}
13162interface D1Response {
13163 success: true;
13164 meta: D1Meta & Record<string, unknown>;
13165 error?: never;
13166}
13167type D1Result<T = unknown> = D1Response & {
13168 results: T[];
13169};
13170interface D1ExecResult {
13171 count: number;
13172 duration: number;
13173}
13174type D1SessionConstraint =
13175// Indicates that the first query should go to the primary, and the rest queries
13176// using the same D1DatabaseSession will go to any replica that is consistent with
13177// the bookmark maintained by the session (returned by the first query).
13178'first-primary'
13179// Indicates that the first query can go anywhere (primary or replica), and the rest queries
13180// using the same D1DatabaseSession will go to any replica that is consistent with
13181// the bookmark maintained by the session (returned by the first query).
13182 | 'first-unconstrained';
13183type D1SessionBookmark = string;
13184declare abstract class D1Database {
13185 prepare(query: string): D1PreparedStatement;
13186 batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;
13187 exec(query: string): Promise<D1ExecResult>;
13188 /**
13189 * Creates a new D1 Session anchored at the given constraint or the bookmark.
13190 * All queries executed using the created session will have sequential consistency,
13191 * meaning that all writes done through the session will be visible in subsequent reads.
13192 *
13193 * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session.
13194 */
13195 withSession(constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession;
13196 /**
13197 * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases.
13198 */
13199 dump(): Promise<ArrayBuffer>;
13200}
13201declare abstract class D1DatabaseSession {
13202 prepare(query: string): D1PreparedStatement;
13203 batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;
13204 /**
13205 * @returns The latest session bookmark across all executed queries on the session.
13206 * If no query has been executed yet, `null` is returned.
13207 */
13208 getBookmark(): D1SessionBookmark | null;
13209}
13210declare abstract class D1PreparedStatement {
13211 bind(...values: unknown[]): D1PreparedStatement;
13212 first<T = unknown>(colName: string): Promise<T | null>;
13213 first<T = Record<string, unknown>>(): Promise<T | null>;
13214 run<T = Record<string, unknown>>(): Promise<D1Result<T>>;
13215 all<T = Record<string, unknown>>(): Promise<D1Result<T>>;
13216 raw<T = unknown[]>(options: {
13217 columnNames: true;
13218 }): Promise<[
13219 string[],
13220 ...T[]
13221 ]>;
13222 raw<T = unknown[]>(options?: {
13223 columnNames?: false;
13224 }): Promise<T[]>;
13225}
13226// `Disposable` was added to TypeScript's standard lib types in version 5.2.
13227// To support older TypeScript versions, define an empty `Disposable` interface.
13228// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2,
13229// but this will ensure type checking on older versions still passes.
13230// TypeScript's interface merging will ensure our empty interface is effectively
13231// ignored when `Disposable` is included in the standard lib.
13232interface Disposable {
13233}
13234declare module 'cloudflare:durable-objects' {
13235 /**
13236 * Marks a Durable Object method as safe to run more than once. The runtime may then retry calls
13237 * to it after a disconnect that might have happened after the method started. It does not
13238 * enable retries or change how many are made.
13239 *
13240 * Each attempt creates its own return value, so if the method returns an `RpcTarget`, its
13241 * `[Symbol.dispose]()` may run once per attempt.
13242 *
13243 * Only public instance methods can be decorated. When composing decorators, apply `@retryable`
13244 * outermost (first in source order) so it marks the method that is finally installed.
13245 * Otherwise `@retryable` has no effect, and constructing the object logs a warning.
13246 * Requires standard (not `experimentalDecorators`) decorators and a bundler that transforms
13247 * them, such as Wrangler.
13248 */
13249 export function retryable<This, Args extends unknown[], Return>(value: (this: This, ...args: Args) => Return, context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>): (this: This, ...args: Args) => Return;
13250}
13251/**
13252 * The returned data after sending an email
13253 */
13254interface EmailSendResult {
13255 /**
13256 * The Email Message ID
13257 */
13258 messageId: string;
13259}
13260/**
13261 * An email message that can be sent from a Worker.
13262 */
13263interface EmailMessage {
13264 /**
13265 * Envelope From attribute of the email message.
13266 */
13267 readonly from: string;
13268 /**
13269 * Envelope To attribute of the email message.
13270 */
13271 readonly to: string;
13272}
13273/**
13274 * An email message that is sent to a consumer Worker and can be rejected/forwarded.
13275 */
13276interface ForwardableEmailMessage extends EmailMessage {
13277 /**
13278 * Stream of the email message content.
13279 */
13280 readonly raw: ReadableStream<Uint8Array>;
13281 /**
13282 * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers).
13283 */
13284 readonly headers: Headers;
13285 /**
13286 * Size of the email message content.
13287 */
13288 readonly rawSize: number;
13289 /**
13290 * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason.
13291 * @param reason The reject reason.
13292 * @returns void
13293 */
13294 setReject(reason: string): void;
13295 /**
13296 * Forward this email message to a verified destination address of the account.
13297 * @param rcptTo Verified destination address.
13298 * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers).
13299 * @returns A promise that resolves when the email message is forwarded.
13300 */
13301 forward(rcptTo: string, headers?: Headers): Promise<EmailSendResult>;
13302 /**
13303 * Reply to the sender of this email message with a new EmailMessage object.
13304 * @param message The reply message.
13305 * @returns A promise that resolves when the email message is replied.
13306 */
13307 reply(message: EmailMessage): Promise<EmailSendResult>;
13308 /**
13309 * Reply to the sender of this email message with a message built from the given
13310 * fields. Threading headers (In-Reply-To/References) are set automatically.
13311 * @param builder The reply message contents.
13312 * @returns A promise that resolves when the email message is replied.
13313 */
13314 reply(builder: EmailReplyMessageBuilder): Promise<EmailSendResult>;
13315}
13316/** A file attachment for an email message */
13317type EmailAttachment = {
13318 disposition: 'inline';
13319 contentId: string;
13320 filename: string;
13321 type: string;
13322 content: string | ArrayBuffer | ArrayBufferView;
13323} | {
13324 disposition: 'attachment';
13325 contentId?: undefined;
13326 filename: string;
13327 type: string;
13328 content: string | ArrayBuffer | ArrayBufferView;
13329};
13330/** An Email Address */
13331interface EmailAddress {
13332 name: string;
13333 email: string;
13334}
13335/**
13336 * Recipient fields for `SendEmail.send()`. At least one of `to`, `cc`, or
13337 * `bcc` must be provided.
13338 */
13339type EmailDestinations = {
13340 to?: string | EmailAddress | (string | EmailAddress)[];
13341 cc?: string | EmailAddress | (string | EmailAddress)[];
13342 bcc?: string | EmailAddress | (string | EmailAddress)[];
13343} & ({
13344 to: string | EmailAddress | (string | EmailAddress)[];
13345} | {
13346 cc: string | EmailAddress | (string | EmailAddress)[];
13347} | {
13348 bcc: string | EmailAddress | (string | EmailAddress)[];
13349});
13350/**
13351 * Fields shared by all composed emails (no recipients). Used directly by
13352 * `ForwardableEmailMessage.reply()`, which always replies to the original
13353 * sender, and extended by `EmailMessageBuilder` for `SendEmail.send()`.
13354 */
13355interface EmailReplyMessageBuilder {
13356 from: string | EmailAddress;
13357 subject: string;
13358 replyTo?: string | EmailAddress;
13359 headers?: Record<string, string>;
13360 text?: string;
13361 html?: string;
13362 attachments?: EmailAttachment[];
13363}
13364/**
13365 * Fields for composing an email without constructing raw MIME, for
13366 * `SendEmail.send()`. Requires at least one of `to`, `cc`, or `bcc`.
13367 */
13368type EmailMessageBuilder = EmailReplyMessageBuilder & EmailDestinations;
13369/**
13370 * A binding that allows a Worker to send email messages.
13371 */
13372interface SendEmail {
13373 send(message: EmailMessage): Promise<EmailSendResult>;
13374 send(builder: EmailMessageBuilder): Promise<EmailSendResult>;
13375}
13376declare abstract class EmailEvent extends ExtendableEvent {
13377 readonly message: ForwardableEmailMessage;
13378}
13379declare type EmailExportedHandler<Env = unknown, Props = unknown> = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
13380declare module "cloudflare:email" {
13381 let _EmailMessage: {
13382 prototype: EmailMessage;
13383 new (from: string, to: string, raw: ReadableStream | string): EmailMessage;
13384 };
13385 export { _EmailMessage as EmailMessage };
13386}
13387/**
13388 * Evaluation context for targeting rules.
13389 * Keys are attribute names (e.g. "userId", "country"), values are the attribute values.
13390 */
13391type FlagshipEvaluationContext = Record<string, string | number | boolean>;
13392interface FlagshipEvaluationDetails<T> {
13393 flagKey: string;
13394 value: T;
13395 variant?: string | undefined;
13396 reason?: string | undefined;
13397 errorCode?: string | undefined;
13398 errorMessage?: string | undefined;
13399}
13400interface FlagshipEvaluationError extends Error {
13401}
13402/**
13403 * Feature flags binding for evaluating feature flags from a Cloudflare Workers script.
13404 *
13405 * @example
13406 * ```typescript
13407 * // Get a boolean flag value with a default
13408 * const enabled = await env.FLAGS.getBooleanValue('my-feature', false);
13409 *
13410 * // Get a flag value with evaluation context for targeting
13411 * const variant = await env.FLAGS.getStringValue('experiment', 'control', {
13412 * userId: 'user-123',
13413 * country: 'US',
13414 * });
13415 *
13416 * // Get full evaluation details including variant and reason
13417 * const details = await env.FLAGS.getBooleanDetails('my-feature', false);
13418 * console.log(details.variant, details.reason);
13419 * ```
13420 */
13421declare abstract class Flagship {
13422 /**
13423 * Get a flag value without type checking.
13424 * @param flagKey The key of the flag to evaluate.
13425 * @param defaultValue Optional default value returned when evaluation fails.
13426 * @param context Optional evaluation context for targeting rules.
13427 */
13428 get(flagKey: string, defaultValue?: unknown, context?: FlagshipEvaluationContext): Promise<unknown>;
13429 /**
13430 * Get a boolean flag value.
13431 * @param flagKey The key of the flag to evaluate.
13432 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
13433 * @param context Optional evaluation context for targeting rules.
13434 */
13435 getBooleanValue(flagKey: string, defaultValue: boolean, context?: FlagshipEvaluationContext): Promise<boolean>;
13436 /**
13437 * Get a string flag value.
13438 * @param flagKey The key of the flag to evaluate.
13439 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
13440 * @param context Optional evaluation context for targeting rules.
13441 */
13442 getStringValue(flagKey: string, defaultValue: string, context?: FlagshipEvaluationContext): Promise<string>;
13443 /**
13444 * Get a number flag value.
13445 * @param flagKey The key of the flag to evaluate.
13446 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
13447 * @param context Optional evaluation context for targeting rules.
13448 */
13449 getNumberValue(flagKey: string, defaultValue: number, context?: FlagshipEvaluationContext): Promise<number>;
13450 /**
13451 * Get an object flag value.
13452 * @param flagKey The key of the flag to evaluate.
13453 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
13454 * @param context Optional evaluation context for targeting rules.
13455 */
13456 getObjectValue<T extends object>(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise<T>;
13457 /**
13458 * Get a boolean flag value with full evaluation details.
13459 * @param flagKey The key of the flag to evaluate.
13460 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
13461 * @param context Optional evaluation context for targeting rules.
13462 */
13463 getBooleanDetails(flagKey: string, defaultValue: boolean, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<boolean>>;
13464 /**
13465 * Get a string flag value with full evaluation details.
13466 * @param flagKey The key of the flag to evaluate.
13467 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
13468 * @param context Optional evaluation context for targeting rules.
13469 */
13470 getStringDetails(flagKey: string, defaultValue: string, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<string>>;
13471 /**
13472 * Get a number flag value with full evaluation details.
13473 * @param flagKey The key of the flag to evaluate.
13474 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
13475 * @param context Optional evaluation context for targeting rules.
13476 */
13477 getNumberDetails(flagKey: string, defaultValue: number, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<number>>;
13478 /**
13479 * Get an object flag value with full evaluation details.
13480 * @param flagKey The key of the flag to evaluate.
13481 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
13482 * @param context Optional evaluation context for targeting rules.
13483 */
13484 getObjectDetails<T extends object>(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<T>>;
13485}
13486/**
13487 * Hello World binding to serve as an explanatory example. DO NOT USE
13488 */
13489interface HelloWorldBinding {
13490 /**
13491 * Retrieve the current stored value
13492 */
13493 get(): Promise<{
13494 value: string;
13495 ms?: number;
13496 }>;
13497 /**
13498 * Set a new stored value
13499 */
13500 set(value: string): Promise<void>;
13501}
13502interface Hyperdrive {
13503 /**
13504 * Connect directly to Hyperdrive as if it's your database, returning a TCP socket.
13505 *
13506 * Calling this method returns an identical socket to if you call
13507 * `connect("host:port")` using the `host` and `port` fields from this object.
13508 * Pick whichever approach works better with your preferred DB client library.
13509 *
13510 * Note that this socket is not yet authenticated -- it's expected that your
13511 * code (or preferably, the client library of your choice) will authenticate
13512 * using the information in this class's readonly fields.
13513 */
13514 connect(): Socket;
13515 /**
13516 * A valid DB connection string that can be passed straight into the typical
13517 * client library/driver/ORM. This will typically be the easiest way to use
13518 * Hyperdrive.
13519 */
13520 readonly connectionString: string;
13521 /*
13522 * A randomly generated hostname that is only valid within the context of the
13523 * currently running Worker which, when passed into `connect()` function from
13524 * the "cloudflare:sockets" module, will connect to the Hyperdrive instance
13525 * for your database.
13526 */
13527 readonly host: string;
13528 /*
13529 * A synthetic IPv4 address (in the reserved 240.0.0.0/4 range) that, like the
13530 * host field, is only valid within the context of the currently running
13531 * Worker and, when passed into the `connect()` function from the
13532 * "cloudflare:sockets" module, will connect to the Hyperdrive instance for
13533 * your database. This is provided for database drivers that require the host
13534 * to be an IP literal rather than a hostname.
13535 */
13536 readonly ip: string;
13537 /*
13538 * The port that must be paired the the host field when connecting.
13539 */
13540 readonly port: number;
13541 /*
13542 * The username to use when authenticating to your database via Hyperdrive.
13543 * Unlike the host and password, this will be the same every time
13544 */
13545 readonly user: string;
13546 /*
13547 * The randomly generated password to use when authenticating to your
13548 * database via Hyperdrive. Like the host field, this password is only valid
13549 * within the context of the currently running Worker instance from which
13550 * it's read.
13551 */
13552 readonly password: string;
13553 /*
13554 * The name of the database to connect to.
13555 */
13556 readonly database: string;
13557}
13558/**
13559 * A handle to a dynamically-provisioned Hyperdrive connection, returned by
13560 * `HyperdriveApi.get()`.
13561 */
13562interface HyperdriveDynamic extends Disposable {
13563 /**
13564 * The database name to use when connecting through this Hyperdrive.
13565 */
13566 readonly database: Promise<string>;
13567 /*
13568 * The randomly generated user to use when authenticating to your
13569 * database via Hyperdrive.
13570 */
13571 readonly user: Promise<string>;
13572 /*
13573 * The randomly generated password to use when authenticating to your
13574 * database via Hyperdrive.
13575 */
13576 readonly password: Promise<string>;
13577 /**
13578 * Open a TCP socket to the target database through this Hyperdrive.
13579 *
13580 */
13581 connect(): Promise<Socket>;
13582}
13583/**
13584 * Binding that provisions Hyperdrive connections at request time, rather than
13585 * from static configuration.
13586 */
13587interface HyperdriveDynamicApi {
13588 /**
13589 * Provision a connection for the database described by `args`.
13590 *
13591 */
13592 get(args: HyperdriveDynamicConfig): Promise<HyperdriveDynamic>;
13593 /**
13594 * Get a pre-generated connection string used for connecting to dynamic Hyperdrive.
13595 */
13596 getHyperdriveConnectionString(connectionString: string): Promise<string>;
13597}
13598/**
13599 * Parameters identifying the database that a dynamically-provisioned
13600 * Hyperdrive connection should target.
13601 */
13602interface HyperdriveDynamicConfig {
13603 /**
13604 * Generated connection string to pass into the dynamic worker.
13605 *
13606 */
13607 dynamicHyperdriveConnectionString: string;
13608 /**
13609 * Connection string for the origin database Hyperdrive should connect to.
13610 * Contains credentials, so treat it as a secret.
13611 *
13612 * The scheme selects the database engine. PostgreSQL origins are supported.
13613 */
13614 connectionString: string;
13615 /**
13616 * Region in which to place the connection pool. See the Hyperdrive
13617 * documentation for the set of supported regions.
13618 */
13619 targetRegion: string;
13620 /**
13621 * Whether Hyperdrive should cache query results for this connection.
13622 */
13623 cachingEnabled?: boolean;
13624 /**
13625 * Maximum number of connections the pool may open to the origin database.
13626 * Defaults to 60.
13627 */
13628 maxConnections?: number;
13629}
13630// Copyright (c) 2024 Cloudflare, Inc.
13631// Licensed under the Apache 2.0 license found in the LICENSE file or at:
13632// https://opensource.org/licenses/Apache-2.0
13633type ImageInfoResponse = {
13634 format: 'image/svg+xml';
13635} | {
13636 format: string;
13637 fileSize: number;
13638 width: number;
13639 height: number;
13640};
13641/**
13642 * Parameters for rasterizing text into an image.
13643 */
13644type TextRasterize = {
13645 /** The text content to render */
13646 content: string;
13647 /** rasterization options for the text **/
13648 options: TextOptions;
13649};
13650type TextOptions = {
13651 /** Font configuration */
13652 font: {
13653 /** URL to a font file in TrueType (.ttf), OpenType (.otf), WOFF (.woff), or WOFF2 (.woff2) format */
13654 url: string;
13655 };
13656 /** Font size in points (pt) */
13657 size?: number;
13658 /** Text color in CSS format: hex (#RRGGBB or #RRGGBBAA), rgb(r,g,b), rgba(r,g,b,a), or named colors */
13659 color?: string;
13660};
13661type ImageSource = ReadableStream<Uint8Array> | TextRasterize;
13662type ImageTransform = {
13663 width?: number;
13664 height?: number;
13665 background?: string;
13666 blur?: number;
13667 border?: {
13668 color?: string;
13669 width?: number;
13670 } | {
13671 top?: number;
13672 bottom?: number;
13673 left?: number;
13674 right?: number;
13675 };
13676 brightness?: number;
13677 contrast?: number;
13678 fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop';
13679 flip?: 'h' | 'v' | 'hv';
13680 gamma?: number;
13681 segment?: 'foreground';
13682 gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | {
13683 x?: number;
13684 y?: number;
13685 mode: 'remainder' | 'box-center';
13686 };
13687 rotate?: 0 | 90 | 180 | 270;
13688 saturation?: number;
13689 sharpen?: number;
13690 trim?: 'border' | {
13691 top?: number;
13692 bottom?: number;
13693 left?: number;
13694 right?: number;
13695 width?: number;
13696 height?: number;
13697 border?: boolean | {
13698 color?: string;
13699 tolerance?: number;
13700 keep?: number;
13701 };
13702 };
13703};
13704type ImageDrawOptions = {
13705 opacity?: number;
13706 repeat?: boolean | string;
13707 composite?: ImageCompositeMode;
13708 top?: number;
13709 left?: number;
13710 bottom?: number;
13711 right?: number;
13712};
13713type ImageCompositeMode =
13714/** Foreground drawn on top of backdrop (default) */
13715'over'
13716/** Foreground shown only where backdrop is opaque */
13717 | 'in'
13718/** Foreground drawn on top, but clipped to the backdrop's shape */
13719 | 'atop'
13720/** Foreground shown only where backdrop is transparent */
13721 | 'out'
13722/** Foreground and backdrop visible only where the other is not */
13723 | 'xor'
13724/** Foreground and backdrop channels added (brightening) */
13725 | 'lighter';
13726type ImageInputOptions = {
13727 encoding?: 'base64';
13728};
13729type ImageOutputOptions = {
13730 format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba';
13731 quality?: number;
13732 background?: string;
13733 anim?: boolean;
13734};
13735interface ImageMetadata {
13736 id: string;
13737 filename?: string;
13738 uploaded?: string;
13739 requireSignedURLs: boolean;
13740 meta?: Record<string, unknown>;
13741 variants: string[];
13742 draft?: boolean;
13743 creator?: string;
13744}
13745interface ImageUploadOptions {
13746 id?: string;
13747 filename?: string;
13748 requireSignedURLs?: boolean;
13749 metadata?: Record<string, unknown>;
13750 creator?: string;
13751 /**
13752 * If 'base64', the input data will be decoded from base64 before processing
13753 */
13754 encoding?: 'base64';
13755}
13756interface ImageUpdateOptions {
13757 requireSignedURLs?: boolean;
13758 metadata?: Record<string, unknown>;
13759 creator?: string;
13760}
13761type ImageMetadataFilterOperators = {
13762 eq?: string | number | boolean;
13763 in?: string[] | number[];
13764 gt?: number;
13765 gte?: number;
13766 lt?: number;
13767 lte?: number;
13768};
13769type ImageMetadataFilterValue = string | number | boolean | ImageMetadataFilterOperators;
13770interface ImageListFilter {
13771 metadata?: Record<string, ImageMetadataFilterValue>;
13772}
13773interface ImageListOptions {
13774 limit?: number;
13775 cursor?: string;
13776 sortOrder?: 'asc' | 'desc';
13777 creator?: string;
13778 filter?: ImageListFilter;
13779}
13780interface ImageSignedUrlOptions {
13781 variant: string;
13782 expiresIn?: number;
13783 keyName?: string;
13784}
13785interface ImageDirectUploadOptions {
13786 id?: string;
13787 requireSignedURLs?: boolean;
13788 metadata?: Record<string, unknown>;
13789 creator?: string;
13790 expiresIn?: number;
13791}
13792interface ImageDirectUploadResult {
13793 id: string;
13794 uploadURL: string;
13795}
13796interface ImageList {
13797 images: ImageMetadata[];
13798 cursor?: string;
13799 listComplete: boolean;
13800}
13801interface ImageHandle {
13802 /**
13803 * Get metadata for a hosted image
13804 * @returns Image metadata, or null if not found
13805 */
13806 details(): Promise<ImageMetadata | null>;
13807 /**
13808 * Get the raw image data for a hosted image
13809 * @returns ReadableStream of image bytes, or null if not found
13810 */
13811 bytes(): Promise<ReadableStream<Uint8Array> | null>;
13812 /**
13813 * Generate a signed delivery URL for this hosted image.
13814 * @param options Signing configuration
13815 * @returns A signed image delivery URL
13816 * @throws {@link ImagesError} if signing fails
13817 */
13818 signedUrl(options: ImageSignedUrlOptions): Promise<string>;
13819 /**
13820 * Update hosted image metadata
13821 * @param options Properties to update
13822 * @returns Updated image metadata
13823 * @throws {@link ImagesError} if update fails
13824 */
13825 update(options: ImageUpdateOptions): Promise<ImageMetadata>;
13826 /**
13827 * Delete a hosted image
13828 * @returns True if deleted, false if not found
13829 */
13830 delete(): Promise<boolean>;
13831}
13832interface HostedImagesBinding {
13833 /**
13834 * Get a handle for a hosted image
13835 * @param imageId The ID of the image (UUID or custom ID)
13836 * @returns A handle for per-image operations
13837 */
13838 image(imageId: string): ImageHandle;
13839 /**
13840 * Upload a new hosted image
13841 * @param image The image file to upload
13842 * @param options Upload configuration
13843 * @returns Metadata for the uploaded image
13844 * @throws {@link ImagesError} if upload fails
13845 */
13846 upload(image: ReadableStream<Uint8Array> | ArrayBuffer, options?: ImageUploadOptions): Promise<ImageMetadata>;
13847 /**
13848 * List hosted images with pagination
13849 * @param options List configuration
13850 * @returns List of images with pagination info
13851 * @throws {@link ImagesError} if list fails
13852 */
13853 list(options?: ImageListOptions): Promise<ImageList>;
13854 /**
13855 * Create a Direct Creator Upload link, letting an end user upload an
13856 * image straight to Cloudflare without exposing an API token
13857 * @param options Upload link configuration
13858 * @returns The new image ID and the upload URL to hand to the end user
13859 * @throws {@link ImagesError} if creation fails
13860 */
13861 createDirectUpload(options?: ImageDirectUploadOptions): Promise<ImageDirectUploadResult>;
13862}
13863interface ImagesBinding {
13864 /**
13865 * Get image metadata (type, width and height)
13866 * @throws {@link ImagesError} with code 9412 if input is not an image
13867 * @param stream The image bytes
13868 */
13869 info(stream: ReadableStream<Uint8Array>, options?: ImageInputOptions): Promise<ImageInfoResponse>;
13870 /**
13871 * Begin applying a series of transformations to an image
13872 * @param stream The image bytes
13873 * @returns A transform handle
13874 */
13875 input(stream: ReadableStream<Uint8Array>, options?: ImageInputOptions): ImageTransformer;
13876 /**
13877 * Begin applying a series of transformations to text
13878 * @param content string to be rendered
13879 * @param options font, optional color and size to use in rendering text
13880 * @returns A transform handle
13881 */
13882 text(content: string, options: TextOptions): ImageTransformer;
13883 /**
13884 * Access hosted images CRUD operations
13885 */
13886 readonly hosted: HostedImagesBinding;
13887}
13888interface ImageTransformer {
13889 /**
13890 * Apply transform next, returning a transform handle.
13891 * You can then apply more transformations, draw, or retrieve the output.
13892 * @param transform
13893 */
13894 transform(transform: ImageTransform): ImageTransformer;
13895 /**
13896 * Draw an image on this transformer, returning a transform handle.
13897 * You can then apply more transformations, draw, or retrieve the output.
13898 * @param image The image (or transformer that will give the image) to draw
13899 * @param options The options configuring how to draw the image
13900 */
13901 draw(image: ReadableStream<Uint8Array> | ImageTransformer, options?: ImageDrawOptions): ImageTransformer;
13902 /**
13903 * Retrieve the image that results from applying the transforms to the
13904 * provided input
13905 * @param options Options that apply to the output e.g. output format
13906 */
13907 output(options: ImageOutputOptions): Promise<ImageTransformationResult>;
13908}
13909type ImageTransformationOutputOptions = {
13910 encoding?: 'base64';
13911};
13912type ImageTransformationResponseOptions = {
13913 headers?: HeadersInit;
13914};
13915interface ImageTransformationResult {
13916 /**
13917 * The image as a response, ready to store in cache or return to users
13918 * @param options Options that apply to the returned response, e.g. additional headers
13919 */
13920 response(options?: ImageTransformationResponseOptions): Response;
13921 /**
13922 * The content type of the returned image
13923 */
13924 contentType(): string;
13925 /**
13926 * The bytes of the response
13927 */
13928 image(options?: ImageTransformationOutputOptions): ReadableStream<Uint8Array>;
13929}
13930interface ImagesError extends Error {
13931 readonly code: number;
13932 readonly message: string;
13933 readonly stack?: string;
13934}
13935/**
13936 * Media binding for transforming media streams.
13937 * Provides the entry point for media transformation operations.
13938 */
13939interface MediaBinding {
13940 /**
13941 * Creates a media transformer from an input stream.
13942 * @param media - The input media bytes
13943 * @returns A MediaTransformer instance for applying transformations
13944 */
13945 input(media: ReadableStream<Uint8Array>): MediaTransformer;
13946}
13947/**
13948 * Media transformer for applying transformation operations to media content.
13949 * Handles sizing, fitting, and other input transformation parameters.
13950 */
13951interface MediaTransformer {
13952 /**
13953 * Applies transformation options to the media content.
13954 * @param transform - Configuration for how the media should be transformed
13955 * @returns A generator for producing the transformed media output
13956 */
13957 transform(transform?: MediaTransformationInputOptions): MediaTransformationGenerator;
13958 /**
13959 * Generates the final media output with specified options.
13960 * @param output - Configuration for the output format and parameters
13961 * @returns The final transformation result containing the transformed media
13962 */
13963 output(output?: MediaTransformationOutputOptions): MediaTransformationResult;
13964}
13965/**
13966 * Generator for producing media transformation results.
13967 * Configures the output format and parameters for the transformed media.
13968 */
13969interface MediaTransformationGenerator {
13970 /**
13971 * Generates the final media output with specified options.
13972 * @param output - Configuration for the output format and parameters
13973 * @returns The final transformation result containing the transformed media
13974 */
13975 output(output?: MediaTransformationOutputOptions): MediaTransformationResult;
13976}
13977/**
13978 * Result of a media transformation operation.
13979 * Provides multiple ways to access the transformed media content.
13980 */
13981interface MediaTransformationResult {
13982 /**
13983 * Returns the transformed media as a readable stream of bytes.
13984 * @returns A promise containing a readable stream with the transformed media
13985 */
13986 media(): Promise<ReadableStream<Uint8Array>>;
13987 /**
13988 * Returns the transformed media as an HTTP response object.
13989 * @returns The transformed media as a Promise<Response>, ready to store in cache or return to users
13990 */
13991 response(): Promise<Response>;
13992 /**
13993 * Returns the MIME type of the transformed media.
13994 * @returns A promise containing the content type string (e.g., 'image/jpeg', 'video/mp4')
13995 */
13996 contentType(): Promise<string>;
13997}
13998/**
13999 * Configuration options for transforming media input.
14000 * Controls how the media should be resized and fitted.
14001 */
14002type MediaTransformationInputOptions = {
14003 /** How the media should be resized to fit the specified dimensions */
14004 fit?: 'contain' | 'cover' | 'scale-down';
14005 /** Target width in pixels */
14006 width?: number;
14007 /** Target height in pixels */
14008 height?: number;
14009};
14010/**
14011 * Configuration options for Media Transformations output.
14012 * Controls the format, timing, and type of the generated output.
14013 */
14014type MediaTransformationOutputOptions = {
14015 /**
14016 * Output mode determining the type of media to generate
14017 */
14018 mode?: 'video' | 'spritesheet' | 'frame' | 'audio';
14019 /** Whether to include audio in the output */
14020 audio?: boolean;
14021 /**
14022 * Starting timestamp for frame extraction or start time for clips. (e.g. '2s').
14023 */
14024 time?: string;
14025 /**
14026 * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s').
14027 */
14028 duration?: string;
14029 /**
14030 * Number of frames in the spritesheet.
14031 */
14032 imageCount?: number;
14033 /**
14034 * Output format for the generated media.
14035 */
14036 format?: 'jpg' | 'png' | 'm4a';
14037};
14038/**
14039 * Error object for media transformation operations.
14040 * Extends the standard Error interface with additional media-specific information.
14041 */
14042interface MediaError extends Error {
14043 readonly code: number;
14044 readonly message: string;
14045 readonly stack?: string;
14046}
14047declare module 'cloudflare:node' {
14048 interface NodeStyleServer {
14049 listen(...args: unknown[]): this;
14050 address(): {
14051 port?: number | null | undefined;
14052 } | null;
14053 }
14054 export function httpServerHandler(port: number): ExportedHandler;
14055 export function httpServerHandler(options: {
14056 port: number;
14057 }): ExportedHandler;
14058 export function httpServerHandler(server: NodeStyleServer): ExportedHandler;
14059 /**
14060 * Dispatches a request to the `http.Server` listening on the given port and
14061 * resolves with its response. The direct form of `httpServerHandler()`.
14062 */
14063 export function handleAsNodeRequest(port: number | {
14064 port: number;
14065 }, request: Request, env?: unknown, ctx?: ExecutionContext): Promise<Response>;
14066 /**
14067 * Routes inbound sockets to the `net.Server` listening on the port each
14068 * socket arrived on.
14069 */
14070 export function connectHandler(): ExportedHandler;
14071 /**
14072 * Dispatches an inbound socket to the `net.Server` listening on the port it
14073 * arrived on, resolving when the connection has closed. The direct form of
14074 * `connectHandler()`, for use inside a `connect()` handler, such as a
14075 * Durable Object's.
14076 */
14077 export function handleAsNodeConnection(socket: Socket, env?: unknown, ctx?: ExecutionContext): Promise<void>;
14078}
14079type Params<P extends string = any> = Record<P, string | string[]>;
14080type EventContext<Env, P extends string, Data> = {
14081 request: Request<unknown, IncomingRequestCfProperties<unknown>>;
14082 functionPath: string;
14083 waitUntil: (promise: Promise<any>) => void;
14084 passThroughOnException: () => void;
14085 next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
14086 env: Env & {
14087 ASSETS: {
14088 fetch: typeof fetch;
14089 };
14090 };
14091 params: Params<P>;
14092 data: Data;
14093};
14094type PagesFunction<Env = unknown, Params extends string = any, Data extends Record<string, unknown> = Record<string, unknown>> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>;
14095type EventPluginContext<Env, P extends string, Data, PluginArgs> = {
14096 request: Request<unknown, IncomingRequestCfProperties<unknown>>;
14097 functionPath: string;
14098 waitUntil: (promise: Promise<any>) => void;
14099 passThroughOnException: () => void;
14100 next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
14101 env: Env & {
14102 ASSETS: {
14103 fetch: typeof fetch;
14104 };
14105 };
14106 params: Params<P>;
14107 data: Data;
14108 pluginArgs: PluginArgs;
14109};
14110type 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>;
14111declare module "assets:*" {
14112 export const onRequest: PagesFunction;
14113}
14114// Copyright (c) 2022-2023 Cloudflare, Inc.
14115// Licensed under the Apache 2.0 license found in the LICENSE file or at:
14116// https://opensource.org/licenses/Apache-2.0
14117declare module "cloudflare:pipelines" {
14118 export abstract class PipelineTransformationEntrypoint<Env = unknown, I extends PipelineRecord = PipelineRecord, O extends PipelineRecord = PipelineRecord> {
14119 protected env: Env;
14120 protected ctx: ExecutionContext;
14121 constructor(ctx: ExecutionContext, env: Env);
14122 /**
14123 * run receives an array of PipelineRecord which can be
14124 * transformed and returned to the pipeline
14125 * @param records Incoming records from the pipeline to be transformed
14126 * @param metadata Information about the specific pipeline calling the transformation entrypoint
14127 * @returns A promise containing the transformed PipelineRecord array
14128 */
14129 public run(records: I[], metadata: PipelineBatchMetadata): Promise<O[]>;
14130 }
14131 export type PipelineRecord = Record<string, unknown>;
14132 export type PipelineBatchMetadata = {
14133 pipelineId: string;
14134 pipelineName: string;
14135 };
14136 export interface Pipeline<T extends PipelineRecord = PipelineRecord> {
14137 /**
14138 * The Pipeline interface represents the type of a binding to a Pipeline
14139 *
14140 * @param records The records to send to the pipeline
14141 */
14142 send(records: T[]): Promise<void>;
14143 }
14144}
14145// PubSubMessage represents an incoming PubSub message.
14146// The message includes metadata about the broker, the client, and the payload
14147// itself.
14148// https://developers.cloudflare.com/pub-sub/
14149interface PubSubMessage {
14150 // Message ID
14151 readonly mid: number;
14152 // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT
14153 readonly broker: string;
14154 // The MQTT topic the message was sent on.
14155 readonly topic: string;
14156 // The client ID of the client that published this message.
14157 readonly clientId: string;
14158 // The unique identifier (JWT ID) used by the client to authenticate, if token
14159 // auth was used.
14160 readonly jti?: string;
14161 // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker
14162 // received the message from the client.
14163 readonly receivedAt: number;
14164 // An (optional) string with the MIME type of the payload, if set by the
14165 // client.
14166 readonly contentType: string;
14167 // Set to 1 when the payload is a UTF-8 string
14168 // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063
14169 readonly payloadFormatIndicator: number;
14170 // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays.
14171 // You can use payloadFormatIndicator to inspect this before decoding.
14172 payload: string | Uint8Array;
14173}
14174// JsonWebKey extended by kid parameter
14175interface JsonWebKeyWithKid extends JsonWebKey {
14176 // Key Identifier of the JWK
14177 readonly kid: string;
14178}
14179interface RateLimitOptions {
14180 key: string;
14181}
14182interface RateLimitOutcome {
14183 success: boolean;
14184}
14185interface RateLimit {
14186 /**
14187 * Rate limit a request based on the provided options.
14188 * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/
14189 * @returns A promise that resolves with the outcome of the rate limit.
14190 */
14191 limit(options: RateLimitOptions): Promise<RateLimitOutcome>;
14192}
14193// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need
14194// to referenced by `Fetcher`. This is included in the "importable" version of the types which
14195// strips all `module` blocks.
14196declare namespace Rpc {
14197 // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s.
14198 // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`.
14199 // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to
14200 // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape)
14201 export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND';
14202 export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND';
14203 export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND';
14204 export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND';
14205 export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND';
14206 export interface RpcTargetBranded {
14207 [__RPC_TARGET_BRAND]: never;
14208 }
14209 export interface WorkerEntrypointBranded {
14210 [__WORKER_ENTRYPOINT_BRAND]: never;
14211 }
14212 export interface DurableObjectBranded {
14213 [__DURABLE_OBJECT_BRAND]: never;
14214 }
14215 export interface WorkflowEntrypointBranded {
14216 [__WORKFLOW_ENTRYPOINT_BRAND]: never;
14217 }
14218 export type EntrypointBranded = WorkerEntrypointBranded | DurableObjectBranded | WorkflowEntrypointBranded;
14219 // Types that can be used through `Stub`s
14220 export type Stubable = RpcTargetBranded | ((...args: any[]) => any);
14221 // Types that can be passed over RPC
14222 // The reason for using a generic type here is to build a serializable subset of structured
14223 // cloneable composite types. This allows types defined with the "interface" keyword to pass the
14224 // serializable check as well. Otherwise, only types defined with the "type" keyword would pass.
14225 type Serializable<T> =
14226 // Structured cloneables
14227 BaseType
14228 // Structured cloneable composites
14229 | 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> | {
14230 [K in keyof T]: K extends number | string ? Serializable<T[K]> : never;
14231 }
14232 // Special types
14233 | Stub<Stubable>
14234 // Serialized as stubs, see `Stubify`
14235 | Stubable;
14236 // Base type for all RPC stubs, including common memory management methods.
14237 // `T` is used as a marker type for unwrapping `Stub`s later.
14238 interface StubBase<T extends Stubable> extends Disposable {
14239 [__RPC_STUB_BRAND]: T;
14240 dup(): this;
14241 }
14242 export type Stub<T extends Stubable> = Provider<T> & StubBase<T>;
14243 // This represents all the types that can be sent as-is over an RPC boundary
14244 type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | ReadableStream<Uint8Array> | WritableStream<Uint8Array> | Request | Response | Headers;
14245 // Recursively rewrite all `Stubable` types with `Stub`s
14246 // prettier-ignore
14247 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 {
14248 [key: string | number]: any;
14249 } ? {
14250 [K in keyof T]: Stubify<T[K]>;
14251 } : T;
14252 // Recursively rewrite all `Stub<T>`s with the corresponding `T`s.
14253 // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies:
14254 // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`.
14255 // prettier-ignore
14256 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 {
14257 [key: string | number]: unknown;
14258 } ? {
14259 [K in keyof T]: Unstubify<T[K]>;
14260 } : T;
14261 type UnstubifyAll<A extends any[]> = {
14262 [I in keyof A]: Unstubify<A[I]>;
14263 };
14264 // Utility type for adding `Provider`/`Disposable`s to `object` types only.
14265 // Note `unknown & T` is equivalent to `T`.
14266 type MaybeProvider<T> = T extends object ? Provider<T> : unknown;
14267 type MaybeDisposable<T> = T extends object ? Disposable : unknown;
14268 // Type for method return or property on an RPC interface.
14269 // - Stubable types are replaced by stubs.
14270 // - Serializable types are passed by value, with stubable types replaced by stubs
14271 // and a top-level `Disposer`.
14272 // Everything else can't be passed over PRC.
14273 // Technically, we use custom thenables here, but they quack like `Promise`s.
14274 // Intersecting with `(Maybe)Provider` allows pipelining.
14275 // prettier-ignore
14276 type Result<R> = R extends Stubable ? Promise<Stub<R>> & Provider<R> : R extends Serializable<R> ? Promise<Stubify<R> & MaybeDisposable<R>> & MaybeProvider<R> : never;
14277 // Type for method or property on an RPC interface.
14278 // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
14279 // Unwrapping `Stub`s allows calling with `Stubable` arguments.
14280 // For properties, rewrite types to be `Result`s.
14281 // In each case, unwrap `Promise`s.
14282 type MethodOrProperty<V> = V extends (...args: infer P) => infer R ? (...args: UnstubifyAll<P>) => Result<Awaited<R>> : Result<Awaited<V>>;
14283 // Type for the callable part of an `Provider` if `T` is callable.
14284 // This is intersected with methods/properties.
14285 type MaybeCallableProvider<T> = T extends (...args: any[]) => any ? MethodOrProperty<T> : unknown;
14286 // Base type for all other types providing RPC-like interfaces.
14287 // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
14288 // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC.
14289 export type Provider<T extends object, Reserved extends string = never> = MaybeCallableProvider<T> & Pick<{
14290 [K in keyof T]: MethodOrProperty<T[K]>;
14291 }, Exclude<keyof T, Reserved | symbol | keyof StubBase<never>>>;
14292}
14293declare namespace Cloudflare {
14294 // Type of `env`.
14295 //
14296 // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript
14297 // will merge all declarations.
14298 //
14299 // You can use `wrangler types` to generate the `Env` type automatically.
14300 interface Env {
14301 }
14302 // Project-specific parameters used to inform types.
14303 //
14304 // This interface is, again, intended to be declared in project-specific files, and then that
14305 // declaration will be merged with this one.
14306 //
14307 // A project should have a declaration like this:
14308 //
14309 // interface GlobalProps {
14310 // // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type
14311 // // of `ctx.exports`.
14312 // mainModule: typeof import("my-main-module");
14313 //
14314 // // Declares which of the main module's exports are configured with durable storage, and
14315 // // thus should behave as Durable Object namsepace bindings.
14316 // durableNamespaces: "MyDurableObject" | "AnotherDurableObject";
14317 // }
14318 //
14319 // You can use `wrangler types` to generate `GlobalProps` automatically.
14320 interface GlobalProps {
14321 }
14322 // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not
14323 // present.
14324 type GlobalProp<K extends string, Default> = K extends keyof GlobalProps ? GlobalProps[K] : Default;
14325 // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the
14326 // `mainModule` property.
14327 type MainModule = GlobalProp<"mainModule", {}>;
14328 // The type of ctx.exports, which contains loopback bindings for all top-level exports.
14329 type Exports = {
14330 [K in keyof MainModule]: LoopbackForExport<MainModule[K]>
14331 // If the export is listed in `durableNamespaces`, then it is also a
14332 // DurableObjectNamespace.
14333 & (K extends GlobalProp<"durableNamespaces", never> ? MainModule[K] extends new (...args: any[]) => infer DoInstance ? DoInstance extends Rpc.DurableObjectBranded ? DurableObjectNamespace<DoInstance> : DurableObjectNamespace<undefined> : DurableObjectNamespace<undefined> : {});
14334 };
14335}
14336declare namespace CloudflareWorkersModule {
14337 export type RpcStub<T extends Rpc.Stubable> = Rpc.Stub<T>;
14338 export const RpcStub: {
14339 new <T extends Rpc.Stubable>(value: T): Rpc.Stub<T>;
14340 };
14341 export abstract class RpcTarget implements Rpc.RpcTargetBranded {
14342 [Rpc.__RPC_TARGET_BRAND]: never;
14343 }
14344 // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC
14345 export abstract class WorkerEntrypoint<Env = Cloudflare.Env, Props = {}> implements Rpc.WorkerEntrypointBranded {
14346 [Rpc.__WORKER_ENTRYPOINT_BRAND]: never;
14347 protected ctx: ExecutionContext<Props>;
14348 protected env: Env;
14349 constructor(ctx: ExecutionContext, env: Env);
14350 email?(message: ForwardableEmailMessage): void | Promise<void>;
14351 fetch?(request: Request): Response | Promise<Response>;
14352 connect?(socket: Socket): void | Promise<void>;
14353 queue?(batch: MessageBatch): void | Promise<void>;
14354 scheduled?(controller: ScheduledController): void | Promise<void>;
14355 tail?(events: TraceItem[]): void | Promise<void>;
14356 tailStream?(event: TailStream.TailEvent<TailStream.Onset>): TailStream.TailEventHandlerType | undefined | Promise<TailStream.TailEventHandlerType | undefined>;
14357 test?(controller: TestController): void | Promise<void>;
14358 trace?(traces: TraceItem[]): void | Promise<void>;
14359 }
14360 export abstract class DurableObject<Env = Cloudflare.Env, Props = {}> implements Rpc.DurableObjectBranded {
14361 [Rpc.__DURABLE_OBJECT_BRAND]: never;
14362 protected ctx: DurableObjectState<Props>;
14363 protected env: Env;
14364 constructor(ctx: DurableObjectState, env: Env);
14365 alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise<void>;
14366 fetch?(request: Request): Response | Promise<Response>;
14367 connect?(socket: Socket): void | Promise<void>;
14368 webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise<void>;
14369 webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise<void>;
14370 webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>;
14371 }
14372 export type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';
14373 export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number;
14374 export type WorkflowDelayDuration = WorkflowSleepDuration;
14375 export type WorkflowDynamicDelayContext = {
14376 ctx: WorkflowStepContext<WorkflowDelayFunction>;
14377 error: Error;
14378 };
14379 export type WorkflowDelayFunction = (input: WorkflowDynamicDelayContext) => WorkflowDelayDuration | Promise<WorkflowDelayDuration>;
14380 export type WorkflowTimeoutDuration = WorkflowSleepDuration;
14381 export type WorkflowRetentionDuration = WorkflowSleepDuration;
14382 export type WorkflowBackoff = 'constant' | 'linear' | 'exponential';
14383 export type WorkflowStepSensitivity = 'output';
14384 export type WorkflowStepConfig = {
14385 retries?: {
14386 limit: number;
14387 delay: WorkflowDelayDuration | number | WorkflowDelayFunction;
14388 backoff?: WorkflowBackoff;
14389 };
14390 timeout?: WorkflowTimeoutDuration | number;
14391 sensitive?: WorkflowStepSensitivity;
14392 };
14393 // Internal discriminators used only for `WorkflowStep.do` overload
14394 // resolution. They mirror `WorkflowStepConfig` but pin `retries.delay` to a
14395 // single kind so the callback context can be narrowed based on the shape of
14396 // the config argument (rather than on an inferred type parameter, which is
14397 // lost when the caller supplies an explicit return-type argument). Not
14398 // exported: they must not widen the public type surface.
14399 type WorkflowStepConfigWithStaticDelay = Omit<WorkflowStepConfig, 'retries'> & {
14400 retries?: {
14401 limit: number;
14402 delay: WorkflowDelayDuration | number;
14403 backoff?: WorkflowBackoff;
14404 };
14405 };
14406 type WorkflowStepConfigWithDelayFunction = Omit<WorkflowStepConfig, 'retries'> & {
14407 retries: {
14408 limit: number;
14409 delay: WorkflowDelayFunction;
14410 backoff?: WorkflowBackoff;
14411 };
14412 };
14413 export type WorkflowStepRollbackConfig = Pick<WorkflowStepConfig, 'retries' | 'timeout'>;
14414 export type WorkflowCronSchedule = {
14415 /** Cron expression that triggered this event. */
14416 cron: string;
14417 /** Timestamp of the scheduled trigger, in milliseconds since the Unix epoch. */
14418 scheduledTime: number;
14419 };
14420 export type WorkflowEvent<T> = {
14421 payload: Readonly<T>;
14422 timestamp: Date;
14423 instanceId: string;
14424 workflowName: string;
14425 schedule?: WorkflowCronSchedule;
14426 };
14427 export type WorkflowStepEvent<T> = {
14428 payload: Readonly<T>;
14429 timestamp: Date;
14430 type: string;
14431 sensitive?: WorkflowStepSensitivity;
14432 };
14433 export type WorkflowStepContext<Delay = WorkflowDelayDuration | number> = {
14434 step: {
14435 name: string;
14436 count: number;
14437 };
14438 attempt: number;
14439 config: {
14440 retries?: {
14441 limit: number;
14442 backoff?: WorkflowBackoff;
14443 } & (Delay extends WorkflowDelayFunction ? {} : {
14444 delay: WorkflowDelayDuration | number;
14445 });
14446 timeout?: WorkflowTimeoutDuration | number;
14447 sensitive?: WorkflowStepSensitivity;
14448 };
14449 };
14450 // The rollback handler receives the step context, so it mirrors the same
14451 // delay discriminant as the step callback: when the step was configured with
14452 // a dynamic delay function the resolved `config.retries.delay` is omitted,
14453 // otherwise it is present. `Delay` is threaded from the `WorkflowStep.do`
14454 // overload that matched the step config.
14455 export type WorkflowRollbackContext<T = unknown, Delay = WorkflowDelayDuration | number> = {
14456 ctx: WorkflowStepContext<Delay>;
14457 error: Error;
14458 output: T | undefined;
14459 /** @deprecated Use `ctx.step.name` and `ctx.step.count` instead. */
14460 stepName: string;
14461 };
14462 export type WorkflowRollbackHandler<T = unknown, Delay = WorkflowDelayDuration | number> = (ctx: WorkflowRollbackContext<T, Delay>) => Promise<void>;
14463 export type WorkflowStepRollbackOptions<T = unknown, Delay = WorkflowDelayDuration | number> = {
14464 rollback: WorkflowRollbackHandler<T, Delay>;
14465 rollbackConfig?: WorkflowStepRollbackConfig;
14466 };
14467 export abstract class WorkflowStep {
14468 do<T extends Rpc.Serializable<T>>(name: string, callback: (ctx: WorkflowStepContext) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T>): Promise<T>;
14469 // The config overloads discriminate on the shape of `config.retries.delay`
14470 // so the callback context reflects whether the resolved delay is present
14471 // (static delay) or omitted (dynamic delay function). Each has a single
14472 // type parameter, so an explicit return-type argument (`do<T>(...)`) still
14473 // resolves here. ORDERING IS LOAD-BEARING: the broad `WorkflowStepConfig`
14474 // fallback MUST remain last, otherwise it shadows the discriminating
14475 // overloads and narrowing is silently lost.
14476 do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfigWithDelayFunction, callback: (ctx: WorkflowStepContext<WorkflowDelayFunction>) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T, WorkflowDelayFunction>): Promise<T>;
14477 do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfigWithStaticDelay, callback: (ctx: WorkflowStepContext<WorkflowDelayDuration | number>) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T, WorkflowDelayDuration | number>): Promise<T>;
14478 do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfig, callback: (ctx: WorkflowStepContext) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T>): Promise<T>;
14479 sleep: (name: string, duration: WorkflowSleepDuration) => Promise<void>;
14480 sleepUntil: (name: string, timestamp: Date | number) => Promise<void>;
14481 waitForEvent<T extends Rpc.Serializable<T>>(name: string, options: {
14482 type: string;
14483 timeout?: WorkflowTimeoutDuration | number;
14484 }): Promise<WorkflowStepEvent<T>>;
14485 }
14486 export type WorkflowInstanceStatus = 'queued' | 'running' | 'paused' | 'errored' | 'terminated' | 'complete' | 'waiting' | 'waitingForPause' | 'unknown';
14487 export abstract class WorkflowEntrypoint<Env = unknown, T extends Rpc.Serializable<T> | unknown = unknown> implements Rpc.WorkflowEntrypointBranded {
14488 [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never;
14489 protected ctx: ExecutionContext;
14490 protected env: Env;
14491 constructor(ctx: ExecutionContext, env: Env);
14492 run(event: Readonly<WorkflowEvent<T>>, step: WorkflowStep): Promise<unknown>;
14493 }
14494 export function waitUntil(promise: Promise<unknown>): void;
14495 export function withEnv(newEnv: unknown, fn: () => unknown): unknown;
14496 export function withExports(newExports: unknown, fn: () => unknown): unknown;
14497 export function withEnvAndExports(newEnv: unknown, newExports: unknown, fn: () => unknown): unknown;
14498 export const env: Cloudflare.Env;
14499 export const exports: Cloudflare.Exports;
14500 export const cache: CacheContext;
14501 export const tracing: Tracing;
14502}
14503declare module 'cloudflare:workers' {
14504 export = CloudflareWorkersModule;
14505}
14506interface SecretsStoreSecret {
14507 /**
14508 * Get a secret from the Secrets Store, returning a string of the secret value
14509 * if it exists, or throws an error if it does not exist
14510 */
14511 get(): Promise<string>;
14512}
14513declare module "cloudflare:sockets" {
14514 function _connect(address: string | SocketAddress, options?: SocketOptions): Socket;
14515 export { _connect as connect };
14516}
14517/**
14518 * Binding entrypoint for Cloudflare Stream.
14519 *
14520 * Usage:
14521 * - Binding-level operations:
14522 * `await env.STREAM.videos.upload`
14523 * `await env.STREAM.videos.createDirectUpload`
14524 * `await env.STREAM.videos.*`
14525 * `await env.STREAM.watermarks.*`
14526 * - Per-video operations:
14527 * `await env.STREAM.video(id).downloads.*`
14528 * `await env.STREAM.video(id).captions.*`
14529 *
14530 * Example usage:
14531 * ```ts
14532 * await env.STREAM.video(id).downloads.generate();
14533 *
14534 * const video = env.STREAM.video(id)
14535 * const captions = video.captions.list();
14536 * const videoDetails = video.details()
14537 * ```
14538 */
14539interface StreamBinding {
14540 /**
14541 * Returns a handle scoped to a single video for per-video operations.
14542 * @param id The unique identifier for the video.
14543 * @returns A handle for per-video operations.
14544 */
14545 video(id: string): StreamVideoHandle;
14546 /**
14547 * Uploads a new video from a provided URL.
14548 * @param url The URL to upload from.
14549 * @param params Optional upload parameters.
14550 * @returns The uploaded video details.
14551 * @throws {BadRequestError} if the upload parameter is invalid or the URL is invalid
14552 * @throws {QuotaReachedError} if the account storage capacity is exceeded
14553 * @throws {MaxFileSizeError} if the file size is too large
14554 * @throws {RateLimitedError} if the server received too many requests
14555 * @throws {AlreadyUploadedError} if a video was already uploaded to this URL
14556 * @throws {InternalError} if an unexpected error occurs
14557 */
14558 upload(url: string, params?: StreamUrlUploadParams): Promise<StreamVideo>;
14559 /**
14560 * Creates a direct upload that allows video uploads without an API key.
14561 * @param params Parameters for the direct upload
14562 * @returns The direct upload details.
14563 * @throws {BadRequestError} if the parameters are invalid
14564 * @throws {RateLimitedError} if the server received too many requests
14565 * @throws {InternalError} if an unexpected error occurs
14566 */
14567 createDirectUpload(params: StreamDirectUploadCreateParams): Promise<StreamDirectUpload>;
14568 videos: StreamVideos;
14569 watermarks: StreamWatermarks;
14570}
14571/**
14572 * Handle for operations scoped to a single Stream video.
14573 */
14574interface StreamVideoHandle {
14575 /**
14576 * The unique identifier for the video.
14577 */
14578 id: string;
14579 /**
14580 * Get a full videos details
14581 * @returns The full video details.
14582 * @throws {NotFoundError} if the video is not found
14583 * @throws {InternalError} if an unexpected error occurs
14584 */
14585 details(): Promise<StreamVideo>;
14586 /**
14587 * Update details for a single video.
14588 * @param params The fields to update for the video.
14589 * @returns The updated video details.
14590 * @throws {NotFoundError} if the video is not found
14591 * @throws {BadRequestError} if the parameters are invalid
14592 * @throws {InternalError} if an unexpected error occurs
14593 */
14594 update(params: StreamUpdateVideoParams): Promise<StreamVideo>;
14595 /**
14596 * Deletes a video and its copies from Cloudflare Stream.
14597 * @returns A promise that resolves when deletion completes.
14598 * @throws {NotFoundError} if the video is not found
14599 * @throws {InternalError} if an unexpected error occurs
14600 */
14601 delete(): Promise<void>;
14602 /**
14603 * Creates a signed URL token for a video.
14604 * @returns The signed token that was created.
14605 * @throws {InternalError} if the signing key cannot be retrieved or the token cannot be signed
14606 */
14607 generateToken(): Promise<string>;
14608 downloads: StreamScopedDownloads;
14609 captions: StreamScopedCaptions;
14610}
14611interface StreamVideo {
14612 /**
14613 * The unique identifier for the video.
14614 */
14615 id: string;
14616 /**
14617 * A user-defined identifier for the media creator.
14618 */
14619 creator: string | null;
14620 /**
14621 * The thumbnail URL for the video.
14622 */
14623 thumbnail: string;
14624 /**
14625 * The thumbnail timestamp percentage.
14626 */
14627 thumbnailTimestampPct: number;
14628 /**
14629 * Indicates whether the video is ready to stream.
14630 */
14631 readyToStream: boolean;
14632 /**
14633 * The date and time the video became ready to stream.
14634 */
14635 readyToStreamAt: string | null;
14636 /**
14637 * Processing status information.
14638 */
14639 status: StreamVideoStatus;
14640 /**
14641 * A user modifiable key-value store.
14642 */
14643 meta: Record<string, string>;
14644 /**
14645 * The date and time the video was created.
14646 */
14647 created: string;
14648 /**
14649 * The date and time the video was last modified.
14650 */
14651 modified: string;
14652 /**
14653 * The date and time at which the video will be deleted.
14654 */
14655 scheduledDeletion: string | null;
14656 /**
14657 * The size of the video in bytes.
14658 */
14659 size: number;
14660 /**
14661 * The preview URL for the video.
14662 */
14663 preview?: string;
14664 /**
14665 * Origins allowed to display the video.
14666 */
14667 allowedOrigins: Array<string>;
14668 /**
14669 * Indicates whether signed URLs are required.
14670 */
14671 requireSignedURLs: boolean | null;
14672 /**
14673 * The date and time the video was uploaded.
14674 */
14675 uploaded: string | null;
14676 /**
14677 * The date and time when the upload URL expires.
14678 */
14679 uploadExpiry: string | null;
14680 /**
14681 * The maximum size in bytes for direct uploads.
14682 */
14683 maxSizeBytes: number | null;
14684 /**
14685 * The maximum duration in seconds for direct uploads.
14686 */
14687 maxDurationSeconds: number | null;
14688 /**
14689 * The video duration in seconds. -1 indicates unknown.
14690 */
14691 duration: number;
14692 /**
14693 * Input metadata for the original upload.
14694 */
14695 input: StreamVideoInput;
14696 /**
14697 * Playback URLs for the video.
14698 */
14699 hlsPlaybackUrl: string;
14700 dashPlaybackUrl: string;
14701 /**
14702 * The watermark applied to the video, if any.
14703 */
14704 watermark: StreamWatermark | null;
14705 /**
14706 * The live input id associated with the video, if any.
14707 */
14708 liveInputId?: string | null;
14709 /**
14710 * The source video id if this is a clip.
14711 */
14712 clippedFromId: string | null;
14713 /**
14714 * Public details associated with the video.
14715 */
14716 publicDetails: StreamPublicDetails | null;
14717}
14718type StreamVideoStatus = {
14719 /**
14720 * The current processing state.
14721 */
14722 state: string;
14723 /**
14724 * The current processing step.
14725 */
14726 step?: string;
14727 /**
14728 * The percent complete as a string.
14729 */
14730 pctComplete?: string;
14731 /**
14732 * An error reason code, if applicable.
14733 */
14734 errorReasonCode: string;
14735 /**
14736 * An error reason text, if applicable.
14737 */
14738 errorReasonText: string;
14739};
14740type StreamVideoInput = {
14741 /**
14742 * The input width in pixels.
14743 */
14744 width: number;
14745 /**
14746 * The input height in pixels.
14747 */
14748 height: number;
14749};
14750type StreamPublicDetails = {
14751 /**
14752 * The public title for the video.
14753 */
14754 title: string | null;
14755 /**
14756 * The public share link.
14757 */
14758 share_link: string | null;
14759 /**
14760 * The public channel link.
14761 */
14762 channel_link: string | null;
14763 /**
14764 * The public logo URL.
14765 */
14766 logo: string | null;
14767};
14768type StreamDirectUpload = {
14769 /**
14770 * The URL an unauthenticated upload can use for a single multipart request.
14771 */
14772 uploadURL: string;
14773 /**
14774 * A Cloudflare-generated unique identifier for a media item.
14775 */
14776 id: string;
14777 /**
14778 * The watermark profile applied to the upload.
14779 */
14780 watermark: StreamWatermark | null;
14781 /**
14782 * The scheduled deletion time, if any.
14783 */
14784 scheduledDeletion: string | null;
14785};
14786type StreamDirectUploadCreateParams = {
14787 /**
14788 * The maximum duration in seconds for a video upload.
14789 */
14790 maxDurationSeconds: number;
14791 /**
14792 * The date and time after upload when videos will not be accepted.
14793 */
14794 expiry?: string;
14795 /**
14796 * A user-defined identifier for the media creator.
14797 */
14798 creator?: string;
14799 /**
14800 * A user modifiable key-value store used to reference other systems of record for
14801 * managing videos.
14802 */
14803 meta?: Record<string, string>;
14804 /**
14805 * Lists the origins allowed to display the video.
14806 */
14807 allowedOrigins?: Array<string>;
14808 /**
14809 * Indicates whether the video can be accessed using the id. When set to `true`,
14810 * a signed token must be generated with a signing key to view the video.
14811 */
14812 requireSignedURLs?: boolean;
14813 /**
14814 * The thumbnail timestamp percentage.
14815 */
14816 thumbnailTimestampPct?: number;
14817 /**
14818 * The date and time at which the video will be deleted. Include `null` to remove
14819 * a scheduled deletion.
14820 */
14821 scheduledDeletion?: string | null;
14822 /**
14823 * The watermark profile to apply.
14824 */
14825 watermark?: StreamDirectUploadWatermark;
14826};
14827type StreamDirectUploadWatermark = {
14828 /**
14829 * The unique identifier for the watermark profile.
14830 */
14831 id: string;
14832};
14833type StreamUrlUploadParams = {
14834 /**
14835 * Lists the origins allowed to display the video. Enter allowed origin
14836 * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the
14837 * video to be viewed on any origin.
14838 */
14839 allowedOrigins?: Array<string>;
14840 /**
14841 * A user-defined identifier for the media creator.
14842 */
14843 creator?: string;
14844 /**
14845 * A user modifiable key-value store used to reference other systems of
14846 * record for managing videos.
14847 */
14848 meta?: Record<string, string>;
14849 /**
14850 * Indicates whether the video can be a accessed using the id. When
14851 * set to `true`, a signed token must be generated with a signing key to view the
14852 * video.
14853 */
14854 requireSignedURLs?: boolean;
14855 /**
14856 * Indicates the date and time at which the video will be deleted. Omit
14857 * the field to indicate no change, or include with a `null` value to remove an
14858 * existing scheduled deletion. If specified, must be at least 30 days from upload
14859 * time.
14860 */
14861 scheduledDeletion?: string | null;
14862 /**
14863 * The timestamp for a thumbnail image calculated as a percentage value
14864 * of the video's duration. To convert from a second-wise timestamp to a
14865 * percentage, divide the desired timestamp by the total duration of the video. If
14866 * this value is not set, the default thumbnail image is taken from 0s of the
14867 * video.
14868 */
14869 thumbnailTimestampPct?: number;
14870 /**
14871 * The identifier for the watermark profile
14872 */
14873 watermarkId?: string;
14874};
14875interface StreamScopedCaptions {
14876 /**
14877 * Uploads the caption or subtitle file to the endpoint for a specific BCP47 language.
14878 * One caption or subtitle file per language is allowed.
14879 * @param language The BCP 47 language tag for the caption or subtitle.
14880 * @param input The caption or subtitle stream to upload.
14881 * @returns The created caption entry.
14882 * @throws {NotFoundError} if the video is not found
14883 * @throws {BadRequestError} if the language or file is invalid
14884 * @throws {InternalError} if an unexpected error occurs
14885 */
14886 upload(language: string, input: ReadableStream): Promise<StreamCaption>;
14887 /**
14888 * Generate captions or subtitles for the provided language via AI.
14889 * @param language The BCP 47 language tag to generate.
14890 * @returns The generated caption entry.
14891 * @throws {NotFoundError} if the video is not found
14892 * @throws {BadRequestError} if the language is invalid
14893 * @throws {StreamError} if a generated caption already exists
14894 * @throws {StreamError} if the video duration is too long
14895 * @throws {StreamError} if the video is missing audio
14896 * @throws {StreamError} if the requested language is not supported
14897 * @throws {InternalError} if an unexpected error occurs
14898 */
14899 generate(language: string): Promise<StreamCaption>;
14900 /**
14901 * Lists the captions or subtitles.
14902 * Use the language parameter to filter by a specific language.
14903 * @param language The optional BCP 47 language tag to filter by.
14904 * @returns The list of captions or subtitles.
14905 * @throws {NotFoundError} if the video or caption is not found
14906 * @throws {InternalError} if an unexpected error occurs
14907 */
14908 list(language?: string): Promise<StreamCaption[]>;
14909 /**
14910 * Removes the captions or subtitles from a video.
14911 * @param language The BCP 47 language tag to remove.
14912 * @returns A promise that resolves when deletion completes.
14913 * @throws {NotFoundError} if the video or caption is not found
14914 * @throws {InternalError} if an unexpected error occurs
14915 */
14916 delete(language: string): Promise<void>;
14917}
14918interface StreamScopedDownloads {
14919 /**
14920 * Generates a download for a video when a video is ready to view. Available
14921 * types are `default` and `audio`. Defaults to `default` when omitted.
14922 * @param downloadType The download type to create.
14923 * @returns The current downloads for the video.
14924 * @throws {NotFoundError} if the video is not found
14925 * @throws {BadRequestError} if the download type is invalid
14926 * @throws {StreamError} if the video duration is too long to generate a download
14927 * @throws {StreamError} if the video is not ready to stream
14928 * @throws {InternalError} if an unexpected error occurs
14929 */
14930 generate(downloadType?: StreamDownloadType): Promise<StreamDownloadGetResponse>;
14931 /**
14932 * Lists the downloads created for a video.
14933 * @returns The current downloads for the video.
14934 * @throws {NotFoundError} if the video or downloads are not found
14935 * @throws {InternalError} if an unexpected error occurs
14936 */
14937 get(): Promise<StreamDownloadGetResponse>;
14938 /**
14939 * Delete the downloads for a video. Available types are `default` and `audio`.
14940 * Defaults to `default` when omitted.
14941 * @param downloadType The download type to delete.
14942 * @returns A promise that resolves when deletion completes.
14943 * @throws {NotFoundError} if the video or downloads are not found
14944 * @throws {InternalError} if an unexpected error occurs
14945 */
14946 delete(downloadType?: StreamDownloadType): Promise<void>;
14947}
14948interface StreamVideos {
14949 /**
14950 * Lists all videos in a users account.
14951 * @returns The list of videos.
14952 * @throws {BadRequestError} if the parameters are invalid
14953 * @throws {InternalError} if an unexpected error occurs
14954 */
14955 list(params?: StreamVideosListParams): Promise<StreamVideo[]>;
14956}
14957interface StreamWatermarks {
14958 /**
14959 * Generate a new watermark profile
14960 * @param input The image stream to upload
14961 * @param params The watermark creation parameters.
14962 * @returns The created watermark profile.
14963 * @throws {BadRequestError} if the parameters are invalid
14964 * @throws {InvalidURLError} if the URL is invalid
14965 * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached
14966 * @throws {InternalError} if an unexpected error occurs
14967 */
14968 generate(input: ReadableStream, params: StreamWatermarkCreateParams): Promise<StreamWatermark>;
14969 /**
14970 * Generate a new watermark profile
14971 * @param url The image url to upload
14972 * @param params The watermark creation parameters.
14973 * @returns The created watermark profile.
14974 * @throws {BadRequestError} if the parameters are invalid
14975 * @throws {InvalidURLError} if the URL is invalid
14976 * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached
14977 * @throws {InternalError} if an unexpected error occurs
14978 */
14979 generate(url: string, params: StreamWatermarkCreateParams): Promise<StreamWatermark>;
14980 /**
14981 * Lists all watermark profiles for an account.
14982 * @returns The list of watermark profiles.
14983 * @throws {InternalError} if an unexpected error occurs
14984 */
14985 list(): Promise<StreamWatermark[]>;
14986 /**
14987 * Retrieves details for a single watermark profile.
14988 * @param watermarkId The watermark profile identifier.
14989 * @returns The watermark profile details.
14990 * @throws {NotFoundError} if the watermark is not found
14991 * @throws {InternalError} if an unexpected error occurs
14992 */
14993 get(watermarkId: string): Promise<StreamWatermark>;
14994 /**
14995 * Deletes a watermark profile.
14996 * @param watermarkId The watermark profile identifier.
14997 * @returns A promise that resolves when deletion completes.
14998 * @throws {NotFoundError} if the watermark is not found
14999 * @throws {InternalError} if an unexpected error occurs
15000 */
15001 delete(watermarkId: string): Promise<void>;
15002}
15003type StreamUpdateVideoParams = {
15004 /**
15005 * Lists the origins allowed to display the video. Enter allowed origin
15006 * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the
15007 * video to be viewed on any origin.
15008 */
15009 allowedOrigins?: Array<string>;
15010 /**
15011 * A user-defined identifier for the media creator.
15012 */
15013 creator?: string;
15014 /**
15015 * The maximum duration in seconds for a video upload. Can be set for a
15016 * video that is not yet uploaded to limit its duration. Uploads that exceed the
15017 * specified duration will fail during processing. A value of `-1` means the value
15018 * is unknown.
15019 */
15020 maxDurationSeconds?: number;
15021 /**
15022 * A user modifiable key-value store used to reference other systems of
15023 * record for managing videos.
15024 */
15025 meta?: Record<string, string>;
15026 /**
15027 * Indicates whether the video can be a accessed using the id. When
15028 * set to `true`, a signed token must be generated with a signing key to view the
15029 * video.
15030 */
15031 requireSignedURLs?: boolean;
15032 /**
15033 * Indicates the date and time at which the video will be deleted. Omit
15034 * the field to indicate no change, or include with a `null` value to remove an
15035 * existing scheduled deletion. If specified, must be at least 30 days from upload
15036 * time.
15037 */
15038 scheduledDeletion?: string | null;
15039 /**
15040 * The timestamp for a thumbnail image calculated as a percentage value
15041 * of the video's duration. To convert from a second-wise timestamp to a
15042 * percentage, divide the desired timestamp by the total duration of the video. If
15043 * this value is not set, the default thumbnail image is taken from 0s of the
15044 * video.
15045 */
15046 thumbnailTimestampPct?: number;
15047};
15048type StreamCaption = {
15049 /**
15050 * Whether the caption was generated via AI.
15051 */
15052 generated?: boolean;
15053 /**
15054 * The language label displayed in the native language to users.
15055 */
15056 label: string;
15057 /**
15058 * The language tag in BCP 47 format.
15059 */
15060 language: string;
15061 /**
15062 * The status of a generated caption.
15063 */
15064 status?: 'ready' | 'inprogress' | 'error';
15065};
15066type StreamDownloadStatus = 'ready' | 'inprogress' | 'error';
15067type StreamDownloadType = 'default' | 'audio';
15068type StreamDownload = {
15069 /**
15070 * Indicates the progress as a percentage between 0 and 100.
15071 */
15072 percentComplete: number;
15073 /**
15074 * The status of a generated download.
15075 */
15076 status: StreamDownloadStatus;
15077 /**
15078 * The URL to access the generated download.
15079 */
15080 url?: string;
15081};
15082/**
15083 * An object with download type keys. Each key is optional and only present if that
15084 * download type has been created.
15085 */
15086type StreamDownloadGetResponse = {
15087 /**
15088 * The audio-only download. Only present if this download type has been created.
15089 */
15090 audio?: StreamDownload;
15091 /**
15092 * The default video download. Only present if this download type has been created.
15093 */
15094 default?: StreamDownload;
15095};
15096type StreamWatermarkPosition = 'upperRight' | 'upperLeft' | 'lowerLeft' | 'lowerRight' | 'center';
15097type StreamWatermark = {
15098 /**
15099 * The unique identifier for a watermark profile.
15100 */
15101 id: string;
15102 /**
15103 * The size of the image in bytes.
15104 */
15105 size: number;
15106 /**
15107 * The height of the image in pixels.
15108 */
15109 height: number;
15110 /**
15111 * The width of the image in pixels.
15112 */
15113 width: number;
15114 /**
15115 * The date and a time a watermark profile was created.
15116 */
15117 created: string;
15118 /**
15119 * The source URL for a downloaded image. If the watermark profile was created via
15120 * direct upload, this field is null.
15121 */
15122 downloadedFrom: string | null;
15123 /**
15124 * A short description of the watermark profile.
15125 */
15126 name: string;
15127 /**
15128 * The translucency of the image. A value of `0.0` makes the image completely
15129 * transparent, and `1.0` makes the image completely opaque. Note that if the image
15130 * is already semi-transparent, setting this to `1.0` will not make the image
15131 * completely opaque.
15132 */
15133 opacity: number;
15134 /**
15135 * The whitespace between the adjacent edges (determined by position) of the video
15136 * and the image. `0.0` indicates no padding, and `1.0` indicates a fully padded
15137 * video width or length, as determined by the algorithm.
15138 */
15139 padding: number;
15140 /**
15141 * The size of the image relative to the overall size of the video. This parameter
15142 * will adapt to horizontal and vertical videos automatically. `0.0` indicates no
15143 * scaling (use the size of the image as-is), and `1.0 `fills the entire video.
15144 */
15145 scale: number;
15146 /**
15147 * The location of the image. Valid positions are: `upperRight`, `upperLeft`,
15148 * `lowerLeft`, `lowerRight`, and `center`. Note that `center` ignores the
15149 * `padding` parameter.
15150 */
15151 position: StreamWatermarkPosition;
15152};
15153type StreamWatermarkCreateParams = {
15154 /**
15155 * A short description of the watermark profile.
15156 */
15157 name?: string;
15158 /**
15159 * The translucency of the image. A value of `0.0` makes the image completely
15160 * transparent, and `1.0` makes the image completely opaque. Note that if the
15161 * image is already semi-transparent, setting this to `1.0` will not make the
15162 * image completely opaque.
15163 */
15164 opacity?: number;
15165 /**
15166 * The whitespace between the adjacent edges (determined by position) of the
15167 * video and the image. `0.0` indicates no padding, and `1.0` indicates a fully
15168 * padded video width or length, as determined by the algorithm.
15169 */
15170 padding?: number;
15171 /**
15172 * The size of the image relative to the overall size of the video. This
15173 * parameter will adapt to horizontal and vertical videos automatically. `0.0`
15174 * indicates no scaling (use the size of the image as-is), and `1.0 `fills the
15175 * entire video.
15176 */
15177 scale?: number;
15178 /**
15179 * The location of the image.
15180 */
15181 position?: StreamWatermarkPosition;
15182};
15183type StreamVideosListParams = {
15184 /**
15185 * The maximum number of videos to return.
15186 */
15187 limit?: number;
15188 /**
15189 * Return videos created before this timestamp.
15190 * (RFC3339/RFC3339Nano)
15191 */
15192 before?: string;
15193 /**
15194 * Comparison operator for the `before` field.
15195 * @default 'lt'
15196 */
15197 beforeComp?: StreamPaginationComparison;
15198 /**
15199 * Return videos created after this timestamp.
15200 * (RFC3339/RFC3339Nano)
15201 */
15202 after?: string;
15203 /**
15204 * Comparison operator for the `after` field.
15205 * @default 'gte'
15206 */
15207 afterComp?: StreamPaginationComparison;
15208};
15209type StreamPaginationComparison = 'eq' | 'gt' | 'gte' | 'lt' | 'lte';
15210/**
15211 * Error object for Stream binding operations.
15212 */
15213interface StreamError extends Error {
15214 readonly code: number;
15215 readonly statusCode: number;
15216 readonly message: string;
15217 readonly stack?: string;
15218}
15219interface InternalError extends StreamError {
15220 name: 'InternalError';
15221}
15222interface BadRequestError extends StreamError {
15223 name: 'BadRequestError';
15224}
15225interface NotFoundError extends StreamError {
15226 name: 'NotFoundError';
15227}
15228interface ForbiddenError extends StreamError {
15229 name: 'ForbiddenError';
15230}
15231interface RateLimitedError extends StreamError {
15232 name: 'RateLimitedError';
15233}
15234interface QuotaReachedError extends StreamError {
15235 name: 'QuotaReachedError';
15236}
15237interface MaxFileSizeError extends StreamError {
15238 name: 'MaxFileSizeError';
15239}
15240interface InvalidURLError extends StreamError {
15241 name: 'InvalidURLError';
15242}
15243interface AlreadyUploadedError extends StreamError {
15244 name: 'AlreadyUploadedError';
15245}
15246interface TooManyWatermarksError extends StreamError {
15247 name: 'TooManyWatermarksError';
15248}
15249type MarkdownDocument = {
15250 name: string;
15251 blob: Blob;
15252};
15253type OutputFormat = 'markdown' | 'text';
15254type ConversionResponse = {
15255 id: string;
15256 name: string;
15257 mimeType: string;
15258 format: OutputFormat;
15259 tokens: number;
15260 data: string;
15261} | {
15262 id: string;
15263 name: string;
15264 mimeType: string;
15265 format: 'error';
15266 error: string;
15267};
15268type ImageConversionOptions = {
15269 descriptionLanguage?: 'en' | 'es' | 'fr' | 'it' | 'pt' | 'de';
15270};
15271type EmbeddedImageConversionOptions = ImageConversionOptions & {
15272 convert?: boolean;
15273 maxConvertedImages?: number;
15274};
15275type ConversionOutputOptions = {
15276 format?: OutputFormat;
15277};
15278type ConversionOptions = {
15279 output?: ConversionOutputOptions;
15280 html?: {
15281 images?: EmbeddedImageConversionOptions & {
15282 convertOGImage?: boolean;
15283 };
15284 hostname?: string;
15285 cssSelector?: string;
15286 };
15287 docx?: {
15288 images?: EmbeddedImageConversionOptions;
15289 };
15290 image?: ImageConversionOptions;
15291 pdf?: {
15292 images?: EmbeddedImageConversionOptions;
15293 metadata?: boolean;
15294 };
15295};
15296type ConversionRequestOptions = {
15297 gateway?: GatewayOptions;
15298 extraHeaders?: object;
15299 conversionOptions?: ConversionOptions;
15300};
15301type SupportedFileFormat = {
15302 mimeType: string;
15303 extension: string;
15304};
15305declare abstract class ToMarkdownService {
15306 transform(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise<ConversionResponse[]>;
15307 transform(files: MarkdownDocument, options?: ConversionRequestOptions): Promise<ConversionResponse>;
15308 supported(): Promise<SupportedFileFormat[]>;
15309}
15310declare namespace TailStream {
15311 interface Header {
15312 readonly name: string;
15313 readonly value: string;
15314 }
15315 interface FetchEventInfo {
15316 readonly type: "fetch";
15317 readonly method: string;
15318 readonly url: string;
15319 readonly cfJson?: object;
15320 readonly headers: Header[];
15321 }
15322 interface JsRpcEventInfo {
15323 readonly type: "jsrpc";
15324 }
15325 interface ScheduledEventInfo {
15326 readonly type: "scheduled";
15327 readonly scheduledTime: Date;
15328 readonly cron: string;
15329 }
15330 interface AlarmEventInfo {
15331 readonly type: "alarm";
15332 readonly scheduledTime: Date;
15333 }
15334 interface QueueEventInfo {
15335 readonly type: "queue";
15336 readonly queueName: string;
15337 readonly batchSize: number;
15338 }
15339 interface EmailEventInfo {
15340 readonly type: "email";
15341 readonly mailFrom: string;
15342 readonly rcptTo: string;
15343 readonly rawSize: number;
15344 }
15345 interface TraceEventInfo {
15346 readonly type: "trace";
15347 readonly traces: (string | null)[];
15348 }
15349 interface HibernatableWebSocketEventInfoMessage {
15350 readonly type: "message";
15351 }
15352 interface HibernatableWebSocketEventInfoError {
15353 readonly type: "error";
15354 }
15355 interface HibernatableWebSocketEventInfoClose {
15356 readonly type: "close";
15357 readonly code: number;
15358 readonly wasClean: boolean;
15359 }
15360 interface HibernatableWebSocketEventInfo {
15361 readonly type: "hibernatableWebSocket";
15362 readonly info: HibernatableWebSocketEventInfoClose | HibernatableWebSocketEventInfoError | HibernatableWebSocketEventInfoMessage;
15363 }
15364 interface CustomEventInfo {
15365 readonly type: "custom";
15366 }
15367 interface FetchResponseInfo {
15368 readonly type: "fetch";
15369 readonly statusCode: number;
15370 }
15371 interface ConnectEventInfo {
15372 readonly type: "connect";
15373 }
15374 type EventOutcome = "ok" | "canceled" | "exception" | "unknown" | "killSwitch" | "daemonDown" | "exceededCpu" | "exceededMemory" | "loadShed" | "responseStreamDisconnected" | "scriptNotFound" | "internalError" | "exceededWallTime" | "aborted";
15375 interface ScriptVersion {
15376 readonly id: string;
15377 readonly tag?: string;
15378 readonly message?: string;
15379 }
15380 interface TracePreviewInfo {
15381 readonly id: string;
15382 readonly slug: string;
15383 readonly name: string;
15384 }
15385 interface Onset {
15386 readonly type: "onset";
15387 readonly attributes: Attribute[];
15388 // id for the span being opened by this Onset event.
15389 readonly spanId: string;
15390 readonly dispatchNamespace?: string;
15391 readonly entrypoint?: string;
15392 readonly executionModel: string;
15393 readonly durableObjectId?: string;
15394 readonly scriptName?: string;
15395 readonly scriptTags?: string[];
15396 readonly scriptVersion?: ScriptVersion;
15397 readonly preview?: TracePreviewInfo;
15398 readonly info: FetchEventInfo | ConnectEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | CustomEventInfo;
15399 }
15400 interface Outcome {
15401 readonly type: "outcome";
15402 readonly outcome: EventOutcome;
15403 readonly cpuTime: number;
15404 readonly wallTime: number;
15405 }
15406 type SpanStatusCode = "unset" | "ok" | "error";
15407 interface SpanStatus {
15408 readonly code: SpanStatusCode;
15409 /** A developer-facing error message, present only when code is "error". */
15410 readonly message?: string;
15411 }
15412 interface SpanOpen {
15413 readonly type: "spanOpen";
15414 readonly name: string;
15415 // id for the span being opened by this SpanOpen event.
15416 readonly spanId: string;
15417 readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes;
15418 }
15419 interface SpanClose {
15420 readonly type: "spanClose";
15421 readonly outcome: EventOutcome;
15422 }
15423 type SpanUpdateInfo = {
15424 readonly type: "name";
15425 readonly name: string;
15426 } | {
15427 readonly type: "status";
15428 readonly status: SpanStatus;
15429 };
15430 interface SpanUpdate {
15431 readonly type: "spanUpdate";
15432 readonly info: SpanUpdateInfo;
15433 }
15434 interface DiagnosticChannelEvent {
15435 readonly type: "diagnosticChannel";
15436 readonly channel: string;
15437 readonly message: any;
15438 }
15439 interface Exception {
15440 readonly type: "exception";
15441 readonly code?: string | number;
15442 readonly name: string;
15443 readonly message: string;
15444 readonly stack?: string;
15445 }
15446 interface TailStreamErrorInfo {
15447 readonly name: string;
15448 readonly message: string;
15449 readonly stack?: string;
15450 }
15451 type Log = {
15452 readonly type: "log";
15453 readonly level: "debug" | "error" | "info" | "log" | "warn";
15454 readonly errorInfo?: readonly (TailStreamErrorInfo | null)[];
15455 } & ({
15456 readonly message: object;
15457 readonly truncated?: false;
15458 } | {
15459 readonly message: string;
15460 readonly truncated: true;
15461 });
15462 interface DroppedEventsDiagnostic {
15463 readonly diagnosticsType: "droppedEvents";
15464 readonly count: number;
15465 }
15466 interface StreamDiagnostic {
15467 readonly type: 'streamDiagnostic';
15468 // To add new diagnostic types, define a new interface and add it to this union type.
15469 readonly diagnostic: DroppedEventsDiagnostic;
15470 }
15471 // This marks the worker handler return information.
15472 // This is separate from Outcome because the worker invocation can live for a long time after
15473 // returning. For example - Websockets that return an http upgrade response but then continue
15474 // streaming information or SSE http connections.
15475 interface Return {
15476 readonly type: "return";
15477 readonly info?: FetchResponseInfo;
15478 }
15479 interface Attribute {
15480 readonly name: string;
15481 readonly value: string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[];
15482 }
15483 interface Attributes {
15484 readonly type: "attributes";
15485 readonly info: Attribute[];
15486 }
15487 type EventType = Onset | Outcome | SpanOpen | SpanClose | SpanUpdate | DiagnosticChannelEvent | Exception | Log | StreamDiagnostic | Return | Attributes;
15488 // Context in which this trace event lives.
15489 interface SpanContext {
15490 // Single id for the entire top-level invocation
15491 // This should be a new traceId for the first worker stage invoked in the eyeball request and then
15492 // same-account service-bindings should reuse the same traceId but cross-account service-bindings
15493 // should use a new traceId.
15494 readonly traceId: string;
15495 // spanId in which this event is handled
15496 // for Onset and SpanOpen events this would be the parent span id
15497 // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events
15498 // For Hibernate and Mark this would be the span under which they were emitted.
15499 // spanId is not set ONLY if:
15500 // 1. This is an Onset event
15501 // 2. We are not inheriting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation)
15502 readonly spanId?: string;
15503 // W3C trace flags from an upstream traceparent. Absent when no upstream
15504 // sampling decision was made.
15505 readonly traceFlags?: number;
15506 }
15507 interface TailEvent<Event extends EventType> {
15508 // invocation id of the currently invoked worker stage.
15509 // invocation id will always be unique to every Onset event and will be the same until the Outcome event.
15510 readonly invocationId: string;
15511 // Inherited spanContext for this event.
15512 readonly spanContext: SpanContext;
15513 readonly timestamp: Date;
15514 readonly sequence: number;
15515 readonly event: Event;
15516 }
15517 type TailEventHandler<Event extends EventType = EventType> = (event: TailEvent<Event>) => void | Promise<void>;
15518 type TailEventHandlerObject = {
15519 outcome?: TailEventHandler<Outcome>;
15520 spanOpen?: TailEventHandler<SpanOpen>;
15521 spanClose?: TailEventHandler<SpanClose>;
15522 spanUpdate?: TailEventHandler<SpanUpdate>;
15523 diagnosticChannel?: TailEventHandler<DiagnosticChannelEvent>;
15524 exception?: TailEventHandler<Exception>;
15525 log?: TailEventHandler<Log>;
15526 return?: TailEventHandler<Return>;
15527 attributes?: TailEventHandler<Attributes>;
15528 };
15529 type TailEventHandlerType = TailEventHandler | TailEventHandlerObject;
15530}
15531// Copyright (c) 2022-2023 Cloudflare, Inc.
15532// Licensed under the Apache 2.0 license found in the LICENSE file or at:
15533// https://opensource.org/licenses/Apache-2.0
15534/**
15535 * Data types supported for holding vector metadata.
15536 */
15537type VectorizeVectorMetadataValue = string | number | boolean | string[];
15538/**
15539 * Additional information to associate with a vector.
15540 */
15541type VectorizeVectorMetadata = VectorizeVectorMetadataValue | Record<string, VectorizeVectorMetadataValue>;
15542type VectorFloatArray = Float32Array | Float64Array;
15543interface VectorizeError {
15544 code?: number;
15545 error: string;
15546}
15547/**
15548 * Comparison logic/operation to use for metadata filtering.
15549 *
15550 * This list is expected to grow as support for more operations are released.
15551 */
15552type VectorizeVectorMetadataFilterOp = '$eq' | '$ne' | '$lt' | '$lte' | '$gt' | '$gte';
15553type VectorizeVectorMetadataFilterCollectionOp = '$in' | '$nin';
15554/**
15555 * Filter criteria for vector metadata used to limit the retrieved query result set.
15556 */
15557type VectorizeVectorMetadataFilter = {
15558 [field: string]: Exclude<VectorizeVectorMetadataValue, string[]> | null | {
15559 [Op in VectorizeVectorMetadataFilterOp]?: Exclude<VectorizeVectorMetadataValue, string[]> | null;
15560 } | {
15561 [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude<VectorizeVectorMetadataValue, string[]>[];
15562 };
15563};
15564/**
15565 * Supported distance metrics for an index.
15566 * Distance metrics determine how other "similar" vectors are determined.
15567 */
15568type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product";
15569/**
15570 * Metadata return levels for a Vectorize query.
15571 *
15572 * Default to "none".
15573 *
15574 * @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.
15575 * @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).
15576 * @property none No indexed metadata will be returned.
15577 */
15578type VectorizeMetadataRetrievalLevel = "all" | "indexed" | "none";
15579interface VectorizeQueryOptions {
15580 topK?: number;
15581 namespace?: string;
15582 returnValues?: boolean;
15583 returnMetadata?: boolean | VectorizeMetadataRetrievalLevel;
15584 filter?: VectorizeVectorMetadataFilter;
15585}
15586/**
15587 * Information about the configuration of an index.
15588 */
15589type VectorizeIndexConfig = {
15590 dimensions: number;
15591 metric: VectorizeDistanceMetric;
15592} | {
15593 preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity
15594};
15595/**
15596 * Metadata about an existing index.
15597 *
15598 * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.
15599 * See {@link VectorizeIndexInfo} for its post-beta equivalent.
15600 */
15601interface VectorizeIndexDetails {
15602 /** The unique ID of the index */
15603 readonly id: string;
15604 /** The name of the index. */
15605 name: string;
15606 /** (optional) A human readable description for the index. */
15607 description?: string;
15608 /** The index configuration, including the dimension size and distance metric. */
15609 config: VectorizeIndexConfig;
15610 /** The number of records containing vectors within the index. */
15611 vectorsCount: number;
15612}
15613/**
15614 * Metadata about an existing index.
15615 */
15616interface VectorizeIndexInfo {
15617 /** The number of records containing vectors within the index. */
15618 vectorCount: number;
15619 /** Number of dimensions the index has been configured for. */
15620 dimensions: number;
15621 /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */
15622 processedUpToDatetime: number;
15623 /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */
15624 processedUpToMutation: number;
15625}
15626/**
15627 * Represents a single vector value set along with its associated metadata.
15628 */
15629interface VectorizeVector {
15630 /** 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. */
15631 id: string;
15632 /** The vector values */
15633 values: VectorFloatArray | number[];
15634 /** The namespace this vector belongs to. */
15635 namespace?: string;
15636 /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */
15637 metadata?: Record<string, VectorizeVectorMetadata>;
15638}
15639/**
15640 * Represents a matched vector for a query along with its score and (if specified) the matching vector information.
15641 */
15642type VectorizeMatch = Pick<Partial<VectorizeVector>, "values"> & Omit<VectorizeVector, "values"> & {
15643 /** The score or rank for similarity, when returned as a result */
15644 score: number;
15645};
15646/**
15647 * A set of matching {@link VectorizeMatch} for a particular query.
15648 */
15649interface VectorizeMatches {
15650 matches: VectorizeMatch[];
15651 count: number;
15652}
15653/**
15654 * Results of an operation that performed a mutation on a set of vectors.
15655 * Here, `ids` is a list of vectors that were successfully processed.
15656 *
15657 * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.
15658 * See {@link VectorizeAsyncMutation} for its post-beta equivalent.
15659 */
15660interface VectorizeVectorMutation {
15661 /* List of ids of vectors that were successfully processed. */
15662 ids: string[];
15663 /* Total count of the number of processed vectors. */
15664 count: number;
15665}
15666/**
15667 * Result type indicating a mutation on the Vectorize Index.
15668 * Actual mutations are processed async where the `mutationId` is the unique identifier for the operation.
15669 */
15670interface VectorizeAsyncMutation {
15671 /** The unique identifier for the async mutation operation containing the changeset. */
15672 mutationId: string;
15673}
15674/**
15675 * A Vectorize Vector Search Index for querying vectors/embeddings.
15676 *
15677 * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.
15678 * See {@link Vectorize} for its new implementation.
15679 */
15680declare abstract class VectorizeIndex {
15681 /**
15682 * Get information about the currently bound index.
15683 * @returns A promise that resolves with information about the current index.
15684 */
15685 public describe(): Promise<VectorizeIndexDetails>;
15686 /**
15687 * Use the provided vector to perform a similarity search across the index.
15688 * @param vector Input vector that will be used to drive the similarity search.
15689 * @param options Configuration options to massage the returned data.
15690 * @returns A promise that resolves with matched and scored vectors.
15691 */
15692 public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise<VectorizeMatches>;
15693 /**
15694 * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown.
15695 * @param vectors List of vectors that will be inserted.
15696 * @returns A promise that resolves with the ids & count of records that were successfully processed.
15697 */
15698 public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>;
15699 /**
15700 * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values.
15701 * @param vectors List of vectors that will be upserted.
15702 * @returns A promise that resolves with the ids & count of records that were successfully processed.
15703 */
15704 public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>;
15705 /**
15706 * Delete a list of vectors with a matching id.
15707 * @param ids List of vector ids that should be deleted.
15708 * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted).
15709 */
15710 public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>;
15711 /**
15712 * Get a list of vectors with a matching id.
15713 * @param ids List of vector ids that should be returned.
15714 * @returns A promise that resolves with the raw unscored vectors matching the id set.
15715 */
15716 public getByIds(ids: string[]): Promise<VectorizeVector[]>;
15717}
15718/**
15719 * A Vectorize Vector Search Index for querying vectors/embeddings.
15720 *
15721 * Mutations in this version are async, returning a mutation id.
15722 */
15723declare abstract class Vectorize {
15724 /**
15725 * Get information about the currently bound index.
15726 * @returns A promise that resolves with information about the current index.
15727 */
15728 public describe(): Promise<VectorizeIndexInfo>;
15729 /**
15730 * Use the provided vector to perform a similarity search across the index.
15731 * @param vector Input vector that will be used to drive the similarity search.
15732 * @param options Configuration options to massage the returned data.
15733 * @returns A promise that resolves with matched and scored vectors.
15734 */
15735 public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise<VectorizeMatches>;
15736 /**
15737 * Use the provided vector-id to perform a similarity search across the index.
15738 * @param vectorId Id for a vector in the index against which the index should be queried.
15739 * @param options Configuration options to massage the returned data.
15740 * @returns A promise that resolves with matched and scored vectors.
15741 */
15742 public queryById(vectorId: string, options?: VectorizeQueryOptions): Promise<VectorizeMatches>;
15743 /**
15744 * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown.
15745 * @param vectors List of vectors that will be inserted.
15746 * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset.
15747 */
15748 public insert(vectors: VectorizeVector[]): Promise<VectorizeAsyncMutation>;
15749 /**
15750 * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values.
15751 * @param vectors List of vectors that will be upserted.
15752 * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset.
15753 */
15754 public upsert(vectors: VectorizeVector[]): Promise<VectorizeAsyncMutation>;
15755 /**
15756 * Delete a list of vectors with a matching id.
15757 * @param ids List of vector ids that should be deleted.
15758 * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset.
15759 */
15760 public deleteByIds(ids: string[]): Promise<VectorizeAsyncMutation>;
15761 /**
15762 * Get a list of vectors with a matching id.
15763 * @param ids List of vector ids that should be returned.
15764 * @returns A promise that resolves with the raw unscored vectors matching the id set.
15765 */
15766 public getByIds(ids: string[]): Promise<VectorizeVector[]>;
15767}
15768/**
15769 * The interface for "version_metadata" binding
15770 * providing metadata about the Worker Version using this binding.
15771 */
15772type WorkerVersionMetadata = {
15773 /** The ID of the Worker Version using this binding */
15774 id: string;
15775 /** The tag of the Worker Version using this binding */
15776 tag: string;
15777 /** The timestamp of when the Worker Version was uploaded */
15778 timestamp: string;
15779};
15780// ============ Web Search Request Types ============
15781/**
15782 * Options for a Web Search query.
15783 */
15784type WebSearchSearchOptions = {
15785 /** The search query. */
15786 query: string;
15787 /**
15788 * Maximum number of results to return. Defaults to 10, capped at 20.
15789 * The actual count may be lower if fewer matches exist.
15790 */
15791 limit?: number;
15792};
15793// ============ Web Search Response Types ============
15794/**
15795 * A single Web Search result.
15796 *
15797 * Web Search is discovery-only -- results carry catalog metadata about a page
15798 * but never the page body. To read a result's content the caller invokes the
15799 * global `fetch()` API against the result's `url`, at which point the
15800 * destination's own access controls apply (including Cloudflare Pay-per-Crawl).
15801 */
15802type WebSearchResult = {
15803 /** Canonical URL. */
15804 url: string;
15805 /** Page title. */
15806 title: string;
15807 /** Page-level description. May be absent. */
15808 description?: string;
15809 /**
15810 * Last-modified date for the page, when known. Naive (no timezone)
15811 * ISO-8601 datetime, e.g. `"2025-11-30T04:39:48"`.
15812 */
15813 lastModifiedDate?: string;
15814 /**
15815 * Page meta image URL (typically the `og:image`). May be absent.
15816 */
15817 imageUrl?: string;
15818 /** Optional favicon URL for UI hints. */
15819 faviconUrl?: string;
15820};
15821/**
15822 * Per-response metadata for a Web Search query. Carries operational
15823 * fields useful for support and debugging.
15824 */
15825type WebSearchResponseMetadata = {
15826 /** The query that was executed. */
15827 query: string;
15828 /** Opaque request identifier used for support and debugging. */
15829 requestId: string;
15830 /** End-to-end latency for this search request, in milliseconds. */
15831 latencyMs: number;
15832};
15833/**
15834 * Response from a Web Search query.
15835 */
15836type WebSearchSearchResponse = {
15837 items: WebSearchResult[];
15838 metadata: WebSearchResponseMetadata;
15839};
15840// ============ Web Search Binding Class ============
15841/**
15842 * Cloudflare Web Search binding.
15843 *
15844 * Discovery-only primitive for agents and Workers. Returns URLs and catalog
15845 * metadata for a query; never returns page content or excerpts. To read a
15846 * result's body, fetch the URL with the global `fetch()` API.
15847 *
15848 * Declared in wrangler with a single object (there is exactly one corpus, the
15849 * public web, so there is no name, namespace, or instance to specify):
15850 *
15851 * ```jsonc
15852 * { "web_search": { "binding": "WEBSEARCH" } }
15853 * ```
15854 *
15855 * @example
15856 * ```ts
15857 * const { items, metadata } = await env.WEBSEARCH.search({
15858 * query: "Cloudflare Workers",
15859 * });
15860 *
15861 * const top = items[0];
15862 * console.log(top.url, top.title, metadata.latencyMs);
15863 *
15864 * // Read content yourself; pay-per-crawl and other publisher
15865 * // controls apply at the fetch site, not at search time.
15866 * const page = await fetch(top.url);
15867 * ```
15868 */
15869declare abstract class WebSearch {
15870 /**
15871 * Run a Web Search query.
15872 * @param options Search options. Only `query` is required.
15873 * @returns The matching results plus per-response metadata.
15874 */
15875 search(options: WebSearchSearchOptions): Promise<WebSearchSearchResponse>;
15876}
15877interface DynamicDispatchLimits {
15878 /**
15879 * Limit CPU time in milliseconds.
15880 */
15881 cpuMs?: number;
15882 /**
15883 * Limit number of subrequests.
15884 */
15885 subRequests?: number;
15886}
15887interface DynamicDispatchOptions {
15888 /**
15889 * Limit resources of invoked Worker script.
15890 */
15891 limits?: DynamicDispatchLimits;
15892 /**
15893 * Arguments for outbound Worker script, if configured.
15894 */
15895 outbound?: {
15896 [key: string]: any;
15897 };
15898}
15899interface DispatchNamespace {
15900 /**
15901 * @param name Name of the Worker script.
15902 * @param args Arguments to Worker script.
15903 * @param options Options for Dynamic Dispatch invocation.
15904 * @returns A Fetcher object that allows you to send requests to the Worker script.
15905 * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown.
15906 */
15907 get(name: string, args?: {
15908 [key: string]: any;
15909 }, options?: DynamicDispatchOptions): Fetcher;
15910}
15911declare module 'cloudflare:workflows' {
15912 /**
15913 * NonRetryableError allows for a user to throw a fatal error
15914 * that makes a Workflow instance fail immediately without triggering a retry
15915 */
15916 export class NonRetryableError extends Error {
15917 public constructor(message: string, name?: string);
15918 }
15919}
15920declare abstract class Workflow<PARAMS = unknown> {
15921 /**
15922 * Get a handle to an existing instance of the Workflow.
15923 * @param id Id for the instance of this Workflow
15924 * @returns A promise that resolves with a handle for the Instance
15925 */
15926 public get(id: string): Promise<WorkflowInstance>;
15927 /**
15928 * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown.
15929 * @param options Options when creating an instance including id and params
15930 * @returns A promise that resolves with a handle for the Instance
15931 */
15932 public create(options?: WorkflowInstanceCreateOptions<PARAMS>): Promise<WorkflowInstance>;
15933 /**
15934 * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown.
15935 * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached.
15936 * @param batch List of Options when creating an instance including name and params
15937 * @returns A promise that resolves with a list of handles for the created instances.
15938 */
15939 public createBatch(batch: WorkflowInstanceCreateOptions<PARAMS>[]): Promise<WorkflowInstance[]>;
15940 /**
15941 * Delete a batch of Workflow instances and their stored state.
15942 * `deleteBatch` is limited to 100 instances at a time. Duplicate IDs are deleted once.
15943 * The result contains one entry for each input position; IDs that do not exist are returned as per-instance errors.
15944 * @param instanceIds IDs of the Workflow instances to delete
15945 * @returns A promise that resolves with the successfully deleted instances and any per-instance errors.
15946 */
15947 public deleteBatch(instanceIds: string[]): Promise<WorkflowBatchDeleteResult>;
15948}
15949type WorkflowBatchDeleteResult = {
15950 deleted: {
15951 id: string;
15952 }[];
15953 errors: {
15954 id: string;
15955 code: number;
15956 message: string;
15957 }[];
15958};
15959type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';
15960type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number;
15961type WorkflowRetentionDuration = WorkflowSleepDuration;
15962/** Geographic regions supported when creating a Workflow instance.
15963 * Location hints are best-effort placement preferences. */
15964type WorkflowInstanceLocationHint = 'wnam' | 'enam' | 'sam' | 'weur' | 'eeur' | 'apac' | 'apac-ne' | 'apac-se' | 'oc' | 'afr' | 'me';
15965interface WorkflowInstanceCreateOptions<PARAMS = unknown> {
15966 /**
15967 * An id for your Workflow instance. Must be unique within the Workflow.
15968 */
15969 id?: string;
15970 /**
15971 * The event payload the Workflow instance is triggered with
15972 */
15973 params?: PARAMS;
15974 /**
15975 * The retention policy for Workflow instance.
15976 * Defaults to the maximum retention period available for the owner's account.
15977 */
15978 retention?: {
15979 successRetention?: WorkflowRetentionDuration;
15980 errorRetention?: WorkflowRetentionDuration;
15981 };
15982 /** A best-effort geographic placement preference for the Workflow instance.
15983 * See `WorkflowInstanceLocationHint` for supported regions. */
15984 locationHint?: WorkflowInstanceLocationHint;
15985}
15986type InstanceStatus = {
15987 status: 'queued' // means that instance is waiting to be started (see concurrency limits)
15988 | 'running' | 'paused' | 'errored' | 'terminated' // user terminated the instance while it was running
15989 | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish
15990 | 'waitingForPause' // instance is finishing the current work to pause
15991 | 'rollingBack' | 'unknown';
15992 error?: {
15993 name: string;
15994 message: string;
15995 };
15996 output?: unknown;
15997};
15998interface WorkflowError {
15999 code?: number;
16000 message: string;
16001}
16002interface WorkflowInstanceTerminateOptions {
16003 /**
16004 * If true, run registered rollback handlers before terminating the instance.
16005 * Only steps that registered rollback handlers are rolled back.
16006 */
16007 rollback?: boolean;
16008}
16009interface WorkflowInstanceRestartOptions {
16010 /**
16011 * Restart from a specific step. If omitted, the instance restarts from the beginning.
16012 * The step must exist in the instance's execution history.
16013 */
16014 from?: {
16015 /**
16016 * The step name as defined in your workflow code.
16017 */
16018 name: string;
16019 /**
16020 * 1-indexed occurrence of this step name. Use when the same step name appears multiple times (e.g. in a loop).
16021 * @default 1
16022 */
16023 count?: number;
16024 /**
16025 * Step type filter. Use when different step types share the same name.
16026 */
16027 type?: 'do' | 'sleep' | 'waitForEvent';
16028 };
16029}
16030/** An event emitted by a Workflow instance. */
16031type WorkflowInstanceEvent = {
16032 instanceId: string;
16033 eventId: number;
16034 timestamp: number;
16035} & ({
16036 type: 'workflow_queued';
16037} | {
16038 type: 'workflow_started';
16039 params?: unknown;
16040} | {
16041 type: 'workflow_running';
16042} | {
16043 type: 'workflow_paused';
16044} | {
16045 type: 'workflow_waiting_for_pause';
16046} | {
16047 type: 'workflow_waiting';
16048} | {
16049 type: 'workflow_completed';
16050 output?: unknown;
16051} | {
16052 type: 'workflow_errored';
16053 error: {
16054 name: string;
16055 message: string;
16056 };
16057} | {
16058 type: 'workflow_terminated';
16059} | {
16060 type: 'step_started';
16061 stepName: string;
16062 config?: {
16063 retries: {
16064 limit: number;
16065 delay: WorkflowSleepDuration | '[dynamic]';
16066 backoff?: 'constant' | 'linear' | 'exponential';
16067 };
16068 timeout: WorkflowSleepDuration;
16069 sensitive?: 'output';
16070 };
16071} | {
16072 type: 'step_completed';
16073 stepName: string;
16074 output?: unknown;
16075} | {
16076 type: 'step_errored';
16077 stepName: string;
16078} | {
16079 type: 'attempt_started';
16080 stepName: string;
16081 attempt: number;
16082} | {
16083 type: 'attempt_completed';
16084 stepName: string;
16085 attempt: number;
16086} | {
16087 type: 'attempt_errored';
16088 stepName: string;
16089 attempt: number;
16090 retryDelayMs?: number;
16091 error: {
16092 name: string;
16093 message: string;
16094 };
16095} | {
16096 type: 'sleep_started';
16097 stepName: string;
16098 durationMs: number;
16099} | {
16100 type: 'sleep_completed';
16101 stepName: string;
16102} | {
16103 type: 'wait_started';
16104 stepName: string;
16105 eventType: string;
16106} | {
16107 type: 'wait_completed';
16108 stepName: string;
16109} | {
16110 type: 'wait_timed_out';
16111 stepName: string;
16112} | {
16113 type: 'rollback_started';
16114} | {
16115 type: 'rollback_step_started';
16116 stepName: string;
16117 config?: {
16118 retries: {
16119 limit: number;
16120 delay: WorkflowSleepDuration | '[dynamic]';
16121 backoff?: 'constant' | 'linear' | 'exponential';
16122 };
16123 timeout: WorkflowSleepDuration;
16124 sensitive?: 'output';
16125 };
16126} | {
16127 type: 'rollback_step_completed';
16128 stepName: string;
16129} | {
16130 type: 'rollback_step_errored';
16131 stepName: string;
16132 error: {
16133 name: string;
16134 message: string;
16135 };
16136} | {
16137 type: 'rollback_attempt_started';
16138 stepName: string;
16139 attempt: number;
16140} | {
16141 type: 'rollback_attempt_completed';
16142 stepName: string;
16143 attempt: number;
16144} | {
16145 type: 'rollback_attempt_errored';
16146 stepName: string;
16147 attempt: number;
16148 retryDelayMs?: number;
16149 error: {
16150 name: string;
16151 message: string;
16152 };
16153} | {
16154 type: 'rollback_completed';
16155} | {
16156 type: 'rollback_errored';
16157});
16158type WorkflowInstanceEventType = WorkflowInstanceEvent['type'];
16159/** Options available for a Workflow instance subscription. */
16160type WorkflowInstanceSubscribeOptions = {
16161 /** The value from which to start the subscription. */
16162 cursor?: number;
16163 /** The event types to include in the subscription. */
16164 filter?: WorkflowInstanceEventType[];
16165};
16166/** A disposable subscription to a Workflow instance's events. */
16167interface WorkflowInstanceSubscription extends Disposable {
16168 next(): Promise<IteratorResult<WorkflowInstanceEvent, void>>;
16169}
16170declare abstract class WorkflowInstance {
16171 public id: string;
16172 /**
16173 * Pause the instance.
16174 */
16175 public pause(): Promise<void>;
16176 /**
16177 * Resume the instance. If it is already running, an error will be thrown.
16178 */
16179 public resume(): Promise<void>;
16180 /**
16181 * Terminate the instance. If it is errored, terminated or complete, an error will be thrown.
16182 * @param options Options for termination, including whether registered rollback handlers should run.
16183 */
16184 public terminate(options?: WorkflowInstanceTerminateOptions): Promise<void>;
16185 /**
16186 * Restart the instance. Optionally restart from a specific step, preserving
16187 * cached results for all steps before it.
16188 * @param options Options for the restart, including an optional step to restart from.
16189 */
16190 public restart(options?: WorkflowInstanceRestartOptions): Promise<void>;
16191 /**
16192 * Delete the instance and its stored state.
16193 */
16194 public delete(): Promise<void>;
16195 /**
16196 * Returns the current status of the instance.
16197 */
16198 public status(): Promise<InstanceStatus>;
16199 /**
16200 * Send an event to this instance.
16201 */
16202 public sendEvent({ type, payload, }: {
16203 type: string;
16204 payload: unknown;
16205 }): Promise<void>;
16206 /**
16207 * Subscribe to events emitted by this instance.
16208 */
16209 public subscribe(options?: WorkflowInstanceSubscribeOptions): Promise<WorkflowInstanceSubscription>;
16210}